<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include <qapplication.h>
#include <qevent.h>
#include <qaction.h>
#include <qmenu.h>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QAction : public QObject
{
    Q_OBJECT

public:
    tst_QAction();
    virtual ~tst_QAction();

    void updateState(QActionEvent *e);

public slots:
    void initTestCase();
    void cleanupTestCase();
private slots:
    void getSetCheck();
    void setText_data();
    void setText();
    void setIconText_data() { setText_data(); }
    void setIconText();
    void actionEvent();
    void setStandardKeys();
    void alternateShortcuts();
    void enabledVisibleInteraction();
    void task200823_tooltip();
    void task229128TriggeredSignalWithoutActiongroup();
    void task229128TriggeredSignalWhenInActiongroup();

private:
    int m_lastEventType;
    QAction *m_lastAction;
    QWidget *m_tstWidget;
};

// Testing get/set functions
void tst_QAction::getSetCheck()
{
    QAction obj1(0);
    // QActionGroup * QAction::actionGroup()
    // void QAction::setActionGroup(QActionGroup *)
    QActionGroup *var1 = new QActionGroup(0);
    obj1.setActionGroup(var1);
    QCOMPARE(var1, obj1.actionGroup());
    obj1.setActionGroup((QActionGroup *)0);
    QCOMPARE((QActionGroup *)0, obj1.actionGroup());
    delete var1;

    // QMenu * QAction::menu()
    // void QAction::setMenu(QMenu *)
    QMenu *var2 = new QMenu(0);
    obj1.setMenu(var2);
    QCOMPARE(var2, obj1.menu());
    obj1.setMenu((QMenu *)0);
    QCOMPARE((QMenu *)0, obj1.menu());
    delete var2;

    QCOMPARE(obj1.priority(), QAction::NormalPriority);
    obj1.setPriority(QAction::LowPriority);
    QCOMPARE(obj1.priority(), QAction::LowPriority);
}

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    MyWidget(tst_QAction *tst, QWidget *parent = 0) : QWidget(parent) { this->tst = tst; }

protected:
    virtual void actionEvent(QActionEvent *e) { tst->updateState(e); }

private:
    tst_QAction *tst;
};

tst_QAction::tst_QAction()
{
}

tst_QAction::~tst_QAction()
{

}

void tst_QAction::initTestCase()
{
    m_lastEventType = 0;
    m_lastAction = 0;

    MyWidget *mw = new MyWidget(this);
    m_tstWidget = mw;
    mw->show();
    qApp->setActiveWindow(mw);
}

void tst_QAction::cleanupTestCase()
{
    QWidget *testWidget = m_tstWidget;
    if (testWidget) {
        testWidget->hide();
        delete testWidget;
    }
}

void tst_QAction::setText_data()
{
    QTest::addColumn<QString>("text");
    QTest::addColumn<QString>("iconText");
    QTest::addColumn<QString>("textFromIconText");

    //next we fill it with data
    QTest::newRow("Normal") << "Action" << "Action" << "Action";
    QTest::newRow("Ampersand") << "Search && Destroy" << "Search & Destroy" << "Search && Destroy";
    QTest::newRow("Mnemonic and ellipsis") << "O&pen File ..." << "Open File" << "Open File";
}

void tst_QAction::setText()
{
    QFETCH(QString, text);

    QAction action(0);
    action.setText(text);

    QCOMPARE(action.text(), text);

    QFETCH(QString, iconText);
    QCOMPARE(action.iconText(), iconText);
}

void tst_QAction::setIconText()
{
    QFETCH(QString, iconText);

    QAction action(0);
    action.setIconText(iconText);
    QCOMPARE(action.iconText(), iconText);

    QFETCH(QString, textFromIconText);
    QCOMPARE(action.text(), textFromIconText);
}

void tst_QAction::updateState(QActionEvent *e)
{
    if (!e) {
        m_lastEventType = 0;
        m_lastAction = 0;
    } else {
        m_lastEventType = (int)e->type();
        m_lastAction = e->action();
    }
}

void tst_QAction::actionEvent()
{
    QAction a(0);
    a.setText("action text");

    // add action
    m_tstWidget->addAction(&a);
    qApp->processEvents();

    QCOMPARE(m_lastEventType, (int)QEvent::ActionAdded);
    QCOMPARE(m_lastAction, &a);

    // change action
    a.setText("new action text");
    qApp->processEvents();

    QCOMPARE(m_lastEventType, (int)QEvent::ActionChanged);
    QCOMPARE(m_lastAction, &a);

    // remove action
    m_tstWidget->removeAction(&a);
    qApp->processEvents();

    QCOMPARE(m_lastEventType, (int)QEvent::ActionRemoved);
    QCOMPARE(m_lastAction, &a);
}

//basic testing of standard keys
void tst_QAction::setStandardKeys()
{
    QAction act(0);
    act.setShortcut(QKeySequence("CTRL+L"));
    QList<QKeySequence> list;
    act.setShortcuts(list);
    act.setShortcuts(QKeySequence::Copy);
    QVERIFY(act.shortcut() == act.shortcuts().first());

    QList<QKeySequence> expected;
#ifdef Q_WS_MAC
    expected  << QKeySequence("CTRL+C");
#elif defined(Q_WS_WIN) || defined(Q_WS_QWS) || defined(Q_OS_SYMBIAN)
    expected  << QKeySequence("CTRL+C") << QKeySequence("CTRL+INSERT");
#else
    expected  << QKeySequence("CTRL+C") << QKeySequence("F16") << QKeySequence("CTRL+INSERT");
#endif
    QVERIFY(act.shortcuts() == expected);
}

void tst_QAction::alternateShortcuts()
{
    //test the alternate shortcuts (by adding more than 1 shortcut)

    QWidget *wid = m_tstWidget;

    {
        QAction act(wid);
        wid->addAction(&act);
        QList<QKeySequence> shlist = QList<QKeySequence>() << QKeySequence("CTRL+P") << QKeySequence("CTRL+A");
        act.setShortcuts(shlist);

        QSignalSpy spy(&act, SIGNAL(triggered()));

        act.setAutoRepeat(true);
        QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
        QCOMPARE(spy.count(), 1); //act should have been triggered

        act.setAutoRepeat(false);
        QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
        QCOMPARE(spy.count(), 2); //act should have been triggered a 2nd time

        //end of the scope of the action, it will be destroyed and removed from wid
        //This action should also unregister its shortcuts
    }

    //this tests a crash (if the action did not unregister its alternate shortcuts)
    QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
}

void tst_QAction::enabledVisibleInteraction()
{
    QAction act(0);
    // check defaults
    QVERIFY(act.isEnabled());
    QVERIFY(act.isVisible());

    // !visible => !enabled
    act.setVisible(false);
    QVERIFY(!act.isEnabled());
    act.setVisible(true);
    QVERIFY(act.isEnabled());
    act.setEnabled(false);
    QVERIFY(act.isVisible());

    // check if shortcut is disabled if not visible
    m_tstWidget->addAction(&act);
    act.setShortcut(QKeySequence("Ctrl+T"));
    QSignalSpy spy(&act, SIGNAL(triggered()));
    act.setEnabled(true);
    act.setVisible(false);
    QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
    QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
    act.setVisible(false);
    act.setEnabled(true);
    QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
    QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
    act.setVisible(true);
    act.setEnabled(true);
    QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
    QCOMPARE(spy.count(), 1); //act is visible and enabled, so trigger
}

void tst_QAction::task200823_tooltip()
{
    QAction *action = new QAction("foo", 0);
    QString shortcut("ctrl+o");
    action->setShortcut(shortcut);

    // we want a non-standard tooltip that shows the shortcut
    action->setToolTip(QString("%1 (%2)").arg(action->text()).arg(action->shortcut().toString()));

    QString ref = QString("foo (%1)").arg(QKeySequence(shortcut).toString());
    QCOMPARE(action->toolTip(), ref);
}

void tst_QAction::task229128TriggeredSignalWithoutActiongroup()
{
    // test without a group
    QAction *actionWithoutGroup = new QAction("Test", qApp);
    QSignalSpy spyWithoutGroup(actionWithoutGroup, SIGNAL(triggered(bool)));
    QCOMPARE(spyWithoutGroup.count(), 0);
    actionWithoutGroup->trigger();
    // signal should be emitted
    QCOMPARE(spyWithoutGroup.count(), 1);

    // it is now a checkable checked action
    actionWithoutGroup->setCheckable(true);
    actionWithoutGroup->setChecked(true);
    spyWithoutGroup.clear();
    QCOMPARE(spyWithoutGroup.count(), 0);
    actionWithoutGroup->trigger();
    // signal should be emitted
    QCOMPARE(spyWithoutGroup.count(), 1);
}

void tst_QAction::task229128TriggeredSignalWhenInActiongroup()
{
    QActionGroup ag(0);
    QAction *action = new QAction("Test", &ag);
    QAction *checkedAction = new QAction("Test 2", &ag);
    ag.addAction(action);
    action->setCheckable(true);
    ag.addAction(checkedAction);
    checkedAction->setCheckable(true);
    checkedAction->setChecked(true);

    QSignalSpy actionSpy(checkedAction, SIGNAL(triggered(bool)));
    QSignalSpy actionGroupSpy(&ag, SIGNAL(triggered(QAction *)));
    QCOMPARE(actionGroupSpy.count(), 0);
    QCOMPARE(actionSpy.count(), 0);
    checkedAction->trigger();
    // check that both the group and the action have emitted the signal
    QCOMPARE(actionGroupSpy.count(), 1);
    QCOMPARE(actionSpy.count(), 1);
}

QTEST_MAIN(tst_QAction)
#include "tst_qaction.moc"
<commit_msg>Fixed qaction autotest failures for Symbian.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the either Technology Preview License Agreement or the
** Beta Release License Agreement.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include <qapplication.h>
#include <qevent.h>
#include <qaction.h>
#include <qmenu.h>

//TESTED_CLASS=
//TESTED_FILES=

class tst_QAction : public QObject
{
    Q_OBJECT

public:
    tst_QAction();
    virtual ~tst_QAction();

    void updateState(QActionEvent *e);

public slots:
    void initTestCase();
    void cleanupTestCase();
private slots:
    void getSetCheck();
    void setText_data();
    void setText();
    void setIconText_data() { setText_data(); }
    void setIconText();
    void actionEvent();
    void setStandardKeys();
    void alternateShortcuts();
    void enabledVisibleInteraction();
    void task200823_tooltip();
    void task229128TriggeredSignalWithoutActiongroup();
    void task229128TriggeredSignalWhenInActiongroup();

private:
    int m_lastEventType;
    QAction *m_lastAction;
    QWidget *m_tstWidget;
};

// Testing get/set functions
void tst_QAction::getSetCheck()
{
    QAction obj1(0);
    // QActionGroup * QAction::actionGroup()
    // void QAction::setActionGroup(QActionGroup *)
    QActionGroup *var1 = new QActionGroup(0);
    obj1.setActionGroup(var1);
    QCOMPARE(var1, obj1.actionGroup());
    obj1.setActionGroup((QActionGroup *)0);
    QCOMPARE((QActionGroup *)0, obj1.actionGroup());
    delete var1;

    // QMenu * QAction::menu()
    // void QAction::setMenu(QMenu *)
    QMenu *var2 = new QMenu(0);
    obj1.setMenu(var2);
    QCOMPARE(var2, obj1.menu());
    obj1.setMenu((QMenu *)0);
    QCOMPARE((QMenu *)0, obj1.menu());
    delete var2;

    QCOMPARE(obj1.priority(), QAction::NormalPriority);
    obj1.setPriority(QAction::LowPriority);
    QCOMPARE(obj1.priority(), QAction::LowPriority);
}

class MyWidget : public QWidget
{
    Q_OBJECT
public:
    MyWidget(tst_QAction *tst, QWidget *parent = 0) : QWidget(parent) { this->tst = tst; }

protected:
    virtual void actionEvent(QActionEvent *e) { tst->updateState(e); }

private:
    tst_QAction *tst;
};

tst_QAction::tst_QAction()
{
}

tst_QAction::~tst_QAction()
{

}

void tst_QAction::initTestCase()
{
    m_lastEventType = 0;
    m_lastAction = 0;

    MyWidget *mw = new MyWidget(this);
    m_tstWidget = mw;
    mw->show();
    qApp->setActiveWindow(mw);
}

void tst_QAction::cleanupTestCase()
{
    QWidget *testWidget = m_tstWidget;
    if (testWidget) {
        testWidget->hide();
        delete testWidget;
    }
}

void tst_QAction::setText_data()
{
    QTest::addColumn<QString>("text");
    QTest::addColumn<QString>("iconText");
    QTest::addColumn<QString>("textFromIconText");

    //next we fill it with data
    QTest::newRow("Normal") << "Action" << "Action" << "Action";
    QTest::newRow("Ampersand") << "Search && Destroy" << "Search & Destroy" << "Search && Destroy";
    QTest::newRow("Mnemonic and ellipsis") << "O&pen File ..." << "Open File" << "Open File";
}

void tst_QAction::setText()
{
    QFETCH(QString, text);

    QAction action(0);
    action.setText(text);

    QCOMPARE(action.text(), text);

    QFETCH(QString, iconText);
    QCOMPARE(action.iconText(), iconText);
}

void tst_QAction::setIconText()
{
    QFETCH(QString, iconText);

    QAction action(0);
    action.setIconText(iconText);
    QCOMPARE(action.iconText(), iconText);

    QFETCH(QString, textFromIconText);
    QCOMPARE(action.text(), textFromIconText);
}

void tst_QAction::updateState(QActionEvent *e)
{
    if (!e) {
        m_lastEventType = 0;
        m_lastAction = 0;
    } else {
        m_lastEventType = (int)e->type();
        m_lastAction = e->action();
    }
}

void tst_QAction::actionEvent()
{
    QAction a(0);
    a.setText("action text");

    // add action
    m_tstWidget->addAction(&a);
    qApp->processEvents();

    QCOMPARE(m_lastEventType, (int)QEvent::ActionAdded);
    QCOMPARE(m_lastAction, &a);

    // change action
    a.setText("new action text");
    qApp->processEvents();

    QCOMPARE(m_lastEventType, (int)QEvent::ActionChanged);
    QCOMPARE(m_lastAction, &a);

    // remove action
    m_tstWidget->removeAction(&a);
    qApp->processEvents();

    QCOMPARE(m_lastEventType, (int)QEvent::ActionRemoved);
    QCOMPARE(m_lastAction, &a);
}

//basic testing of standard keys
void tst_QAction::setStandardKeys()
{
    QAction act(0);
    act.setShortcut(QKeySequence("CTRL+L"));
    QList<QKeySequence> list;
    act.setShortcuts(list);
    act.setShortcuts(QKeySequence::Copy);
    QVERIFY(act.shortcut() == act.shortcuts().first());

    QList<QKeySequence> expected;
#if defined(Q_WS_MAC) || defined(Q_OS_SYMBIAN)
    expected  << QKeySequence("CTRL+C");
#elif defined(Q_WS_WIN) || defined(Q_WS_QWS)
    expected  << QKeySequence("CTRL+C") << QKeySequence("CTRL+INSERT");
#else
    expected  << QKeySequence("CTRL+C") << QKeySequence("F16") << QKeySequence("CTRL+INSERT");
#endif
    QVERIFY(act.shortcuts() == expected);
}

void tst_QAction::alternateShortcuts()
{
    //test the alternate shortcuts (by adding more than 1 shortcut)

    QWidget *wid = m_tstWidget;

    {
        QAction act(wid);
        wid->addAction(&act);
        QList<QKeySequence> shlist = QList<QKeySequence>() << QKeySequence("CTRL+P") << QKeySequence("CTRL+A");
        act.setShortcuts(shlist);

        QSignalSpy spy(&act, SIGNAL(triggered()));

        act.setAutoRepeat(true);
        QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
        QCOMPARE(spy.count(), 1); //act should have been triggered

        act.setAutoRepeat(false);
        QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
        QCOMPARE(spy.count(), 2); //act should have been triggered a 2nd time

        //end of the scope of the action, it will be destroyed and removed from wid
        //This action should also unregister its shortcuts
    }

    //this tests a crash (if the action did not unregister its alternate shortcuts)
    QTest::keyClick(wid, Qt::Key_A, Qt::ControlModifier);
}

void tst_QAction::enabledVisibleInteraction()
{
    QAction act(0);
    // check defaults
    QVERIFY(act.isEnabled());
    QVERIFY(act.isVisible());

    // !visible => !enabled
    act.setVisible(false);
    QVERIFY(!act.isEnabled());
    act.setVisible(true);
    QVERIFY(act.isEnabled());
    act.setEnabled(false);
    QVERIFY(act.isVisible());

    // check if shortcut is disabled if not visible
    m_tstWidget->addAction(&act);
    act.setShortcut(QKeySequence("Ctrl+T"));
    QSignalSpy spy(&act, SIGNAL(triggered()));
    act.setEnabled(true);
    act.setVisible(false);
    QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
    QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
    act.setVisible(false);
    act.setEnabled(true);
    QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
    QCOMPARE(spy.count(), 0); //act is not visible, so don't trigger
    act.setVisible(true);
    act.setEnabled(true);
    QTest::keyClick(m_tstWidget, Qt::Key_T, Qt::ControlModifier);
    QCOMPARE(spy.count(), 1); //act is visible and enabled, so trigger
}

void tst_QAction::task200823_tooltip()
{
    QAction *action = new QAction("foo", 0);
    QString shortcut("ctrl+o");
    action->setShortcut(shortcut);

    // we want a non-standard tooltip that shows the shortcut
    action->setToolTip(QString("%1 (%2)").arg(action->text()).arg(action->shortcut().toString()));

    QString ref = QString("foo (%1)").arg(QKeySequence(shortcut).toString());
    QCOMPARE(action->toolTip(), ref);
}

void tst_QAction::task229128TriggeredSignalWithoutActiongroup()
{
    // test without a group
    QAction *actionWithoutGroup = new QAction("Test", qApp);
    QSignalSpy spyWithoutGroup(actionWithoutGroup, SIGNAL(triggered(bool)));
    QCOMPARE(spyWithoutGroup.count(), 0);
    actionWithoutGroup->trigger();
    // signal should be emitted
    QCOMPARE(spyWithoutGroup.count(), 1);

    // it is now a checkable checked action
    actionWithoutGroup->setCheckable(true);
    actionWithoutGroup->setChecked(true);
    spyWithoutGroup.clear();
    QCOMPARE(spyWithoutGroup.count(), 0);
    actionWithoutGroup->trigger();
    // signal should be emitted
    QCOMPARE(spyWithoutGroup.count(), 1);
}

void tst_QAction::task229128TriggeredSignalWhenInActiongroup()
{
    QActionGroup ag(0);
    QAction *action = new QAction("Test", &ag);
    QAction *checkedAction = new QAction("Test 2", &ag);
    ag.addAction(action);
    action->setCheckable(true);
    ag.addAction(checkedAction);
    checkedAction->setCheckable(true);
    checkedAction->setChecked(true);

    QSignalSpy actionSpy(checkedAction, SIGNAL(triggered(bool)));
    QSignalSpy actionGroupSpy(&ag, SIGNAL(triggered(QAction *)));
    QCOMPARE(actionGroupSpy.count(), 0);
    QCOMPARE(actionSpy.count(), 0);
    checkedAction->trigger();
    // check that both the group and the action have emitted the signal
    QCOMPARE(actionGroupSpy.count(), 1);
    QCOMPARE(actionSpy.count(), 1);
}

QTEST_MAIN(tst_QAction)
#include "tst_qaction.moc"
<|endoftext|>


<commit_before>#include "detectPeaks.h"

bool peakDetected(volatile SignalState_t* signalState)
{
  float s = 0;
  bool peak = false;

  signalState->offset = (signalState->x_max - signalState->x_min) / 2.208;

  float high_thresh = signalState->x_max - signalState->offset;
  float low_thresh = signalState->x_min + signalState->offset;

  s = signalState->x[1] - signalState->x[0];

  if(s > 0)
  {
    signalState->slopeIsPositive = true;
    signalState->slopeIsNegative = false;
    if (signalState->x[1] > signalState->x_max)
    {
      signalState->x_max = signalState->x[1];
      high_thresh = signalState->x_max - signalState->offset;
    }
  }
  else if(s < 0)
  {
    signalState->slopeIsPositive = false;
    signalState->slopeIsNegative = true;
    if (signalState->x[1] < signalState->x_min)
    {
      signalState->x_min = signalState->x[1];
      low_thresh = signalState->x_min + signalState->offset;
    }
  }

  if(!signalState->slopeIsNegative && signalState->slopeWasNegative)
  {
    signalState->currentMin = signalState->x[0];
  }

  if(!signalState->slopeIsPositive && signalState->slopeWasPositive)
  {
    signalState->currentMax = signalState->x[0];
    if((signalState->currentMax > high_thresh) && (signalState->currentMin < low_thresh))
    {
      peak = true;
    }
  }

  if(signalState->slopeIsPositive)
    signalState->slopeWasPositive = true;
  else
    signalState->slopeWasPositive = false;

  if(signalState->slopeIsNegative)
    signalState->slopeWasNegative = true;
  else
    signalState->slopeWasNegative = false;

  /* Data to plot the waveform measured by the magnetometer. For testing purposes. To be removed when no longer needed. */
  /* Along with the wavefrom, the calculated peaks are marked, where 1 indicates a peak and -2 indicates no peak.*/
  SDPowerUp();
  File waveFile = SD.open("waveform.csv", FILE_WRITE);
  waveFile.print(SignalState->x[1], 4);
  if(peak)
    waveFile.print(",1");   // 1 on the graph means a peak
  else
    waveFile.print(",-2");  // -2 on the graph means no peak
  waveFile.println();
  waveFile.close();
  SDPowerDown();

  return peak;
}
<commit_msg>Update magnetometer.cpp<commit_after>#include "magnetometer.h"
#include <Arduino.h>
#include <SD.h>
#include <DebugMacros.h>
#include <LSM303CTypes.h>
#include <SparkFunIMU.h>
#include <SparkFunLSM303C.h>
#include "powerSleep.h"
#include "state.h"

/*********************************************************************\
 *
 * Library for interfacing with the SparkFun LSM303C magnetometer.
 *
 * Functions:
 *    Initialize Magnetomter
 *    Read Data
 *    Initialize Data
 *
\*********************************************************************/

void magnetometerInit(LSM303C *mag)
{
  twiPowerUp();

  if (mag->begin(
    MODE_I2C,
    MAG_DO_20_Hz,
    MAG_FS_8_Ga,
    MAG_BDU_DISABLE,
    MAG_OMXY_LOW_POWER,
    MAG_OMZ_MEDIUM_PERFORMANCE,
    MAG_MD_CONTINUOUS,
    ACC_FS_2g,
    ACC_BDU_DISABLE,
    ACC_DISABLE_ALL,
    ACC_ODR_POWER_DOWN
    ) != IMU_SUCCESS)
    {
      Serial.println("Magnetometer setup failed. Check connection and reset.");
      while(1);
    }
    twiPowerDown();

    return;
}

void readData(LSM303C* mag, volatile SignalState_t* SignalState)
{
  twiPowerUp();
  SignalState->x[0] = SignalState->x[1];
  SignalState->x[1] = mag->readMagZ();
  twiPowerDown();

  return;
}

void initializeData(LSM303C* mag, volatile SignalState_t* SignalState)
{
  twiPowerUp();
  SignalState->x[0] = mag->readMagZ();
  SignalState->x[1] = SignalState->x[0];
  SignalState->x_max = SignalState->x[1];
  SignalState->x_min = SignalState->x[1];
  SignalState->currentMax = SignalState->x[1];
  SignalState->currentMin = SignalState->x[1];
  twiPowerDown();

  return;
}
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

// test the PETSc SparseDirectMumps solver

#include "../tests.h"
#include "../testmatrix.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <deal.II/base/logstream.h>
#include <deal.II/lac/petsc_sparse_matrix.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>
#include <deal.II/lac/vector_memory.h>
#include <typeinfo>

int main(int argc, char **argv)
{
  std::ofstream logfile("output");
  deallog.attach(logfile);
  deallog << std::setprecision(4);
  deallog.threshold_double(1.e-10);

  Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
  {
    const unsigned int size = 32;
    unsigned int dim = (size-1)*(size-1);

    deallog << "Size " << size << " Unknowns " << dim << std::endl;

    // Make matrix
    FDMatrix testproblem(size, size);
    PETScWrappers::SparseMatrix  A(dim, dim, 5);
    testproblem.five_point(A);

    IndexSet indices(dim);
    indices.add_range(0, dim);
    PETScWrappers::MPI::Vector  f(indices, MPI_COMM_WORLD);
    PETScWrappers::MPI::Vector  u(indices, MPI_COMM_WORLD);
    u = 0.;
    f = 1.;
    A.compress (VectorOperation::insert);

    SolverControl cn;
    PETScWrappers::SparseDirectMUMPS solver(cn);
//    solver.set_symmetric_mode(true);
    solver.solve(A,u,f);

    PETScWrappers::MPI::Vector  tmp(dim);
    deallog << "residual = " << A.residual (tmp, u, f)
            << std::endl;
  }

}
<commit_msg>Fix a PETSc test that doesn't compile.<commit_after>// ---------------------------------------------------------------------
//
// Copyright (C) 2004 - 2016 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------

// test the PETSc SparseDirectMumps solver

#include "../tests.h"
#include "../testmatrix.h"
#include <cmath>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <deal.II/base/logstream.h>
#include <deal.II/lac/petsc_sparse_matrix.h>
#include <deal.II/lac/petsc_parallel_vector.h>
#include <deal.II/lac/petsc_solver.h>
#include <deal.II/lac/petsc_precondition.h>
#include <deal.II/lac/vector_memory.h>
#include <typeinfo>

int main(int argc, char **argv)
{
  std::ofstream logfile("output");
  deallog.attach(logfile);
  deallog << std::setprecision(4);
  deallog.threshold_double(1.e-10);

  Utilities::MPI::MPI_InitFinalize mpi_initialization (argc, argv, 1);
  {
    const unsigned int size = 32;
    unsigned int dim = (size-1)*(size-1);

    deallog << "Size " << size << " Unknowns " << dim << std::endl;

    // Make matrix
    FDMatrix testproblem(size, size);
    PETScWrappers::SparseMatrix  A(dim, dim, 5);
    testproblem.five_point(A);

    IndexSet indices(dim);
    indices.add_range(0, dim);
    PETScWrappers::MPI::Vector  f(indices, MPI_COMM_WORLD);
    PETScWrappers::MPI::Vector  u(indices, MPI_COMM_WORLD);
    u = 0.;
    f = 1.;
    A.compress (VectorOperation::insert);

    SolverControl cn;
    PETScWrappers::SparseDirectMUMPS solver(cn);
//    solver.set_symmetric_mode(true);
    solver.solve(A,u,f);

    PETScWrappers::MPI::Vector  tmp(indices, MPI_COMM_WORLD);
    deallog << "residual = " << A.residual (tmp, u, f)
            << std::endl;
  }

}
<|endoftext|>


<commit_before>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Utils/Validation.h"
#include "llvm/Support/ThreadLocal.h"

#include <assert.h>
#include <errno.h>
#ifdef LLVM_ON_WIN32
# include <Windows.h>
#else
#include <fcntl.h>
# include <unistd.h>
#endif

#define CACHESIZE 8

namespace cling {
  namespace utils {

#ifndef LLVM_ON_WIN32
    struct Cache {
    private:
      const void* lines[CACHESIZE];
      unsigned size, mostRecent;
    public:
      Cache(): lines{0,0,0,0,0,0,0,0}, size(CACHESIZE), mostRecent(0) {}
      bool findInCache(const void* P) {
        for (unsigned index = 0; index < size; index++) {
          if (lines[index] == P)
            return true;
        }
        return false;
      }
      void pushToCache(const void* P) {
        mostRecent = (mostRecent+1)%size;
        lines[mostRecent] = P;
      }
    };

    // Trying to be thread-safe.
    // Each thread creates a new cache when needed.
    static Cache& getCache() {
      static llvm::sys::ThreadLocal<Cache> threadCache;
      if (!threadCache.get()) {
        threadCache.set(new Cache());
      }
      return *threadCache.get();
    }

    static int getNullDevFileDescriptor() {
      struct FileDescriptor {
        int FD;
        const char* file = "/dev/null";
        FileDescriptor() { FD = open(file, O_WRONLY); }
        ~FileDescriptor() {
          close(FD);
        }
      };
      static FileDescriptor nullDev;
      return nullDev.FD;
    }
#endif

    // Checking whether the pointer points to a valid memory location
    bool isAddressValid(const void *P) {
      if (!P || P == (void *) -1)
        return false;

#ifdef LLVM_ON_WIN32
      MEMORY_BASIC_INFORMATION MBI;
      if (!VirtualQuery(P, &MBI, sizeof(MBI)))
        return false;
      if (MBI.State != MEM_COMMIT)
        return false;
      return true;
#else
      // Look-up the address in the cache.
      Cache& currentCache = getCache();
      if (currentCache.findInCache(P))
        return true;
      // There is a POSIX way of finding whether an address
      // can be accessed for reading.
      if (write(getNullDevFileDescriptor(), P, 1/*byte*/) != 1) {
        assert(errno == EFAULT && "unexpected write error at address");
        return false;
      }
      currentCache.pushToCache(P);
      return true;
#endif
    }
  }
}
<commit_msg>Refinements: use std::array+find, comments, func names.<commit_after>//--------------------------------------------------------------------*- C++ -*-
// CLING - the C++ LLVM-based InterpreterG :)
// author:  Vassil Vassilev <vasil.georgiev.vasilev@cern.ch>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

#include "cling/Utils/Validation.h"
#include "llvm/Support/ThreadLocal.h"

#include <assert.h>
#include <errno.h>
#ifdef LLVM_ON_WIN32
# include <Windows.h>
#else
#include <array>
#include <algorithm>
#include <fcntl.h>
# include <unistd.h>
#endif

namespace cling {
  namespace utils {

#ifndef LLVM_ON_WIN32
    // A simple round-robin cache: what enters first, leaves first.
    // MRU cache wasn't worth the extra CPU cycles.
    struct Cache {
    private:
      std::array<const void*, 8> lines;
      unsigned mostRecent = 0;
    public:
      bool contains(const void* P) {
        return std::find(lines.begin(), lines.end(), P) != lines.end();
      }
      void push(const void* P) {
        mostRecent = (mostRecent + 1) % lines.size();
        lines[mostRecent] = P;
      }
    };

    // Trying to be thread-safe.
    // Each thread creates a new cache when needed.
    static Cache& getCache() {
      static llvm::sys::ThreadLocal<Cache> threadCache;
      if (!threadCache.get()) {
        // Leak, 1 Cache/thread.
        threadCache.set(new Cache());
      }
      return *threadCache.get();
    }

    static int getNullDevFileDescriptor() {
      struct FileDescriptor {
        int FD;
        const char* file = "/dev/null";
        FileDescriptor() { FD = open(file, O_WRONLY); }
        ~FileDescriptor() {
          close(FD);
        }
      };
      static FileDescriptor nullDev;
      return nullDev.FD;
    }
#endif

    // Checking whether the pointer points to a valid memory location
    bool isAddressValid(const void *P) {
      if (!P || P == (void *) -1)
        return false;

#ifdef LLVM_ON_WIN32
      MEMORY_BASIC_INFORMATION MBI;
      if (!VirtualQuery(P, &MBI, sizeof(MBI)))
        return false;
      if (MBI.State != MEM_COMMIT)
        return false;
      return true;
#else
      // Look-up the address in the cache.
      Cache& currentCache = getCache();
      if (currentCache.contains(P))
        return true;
      // There is a POSIX way of finding whether an address
      // can be accessed for reading.
      if (write(getNullDevFileDescriptor(), P, 1/*byte*/) != 1) {
        assert(errno == EFAULT && "unexpected write error at address");
        return false;
      }
      currentCache.push(P);
      return true;
#endif
    }
  }
}
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// Test runing a file in the same directory `cling CurrentDir.C`
// More info in CIFactory.cpp createCIImpl (line ~850)

// RUN: cd %S && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s
// RUN: mkdir %T/Remove && cd %T/Remove && rm -rf %T/Remove && %cling -DTEST_CWDRETURN %s -Xclang -verify 2>&1 | FileCheck --check-prefix CHECK --check-prefix CHECKcwd %s
// Test testCurrentDir

extern "C" {
  int printf(const char*, ...);
  char* getcwd(char *buf, std::size_t size);
}

#ifdef TEST_CWDRETURN
  // Make sure include still works
  #include <string.h>
  #include <vector>
#endif

void CurrentDir() {
 #ifdef TEST_CWDRETURN
    char thisDir[1024];
    const char *rslt = getcwd(thisDir, sizeof(thisDir));
    // Make sure cling reported the error
    // CHECKcwd: Could not get current working directory: {{.*}}

    if (rslt)
      printf("Working directory exists\n");
    // CHECK-NOT: Working directory exists
 #endif

  printf("Script ran\n");
  // CHECK: Script ran
}

//expected-no-diagnostics
<commit_msg>Simplify; make Windows compatible (cannot delete cwd).<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// Test running a file in the same directory `cling CurrentDir.C`.
// More info in CIFactory.cpp ("<<< cling interactive line includer >>>")

// RUN: cp "%s" "%T/CurrentDir.C" && cd %T && %cling -Xclang -verify CurrentDir.C 2>&1 | FileCheck %s
// Test testCurrentDir

extern "C" {
  int printf(const char*, ...);
  char* getcwd(char *buf, std::size_t size);
}

void CurrentDir() {
  printf("Script ran\n"); // CHECK: Script ran
}
//expected-no-diagnostics
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::Value V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::Value &) boxes [(const char [5]) "Root"]
// End PR #98146

.rawInput 1
typedef enum {k1 = 0, k2} enumName;
enumName var = k1;
.rawInput 0
var
// CHECK: (enumName) (k1) : ({{(unsigned )?}}int) 0
const enumName constVar = (enumName) 1 // k2 is invisible!
// CHECK: (const enumName) (k2) : ({{(unsigned )?}}int) 1

// ROOT-8036: check that library symbols do not override interpreter symbols
int step = 10 // CHECK: (int) 10
step // CHECK: (int) 10

gCling->process("#ifdef __UNDEFINED__\n42\n#endif")
//CHECK: (cling::Interpreter::CompilationResult) (cling::Interpreter::CompilationResult::kSuccess) : (unsigned int) 0

// ROOT-8300
struct B { static void *fgStaticVar; B(){ printf("B::B()\n"); } };
B b; // CHECK: B::B()

// ROOT-7857
template <class T> void tfunc(T) {}
struct ROOT7857{
  void func() { tfunc((ROOT7857*)0); }
};
ROOT7857* root7857;
<commit_msg>Add test against ROOT-5248.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------

// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/Value.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::Value V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::Value &) boxes [(const char [5]) "Root"]
// End PR #98146

.rawInput 1
typedef enum {k1 = 0, k2} enumName;
enumName var = k1;
.rawInput 0
var
// CHECK: (enumName) (k1) : ({{(unsigned )?}}int) 0
const enumName constVar = (enumName) 1 // k2 is invisible!
// CHECK: (const enumName) (k2) : ({{(unsigned )?}}int) 1

// ROOT-8036: check that library symbols do not override interpreter symbols
int step = 10 // CHECK: (int) 10
step // CHECK: (int) 10

gCling->process("#ifdef __UNDEFINED__\n42\n#endif")
//CHECK: (cling::Interpreter::CompilationResult) (cling::Interpreter::CompilationResult::kSuccess) : (unsigned int) 0

// ROOT-8300
struct B { static void *fgStaticVar; B(){ printf("B::B()\n"); } };
B b; // CHECK: B::B()

// ROOT-7857
template <class T> void tfunc(T) {}
struct ROOT7857{
  void func() { tfunc((ROOT7857*)0); }
};
ROOT7857* root7857;

// ROOT-5248
class MyClass;
extern MyClass* my;
class MyClass {public: MyClass* getMyClass() {return 0;}} cl;
MyClass* my = cl.getMyClass();
<|endoftext|>


<commit_before>// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char [5]) "Root"]
// End PR #98146
<commit_msg>[5] now becomes * because we use the wrapper return type.<commit_after>// RUN: cat %s | %cling -I%p | FileCheck %s

// This file should be used as regression test for the meta processing subsystem
// Reproducers of fixed bugs should be put here

// PR #96277
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/StoredValueRef.h"
#include <stdio.h>
gCling->declare("int print() { printf(\"print is run.\\n\"); return 1; }");
cling::StoredValueRef V;
gCling->process("int a = print();",&V);
//CHECK: print is run.
gCling->process("a", &V);
//CHECK: (int) 1
gCling->process("a;", &V);
//CHECK-NOT: print is run.
// End PR #96277
// PR #98146
gCling->process("\"Root\"", &V);
// CHECK: (const char [5]) "Root"
V
// CHECK: (cling::StoredValueRef) boxes [(const char *) "Root"]
// End PR #98146
<|endoftext|>


<commit_before><commit_msg>sudeep : fixed issues with image handling<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtTest/QtTest>
#include <private/qmlpixmapcache_p.h>
#include <QtDeclarative/qmlengine.h>
#include <QNetworkReply>

// These don't let normal people run tests!
//#include "../network-settings.h"

class tst_qmlpixmapcache : public QObject
{
    Q_OBJECT
public:
    tst_qmlpixmapcache() :
        thisfile(QUrl::fromLocalFile(__FILE__))
    {
    }

private slots:
    void single();
    void single_data();
    void parallel();
    void parallel_data();

private:
    QmlEngine engine;
    QUrl thisfile;
};

static int slotters=0;

class Slotter : public QObject
{
    Q_OBJECT
public:
    Slotter()
    {
        gotslot = false;
        slotters++;
    }
    bool gotslot;

public slots:
    void got()
    {
        gotslot = true;
        --slotters;
        if (slotters==0)
            QTestEventLoop::instance().exitLoop();
    }
};

#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
static const bool localfile_optimized = true;
#else
static const bool localfile_optimized = false;
#endif

void tst_qmlpixmapcache::single_data()
{
    // Note, since QmlPixmapCache is shared, tests affect each other!
    // so use different files fore all test functions.

    QTest::addColumn<QUrl>("target");
    QTest::addColumn<bool>("incache");
    QTest::addColumn<bool>("exists");
    QTest::addColumn<bool>("neterror");

    // File URLs are optimized
    QTest::newRow("local") << thisfile.resolved(QUrl("data/exists.png")) << localfile_optimized << true << false;
    QTest::newRow("local") << thisfile.resolved(QUrl("data/notexists.png")) << localfile_optimized << false << false;
    QTest::newRow("remote") << QUrl("http://qt.nokia.com/logo.png") << false << true << false;
    QTest::newRow("remote") << QUrl("http://qt.nokia.com/thereisnologo.png") << false << false << true;
}

void tst_qmlpixmapcache::single()
{
    QFETCH(QUrl, target);
    QFETCH(bool, incache);
    QFETCH(bool, exists);
    QFETCH(bool, neterror);

    if (neterror) {
        QString expected = "Network error loading \""
                +target.toString()+"\" \"Error downloading "
                +target.toString()+" - server replied: Not Found\" ";
        QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
    } else if (!exists) {
        QString expected = "Cannot open  QUrl( \"" + target.toString() + "\" )  ";
        QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
    }

    QPixmap pixmap;
    QVERIFY(pixmap.width() <= 0); // Check Qt assumption
    QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);

    if (incache) {
        if (exists) {
            QVERIFY(status == QmlPixmapReply::Ready);
            QVERIFY(pixmap.width() > 0);
        } else {
            QVERIFY(status == QmlPixmapReply::Error);
            QVERIFY(pixmap.width() <= 0);
        }
    } else {
        QmlPixmapReply *reply = QmlPixmapCache::request(&engine, target);
        QVERIFY(reply);
        QVERIFY(pixmap.width() <= 0);

        Slotter getter;
        connect(reply, SIGNAL(finished()), &getter, SLOT(got()));
        QTestEventLoop::instance().enterLoop(10);
        QVERIFY(!QTestEventLoop::instance().timeout());
        QVERIFY(getter.gotslot);
        if (exists) {
            QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Ready);
            QVERIFY(pixmap.width() > 0);
        } else {
            QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Error);
            QVERIFY(pixmap.width() <= 0);
        }
    }

    QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}

void tst_qmlpixmapcache::parallel_data()
{
    // Note, since QmlPixmapCache is shared, tests affect each other!
    // so use different files fore all test functions.

    QTest::addColumn<QUrl>("target1");
    QTest::addColumn<QUrl>("target2");
    QTest::addColumn<int>("incache");
    QTest::addColumn<int>("cancel"); // which one to cancel
    QTest::addColumn<int>("requests");

    QTest::newRow("local")
            << thisfile.resolved(QUrl("data/exists1.png"))
            << thisfile.resolved(QUrl("data/exists2.png"))
            << (localfile_optimized ? 2 : 0)
            << -1
            << (localfile_optimized ? 0 : 2)
            ;

    QTest::newRow("remote")
            << QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
            << QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
            << 0
            << -1
            << 2
            ;

    QTest::newRow("remoteagain")
            << QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
            << QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
            << 2
            << -1
            << 0
            ;

    QTest::newRow("remotecopy")
            << QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
            << QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
            << 0
            << -1
            << 1
            ;

    QTest::newRow("remotecopycancel")
            << QUrl("http://qt.nokia.com/rounded_block_bg.png")
            << QUrl("http://qt.nokia.com/rounded_block_bg.png")
            << 0
            << 0
            << 1
            ;
}

void tst_qmlpixmapcache::parallel()
{
    QFETCH(QUrl, target1);
    QFETCH(QUrl, target2);
    QFETCH(int, incache);
    QFETCH(int, cancel);
    QFETCH(int, requests);

    QList<QUrl> targets;
    targets << target1 << target2;

    QList<QmlPixmapReply*> replies;
    QList<Slotter*> getters;
    for (int i=0; i<targets.count(); ++i) {
        QUrl target = targets.at(i);
        QPixmap pixmap;
        QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);
        QmlPixmapReply *reply = 0;
        if (status != QmlPixmapReply::Error && status != QmlPixmapReply::Ready)
            reply = QmlPixmapCache::request(&engine, target);
        replies.append(reply);
        if (!reply) {
            QVERIFY(pixmap.width() > 0);
            getters.append(0);
        } else {
            QVERIFY(pixmap.width() <= 0);
            getters.append(new Slotter);
            connect(reply, SIGNAL(finished()), getters[i], SLOT(got()));
        }
    }

    QCOMPARE(incache+slotters, targets.count());
    QCOMPARE(QmlPixmapCache::pendingRequests(), requests);

    if (cancel >= 0) {
        QmlPixmapCache::cancel(targets.at(cancel), getters[cancel]);
        slotters--;
    }

    if (slotters) {
        QTestEventLoop::instance().enterLoop(10);
        QVERIFY(!QTestEventLoop::instance().timeout());
    }

    for (int i=0; i<targets.count(); ++i) {
        QmlPixmapReply *reply = replies[i];
        if (reply) {
            if (i == cancel) {
                QVERIFY(!getters[i]->gotslot);
            } else {
                QVERIFY(getters[i]->gotslot);
                QPixmap pixmap;
                QVERIFY(QmlPixmapCache::get(targets[i], &pixmap) == QmlPixmapReply::Ready);
                QVERIFY(pixmap.width() > 0);
            }
            delete getters[i];
        }
    }

    QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}

QTEST_MAIN(tst_qmlpixmapcache)

#include "tst_qmlpixmapcache.moc"
<commit_msg>Fix expected error message.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <QtTest/QtTest>
#include <private/qmlpixmapcache_p.h>
#include <QtDeclarative/qmlengine.h>
#include <QNetworkReply>

// These don't let normal people run tests!
//#include "../network-settings.h"

class tst_qmlpixmapcache : public QObject
{
    Q_OBJECT
public:
    tst_qmlpixmapcache() :
        thisfile(QUrl::fromLocalFile(__FILE__))
    {
    }

private slots:
    void single();
    void single_data();
    void parallel();
    void parallel_data();

private:
    QmlEngine engine;
    QUrl thisfile;
};

static int slotters=0;

class Slotter : public QObject
{
    Q_OBJECT
public:
    Slotter()
    {
        gotslot = false;
        slotters++;
    }
    bool gotslot;

public slots:
    void got()
    {
        gotslot = true;
        --slotters;
        if (slotters==0)
            QTestEventLoop::instance().exitLoop();
    }
};

#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML
static const bool localfile_optimized = true;
#else
static const bool localfile_optimized = false;
#endif

void tst_qmlpixmapcache::single_data()
{
    // Note, since QmlPixmapCache is shared, tests affect each other!
    // so use different files fore all test functions.

    QTest::addColumn<QUrl>("target");
    QTest::addColumn<bool>("incache");
    QTest::addColumn<bool>("exists");
    QTest::addColumn<bool>("neterror");

    // File URLs are optimized
    QTest::newRow("local") << thisfile.resolved(QUrl("data/exists.png")) << localfile_optimized << true << false;
    QTest::newRow("local") << thisfile.resolved(QUrl("data/notexists.png")) << localfile_optimized << false << false;
    QTest::newRow("remote") << QUrl("http://qt.nokia.com/logo.png") << false << true << false;
    QTest::newRow("remote") << QUrl("http://qt.nokia.com/thereisnologo.png") << false << false << true;
}

void tst_qmlpixmapcache::single()
{
    QFETCH(QUrl, target);
    QFETCH(bool, incache);
    QFETCH(bool, exists);
    QFETCH(bool, neterror);

    if (neterror) {
        QString expected = "\"Error downloading " + target.toString() + " - server replied: Not Found\" ";
        QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
    } else if (!exists) {
        QString expected = "Cannot open  QUrl( \"" + target.toString() + "\" )  ";
        QTest::ignoreMessage(QtWarningMsg, expected.toLatin1());
    }

    QPixmap pixmap;
    QVERIFY(pixmap.width() <= 0); // Check Qt assumption
    QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);

    if (incache) {
        if (exists) {
            QVERIFY(status == QmlPixmapReply::Ready);
            QVERIFY(pixmap.width() > 0);
        } else {
            QVERIFY(status == QmlPixmapReply::Error);
            QVERIFY(pixmap.width() <= 0);
        }
    } else {
        QmlPixmapReply *reply = QmlPixmapCache::request(&engine, target);
        QVERIFY(reply);
        QVERIFY(pixmap.width() <= 0);

        Slotter getter;
        connect(reply, SIGNAL(finished()), &getter, SLOT(got()));
        QTestEventLoop::instance().enterLoop(10);
        QVERIFY(!QTestEventLoop::instance().timeout());
        QVERIFY(getter.gotslot);
        if (exists) {
            QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Ready);
            QVERIFY(pixmap.width() > 0);
        } else {
            QVERIFY(QmlPixmapCache::get(target, &pixmap) == QmlPixmapReply::Error);
            QVERIFY(pixmap.width() <= 0);
        }
    }

    QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}

void tst_qmlpixmapcache::parallel_data()
{
    // Note, since QmlPixmapCache is shared, tests affect each other!
    // so use different files fore all test functions.

    QTest::addColumn<QUrl>("target1");
    QTest::addColumn<QUrl>("target2");
    QTest::addColumn<int>("incache");
    QTest::addColumn<int>("cancel"); // which one to cancel
    QTest::addColumn<int>("requests");

    QTest::newRow("local")
            << thisfile.resolved(QUrl("data/exists1.png"))
            << thisfile.resolved(QUrl("data/exists2.png"))
            << (localfile_optimized ? 2 : 0)
            << -1
            << (localfile_optimized ? 0 : 2)
            ;

    QTest::newRow("remote")
            << QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
            << QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
            << 0
            << -1
            << 2
            ;

    QTest::newRow("remoteagain")
            << QUrl("http://qt.nokia.com/images/template/checkbox-on.png")
            << QUrl("http://qt.nokia.com/images/products/qt-logo/image_tile")
            << 2
            << -1
            << 0
            ;

    QTest::newRow("remotecopy")
            << QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
            << QUrl("http://qt.nokia.com/images/template/checkbox-off.png")
            << 0
            << -1
            << 1
            ;

    QTest::newRow("remotecopycancel")
            << QUrl("http://qt.nokia.com/rounded_block_bg.png")
            << QUrl("http://qt.nokia.com/rounded_block_bg.png")
            << 0
            << 0
            << 1
            ;
}

void tst_qmlpixmapcache::parallel()
{
    QFETCH(QUrl, target1);
    QFETCH(QUrl, target2);
    QFETCH(int, incache);
    QFETCH(int, cancel);
    QFETCH(int, requests);

    QList<QUrl> targets;
    targets << target1 << target2;

    QList<QmlPixmapReply*> replies;
    QList<Slotter*> getters;
    for (int i=0; i<targets.count(); ++i) {
        QUrl target = targets.at(i);
        QPixmap pixmap;
        QmlPixmapReply::Status status = QmlPixmapCache::get(target, &pixmap);
        QmlPixmapReply *reply = 0;
        if (status != QmlPixmapReply::Error && status != QmlPixmapReply::Ready)
            reply = QmlPixmapCache::request(&engine, target);
        replies.append(reply);
        if (!reply) {
            QVERIFY(pixmap.width() > 0);
            getters.append(0);
        } else {
            QVERIFY(pixmap.width() <= 0);
            getters.append(new Slotter);
            connect(reply, SIGNAL(finished()), getters[i], SLOT(got()));
        }
    }

    QCOMPARE(incache+slotters, targets.count());
    QCOMPARE(QmlPixmapCache::pendingRequests(), requests);

    if (cancel >= 0) {
        QmlPixmapCache::cancel(targets.at(cancel), getters[cancel]);
        slotters--;
    }

    if (slotters) {
        QTestEventLoop::instance().enterLoop(10);
        QVERIFY(!QTestEventLoop::instance().timeout());
    }

    for (int i=0; i<targets.count(); ++i) {
        QmlPixmapReply *reply = replies[i];
        if (reply) {
            if (i == cancel) {
                QVERIFY(!getters[i]->gotslot);
            } else {
                QVERIFY(getters[i]->gotslot);
                QPixmap pixmap;
                QVERIFY(QmlPixmapCache::get(targets[i], &pixmap) == QmlPixmapReply::Ready);
                QVERIFY(pixmap.width() > 0);
            }
            delete getters[i];
        }
    }

    QCOMPARE(QmlPixmapCache::pendingRequests(), 0);
}

QTEST_MAIN(tst_qmlpixmapcache)

#include "tst_qmlpixmapcache.moc"
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DataBrowser.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2008-02-18 15:40:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef CHART_DATA_BROWSER_HXX
#define CHART_DATA_BROWSER_HXX

#ifndef _SVTOOLS_EDITBROWSEBOX_HXX_
#include <svtools/editbrowsebox.hxx>
#endif
#ifndef _SV_OUTDEV_HXX
#include <vcl/outdev.hxx>
#endif
#ifndef _FMTFIELD_HXX_
#include <svtools/fmtfield.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include <vector>
#include <memory>
#include <boost/shared_ptr.hpp>

namespace com { namespace sun { namespace star {
    namespace chart2 {
        class XChartDocument;
    }
}}}

namespace chart
{

class DataBrowserModel;
class NumberFormatterWrapper;

namespace impl
{
class SeriesHeader;
class SeriesHeaderEdit;
}

class DataBrowser : public ::svt::EditBrowseBox
{
protected:
    // EditBrowseBox overridables
    virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, sal_uInt16 nColumnId ) const;
    virtual sal_Bool SeekRow( long nRow );
    virtual sal_Bool IsTabAllowed( sal_Bool bForward ) const;
    virtual ::svt::CellController* GetController( long nRow, sal_uInt16 nCol );
    virtual void InitController( ::svt::CellControllerRef& rController, long nRow, sal_uInt16 nCol );
    virtual sal_Bool SaveModified();
    virtual void CursorMoved();
    // called whenever the control of the current cell has been modified
    virtual void CellModified();
    virtual void ColumnResized( USHORT nColId );
    virtual void EndScroll();
    virtual void MouseButtonDown( const BrowserMouseEvent& rEvt );

    void SetDirty();

public:
    DataBrowser( Window* pParent, const ResId & rId, bool bLiveUpdate );
    virtual ~DataBrowser();

    /** GetCellText returns the text at the given position
        @param  nRow
            the number of the row
        @param  nColId
            the ID of the column
        @return
            the text out of the cell
    */
    virtual String  GetCellText(long nRow, USHORT nColId) const;

    /** returns the number in the given cell. If a cell is empty or contains a
        string, the result will be Nan
    */
    double GetCellNumber( long nRow, USHORT nColumnId ) const;

    // Window
    virtual void Resize();

    /// @return old state
    bool SetReadOnly( bool bNewState );
    bool IsReadOnly() const;

    /// @return true, if data has been modified
    bool IsDirty() const;
    /// reset the dirty status, if changes have been saved
    void SetClean();

    void SetDataFromModel( const ::com::sun::star::uno::Reference<
                               ::com::sun::star::chart2::XChartDocument > & xChartDoc,
                           const ::com::sun::star::uno::Reference<
                               ::com::sun::star::uno::XComponentContext > & xContext );

//     void setNumberFormatter();

    // predicates to determine what actions are possible at the current cursor
    // position.  This depends on the implementation of the according mutators
    // below.  (They are used for enabling toolbar icons)
    bool MayInsertRow() const;
    bool MayInsertColumn() const;
    bool MayDeleteRow() const;
    bool MayDeleteColumn() const;

    bool MaySwapRows() const;
    bool MaySwapColumns() const;

//     bool MaySortRow() const;
//     bool MaySortColumn() const;

    // mutators mutating data
    void InsertRow();
    void InsertColumn();
    void RemoveRow();
    void RemoveColumn();

    using BrowseBox::RemoveColumn;
    using BrowseBox::MouseButtonDown;

    void SwapRow();
    void SwapColumn();

//  void QuickSortRow();
//  void QuickSortCol();

    // sorting the entire table
//  void QuickSortTableCols ();
//  void QuickSortTableRows ();

    void SetCursorMovedHdl( const Link& rLink );
    const Link& GetCursorMovedHdl() const;

    void SetCellModifiedHdl( const Link& rLink );

    /// confirms all pending changes to be ready to be closed
    bool EndEditing();

    // calls the protected inline-function BrowseBox::GetFirstVisibleColNumber()
    sal_Int16 GetFirstVisibleColumNumber() const;

    sal_Int32 GetTotalWidth() const;

    bool CellContainsNumbers( sal_Int32 nRow, sal_uInt16 nCol ) const;

    sal_uInt32 GetNumberFormatKey( sal_Int32 nRow, sal_uInt16 nCol ) const;

    bool IsEnableItem();
    bool IsDataValid();
    void ShowWarningBox();
    bool ShowQueryBox();

private:
    ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XChartDocument > m_xChartDoc;
    ::std::auto_ptr< DataBrowserModel > m_apDataBrowserModel;

    typedef ::std::vector< ::boost::shared_ptr< impl::SeriesHeader > > tSeriesHeaderContainer;
    tSeriesHeaderContainer m_aSeriesHeaders;

    ::boost::shared_ptr< NumberFormatterWrapper >  m_spNumberFormatterWrapper;

    /// the row that is currently painted
    long                m_nSeekRow;
    bool                m_bIsReadOnly;
    bool                m_bIsDirty;
    bool                m_bLiveUpdate;
    bool                m_bDataValid;

    FormattedField      m_aNumberEditField;
    Edit                m_aTextEditField;

    /// note: m_aNumberEditField must precede this member!
    ::svt::CellControllerRef m_rNumberEditController;
    /// note: m_aTextEditField must precede this member!
    ::svt::CellControllerRef m_rTextEditController;

    Link                m_aCursorMovedHdlLink;
    Link                m_aCellModifiedLink;

    void clearHeaders();
    void RenewTable();
    void ImplAdjustHeaderControls();

    String GetColString( sal_Int32 nColumnId ) const;
    String GetRowString( sal_Int32 nRow ) const;

    DECL_LINK( SeriesHeaderGotFocus, impl::SeriesHeaderEdit* );
    DECL_LINK( SeriesHeaderChanged,  impl::SeriesHeaderEdit* );

    /// not implemented: inhibit copy construction
    DataBrowser( const DataBrowser & );
};

} // namespace chart

#endif  // CHART_DATA_BROWSER_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.4.34); FILE MERGED 2008/04/01 15:03:59 thb 1.4.34.3: #i85898# Stripping all external header guards 2008/04/01 10:50:18 thb 1.4.34.2: #i85898# Stripping all external header guards 2008/03/28 16:43:20 rt 1.4.34.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: DataBrowser.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef CHART_DATA_BROWSER_HXX
#define CHART_DATA_BROWSER_HXX

#include <svtools/editbrowsebox.hxx>
#include <vcl/outdev.hxx>
#include <svtools/fmtfield.hxx>
#include <com/sun/star/uno/XComponentContext.hpp>

#include <vector>
#include <memory>
#include <boost/shared_ptr.hpp>

namespace com { namespace sun { namespace star {
    namespace chart2 {
        class XChartDocument;
    }
}}}

namespace chart
{

class DataBrowserModel;
class NumberFormatterWrapper;

namespace impl
{
class SeriesHeader;
class SeriesHeaderEdit;
}

class DataBrowser : public ::svt::EditBrowseBox
{
protected:
    // EditBrowseBox overridables
    virtual void PaintCell( OutputDevice& rDev, const Rectangle& rRect, sal_uInt16 nColumnId ) const;
    virtual sal_Bool SeekRow( long nRow );
    virtual sal_Bool IsTabAllowed( sal_Bool bForward ) const;
    virtual ::svt::CellController* GetController( long nRow, sal_uInt16 nCol );
    virtual void InitController( ::svt::CellControllerRef& rController, long nRow, sal_uInt16 nCol );
    virtual sal_Bool SaveModified();
    virtual void CursorMoved();
    // called whenever the control of the current cell has been modified
    virtual void CellModified();
    virtual void ColumnResized( USHORT nColId );
    virtual void EndScroll();
    virtual void MouseButtonDown( const BrowserMouseEvent& rEvt );

    void SetDirty();

public:
    DataBrowser( Window* pParent, const ResId & rId, bool bLiveUpdate );
    virtual ~DataBrowser();

    /** GetCellText returns the text at the given position
        @param  nRow
            the number of the row
        @param  nColId
            the ID of the column
        @return
            the text out of the cell
    */
    virtual String  GetCellText(long nRow, USHORT nColId) const;

    /** returns the number in the given cell. If a cell is empty or contains a
        string, the result will be Nan
    */
    double GetCellNumber( long nRow, USHORT nColumnId ) const;

    // Window
    virtual void Resize();

    /// @return old state
    bool SetReadOnly( bool bNewState );
    bool IsReadOnly() const;

    /// @return true, if data has been modified
    bool IsDirty() const;
    /// reset the dirty status, if changes have been saved
    void SetClean();

    void SetDataFromModel( const ::com::sun::star::uno::Reference<
                               ::com::sun::star::chart2::XChartDocument > & xChartDoc,
                           const ::com::sun::star::uno::Reference<
                               ::com::sun::star::uno::XComponentContext > & xContext );

//     void setNumberFormatter();

    // predicates to determine what actions are possible at the current cursor
    // position.  This depends on the implementation of the according mutators
    // below.  (They are used for enabling toolbar icons)
    bool MayInsertRow() const;
    bool MayInsertColumn() const;
    bool MayDeleteRow() const;
    bool MayDeleteColumn() const;

    bool MaySwapRows() const;
    bool MaySwapColumns() const;

//     bool MaySortRow() const;
//     bool MaySortColumn() const;

    // mutators mutating data
    void InsertRow();
    void InsertColumn();
    void RemoveRow();
    void RemoveColumn();

    using BrowseBox::RemoveColumn;
    using BrowseBox::MouseButtonDown;

    void SwapRow();
    void SwapColumn();

//  void QuickSortRow();
//  void QuickSortCol();

    // sorting the entire table
//  void QuickSortTableCols ();
//  void QuickSortTableRows ();

    void SetCursorMovedHdl( const Link& rLink );
    const Link& GetCursorMovedHdl() const;

    void SetCellModifiedHdl( const Link& rLink );

    /// confirms all pending changes to be ready to be closed
    bool EndEditing();

    // calls the protected inline-function BrowseBox::GetFirstVisibleColNumber()
    sal_Int16 GetFirstVisibleColumNumber() const;

    sal_Int32 GetTotalWidth() const;

    bool CellContainsNumbers( sal_Int32 nRow, sal_uInt16 nCol ) const;

    sal_uInt32 GetNumberFormatKey( sal_Int32 nRow, sal_uInt16 nCol ) const;

    bool IsEnableItem();
    bool IsDataValid();
    void ShowWarningBox();
    bool ShowQueryBox();

private:
    ::com::sun::star::uno::Reference<
            ::com::sun::star::chart2::XChartDocument > m_xChartDoc;
    ::std::auto_ptr< DataBrowserModel > m_apDataBrowserModel;

    typedef ::std::vector< ::boost::shared_ptr< impl::SeriesHeader > > tSeriesHeaderContainer;
    tSeriesHeaderContainer m_aSeriesHeaders;

    ::boost::shared_ptr< NumberFormatterWrapper >  m_spNumberFormatterWrapper;

    /// the row that is currently painted
    long                m_nSeekRow;
    bool                m_bIsReadOnly;
    bool                m_bIsDirty;
    bool                m_bLiveUpdate;
    bool                m_bDataValid;

    FormattedField      m_aNumberEditField;
    Edit                m_aTextEditField;

    /// note: m_aNumberEditField must precede this member!
    ::svt::CellControllerRef m_rNumberEditController;
    /// note: m_aTextEditField must precede this member!
    ::svt::CellControllerRef m_rTextEditController;

    Link                m_aCursorMovedHdlLink;
    Link                m_aCellModifiedLink;

    void clearHeaders();
    void RenewTable();
    void ImplAdjustHeaderControls();

    String GetColString( sal_Int32 nColumnId ) const;
    String GetRowString( sal_Int32 nRow ) const;

    DECL_LINK( SeriesHeaderGotFocus, impl::SeriesHeaderEdit* );
    DECL_LINK( SeriesHeaderChanged,  impl::SeriesHeaderEdit* );

    /// not implemented: inhibit copy construction
    DataBrowser( const DataBrowser & );
};

} // namespace chart

#endif  // CHART_DATA_BROWSER_HXX
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include "qtorganizer.h"
#include "qorganizeritemid.h"
#include "qorganizercollectionenginelocalid.h"
#include <QSet>

//TESTED_COMPONENT=src/organizer
//TESTED_CLASS=
//TESTED_FILES=

QTM_USE_NAMESPACE
class tst_QOrganizerCollection: public QObject
{
Q_OBJECT

public:
    tst_QOrganizerCollection();
    virtual ~tst_QOrganizerCollection();

private slots:
    void metaData();
    void idLessThan();
    void idHash();
    void hash();
    void datastream();
    void traits();
    void idTraits();
    void localIdTraits();
};

tst_QOrganizerCollection::tst_QOrganizerCollection()
{
}

tst_QOrganizerCollection::~tst_QOrganizerCollection()
{
}

void tst_QOrganizerCollection::metaData()
{
    QOrganizerCollection c;
    QVERIFY(c.metaData().isEmpty());
    c.setMetaData("test", 5);
    QVERIFY(c.metaData().contains("test"));

    QVariantMap mdm;
    mdm.insert("test2", 6);
    c.setMetaData(mdm);
    QCOMPARE(c.metaData(), mdm);
}

class BasicCollectionLocalId : public QOrganizerCollectionEngineId
{
public:
    BasicCollectionLocalId(uint id) : m_id(id) {}
    bool isEqualTo(const QOrganizerCollectionEngineId* other) const {
        return m_id == static_cast<const BasicCollectionLocalId*>(other)->m_id;
    }
    bool isLessThan(const QOrganizerCollectionEngineId* other) const {
        return m_id < static_cast<const BasicCollectionLocalId*>(other)->m_id;
    }
    uint engineIdType() const {
        return 0;
    }
    const QString managerUri() const {
        static const QString uri(QLatin1String("qtorganizer:basic:"));
        return uri;
    }
    QOrganizerCollectionEngineId* clone() const {
        BasicCollectionLocalId* cloned = new BasicCollectionLocalId(m_id);
        return cloned;
    }
    QDebug& debugStreamOut(QDebug& dbg) const {
        return dbg << m_id;
    }
    QDataStream& dataStreamOut(QDataStream& out) const {
        return out << static_cast<quint32>(m_id);
    }
    QDataStream& dataStreamIn(QDataStream& in) {
        quint32 id;
        in >> id;
        m_id = id;
        return in;
    }
    uint hash() const {
        return m_id;
    }

private:
    uint m_id;
};

QOrganizerCollectionId makeId(uint id)
{
    return QOrganizerCollectionId(new BasicCollectionLocalId(id));
}

void tst_QOrganizerCollection::idLessThan()
{
    // TODO: review tests
/*    QOrganizerCollectionId id1;
    id1.setManagerUri("a");
    id1.setId(makeId(1));
    QOrganizerCollectionId id2;
    id2.setManagerUri("a");
    id2.setId(makeId(1));
    QVERIFY(!(id1 < id2));
    QVERIFY(!(id2 < id1));
    QOrganizerCollectionId id3;
    id3.setManagerUri("a");
    id3.setId(makeId(2));
    QOrganizerCollectionId id4;
    id4.setManagerUri("b");
    id4.setId(makeId(1));
    QOrganizerCollectionId id5; // no URI
    id5.setId(makeId(2));
    QVERIFY(id1 < id3);
    QVERIFY(!(id3 < id1));
    QVERIFY(id1 < id4);
    QVERIFY(!(id4 < id1));
    QVERIFY(id3 < id4);
    QVERIFY(!(id4 < id3));
    QVERIFY(id5 < id1);
    QVERIFY(!(id1 < id5));*/
}

void tst_QOrganizerCollection::idHash()
{
    // TODO: review tests
/*    QOrganizerCollectionId id1;
    id1.setManagerUri("a");
    id1.setId(makeId(1));
    QOrganizerCollectionId id2;
    id2.setManagerUri("a");
    id2.setId(makeId(1));
    QOrganizerCollectionId id3;
    id3.setManagerUri("b");
    id3.setId(makeId(1));
    QVERIFY(qHash(id1) == qHash(id2));
    QVERIFY(qHash(id1) != qHash(id3));
    QSet<QOrganizerCollectionId> set;
    set.insert(id1);
    set.insert(id2);
    set.insert(id3);
    QCOMPARE(set.size(), 2);*/
}

void tst_QOrganizerCollection::hash()
{
    // TODO: review tests
/*    QOrganizerCollectionId id;
    id.setManagerUri("a");
    id.setId(makeId(1));
    QOrganizerCollection c1;
    c1.setId(id);
    c1.setMetaData("key", "value");
    QOrganizerCollection c2;
    c2.setId(id);
    c2.setMetaData("key", "value");
    QOrganizerCollection c3;
    c3.setId(id);
    c3.setMetaData("key", "another value");
    QOrganizerCollection c4; // no details
    c4.setId(id);
    QOrganizerCollection c5;
    c5.setId(id);
    c5.setMetaData("key", "value");
    QVERIFY(qHash(c1) == qHash(c2));
    QVERIFY(qHash(c1) != qHash(c3));
    QVERIFY(qHash(c1) != qHash(c4));
    QVERIFY(qHash(c1) == qHash(c5));*/
}

void tst_QOrganizerCollection::datastream()
{
    // collection datastreaming
    QByteArray buffer;
    QOrganizerCollection collectionIn;
    collectionIn.setMetaData("key", "value");
    QOrganizerCollection collectionOut;
    QOrganizerCollectionId originalId;

    // first, stream an item with a complete id
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        QOrganizerManager om("memory");
        QVERIFY(om.saveCollection(&collectionIn)); // fill in its ID
        originalId = collectionIn.id();
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
    }

    // second, stream an item with an id with the mgr uri set, local id null
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        collectionIn.setId(QOrganizerCollectionId());
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
    }

    /* TODO: Review tests
    // third, stream an item with an id with the mgr uri null, local id set
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        QOrganizerCollectionId modifiedId = originalId;
        modifiedId.setManagerUri(QString()); // this will clear the local id!
        modifiedId.setId(originalId.localId()); // so reset it and make sure nothing bad happens.
        collectionIn.setId(modifiedId);
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QVERIFY(collectionOut.metaData() == collectionIn.metaData());
        QVERIFY(collectionOut.id() != collectionIn.id()); // no manager uri of input :. won't be serialized.
    }*/

    // fourth, stream an item with a null id
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        collectionIn.setId(QOrganizerCollectionId());
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QVERIFY(collectionOut.metaData() == collectionIn.metaData());
        QVERIFY(collectionOut.id() == collectionIn.id()); // should both be null ids.
    }

    // id datastreaming
    buffer.clear();
    QOrganizerCollectionId inputId;
    QOrganizerCollectionId outputId;

    // first, stream the whole id (mgr uri set, local id set)
    {
        inputId = originalId;
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    /* TODO: review test
    // second, stream a partial id (mgr uri null, local id set)
    {
        inputId.setManagerUri(QString());
        inputId.setId(originalId.localId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;

        // because the manager uri is null, we cannot stream it in.
        QVERIFY(outputId.isNull());
        QVERIFY(!inputId.isNull());
    }

    // third, stream a partial id (mgr uri set, local id null).
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setId(QOrganizerCollectionId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }*/

    // fourth, stream a null id
    {
        inputId = QOrganizerCollectionId();
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    /* TODO: review test
    // fifth, stream an id after changing it's manager uri.
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setId(originalId.localId());
        inputId.setManagerUri("test manager uri"); // should clear the local id.
        QVERIFY(inputId.localId() == QOrganizerCollectionId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    // sixth, stream an id after changing it's manager uri and resetting the local id.
    // this should cause great problems, because the manager doesn't exist so it shouldn't
    // be able to deserialize.  Make sure it's handled gracefully.
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setManagerUri("test manager uri"); // should clear the local id.
        inputId.setId(originalId.localId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QVERIFY(outputId.isNull());
    } */
}

void tst_QOrganizerCollection::traits()
{
    QVERIFY(sizeof(QOrganizerCollection) == sizeof(void *));
    QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollection)> ti;
    QVERIFY(ti.isComplex);
    QVERIFY(!ti.isStatic);
    QVERIFY(!ti.isLarge);
    QVERIFY(!ti.isPointer);
    QVERIFY(!ti.isDummy);
}

void tst_QOrganizerCollection::idTraits()
{
    QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
    QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
    QVERIFY(ti.isComplex);
    QVERIFY(!ti.isStatic);
    QVERIFY(!ti.isLarge);
    QVERIFY(!ti.isPointer);
    QVERIFY(!ti.isDummy);
}

void tst_QOrganizerCollection::localIdTraits()
{
    QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
    QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
    QVERIFY(ti.isComplex); // unlike QContactLocalId (int typedef), we have a ctor
    QVERIFY(!ti.isStatic);
    QVERIFY(!ti.isLarge);
    QVERIFY(!ti.isPointer);
    QVERIFY(!ti.isDummy);
}

QTEST_MAIN(tst_QOrganizerCollection)
#include "tst_qorganizercollection.moc"
<commit_msg>Removed an invalid include from tst_qorganizercollection<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>

#include "qtorganizer.h"
#include "qorganizeritemid.h"
#include <QSet>

//TESTED_COMPONENT=src/organizer
//TESTED_CLASS=
//TESTED_FILES=

QTM_USE_NAMESPACE
class tst_QOrganizerCollection: public QObject
{
Q_OBJECT

public:
    tst_QOrganizerCollection();
    virtual ~tst_QOrganizerCollection();

private slots:
    void metaData();
    void idLessThan();
    void idHash();
    void hash();
    void datastream();
    void traits();
    void idTraits();
    void localIdTraits();
};

tst_QOrganizerCollection::tst_QOrganizerCollection()
{
}

tst_QOrganizerCollection::~tst_QOrganizerCollection()
{
}

void tst_QOrganizerCollection::metaData()
{
    QOrganizerCollection c;
    QVERIFY(c.metaData().isEmpty());
    c.setMetaData("test", 5);
    QVERIFY(c.metaData().contains("test"));

    QVariantMap mdm;
    mdm.insert("test2", 6);
    c.setMetaData(mdm);
    QCOMPARE(c.metaData(), mdm);
}

class BasicCollectionLocalId : public QOrganizerCollectionEngineId
{
public:
    BasicCollectionLocalId(uint id) : m_id(id) {}
    bool isEqualTo(const QOrganizerCollectionEngineId* other) const {
        return m_id == static_cast<const BasicCollectionLocalId*>(other)->m_id;
    }
    bool isLessThan(const QOrganizerCollectionEngineId* other) const {
        return m_id < static_cast<const BasicCollectionLocalId*>(other)->m_id;
    }
    uint engineIdType() const {
        return 0;
    }
    const QString managerUri() const {
        static const QString uri(QLatin1String("qtorganizer:basic:"));
        return uri;
    }
    QOrganizerCollectionEngineId* clone() const {
        BasicCollectionLocalId* cloned = new BasicCollectionLocalId(m_id);
        return cloned;
    }
    QDebug& debugStreamOut(QDebug& dbg) const {
        return dbg << m_id;
    }
    QDataStream& dataStreamOut(QDataStream& out) const {
        return out << static_cast<quint32>(m_id);
    }
    QDataStream& dataStreamIn(QDataStream& in) {
        quint32 id;
        in >> id;
        m_id = id;
        return in;
    }
    uint hash() const {
        return m_id;
    }

private:
    uint m_id;
};

QOrganizerCollectionId makeId(uint id)
{
    return QOrganizerCollectionId(new BasicCollectionLocalId(id));
}

void tst_QOrganizerCollection::idLessThan()
{
    // TODO: review tests
/*    QOrganizerCollectionId id1;
    id1.setManagerUri("a");
    id1.setId(makeId(1));
    QOrganizerCollectionId id2;
    id2.setManagerUri("a");
    id2.setId(makeId(1));
    QVERIFY(!(id1 < id2));
    QVERIFY(!(id2 < id1));
    QOrganizerCollectionId id3;
    id3.setManagerUri("a");
    id3.setId(makeId(2));
    QOrganizerCollectionId id4;
    id4.setManagerUri("b");
    id4.setId(makeId(1));
    QOrganizerCollectionId id5; // no URI
    id5.setId(makeId(2));
    QVERIFY(id1 < id3);
    QVERIFY(!(id3 < id1));
    QVERIFY(id1 < id4);
    QVERIFY(!(id4 < id1));
    QVERIFY(id3 < id4);
    QVERIFY(!(id4 < id3));
    QVERIFY(id5 < id1);
    QVERIFY(!(id1 < id5));*/
}

void tst_QOrganizerCollection::idHash()
{
    // TODO: review tests
/*    QOrganizerCollectionId id1;
    id1.setManagerUri("a");
    id1.setId(makeId(1));
    QOrganizerCollectionId id2;
    id2.setManagerUri("a");
    id2.setId(makeId(1));
    QOrganizerCollectionId id3;
    id3.setManagerUri("b");
    id3.setId(makeId(1));
    QVERIFY(qHash(id1) == qHash(id2));
    QVERIFY(qHash(id1) != qHash(id3));
    QSet<QOrganizerCollectionId> set;
    set.insert(id1);
    set.insert(id2);
    set.insert(id3);
    QCOMPARE(set.size(), 2);*/
}

void tst_QOrganizerCollection::hash()
{
    // TODO: review tests
/*    QOrganizerCollectionId id;
    id.setManagerUri("a");
    id.setId(makeId(1));
    QOrganizerCollection c1;
    c1.setId(id);
    c1.setMetaData("key", "value");
    QOrganizerCollection c2;
    c2.setId(id);
    c2.setMetaData("key", "value");
    QOrganizerCollection c3;
    c3.setId(id);
    c3.setMetaData("key", "another value");
    QOrganizerCollection c4; // no details
    c4.setId(id);
    QOrganizerCollection c5;
    c5.setId(id);
    c5.setMetaData("key", "value");
    QVERIFY(qHash(c1) == qHash(c2));
    QVERIFY(qHash(c1) != qHash(c3));
    QVERIFY(qHash(c1) != qHash(c4));
    QVERIFY(qHash(c1) == qHash(c5));*/
}

void tst_QOrganizerCollection::datastream()
{
    // collection datastreaming
    QByteArray buffer;
    QOrganizerCollection collectionIn;
    collectionIn.setMetaData("key", "value");
    QOrganizerCollection collectionOut;
    QOrganizerCollectionId originalId;

    // first, stream an item with a complete id
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        QOrganizerManager om("memory");
        QVERIFY(om.saveCollection(&collectionIn)); // fill in its ID
        originalId = collectionIn.id();
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
    }

    // second, stream an item with an id with the mgr uri set, local id null
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        collectionIn.setId(QOrganizerCollectionId());
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QCOMPARE(collectionOut, collectionIn); // can use QCOMPARE for collections, since no detail keys.
    }

    /* TODO: Review tests
    // third, stream an item with an id with the mgr uri null, local id set
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        QOrganizerCollectionId modifiedId = originalId;
        modifiedId.setManagerUri(QString()); // this will clear the local id!
        modifiedId.setId(originalId.localId()); // so reset it and make sure nothing bad happens.
        collectionIn.setId(modifiedId);
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QVERIFY(collectionOut.metaData() == collectionIn.metaData());
        QVERIFY(collectionOut.id() != collectionIn.id()); // no manager uri of input :. won't be serialized.
    }*/

    // fourth, stream an item with a null id
    {
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        collectionIn.setId(QOrganizerCollectionId());
        stream1 << collectionIn;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> collectionOut;
        QVERIFY(collectionOut.metaData() == collectionIn.metaData());
        QVERIFY(collectionOut.id() == collectionIn.id()); // should both be null ids.
    }

    // id datastreaming
    buffer.clear();
    QOrganizerCollectionId inputId;
    QOrganizerCollectionId outputId;

    // first, stream the whole id (mgr uri set, local id set)
    {
        inputId = originalId;
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    /* TODO: review test
    // second, stream a partial id (mgr uri null, local id set)
    {
        inputId.setManagerUri(QString());
        inputId.setId(originalId.localId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;

        // because the manager uri is null, we cannot stream it in.
        QVERIFY(outputId.isNull());
        QVERIFY(!inputId.isNull());
    }

    // third, stream a partial id (mgr uri set, local id null).
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setId(QOrganizerCollectionId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }*/

    // fourth, stream a null id
    {
        inputId = QOrganizerCollectionId();
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    /* TODO: review test
    // fifth, stream an id after changing it's manager uri.
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setId(originalId.localId());
        inputId.setManagerUri("test manager uri"); // should clear the local id.
        QVERIFY(inputId.localId() == QOrganizerCollectionId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QCOMPARE(inputId, outputId);
    }

    // sixth, stream an id after changing it's manager uri and resetting the local id.
    // this should cause great problems, because the manager doesn't exist so it shouldn't
    // be able to deserialize.  Make sure it's handled gracefully.
    {
        inputId.setManagerUri(originalId.managerUri());
        inputId.setManagerUri("test manager uri"); // should clear the local id.
        inputId.setId(originalId.localId());
        buffer.clear();
        QDataStream stream1(&buffer, QIODevice::WriteOnly);
        stream1 << inputId;
        QVERIFY(buffer.size() > 0);
        QDataStream stream2(buffer);
        stream2 >> outputId;
        QVERIFY(outputId.isNull());
    } */
}

void tst_QOrganizerCollection::traits()
{
    QVERIFY(sizeof(QOrganizerCollection) == sizeof(void *));
    QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollection)> ti;
    QVERIFY(ti.isComplex);
    QVERIFY(!ti.isStatic);
    QVERIFY(!ti.isLarge);
    QVERIFY(!ti.isPointer);
    QVERIFY(!ti.isDummy);
}

void tst_QOrganizerCollection::idTraits()
{
    QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
    QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
    QVERIFY(ti.isComplex);
    QVERIFY(!ti.isStatic);
    QVERIFY(!ti.isLarge);
    QVERIFY(!ti.isPointer);
    QVERIFY(!ti.isDummy);
}

void tst_QOrganizerCollection::localIdTraits()
{
    QVERIFY(sizeof(QOrganizerCollectionId) == sizeof(void *));
    QTypeInfo<QTM_PREPEND_NAMESPACE(QOrganizerCollectionId)> ti;
    QVERIFY(ti.isComplex); // unlike QContactLocalId (int typedef), we have a ctor
    QVERIFY(!ti.isStatic);
    QVERIFY(!ti.isLarge);
    QVERIFY(!ti.isPointer);
    QVERIFY(!ti.isDummy);
}

QTEST_MAIN(tst_QOrganizerCollection)
#include "tst_qorganizercollection.moc"
<|endoftext|>