summaryrefslogtreecommitdiffstats
path: root/doc/src/statemachine.qdoc
blob: 16eae39a45ced07f8c93709f9ed2c7671e2f1392 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the $MODULE$ of the Qt Toolkit.
**
** $TROLLTECH_DUAL_LICENSE$
**
****************************************************************************/

/*!
  \page statemachine-api.html
  \title The State Machine Framework
  \brief An overview of the State Machine framework for constructing and executing state graphs.
  \ingroup architecture

  \tableofcontents

  The State Machine framework provides classes for creating and executing
  state graphs. The concepts and notation are based on those from Harel's
  \l{Statecharts: A visual formalism for complex systems}{Statecharts}, which
  is also the basis of UML state diagrams. The semantics of state machine
  execution are based on \l{State Chart XML: State Machine Notation for
  Control Abstraction}{State Chart XML (SCXML)}.

  Statecharts provide a graphical way of modeling how a system reacts to
  stimuli. This is done by defining the possible \e states that the system can
  be in, and how the system can move from one state to another (\e transitions
  between states). A key characteristic of event-driven systems (such as Qt
  applications) is that behavior often depends not only on the last or current
  event, but also the events that preceded it. With statecharts, this
  information is easy to express.

  The State Machine framework provides an API and execution model that can be
  used to effectively embed the elements and semantics of statecharts in Qt
  applications. The framework integrates tightly with Qt's meta-object system;
  for example, transitions between states can be triggered by signals, and
  states can be configured to set properties and invoke methods on QObjects.
  Qt's event system is used to drive the state machines.

  \section1 A Simple State Machine

  To demonstrate the core functionality of the State Machine API, let's look
  at a small example: A state machine with three states, \c s1, \c s2 and \c
  s3. The state machine is controlled by a single QPushButton; when the button
  is clicked, the machine transitions to another state. Initially, the state
  machine is in state \c s1. The statechart for this machine is as follows:

    \img statemachine-button.png
    \omit
    \caption This is a caption
    \endomit

  The following snippet shows the code needed to create such a state machine.
  First, we create the state machine and states:

  \code
    QStateMachine machine;
    QState *s1 = new QState();
    QState *s2 = new QState();
    QState *s3 = new QState();
  \endcode

  Then, we create the transitions by using the QState::addTransition()
  function:

  \code
    s1->addTransition(button, SIGNAL(clicked()), s2);
    s2->addTransition(button, SIGNAL(clicked()), s3);
    s3->addTransition(button, SIGNAL(clicked()), s1);
  \endcode

  Next, we add the states to the machine and set the machine's initial state:

  \code
    machine.addState(s1);
    machine.addState(s2);
    machine.addState(s3);
    machine.setInitialState(s1);
  \endcode

  Finally, we start the state machine:

  \code
    machine.start();
  \endcode

  The state machine executes asynchronously, i.e. it becomes part of your
  application's event loop.

  \section1 Doing Useful Work on State Entry and Exit

  The above state machine merely transitions from one state to another, it
  doesn't perform any operations. The QState::assignProperty() function can be
  used to have a state set a property of a QObject when the state is
  entered. In the following snippet, the value that should be assigned to a
  QLabel's text property is specified for each state:

  \code
    s1->assignProperty(label, "text", "In state s1");
    s2->assignProperty(label, "text", "In state s2");
    s3->assignProperty(label, "text", "In state s3");
  \endcode

  When any of the states is entered, the label's text will be changed
  accordingly.

  The QState::entered() signal is emitted when the state is entered, and the
  QState::exited() signal is emitted when the state is exited. In the
  following snippet, the button's showMaximized() slot will be called when
  state \c s3 is entered, and the button's showMinimized() slot will be called
  when \c s3 is exited:

  \code
    QObject::connect(s3, SIGNAL(entered()), button, SLOT(showMaximized()));
    QObject::connect(s3, SIGNAL(exited()), button, SLOT(showMinimized()));
  \endcode

  \section1 State Machines That Finish

  The state machine defined in the previous section never finishes. In order
  for a state machine to be able to finish, it needs to have a top-level \e
  final state (QFinalState object). When the state machine enters a top-level
  final state, the machine will emit the QStateMachine::finished() signal and
  halt.

  \section1 Sharing Transitions By Grouping States

  Assume we wanted the user to be able to quit the application at any time by
  clicking a Quit button. In order to achieve this, we need to create a final
  state and make it the target of a transition associated with the Quit
  button's clicked() signal. We could add a transition from each of \c s1, \c
  s2 and \c s3; however, this seems redundant, and one would also have to
  remember to add such a transition from every new state that is added in the
  future.

  We can achieve the same behavior (namely that clicking the Quit button quits
  the state machine, regardless of which state the state machine is in) by
  grouping states \c s1, \c s2 and \c s3. This is done by creating a new
  top-level state and making the three original states children of the new
  state. The following diagram shows the new state machine.

    \img statemachine-button-nested.png
    \omit
    \caption This is a caption
    \endomit

  The three original states have been renamed \c s11, \c s12 and \c s13 to
  reflect that they are now children of the new top-level state, \c s1.  Child
  states implicitly inherit the transitions of their parent state. This means
  it is now sufficient to add a single transition from \c s1 to the final
  state \c s2. New states added to \c s1 will also automatically inherit this
  transition.

  All that's needed to group states is to specify the proper parent when the
  state is created. You also need to specify which of the child states is the
  initial one (i.e. which child state the state machine should enter when the
  parent state is the target of a transition).

  \code
    QState *s1 = new QState();
    QState *s11 = new QState(s1);
    QState *s12 = new QState(s1);
    QState *s13 = new QState(s1);
    s1->setInitialState(s11);
    machine.addState(s1);
  \endcode

  \code
    QFinalState *s2 = new QFinalState();
    s1->addTransition(quitButton, SIGNAL(clicked()), s2);
    machine.addState(s2);

    QObject::connect(&machine, SIGNAL(finished()), QApplication::instance(), SLOT(quit()));
  \endcode

  In this case we want the application to quit when the state machine is
  finished, so the machine's finished() signal is connected to the
  application's quit() slot.

  A child state can override an inherited transition. For example, the
  following code adds a transition that effectively causes the Quit button to
  be ignored when the state machine is in state \c s12.

  \code
    s12>addTransition(quitButton, SIGNAL(clicked()), s12);
  \endcode

  A transition can have any state as its target, i.e. the target state does
  not have to be on the same level in the state hierarchy as the source state.

  \section1 Using History States to Save and Restore the Current State

  Imagine that we wanted to add an "interrupt" mechanism to the example
  discussed in the previous section; the user should be able to click a button
  to have the state machine perform some non-related task, after which the
  state machine should resume whatever it was doing before (i.e. return to the
  old state, which is one of \c s11, \c s12 and \c s13 in this case).

  Such behavior can easily be modeled using \e{history states}. A history
  state (QHistoryState object) is a pseudo-state that represents the child
  state that the parent state was in the last time the parent state was
  exited.

  A history state is created as a child of the state for which we wish to
  record the current child state; when the state machine detects the presence
  of such a state at runtime, it automatically records the current (real)
  child state when the parent state is exited. A transition to the history
  state is in fact a transition to the child state that the state machine had
  previously saved; the state machine automatically "forwards" the transition
  to the real child state.

  The following diagram shows the state machine after the interrupt mechanism
  has been added.

    \img statemachine-button-history.png
    \omit
    \caption This is a caption
    \endomit

  The following code shows how it can be implemented; in this example we
  simply display a message box when \c s3 is entered, then immediately return
  to the previous child state of \c s1 via the history state.

  \code
    QHistoryState *s1h = s1->addHistoryState();

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

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

  \section1 Using Parallel States to Avoid a Combinatorial Explosion of States

  Assume that you wanted to model a set of mutually exclusive properties of a
  car in a single state machine. Let's say the properties we are interested in
  are Clean vs Dirty, and Moving vs Not moving. It would take four mutually
  exclusive states and eight transitions to be able to represent and freely
  move between all possible combinations.

    \img statemachine-nonparallel.png
    \omit
    \caption This is a caption
    \endomit

  If we added a third property (say, Red vs Blue), the total number of states
  would double, to eight; and if we added a fourth property (say, Enclosed vs
  Convertible), the total number of states would double again, to 16.

  Using parallel states, the total number of states and transitions grows
  linearly as we add more properties, instead of exponentially. Furthermore,
  states can be added to or removed from the parallel state without affecting
  any of their sibling states.

    \img statemachine-parallel.png
    \omit
    \caption This is a caption
    \endomit

  To create a parallel state group, pass QState::ParallelStates to the QState
  constructor.

  \code
    QState *s1 = new QState(QState::ParallelStates);
    // s11 and s12 will be entered in parallel
    QState *s11 = new QState(s1);
    QState *s12 = new QState(s1);
  \endcode

  When a parallel state group is entered, all its child states will be
  simultaneously entered. Transitions within the individual child states
  operate normally. However, any of the child states may take a transition
  outside the parent state. When this happens, the parent state and all of its
  child states are exited.

  \section1 Detecting that a Composite State has Finished

  A child state can be final (a QFinalState object); when a final child state
  is entered, the parent state emits the QState::finished() signal.

    \img statemachine-finished.png
    \omit
    \caption This is a caption
    \endomit

  This is useful when you want to hide the internal details of a state;
  i.e. the only thing the outside world should be able to do is enter the
  state, and get a notification when the state has completed its work.

  For parallel state groups, the QState::finished() signal is emitted when \e
  all the child states have entered final states.

  \section1 Events, Transitions and Guards

  A QStateMachine runs its own event loop. For signal transitions
  (QSignalTransition objects), QStateMachine automatically posts a
  QSignalEvent to itself when it intercepts the corresponding signal;
  similarly, for QObject event transitions (QEventTransition objects) a
  QWrappedEvent is posted.

  You can post your own events to the state machine using
  QStateMachine::postEvent().

  When posting a custom event to the state machine, you typically also have
  one or more custom transitions that can be triggered from events of that
  type. To create such a transition, you subclass QAbstractTransition and
  reimplement QAbstractTransition::eventTest(), where you check if an event
  matches your event type (and optionally other criteria, e.g. attributes of
  the event object).

  Here we define our own custom event type, \c StringEvent, for posting
  strings to the state machine:

  \code
    struct StringEvent : public QEvent
    {
        StringEvent(const QString &val)
        : QEvent(QEvent::Type(QEvent::User+1)),
          value(val) {}

        QString value;
    };
  \endcode

  Next, we define a transition that only triggers when the event's string
  matches a particular string (a \e guarded transition):

  \code
    class StringTransition : public QAbstractTransition
    {
    public:
        StringTransition(const QString &value)
            : m_value(value) {}

    protected:
        virtual bool eventTest(QEvent *e) const
        {
            if (e->type() != QEvent::Type(QEvent::User+1)) // StringEvent
                return false;
            StringEvent *se = static_cast<StringEvent*>(e);
            return (m_value == se->value);
        }
    
        virtual void onTransition(QEvent *) {}

    private:
        QString m_value;
    };
  \endcode

  In the eventTest() reimplementation, we first check if the event type is the
  desired one; if so, we cast the event to a StringEvent and perform the
  string comparison.

  The following is a statechart that uses the custom event and transition:

    \img statemachine-customevents.png
    \omit
    \caption This is a caption
    \endomit

  Here's what the implementation of the statechart looks like:

  \code
    QStateMachine machine;
    QState *s1 = new QState();
    QState *s2 = new QState();
    QFinalState *done = new QFinalState();

    StringTransition *t1 = new StringTransition("Hello");
    t1->setTargetState(s2);
    s1->addTransition(t1);
    StringTransition *t2 = new StringTransition("world");
    t2->setTargetState(done);
    s2->addTransition(t2);

    machine.addState(s1);
    machine.addState(s2);
    machine.addState(done);
    machine.setInitialState(s1);
  \endcode

  Once the machine is started, we can post events to it.

  \code
  machine.postEvent(new StringEvent("Hello"));
  machine.postEvent(new StringEvent("world"));
  \endcode
*/