Пример #1
1
void MainWindow::setupStateMachine()
{
        // set title bar text
        this->setWindowTitle(QString("Excape From Estes"));

        // create the state machine object and its states
        QStateMachine *machine = new QStateMachine(this);
        QState *s1 = new QState();
        QState *s2 = new QState();
        QState *s3 = new QState();

        // assign an event for every state
        s1->assignProperty(ui->label, "text", readFile("intro.txt"));
        s2->assignProperty(ui->label, "text", "In state s2");
        s3->assignProperty(ui->label, "text", "In state s3");

        // set up a trigger to end every state
        s1->addTransition(this, SIGNAL(one()), s2);
        s2->addTransition(this, SIGNAL(two()), s3);
        s3->addTransition(this->ui->pushButton, SIGNAL(clicked()), s1);

        // add the states to the state machine and set a starting state
        machine->addState(s1);
        machine->addState(s2);
        machine->addState(s3);
        machine->setInitialState(s1);

        // enable the machine and print out a message to show that we are done
        machine->start();
        qDebug() << "State Machine Created";
}
Пример #2
0
void DiscountPage::setupItemAnimations()
{
    QState *smallState = new QState();
    QState *bigState = new QState();

    for (int i = 0; i < this->m_itemList.size(); i++) {
        smallState->assignProperty(this->m_itemList[i],"scale", 0);
        bigState->assignProperty(this->m_itemList[i],"scale",1);
    }

    QSequentialAnimationGroup *showItemGroup = new QSequentialAnimationGroup(this);
    for (int i = 0; i < this->m_itemList.size(); i++) {
        QPropertyAnimation *anim = new QPropertyAnimation(this->m_itemList[i], "scale", this);
        anim->setDuration(300);
        anim->setEasingCurve(QEasingCurve::OutBack);
        showItemGroup->addAnimation(anim);
    }

    QSignalTransition *trans = smallState->addTransition(this, SIGNAL(start()), bigState);
    trans->addAnimation(showItemGroup);
    connect(showItemGroup,SIGNAL(finished()),this,SLOT(startSelect()));

    trans = bigState->addTransition(this,SIGNAL(quitPage()),smallState);
    connect(smallState,SIGNAL(entered()),this,SLOT(closeSelect()));

    QStateMachine *states = new QStateMachine(this);
    states->addState(smallState);
    states->addState(bigState);
    states->setInitialState(smallState);

    states->start();
}
void HomeScreenStatePluginTest::testLoadBackupRestoreStateOnEntryExit()
{
    HbInstance::instance();
    HbMainWindow mainWindow;
    mainWindow.show();   
    QCoreApplication::sendPostedEvents();
   
    QStateMachine *sm = new QStateMachine;
    HsBackupRestoreState *brs = new HsBackupRestoreState;

    sm->addState(brs);
    sm->setInitialState(brs);    
    

    QFinalState *fs = new QFinalState;
    sm->addState(fs);

    brs->addTransition(this, SIGNAL(finishStateMachine()), fs);

    sm->start();   
    QCoreApplication::sendPostedEvents();  
    emit finishStateMachine();

    sm->stop();
    // main window deleted -> HsGui must be deleted also
    delete HsGui::takeInstance();
    delete sm;
}
Пример #4
0
void DockPanel::initShowHideAnimation()
{
    QStateMachine * machine = new QStateMachine(this);

    QState * showState = new QState(machine);
    showState->assignProperty(this,"y", 0);
    QState * hideState = new QState(machine);
    //y should change with DockMode changed
    connect(this, &DockPanel::startHide, [=]{
        hideState->assignProperty(this,"y", m_dockModeData->getDockHeight());
    });
    machine->setInitialState(showState);

    QPropertyAnimation *showAnimation = new QPropertyAnimation(this, "y");
    showAnimation->setDuration(SHOW_ANIMATION_DURATION);
    showAnimation->setEasingCurve(SHOW_EASINGCURVE);
    connect(showAnimation,&QPropertyAnimation::finished,this,&DockPanel::onShowPanelFinished);

    QPropertyAnimation *hideAnimation = new QPropertyAnimation(this, "y");
    hideAnimation->setDuration(HIDE_ANIMATION_DURATION);
    hideAnimation->setEasingCurve(HIDE_EASINGCURVE);
    connect(hideAnimation,&QPropertyAnimation::finished,this,&DockPanel::onHidePanelFinished);

    QSignalTransition *st = showState->addTransition(this,SIGNAL(startHide()), hideState);
    st->addAnimation(hideAnimation);
    QSignalTransition *ht = hideState->addTransition(this,SIGNAL(startShow()),showState);
    ht->addAnimation(showAnimation);

    machine->start();
}
Пример #5
0
//! [4]
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);

    QStateMachine machine;
    QState *group = new QState(QState::ParallelStates);
    group->setObjectName("group");
//! [4]

//! [5]
    Pinger *pinger = new Pinger(group);
    pinger->setObjectName("pinger");
    pinger->addTransition(new PongTransition());

    QState *ponger = new QState(group);
    ponger->setObjectName("ponger");
    ponger->addTransition(new PingTransition());
//! [5]

//! [6]
    machine.addState(group);
    machine.setInitialState(group);
    machine.start();

    return app.exec();
}
Пример #6
0
int main(int argc, char* argv[ ])
{
    QApplication app(argc, argv);

    QPushButton button("State Machine");
    QPushButton quitButton("Quit");
    QPushButton interruptButton("interrupt");

    QStateMachine machine;
    QState *s1 = new QState(&machine);
    QState *s11 = new QState(s1);
    QState *s12 = new QState(s1);
    QState *s13 = new QState(s1);
    s1->setInitialState(s11);

    s11->assignProperty(&button, "geometry", QRect(100, 100, 100, 50));
    s12->assignProperty(&button, "geometry", QRect(300, 100, 100, 50));
    s13->assignProperty(&button, "geometry", QRect(200, 200, 100, 50));

    QSignalTransition *transition1 = s11->addTransition(&button,
                                                       SIGNAL(clicked()), s12);
    QSignalTransition *transition2 = s12->addTransition(&button,
                                                       SIGNAL(clicked()), s13);
    QSignalTransition *transition3 = s13->addTransition(&button,
                                                       SIGNAL(clicked()), s11);

    QPropertyAnimation *animation = new QPropertyAnimation(&button, "geometry");
    transition1->addAnimation(animation);
    transition2->addAnimation(animation);
    transition3->addAnimation(animation);

    QObject::connect(s13, SIGNAL(entered()), &button, SLOT(showMinimized()));

    QFinalState *s2 = new QFinalState(&machine);
    s1->addTransition(&quitButton, SIGNAL(clicked()), s2);
    QObject::connect(&machine, SIGNAL(finished()), qApp, SLOT(quit()));

    QHistoryState *s1h = new QHistoryState(s1);

    QState *s3 = new QState(&machine);
    QMessageBox mbox;
    mbox.addButton(QMessageBox::Ok);
    mbox.setText("Interrupted!");
    mbox.setIcon(QMessageBox::Information);
    QObject::connect(s3, SIGNAL(entered()), &mbox, SLOT(exec()));
    s3->addTransition(s1h);

    s1->addTransition(&interruptButton, SIGNAL(clicked()), s3);

    machine.setInitialState(s1);
    machine.start();

    button.show();
    quitButton.move(300, 300);
    quitButton.show();
    interruptButton.show();

    return app.exec();
}
Пример #7
0
int main(int argc, char *argv[])
{
   QApplication a(argc, argv);
   std::random_device rd;
   random_engine gen(rd());

   int imageSize = 300;
   QList<QImage> images;
   for (int n = 0; n < 28; ++n) images << randomImage(imageSize, gen);
   std::uniform_int_distribution<> dImage(0, images.size()-1);

   QStackedWidget display;
   QPushButton ready("I'm Ready!");
   QLabel label, labelHidden;
   display.addWidget(&ready);
   display.addWidget(&label);
   display.addWidget(&labelHidden);

   QTimer splashTimer;
   QStateMachine machine;
   QState s1(&machine), s2(&machine), s3(&machine), s4(&machine);
   splashTimer.setSingleShot(true);

   QObject::connect(&s1, &QState::entered, [&]{
      display.setCurrentWidget(&ready);
      ready.setDefault(true);
      ready.setFocus();
   });
   s1.addTransition(&ready, "clicked()", &s2);

   QObject::connect(&s2, &QState::entered, [&]{
      label.setPixmap(QPixmap::fromImage(images.at(dImage(gen))));
      display.setCurrentWidget(&label);
      splashTimer.start(250 + std::uniform_int_distribution<>(1500, 3000)(gen));
   });
   s2.addTransition(&splashTimer, "timeout()", &s3);

   QObject::connect(&s3, &QState::entered, [&]{
      display.setCurrentWidget(&labelHidden);
      splashTimer.start(2000);
   });
   s3.addTransition(&splashTimer, "timeout()", &s4);

   QObject::connect(&s4, &QState::entered, [&]{
      display.setCurrentWidget(&label);
      splashTimer.start(3000);
   });
   s4.addTransition(&splashTimer, "timeout()", &s1);

   machine.setInitialState(&s1);
   machine.start();
   display.show();

   return a.exec();
}
Пример #8
0
    Window(QWidget *parent = 0)
        : QWidget(parent)
    {
        QPushButton *button = new QPushButton(this);
        button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        QVBoxLayout *layout = new QVBoxLayout;
        layout->addWidget(button);
        layout->setContentsMargins(80, 80, 80, 80);
        setLayout(layout);
//! [0]

//! [1]
        QStateMachine *machine = new QStateMachine(this);

        QState *s1 = new QState();
        s1->assignProperty(button, "text", "Outside");

        QState *s2 = new QState();
        s2->assignProperty(button, "text", "Inside");
//! [1]

//! [2]
        QEventTransition *enterTransition = new QEventTransition(button, QEvent::Enter);
        enterTransition->setTargetState(s2);
        s1->addTransition(enterTransition);
//! [2]

//! [3]
        QEventTransition *leaveTransition = new QEventTransition(button, QEvent::Leave);
        leaveTransition->setTargetState(s1);
        s2->addTransition(leaveTransition);
//! [3]

//! [4]
        QState *s3 = new QState();
        s3->assignProperty(button, "text", "Pressing...");

        QEventTransition *pressTransition = new QEventTransition(button, QEvent::MouseButtonPress);
        pressTransition->setTargetState(s3);
        s2->addTransition(pressTransition);

        QEventTransition *releaseTransition = new QEventTransition(button, QEvent::MouseButtonRelease);
        releaseTransition->setTargetState(s2);
        s3->addTransition(releaseTransition);
//! [4]

//! [5]
        machine->addState(s1);
        machine->addState(s2);
        machine->addState(s3);

        machine->setInitialState(s1);
        machine->start();
    }
// ---------------------------------------------------------------------------
//
// ---------------------------------------------------------------------------
//
void MenuStatesTest::createArrangeCollection()
{
#ifdef Q_OS_SYMBIAN
    User::ResetInactivityTime();//it should help for Viewserver11 panic
#ifdef UT_MEMORY_CHECK
    __UHEAP_MARK;
#endif//UT_MEMORY_CHECK
#endif//Q_OS_SYMBIAN
    {
        HsMenuViewBuilder builder;
        HsMenuModeWrapper menuMode;
        HsMainWindowMock mainWindow;
        QStateMachine *machine = new QStateMachine(0);

        const QString collectionName("testCollection" +
                                     QDateTime::currentDateTime().
                                     toString("ddmmyyyy_hh_mm_ss_zzz"));
        const int collectionId = HsMenuService::createCollection(collectionName);

        HsCollectionState *collectionState =
            new HsCollectionState(builder, menuMode, mainWindow, machine);

        collectionState->mCollectionId = collectionId;

        machine->setInitialState(collectionState);

        AddToHomeScreenMockState *mockState = new AddToHomeScreenMockState(machine);

        // create a transition to the new child state which will be triggered by
        // an event with specified operation type
        HsMenuEventTransition *transition = new HsMenuEventTransition(
            HsMenuEvent::ArrangeCollection, collectionState, mockState);
        collectionState->addTransition(transition);

        machine->start();
        qApp->sendPostedEvents();
        collectionState->createArrangeCollection();
        qApp->sendPostedEvents();

        QVERIFY(mockState->enteredValue());
        qApp->removePostedEvents(0);
        machine->stop();

        delete machine;
    }
#ifdef Q_OS_SYMBIAN
#ifdef UT_MEMORY_CHECK
    __UHEAP_MARKEND;
#endif//UT_MEMORY_CHECK
#endif//Q_OS_SYMBIAN
}
    Window(QWidget *parent = 0)
        : QWidget(parent)
    {
        QPushButton *button = new QPushButton(this);
        button->setGeometry(QRect(100, 100, 100, 100));
//! [0]

//! [1]
        QStateMachine *machine = new QStateMachine(this);

        QState *s1 = new QState();
        s1->assignProperty(button, "text", "Outside");

        QState *s2 = new QState();
        s2->assignProperty(button, "text", "Inside");
//! [1]

//! [2]
        QEventTransition *enterTransition = new QEventTransition(button, QEvent::Enter);
        enterTransition->setTargetState(s2);
        s1->addTransition(enterTransition);
//! [2]

//! [3]
        QEventTransition *leaveTransition = new QEventTransition(button, QEvent::Leave);
        leaveTransition->setTargetState(s1);
        s2->addTransition(leaveTransition);
//! [3]

//! [4]
        QState *s3 = new QState();
        s3->assignProperty(button, "text", "Pressing...");

        QEventTransition *pressTransition = new QEventTransition(button, QEvent::MouseButtonPress);
        pressTransition->setTargetState(s3);
        s2->addTransition(pressTransition);

        QEventTransition *releaseTransition = new QEventTransition(button, QEvent::MouseButtonRelease);
        releaseTransition->setTargetState(s2);
        s3->addTransition(releaseTransition);
//! [4]

//! [5]
        machine->addState(s1);
        machine->addState(s2);
        machine->addState(s3);

        machine->setInitialState(s1);
        machine->start();
    }
int main(int argv, char **args)
{
    QApplication app(argv, args);

    QLabel *label = new QLabel;

//![0]
    QStateMachine machine;
    QState *s1 = new QState();
    QState *s2 = new QState();
    QState *s3 = new QState();
//![0]

//![4]
    s1->assignProperty(label, "text", "In state s1");
    s2->assignProperty(label, "text", "In state s2");
    s3->assignProperty(label, "text", "In state s3");
//![4]

//![5]
    QObject::connect(s3, SIGNAL(entered()), button, SLOT(showMaximized()));
    QObject::connect(s3, SIGNAL(exited()), button, SLOT(showMinimized()));
//![5]

//![1]
    s1->addTransition(button, SIGNAL(clicked()), s2);
    s2->addTransition(button, SIGNAL(clicked()), s3);
    s3->addTransition(button, SIGNAL(clicked()), s1);
//![1]

//![2]
    machine.addState(s1);
    machine.addState(s2);
    machine.addState(s3);
    machine.setInitialState(s1);
//![2]

//![3]
    machine.start();
//![3]

    label->show();

    return app.exec();
}
Пример #12
0
//! [0]
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QPushButton button;
    QStateMachine machine;
//! [0]

//! [1]
    QState *off = new QState();
    off->assignProperty(&button, "text", "Off");
    off->setObjectName("off");

    QState *on = new QState();
    on->setObjectName("on");
    on->assignProperty(&button, "text", "On");
//! [1]

//! [2]
    off->addTransition(&button, SIGNAL(clicked()), on);
    on->addTransition(&button, SIGNAL(clicked()), off);
//! [2]

//! [3]
    machine.addState(off);
    machine.addState(on);
//! [3]

//! [4]
    machine.setInitialState(off);
    machine.start();
//! [4]

//! [5]
#if defined(Q_OS_SYMBIAN)
    button.showMaximized();
#elif defined(Q_WS_MAEMO_5) || defined(Q_WS_SIMULATOR)
    button.show();
#else
    button.resize(100, 50);
    button.show();
#endif
    return app.exec();
}
Пример #13
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
// Загружаем интерфейс пользователя из формы и устанавливаем действия в меню
    ui->setupUi(this);
    connect(ui->action_start, SIGNAL(triggered()), ui->startButton, SLOT(click()));
    connect(ui->action_exit, SIGNAL(triggered()), this, SLOT(close()));
    connect(ui->action_Qt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
    connect(ui->action_help, SIGNAL(triggered()), this, SLOT(showHelp()));
    connect(ui->action_about, SIGNAL(triggered()), this, SLOT(showAbout()));
    connect(ui->action_tech, SIGNAL(triggered()), this, SLOT(showTz()));
// Заводим машину состояний
    QStateMachine *animation = new QStateMachine(this);
    QState *idle = new QState();
    QState *animating = new QState();
    animating->assignProperty(ui->startButton,"text", tr("&Стоп"));
    animating->assignProperty(ui->startButton,"icon", QIcon(":/icons/control-stop-square.png"));
    animating->assignProperty(ui->action_start,"text",tr("О&становить анимацию"));
    animating->assignProperty(ui->action_start,"icon", QIcon(":/icons/control-stop-square.png"));
    idle->assignProperty(ui->startButton,"text", tr("Пу&ск"));
    idle->assignProperty(ui->startButton,"icon", QIcon(":/icons/control.png"));
    idle->assignProperty(ui->action_start,"text",tr("Запу&стить анимацию"));
    idle->assignProperty(ui->action_start,"icon", QIcon(":/icons/control.png"));
    QSignalTransition *startTransition = new QSignalTransition(ui->startButton, SIGNAL(clicked()), idle);
    startTransition->setTargetState(animating);
    QSignalTransition *stopTransition = new QSignalTransition(ui->startButton, SIGNAL(clicked()), animating);
    stopTransition->setTargetState(idle);
    QSignalTransition *doneTransition = new QSignalTransition(ui->widget, SIGNAL(animationStopped()), animating);
    doneTransition->setTargetState(idle);
    connect(startTransition, SIGNAL(triggered()), ui->widget, SLOT(startAnimation()));
    connect(stopTransition, SIGNAL(triggered()), ui->widget, SLOT(stopAnimation()));
    idle->addTransition(startTransition);
    animating->addTransition(stopTransition);
    animating->addTransition(doneTransition);
    animation->addState(idle);
    animation->addState(animating);
    animation->setInitialState(idle);
    animation->start();
 // В Linux мячик иногда сразу не отображается...
    ui->widget->updateGL();
}
Пример #14
0
void ZoneDeDessin::initStateMachine() {
    QStateMachine * mac = new QStateMachine( );
    QState *s1 = new QState(); //mouse up
    QState *s2 = new QState(); //mouse down

    s2->assignProperty(this, "text", "tja");

    mac->addState(s1);
    mac->addState(s2);
    mac->setInitialState(s1);
    mac->start();

    addTrans(s1, s2, this, QEvent::MouseButtonPress, Qt::LeftButton);
    addTrans(s2, s2, this, QEvent::MouseMove, Qt::NoButton);
    addTrans(s2, s1, this, QEvent::MouseButtonRelease, Qt::LeftButton);

    connect(s1, SIGNAL(exited()), this, SLOT(startDraw())); // leave mouseup
    connect(s2, SIGNAL(entered()), this, SLOT(drawing())); // enter mousedown
    connect(s1, SIGNAL(entered()), this, SLOT(endDraw())); // enter mouseup
}
Пример #15
0
void TMainWind::init()
{
	setCentralWidget(m_canvas = new TCanvas);

	QLabel* statusLabel = new QLabel;
	statusBar()->addPermanentWidget(statusLabel);

	QStateMachine* machine = new QStateMachine(this);
	QState* creation = new QState;
	QState* bending = new QState; // transformation
	QState* painting = new QState;
	QState* extrusion = new QState;

	creation->assignProperty(m_canvas, "mode", TCanvas::Creation);
	creation->assignProperty(statusLabel, "text", tr("Mode: Creation"));
	creation->addTransition(m_canvas, SIGNAL(creationFinished()), painting);
	
	bending->assignProperty(m_canvas, "mode", TCanvas::Bending);
	bending->assignProperty(statusLabel, "text", tr("Mode: Bending"));
	bending->addTransition(m_canvas, SIGNAL(bendingFinished()), painting);

	painting->assignProperty(m_canvas, "mode", TCanvas::Painting);
	painting->assignProperty(statusLabel, "text", tr("Mode: Painting"));
	painting->addTransition(m_canvas, SIGNAL(toEdit()), extrusion);

	extrusion->assignProperty(m_canvas, "mode", TCanvas::Extrusion);
	extrusion->assignProperty(statusLabel, "text", tr("Mode: Extrusion"));
	extrusion->addTransition(m_canvas, SIGNAL(extrusionFinished()), painting);

	bending->addTransition(m_canvas, SIGNAL(restart()), creation);
	painting->addTransition(m_canvas, SIGNAL(restart()), creation);
	extrusion->addTransition(m_canvas, SIGNAL(restart()), creation);
	

	machine->addState(creation);
	machine->addState(bending);
	machine->addState(painting);
	machine->addState(extrusion);
	machine->setInitialState(creation);
	machine->start();
}
Пример #16
0
QStateMachine* UIAnimationFramework::installPropertyAnimation(QWidget *pTarget, const char *pszPropertyName,
                                                              const char *pszValuePropertyNameStart, const char *pszValuePropertyNameFinal,
                                                              const char *pSignalForward, const char *pSignalBackward,
                                                              bool fReversive /*= false*/, int iAnimationDuration /*= 300*/)
{
    /* State-machine: */
    QStateMachine *pStateMachine = new QStateMachine(pTarget);
    /* State-machine 'start' state: */
    QState *pStateStart = new QState(pStateMachine);
    /* State-machine 'final' state: */
    QState *pStateFinal = new QState(pStateMachine);

    /* State-machine 'forward' animation: */
    QPropertyAnimation *pForwardAnimation = new QPropertyAnimation(pTarget, pszPropertyName, pStateMachine);
    pForwardAnimation->setEasingCurve(QEasingCurve(QEasingCurve::InOutCubic));
    pForwardAnimation->setDuration(iAnimationDuration);
    pForwardAnimation->setStartValue(pTarget->property(pszValuePropertyNameStart));
    pForwardAnimation->setEndValue(pTarget->property(pszValuePropertyNameFinal));
    /* State-machine 'backward' animation: */
    QPropertyAnimation *pBackwardAnimation = new QPropertyAnimation(pTarget, pszPropertyName, pStateMachine);
    pBackwardAnimation->setEasingCurve(QEasingCurve(QEasingCurve::InOutCubic));
    pBackwardAnimation->setDuration(iAnimationDuration);
    pBackwardAnimation->setStartValue(pTarget->property(pszValuePropertyNameFinal));
    pBackwardAnimation->setEndValue(pTarget->property(pszValuePropertyNameStart));

    /* State-machine state transitions: */
    QSignalTransition *pDefaultToHovered = pStateStart->addTransition(pTarget, pSignalForward, pStateFinal);
    pDefaultToHovered->addAnimation(pForwardAnimation);
    QSignalTransition *pHoveredToDefault = pStateFinal->addTransition(pTarget, pSignalBackward, pStateStart);
    pHoveredToDefault->addAnimation(pBackwardAnimation);

    /* Initial state is 'start': */
    pStateMachine->setInitialState(!fReversive ? pStateStart : pStateFinal);
    /* Start hover-machine: */
    pStateMachine->start();
    /* Return machine: */
    return pStateMachine;
}
Пример #17
0
//! [0]
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    QPushButton button;
    QStateMachine machine;
//! [0]

//! [1]
    QState *off = new QState();
    off->assignProperty(&button, "text", "Off");
    off->setObjectName("off");

    QState *on = new QState();
    on->setObjectName("on");
    on->assignProperty(&button, "text", "On");
//! [1]

//! [2]
    off->addTransition(&button, SIGNAL(clicked()), on);
    on->addTransition(&button, SIGNAL(clicked()), off);
//! [2]

//! [3]
    machine.addState(off);
    machine.addState(on);
//! [3]

//! [4]
    machine.setInitialState(off);
    machine.start();
//! [4]

//! [5]
    button.resize(100, 50);
    button.show();
    return app.exec();
}
Пример #18
0
//! [0]
PadNavigator::PadNavigator(const QSize &size, QWidget *parent)
    : QGraphicsView(parent)
{
//! [0]
//! [1]
    // Splash item
    SplashItem *splash = new SplashItem;
    splash->setZValue(1);
//! [1]

//! [2]
    // Pad item
    FlippablePad *pad = new FlippablePad(size);
    QGraphicsRotation *flipRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *xRotation = new QGraphicsRotation(pad);
    QGraphicsRotation *yRotation = new QGraphicsRotation(pad);
    flipRotation->setAxis(Qt::YAxis);
    xRotation->setAxis(Qt::YAxis);
    yRotation->setAxis(Qt::XAxis);
    pad->setTransformations(QList<QGraphicsTransform *>()
                            << flipRotation
                            << xRotation << yRotation);
//! [2]

//! [3]
    // Back (proxy widget) item
    QGraphicsProxyWidget *backItem = new QGraphicsProxyWidget(pad);
    QWidget *widget = new QWidget;
    form.setupUi(widget);
    form.hostName->setFocus();
    backItem->setWidget(widget);
    backItem->setVisible(false);
    backItem->setFocus();
    backItem->setCacheMode(QGraphicsItem::ItemCoordinateCache);
    const QRectF r = backItem->rect();
    backItem->setTransform(QTransform()
                           .rotate(180, Qt::YAxis)
                           .translate(-r.width()/2, -r.height()/2));
//! [3]

//! [4]
    // Selection item
    RoundRectItem *selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray, pad);
    selectionItem->setZValue(0.5);
//! [4]

//! [5]
    // Splash animations
    QPropertyAnimation *smoothSplashMove = new QPropertyAnimation(splash, "y");
    QPropertyAnimation *smoothSplashOpacity = new QPropertyAnimation(splash, "opacity");
    smoothSplashMove->setEasingCurve(QEasingCurve::InQuad);
    smoothSplashMove->setDuration(250);
    smoothSplashOpacity->setDuration(250);
//! [5]

//! [6]
    // Selection animation
    QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x");
    QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y");
    QPropertyAnimation *smoothXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothYRotation = new QPropertyAnimation(yRotation, "angle");
    smoothXSelection->setDuration(125);
    smoothYSelection->setDuration(125);
    smoothXRotation->setDuration(125);
    smoothYRotation->setDuration(125);
    smoothXSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYSelection->setEasingCurve(QEasingCurve::InOutQuad);
    smoothXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothYRotation->setEasingCurve(QEasingCurve::InOutQuad);
//! [6]

//! [7]
    // Flip animation setup
    QPropertyAnimation *smoothFlipRotation = new QPropertyAnimation(flipRotation, "angle");
    QPropertyAnimation *smoothFlipScale = new QPropertyAnimation(pad, "scale");
    QPropertyAnimation *smoothFlipXRotation = new QPropertyAnimation(xRotation, "angle");
    QPropertyAnimation *smoothFlipYRotation = new QPropertyAnimation(yRotation, "angle");
    QParallelAnimationGroup *flipAnimation = new QParallelAnimationGroup(this);
    smoothFlipScale->setDuration(500);
    smoothFlipRotation->setDuration(500);
    smoothFlipXRotation->setDuration(500);
    smoothFlipYRotation->setDuration(500);
    smoothFlipScale->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipXRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipYRotation->setEasingCurve(QEasingCurve::InOutQuad);
    smoothFlipScale->setKeyValueAt(0, qvariant_cast<qreal>(1.0));
    smoothFlipScale->setKeyValueAt(0.5, qvariant_cast<qreal>(0.7));
    smoothFlipScale->setKeyValueAt(1, qvariant_cast<qreal>(1.0));
    flipAnimation->addAnimation(smoothFlipRotation);
    flipAnimation->addAnimation(smoothFlipScale);
    flipAnimation->addAnimation(smoothFlipXRotation);
    flipAnimation->addAnimation(smoothFlipYRotation);
//! [7]

//! [8]
    // Flip animation delayed property assignment
    QSequentialAnimationGroup *setVariablesSequence = new QSequentialAnimationGroup;
    QPropertyAnimation *setFillAnimation = new QPropertyAnimation(pad, "fill");
    QPropertyAnimation *setBackItemVisibleAnimation = new QPropertyAnimation(backItem, "visible");
    QPropertyAnimation *setSelectionItemVisibleAnimation = new QPropertyAnimation(selectionItem, "visible");
    setFillAnimation->setDuration(0);
    setBackItemVisibleAnimation->setDuration(0);
    setSelectionItemVisibleAnimation->setDuration(0);
    setVariablesSequence->addPause(250);
    setVariablesSequence->addAnimation(setBackItemVisibleAnimation);
    setVariablesSequence->addAnimation(setSelectionItemVisibleAnimation);
    setVariablesSequence->addAnimation(setFillAnimation);
    flipAnimation->addAnimation(setVariablesSequence);
//! [8]

//! [9]
    // Build the state machine
    QStateMachine *stateMachine = new QStateMachine(this);
    QState *splashState = new QState(stateMachine);
    QState *frontState = new QState(stateMachine);
    QHistoryState *historyState = new QHistoryState(frontState);
    QState *backState = new QState(stateMachine);
//! [9]
//! [10]
    frontState->assignProperty(pad, "fill", false);
    frontState->assignProperty(splash, "opacity", 0.0);
    frontState->assignProperty(backItem, "visible", false);
    frontState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(0.0));
    frontState->assignProperty(selectionItem, "visible", true);
    backState->assignProperty(pad, "fill", true);
    backState->assignProperty(backItem, "visible", true);
    backState->assignProperty(xRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(yRotation, "angle", qvariant_cast<qreal>(0.0));
    backState->assignProperty(flipRotation, "angle", qvariant_cast<qreal>(180.0));
    backState->assignProperty(selectionItem, "visible", false);
    stateMachine->addDefaultAnimation(smoothXRotation);
    stateMachine->addDefaultAnimation(smoothYRotation);
    stateMachine->addDefaultAnimation(smoothXSelection);
    stateMachine->addDefaultAnimation(smoothYSelection);
    stateMachine->setInitialState(splashState);
//! [10]

//! [11]
    // Transitions
    QEventTransition *anyKeyTransition = new QEventTransition(this, QEvent::KeyPress, splashState);
    anyKeyTransition->setTargetState(frontState);
    anyKeyTransition->addAnimation(smoothSplashMove);
    anyKeyTransition->addAnimation(smoothSplashOpacity);
//! [11]

//! [12]
    QKeyEventTransition *enterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                   Qt::Key_Enter, backState);
    QKeyEventTransition *returnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                    Qt::Key_Return, backState);
    QKeyEventTransition *backEnterTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                       Qt::Key_Enter, frontState);
    QKeyEventTransition *backReturnTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Return, frontState);
    enterTransition->setTargetState(historyState);
    returnTransition->setTargetState(historyState);
    backEnterTransition->setTargetState(backState);
    backReturnTransition->setTargetState(backState);
    enterTransition->addAnimation(flipAnimation);
    returnTransition->addAnimation(flipAnimation);
    backEnterTransition->addAnimation(flipAnimation);
    backReturnTransition->addAnimation(flipAnimation);
//! [12]

//! [13]
    // Create substates for each icon; store in temporary grid.
    int columns = size.width();
    int rows = size.height();
    QVector< QVector< QState * > > stateGrid;
    stateGrid.resize(rows);
    for (int y = 0; y < rows; ++y) {
        stateGrid[y].resize(columns);
        for (int x = 0; x < columns; ++x)
            stateGrid[y][x] = new QState(frontState);
    }
    frontState->setInitialState(stateGrid[0][0]);
    selectionItem->setPos(pad->iconAt(0, 0)->pos());
//! [13]

//! [14]
    // Enable key navigation using state transitions
    for (int y = 0; y < rows; ++y) {
        for (int x = 0; x < columns; ++x) {
            QState *state = stateGrid[y][x];
            QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                           Qt::Key_Right, state);
            QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Left, state);
            QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Down, state);
            QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Up, state);
            rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]);
            leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]);
            downTransition->setTargetState(stateGrid[(y + 1) % rows][x]);
            upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]);
//! [14]
//! [15]
            RoundRectItem *icon = pad->iconAt(x, y);
            state->assignProperty(xRotation, "angle", -icon->x() / 6.0);
            state->assignProperty(yRotation, "angle", icon->y() / 6.0);
            state->assignProperty(selectionItem, "x", icon->x());
            state->assignProperty(selectionItem, "y", icon->y());
            frontState->assignProperty(icon, "visible", true);
            backState->assignProperty(icon, "visible", false);

            QPropertyAnimation *setIconVisibleAnimation = new QPropertyAnimation(icon, "visible");
            setIconVisibleAnimation->setDuration(0);
            setVariablesSequence->addAnimation(setIconVisibleAnimation);
        }
    }
//! [15]

//! [16]
    // Scene
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setBackgroundBrush(QPixmap(":/images/blue_angle_swirl.jpg"));
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    scene->addItem(pad);
    scene->setSceneRect(scene->itemsBoundingRect());
    setScene(scene);
//! [16]

//! [17]
    // Adjust splash item to scene contents
    const QRectF sbr = splash->boundingRect();
    splash->setPos(-sbr.width() / 2, scene->sceneRect().top() - 2);
    frontState->assignProperty(splash, "y", splash->y() - 100.0);
    scene->addItem(splash);
//! [17]

//! [18]
    // View
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(50, 50);
    setViewportUpdateMode(FullViewportUpdate);
    setCacheMode(CacheBackground);
    setRenderHints(QPainter::Antialiasing
                   | QPainter::SmoothPixmapTransform
                   | QPainter::TextAntialiasing);
#ifndef QT_NO_OPENGL
    setViewport(new QOpenGLWidget);
#endif

    stateMachine->start();
//! [18]
}
Пример #19
0
QWidget *Desktopwidget::createToolbar(void)
   {
   QWidget *group = new QWidget (this);

   //TODO: Move this to use the designer
   /* create the desktop toolbar. We are doing this manually since we can't
      seem to get Qt to insert a QLineEdit into a toolbar */
   _toolbar = new QToolBar (group);
//   _toolbar = new QWidget (group);
//   _toolbar = group;
   addAction (_actionPprev, "Previous page", SLOT(pageLeft ()), "", _toolbar, "pprev.xpm");
   addAction (_actionPprev, "Next page", SLOT(pageRight ()), "", _toolbar, "pnext.xpm");
   addAction (_actionPprev, "Previous stack", SLOT(stackLeft ()), "", _toolbar, "prev.xpm");
   addAction (_actionPprev, "Next stack", SLOT(stackRight ()), "", _toolbar, "next.xpm");

   QWidget *findgroup = new QWidget (_toolbar);

   QHBoxLayout *hboxLayout2 = new QHBoxLayout();
   hboxLayout2->setSpacing(0);
   hboxLayout2->setContentsMargins (0, 0, 0, 0);
   hboxLayout2->setObjectName(QString::fromUtf8("hboxLayout2"));
   findgroup->setLayout (hboxLayout2);

   QLabel *label = new QLabel (findgroup);
   label->setText(QApplication::translate("Mainwindow", "Filter:", 0));
   label->setObjectName(QString::fromUtf8("label"));

   hboxLayout2->addWidget(label);

   _match = new QLineEdit (findgroup);
   _match->setObjectName ("match");
   QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Fixed);
   sizePolicy2.setHorizontalStretch(1);
   sizePolicy2.setVerticalStretch(0);
   sizePolicy2.setHeightForWidth(_match->sizePolicy().hasHeightForWidth());
   _match->setSizePolicy(sizePolicy2);
   _match->setMinimumSize(QSize(50, 0));
   //_match->setDragEnabled(true);

   connect (_match, SIGNAL (returnPressed()),
        this, SLOT (matchUpdate ()));
   connect (_match, SIGNAL (textChanged(const QString&)),
        this, SLOT (matchChange (const QString &)));
   //_reset_filter = new QAction (this);
   //_reset_filter->setShortcut (Qt::Key_Escape);
   //connect (_reset_filter, SIGNAL (triggered()), this, SLOT (resetFilter()));
   //_match->addAction (_reset_filter);
   //_match->installEventFilter (this);

   // When ESC is pressed, clear the field
   QStateMachine *machine = new QStateMachine (this);
   QState *s1 = new QState (machine);

//   QSignalTransition *pressed_esc = new QSignalTransition(_match,
//                                       SIGNAL(textChanged(const QString&)));
   QKeyEventTransition *pressed_esc = new QKeyEventTransition(_match,
                           QEvent::KeyPress, Qt::Key_Escape);
   s1->addTransition (pressed_esc);
   connect(pressed_esc, SIGNAL(triggered()), this, SLOT(resetFilter()));
   machine->setInitialState (s1);
   machine->start ();
#if 0
  QPushButton *test = new QPushButton (findgroup);
  test->setText ("hello");
  hboxLayout2->addWidget (test);

   QStateMachine *test_machine = new QStateMachine (this);
   QState *test_s1 = new QState (test_machine);

   QSignalTransition *trans = new QSignalTransition(test, SIGNAL(clicked()));
   test_s1->addTransition (trans);
   connect(trans, SIGNAL(triggered()), this, SLOT(resetFilter()));
   test_machine->setInitialState (test_s1);
   test_machine->start ();
#endif
    // and change the state
   hboxLayout2->addWidget(label);

   hboxLayout2->addWidget (_match);

   addAction (_find, "Filter stacks", SLOT(findClicked ()), "", findgroup, "find.xpm");
   QToolButton *find = new QToolButton (findgroup);
   find->setDefaultAction (_find);
   hboxLayout2->addWidget (find);
//    connect (_find, SIGNAL (activated ()), this, SLOT (findClicked ()));

   QSpacerItem *spacerItem = new QSpacerItem(16, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

   hboxLayout2->addItem (spacerItem);

   _global = new QCheckBox("Subdirs", findgroup);
   _global->setObjectName(QString::fromUtf8("global"));

   hboxLayout2->addWidget(_global);

   addAction (_reset, "Reset", SLOT(resetFilter ()), "", findgroup);
   QToolButton *reset = new QToolButton (findgroup);
   reset->setDefaultAction (_reset);
   hboxLayout2->addWidget (reset);

   _toolbar->addWidget (findgroup);

#ifndef QT_NO_TOOLTIP
   _match->setToolTip(QApplication::translate("Mainwindow", "Enter part of the name of the stack to search for", 0));
   _find->setToolTip(QApplication::translate("Mainwindow", "Search for the name", 0));
   _global->setToolTip(QApplication::translate("Mainwindow", "Enable this to search all subdirectories also", 0));
   _reset->setToolTip(QApplication::translate("Mainwindow", "Reset the search string", 0));
#endif // QT_NO_TOOLTIP
#ifndef QT_NO_WHATSTHIS
   _match->setWhatsThis(QApplication::translate("Mainwindow", "The filter feature can be used in two ways. To filter out unwanted stacks, type a few characters from the stack name that you are looking for. Everything that does not match will be removed from view. To go back, just delete characters from the filter.\n"
"\n"
"There is also a 'global' mode which allows searching of all subdirectories. To use this, select the 'global' button, then type your filter string. Press return or click 'find' to perform the search. This might take a while.\n"
"\n"
"To reset the filter, click the 'reset' button.", 0));
   _find->setWhatsThis(QApplication::translate("Mainwindow", "Click this button to perform a search when in global mode", 0));
   _global->setWhatsThis(QApplication::translate("Mainwindow", "The filter feature can be used in two ways. To filter out unwanted stacks, type a few characters from the stack name that you are looking for. Everything that does not match will be removed from view. To go back, just delete characters from the filter.\n"
"\n"
"There is also a 'global' mode which allows searching of all subdirectories. To use this, select the 'global' button, then type your filter string. Press return or click 'find' to perform the search. This might take a while.\n"
"\n"
"To reset the filter, click the 'reset' button.", 0));
   _reset->setWhatsThis(QApplication::translate("Mainwindow", "Press this button to reset the filter string and display stacks in the current directory", 0));
#endif // QT_NO_WHATSTHIS
   return group;
   }
Пример #20
0
PadNavigator::PadNavigator( QWidget *parent)
    : QGraphicsView(parent)
{
    QSize size(6,2);

    // Pad item
    this->pad = new FlippablePad(size);

    // Selection item
    RoundRectItem *selectionItem = new RoundRectItem(QRectF(-110, -110, 220, 220),
                                                     Qt::gray, pad);
    selectionItem->setZValue(0.5);

    // Selection animation
    QPropertyAnimation *smoothXSelection = new QPropertyAnimation(selectionItem, "x");
    QPropertyAnimation *smoothYSelection = new QPropertyAnimation(selectionItem, "y");
    smoothXSelection->setDuration(100);
    smoothYSelection->setDuration(100);
    smoothXSelection->setEasingCurve(QEasingCurve::InCurve);
    smoothYSelection->setEasingCurve(QEasingCurve::InCurve);

    // Build the state machine
    QStateMachine *stateMachine = new QStateMachine(this);

    QState *frontState = new QState(stateMachine);

    frontState->assignProperty(pad, "fill", false);

    frontState->assignProperty(selectionItem, "visible", true);

    stateMachine->addDefaultAnimation(smoothXSelection);
    stateMachine->addDefaultAnimation(smoothYSelection);
    stateMachine->setInitialState(frontState);

    // Create substates for each icon; store in temporary grid.
    int columns = size.width();
    int rows = size.height();
    QVector< QVector< QState * > > stateGrid;
    stateGrid.resize(rows);
    for (int y = 0; y < rows; ++y) {
        stateGrid[y].resize(columns);
        for (int x = 0; x < columns; ++x)
            stateGrid[y][x] = new QState(frontState);
    }
    frontState->setInitialState(stateGrid[0][0]);
    selectionItem->setPos(pad->iconAt(0, 0)->pos());

    // Enable key navigation using state transitions
    for (int y = 0; y < rows; ++y) {
        for (int x = 0; x < columns; ++x) {
            QState *state = stateGrid[y][x];
            QKeyEventTransition *rightTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                           Qt::Key_Right, state);
            QKeyEventTransition *leftTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Left, state);
            QKeyEventTransition *downTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                          Qt::Key_Down, state);
            QKeyEventTransition *upTransition = new QKeyEventTransition(this, QEvent::KeyPress,
                                                                        Qt::Key_Up, state);

            rightTransition->setTargetState(stateGrid[y][(x + 1) % columns]);
            leftTransition->setTargetState(stateGrid[y][((x - 1) + columns) % columns]);
            downTransition->setTargetState(stateGrid[(y + 1) % rows][x]);
            upTransition->setTargetState(stateGrid[((y - 1) + rows) % rows][x]);

            RoundRectItem *icon = pad->iconAt(x, y);

            state->assignProperty(selectionItem, "x", icon->x());
            state->assignProperty(selectionItem, "y", icon->y());

        }
    }
    // Scene
    QGraphicsScene *scene = new QGraphicsScene(this);
    scene->setItemIndexMethod(QGraphicsScene::NoIndex);
    scene->addItem(pad);
    scene->setSceneRect(scene->itemsBoundingRect());
    setScene(scene);

    // View
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setMinimumSize(50, 50);
    setCacheMode(CacheBackground);
    setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform | QPainter::TextAntialiasing);

    stateMachine->start();

}
SmoozikSimplestClientWindow::SmoozikSimplestClientWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::SmoozikSimplestClientWindow)
{
    ui->setupUi(this);

    // Initialize SmoozikManager
    smoozikManager = new SmoozikManager(APIKEY, SECRET, SmoozikManager::XML, false, this);
    smoozikPlaylist = new SmoozikPlaylist;
    connect(smoozikManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(processNetworkReply(QNetworkReply*)));

    // Initialize music directory
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    _dirName = QDesktopServices::storageLocation(QDesktopServices::MusicLocation);
#else
    _dirName = QStandardPaths::writableLocation(QStandardPaths::MusicLocation);
#endif

    // Initialize playlist filler
    ui->setupUi(this);
    smoozikPlaylistFillerThread = new QThread();
    smoozikPlaylistFiller = new SmoozikPlaylistFiller(smoozikPlaylist);
    smoozikPlaylistFiller->moveToThread(smoozikPlaylistFillerThread);
    connect(smoozikPlaylistFiller, SIGNAL(trackFound(QString,QString,QString,QString,uint)), this, SLOT(addTrackToPlaylist(QString,QString,QString,QString,uint)));
    connect(smoozikPlaylistFiller, SIGNAL(tracksRetrieved()), this, SIGNAL(tracksRetrieved()));
    connect(smoozikPlaylistFiller, SIGNAL(noTrackRetrieved()), this, SLOT(noTrackRetrievedMessage()));
    connect(smoozikPlaylistFiller, SIGNAL(maxPlaylistSizeReached()), this, SLOT(maxPlaylistSizeReachedMessage()));
    connect(smoozikPlaylistFillerThread, SIGNAL(started()), smoozikPlaylistFiller, SLOT(fillPlaylist()));
    connect(smoozikPlaylistFiller, SIGNAL(finished()), smoozikPlaylistFillerThread, SLOT(quit()), Qt::DirectConnection);

    // Initialize player
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    player = new Phonon::MediaObject(this);
    Phonon::AudioOutput *audioOutput = new Phonon::AudioOutput(Phonon::MusicCategory, this);
    Phonon::createPath(player, audioOutput);
    connect(player, SIGNAL(currentSourceChanged(Phonon::MediaSource)), this, SLOT(updateTrackLabels()));
    connect(player, SIGNAL(stateChanged(Phonon::State,Phonon::State)), this, SLOT(playerStateChanged()));
#else
    player = new QMediaPlayer(this);
    player->setPlaylist(new QMediaPlaylist(player));
    player->playlist()->setPlaybackMode(QMediaPlaylist::Sequential);
    connect(player, SIGNAL(currentMediaChanged(QMediaContent)), this, SLOT(updateTrackLabels()));
    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)), this, SLOT(playerStateChanged()));
#endif
    connect(ui->playButton, SIGNAL(clicked()), player, SLOT(play()));
    connect(ui->pauseButton, SIGNAL(clicked()), player, SLOT(pause()));
    connect(this, SIGNAL(currentTrackSet()), this, SLOT(updateTrackLabels()));
    connect(this, SIGNAL(nextTrackSet()), this, SLOT(updateTrackLabels()));

    // Initialize main state machine which controls what is displayed
    QStateMachine *mainStateMachine = new QStateMachine(this);
    QState *mainState = new QState(mainStateMachine);
    QState *loginState = new QState(mainState);
    QState *startPartyState = new QState(mainState);
    QState *connectedState = new QState(mainState);
    QState *retrieveTracksState = new QState(connectedState);
    QState *sendPlaylistState = new QState(connectedState);
    QState *getTopTracksState = new QState(connectedState);
    QState *partyState = new QState(connectedState);
    QState *waitingState = new QState(partyState);
    QState *sendCurrentTrackState = new QState(partyState);
    QState *sendNextTrackState = new QState(partyState);

    QStateMachine *playerStateMachine = new QStateMachine(this);
    QState *playerState = new QState(playerStateMachine);
    QState *playingState = new QState(playerState);
    QState *pausedState = new QState(playerState);

    // Define state initial states and transitions
    mainStateMachine->setInitialState(mainState);
    mainState->setInitialState(loginState);
    connectedState->setInitialState(retrieveTracksState);
    partyState->setInitialState(waitingState);
    playerStateMachine->setInitialState(playerState);
    playerState->setInitialState(pausedState);

    mainState->addTransition(this, SIGNAL(disconnected()), loginState);
    loginState->addTransition(this, SIGNAL(loggedIn()), startPartyState);
    startPartyState->addTransition(this, SIGNAL(partyStarted()), connectedState);
    connectedState->addTransition(ui->changePlaylistButton, SIGNAL(clicked()), retrieveTracksState);
    retrieveTracksState->addTransition(this, SIGNAL(tracksRetrieved()), sendPlaylistState);
    sendPlaylistState->addTransition(this, SIGNAL(playlistSent()), getTopTracksState);
    getTopTracksState->addTransition(this, SIGNAL(currentTrackSet()), sendCurrentTrackState);
    sendCurrentTrackState->addTransition(this, SIGNAL(currentTrackSent()), getTopTracksState);
    getTopTracksState->addTransition(this, SIGNAL(nextTrackSet()), sendNextTrackState);
    sendNextTrackState->addTransition(this, SIGNAL(nextTrackSent()), waitingState);
#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0)
    waitingState->addTransition(player, SIGNAL(currentSourceChanged(Phonon::MediaSource)), sendCurrentTrackState);
#else
    waitingState->addTransition(player, SIGNAL(currentMediaChanged(QMediaContent)), sendCurrentTrackState);
#endif

    playerState->addTransition(this, SIGNAL(playing()), playingState);
    playerState->addTransition(this, SIGNAL(paused()), pausedState);

    // Define state properties
    loginState->assignProperty(this, "state", Login);
    loginState->assignProperty(ui->stackedWidget, "currentIndex", ui->stackedWidget->indexOf(ui->loginPage));
    loginState->assignProperty(ui->loginButton, "enabled", true);
    loginState->assignProperty(ui->disconnectButton, "visible", false);
    loginState->assignProperty(ui->changePlaylistButton, "visible", false);
    loginState->assignProperty(ui->usernameLineEdit, "enabled", true);
    loginState->assignProperty(ui->passwordLineEdit, "enabled", true);
    loginState->assignProperty(ui->loginStateLabel, "text", QString());

    startPartyState->assignProperty(this, "state", StartParty);
    startPartyState->assignProperty(ui->loginStateLabel, "text", tr("Starting party..."));
    startPartyState->assignProperty(ui->disconnectButton, "visible", false);
    startPartyState->assignProperty(ui->changePlaylistButton, "visible", false);

    connectedState->assignProperty(ui->disconnectButton, "visible", true);

    retrieveTracksState->assignProperty(ui->stackedWidget, "currentIndex", ui->stackedWidget->indexOf(ui->loadingPage));
    retrieveTracksState->assignProperty(ui->loginStateLabel, "text", tr("Connected"));
    retrieveTracksState->assignProperty(ui->loadingLabel, "text", tr("Retrieving tracks..."));
    retrieveTracksState->assignProperty(ui->changePlaylistButton, "visible", false);

    sendPlaylistState->assignProperty(this, "state", SendPlaylist);
    sendPlaylistState->assignProperty(ui->loadingLabel, "text", tr("Sending playlist..."));
    sendPlaylistState->assignProperty(ui->changePlaylistButton, "visible", true);

    getTopTracksState->assignProperty(this, "state", GetTopTracks);
    getTopTracksState->assignProperty(ui->loadingLabel, "text", tr("Get top tracks..."));
    getTopTracksState->assignProperty(ui->nextButton, "enabled", false);
    getTopTracksState->assignProperty(ui->changePlaylistButton, "visible", true);

    partyState->assignProperty(ui->stackedWidget, "currentIndex", ui->stackedWidget->indexOf(ui->playerPage));
    partyState->assignProperty(ui->changePlaylistButton, "visible", true);

    sendCurrentTrackState->assignProperty(this, "state", SendCurrentTrack);
    sendCurrentTrackState->assignProperty(ui->nextButton, "enabled", false);

    sendNextTrackState->assignProperty(this, "state", SendNextTrack);
    sendNextTrackState->assignProperty(ui->nextButton, "enabled", false);

    waitingState->assignProperty(ui->nextButton, "enabled", true);

    playingState->assignProperty(ui->playButton, "visible", false);
    playingState->assignProperty(ui->pauseButton, "visible", true);

    pausedState->assignProperty(ui->playButton, "visible", true);
    pausedState->assignProperty(ui->pauseButton, "visible", false);

    // Connect states and actions
    connect(startPartyState, SIGNAL(entered()), this, SLOT(startParty()));
    connect(retrieveTracksState, SIGNAL(entered()), this, SLOT(retrieveTracksDialog()));
    connect(sendPlaylistState, SIGNAL(entered()), this, SLOT(sendPlaylist()));
    connect(getTopTracksState, SIGNAL(entered()), this, SLOT(getTopTracks()));
    connect(sendCurrentTrackState, SIGNAL(entered()), this, SLOT(sendCurrentTrack()));
    connect(sendNextTrackState, SIGNAL(entered()), this, SLOT(sendNextTrack()));

    // Connect gui and actions
    connect(ui->usernameLineEdit, SIGNAL(returnPressed()), this, SLOT(submitLogin()));
    connect(ui->passwordLineEdit, SIGNAL(returnPressed()), this, SLOT(submitLogin()));
    connect(ui->loginButton, SIGNAL(clicked()), this, SLOT(submitLogin()));
    connect(ui->nextButton, SIGNAL(clicked()), this, SLOT(nextTrack()));
    connect(ui->disconnectButton, SIGNAL(clicked()), this, SLOT(disconnect()));

    // Start state machine
    mainStateMachine->start();
    playerStateMachine->start();
}
Пример #22
0
 Q_SLOT void start() {
    m_stateMachine.start();
 }
Пример #23
0
        void Protocol::prepareStateMachine(){
            qDebug() << "Protocol: Initialising Protocol State";
            QStateMachine *machine = new QStateMachine(this);

            /**
             *  Main states are connected, disconnected and done, we start disconnected
             *  and turn to connected when the socket is operational.
             *  All the other states are part of the connected state
             */
            QState *disconnected = new QState();
            QState *connected = new QState();
            QFinalState *done = new QFinalState();

            /**
             *  When first connected, we need to know the protocol version,
             *  then request authentication. We then either turn to the authenticated
             *  state or flee to *done
             */
            QState *waitingproto = new QState(connected);
            QState *waitingauthrequest = new QState(connected);
            QState *waitingauthstatus = new QState(connected);
            QState *authenticated = new QState(connected);
            connected->setInitialState(waitingproto);

            /**
             * When authenticated, the user must provide some information about himself
             * (nickname, status, planet picture, user picture, attack picture)
             * Then the user can request to join the chat room, get the list of games and users
             * join a game or create a game
             * In the chat room, the user sends and receives messages, and can eventually exit
             */
            QState *waitinguserdetails = new QState(authenticated);
            QState *waitingcommand = new QState(authenticated);
            QState *inchat = new QState(authenticated);
            QState *waitinggamecreation = new QState(authenticated);
            QState *waitinggamelist = new QState(authenticated);
            QState *waitinguserlist = new QState(authenticated);
            QState *joinedgame = new QState(authenticated);
            authenticated->setInitialState(waitinguserdetails);

            /**
             * When entering the game, we wait for the users to show up
             * then receive the game map
             * we then wait for the game to unpause, and the game progresses till
             * there's a winner or cancellation
             */
            QState *waitinguser = new QState(joinedgame);
            QState *waitingmap = new QState(joinedgame);
            QState *paused = new QState(joinedgame);
            QState *ingame = new QState(joinedgame);
            joinedgame->setInitialState(waitinguser);

            qDebug() << "Protocol: Connecting Protocol Signals";
            disconnected->addTransition(this, SIGNAL(connected()), connected);
            connected->addTransition(this, SIGNAL(closed()), done);
            waitingproto->addTransition(this, SIGNAL(protocol(QString)), waitingauthrequest);
            waitingauthrequest->addTransition(this, SIGNAL(authrequest(QString,QString)), waitingauthstatus);
            waitingauthstatus->addTransition(this, SIGNAL(authenticated()), authenticated);
            waitingauthstatus->addTransition(this, SIGNAL(protocolError(QString)), done);

            machine->addState(disconnected);
            machine->addState(connected);
            machine->setInitialState(disconnected);

            qDebug() << "Protocol: Starting State Machine";
            machine->start();
        }