source: trunk/doc/src/frameworks-technologies/statemachine.qdoc@ 651

Last change on this file since 651 was 651, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.2 sources.

  • Property svn:eol-style set to native
File size: 25.6 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the documentation of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42/*!
43 \group statemachine
44 \title State Machine Classes
45*/
46
47/*!
48 \page statemachine-api.html
49 \title The State Machine Framework
50 \brief An overview of the State Machine framework for constructing and executing state graphs.
51
52 \ingroup frameworks-technologies
53
54 \tableofcontents
55
56 The State Machine framework provides classes for creating and executing
57 state graphs. The concepts and notation are based on those from Harel's
58 \l{Statecharts: A visual formalism for complex systems}{Statecharts}, which
59 is also the basis of UML state diagrams. The semantics of state machine
60 execution are based on \l{State Chart XML: State Machine Notation for
61 Control Abstraction}{State Chart XML (SCXML)}.
62
63 Statecharts provide a graphical way of modeling how a system reacts to
64 stimuli. This is done by defining the possible \e states that the system can
65 be in, and how the system can move from one state to another (\e transitions
66 between states). A key characteristic of event-driven systems (such as Qt
67 applications) is that behavior often depends not only on the last or current
68 event, but also the events that preceded it. With statecharts, this
69 information is easy to express.
70
71 The State Machine framework provides an API and execution model that can be
72 used to effectively embed the elements and semantics of statecharts in Qt
73 applications. The framework integrates tightly with Qt's meta-object system;
74 for example, transitions between states can be triggered by signals, and
75 states can be configured to set properties and invoke methods on QObjects.
76 Qt's event system is used to drive the state machines.
77
78 The state graph in the State Machine framework is hierarchical. States can be nested inside of
79 other states, and the current configuration of the state machine consists of the set of states
80 which are currently active. All the states in a valid configuration of the state machine will
81 have a common ancestor.
82
83 \section1 Classes in the State Machine Framework
84
85 These classes are provided by qt for creating event-driven state machines.
86
87 \annotatedlist statemachine
88
89 \section1 A Simple State Machine
90
91 To demonstrate the core functionality of the State Machine API, let's look
92 at a small example: A state machine with three states, \c s1, \c s2 and \c
93 s3. The state machine is controlled by a single QPushButton; when the button
94 is clicked, the machine transitions to another state. Initially, the state
95 machine is in state \c s1. The statechart for this machine is as follows:
96
97 \img statemachine-button.png
98 \omit
99 \caption This is a caption
100 \endomit
101
102 The following snippet shows the code needed to create such a state machine.
103 First, we create the state machine and states:
104
105 \snippet doc/src/snippets/statemachine/main.cpp 0
106
107 Then, we create the transitions by using the QState::addTransition()
108 function:
109
110 \snippet doc/src/snippets/statemachine/main.cpp 1
111
112 Next, we add the states to the machine and set the machine's initial state:
113
114 \snippet doc/src/snippets/statemachine/main.cpp 2
115
116 Finally, we start the state machine:
117
118 \snippet doc/src/snippets/statemachine/main.cpp 3
119
120 The state machine executes asynchronously, i.e. it becomes part of your
121 application's event loop.
122
123 \section1 Doing Useful Work on State Entry and Exit
124
125 The above state machine merely transitions from one state to another, it
126 doesn't perform any operations. The QState::assignProperty() function can be
127 used to have a state set a property of a QObject when the state is
128 entered. In the following snippet, the value that should be assigned to a
129 QLabel's text property is specified for each state:
130
131 \snippet doc/src/snippets/statemachine/main.cpp 4
132
133 When any of the states is entered, the label's text will be changed
134 accordingly.
135
136 The QState::entered() signal is emitted when the state is entered, and the
137 QState::exited() signal is emitted when the state is exited. In the
138 following snippet, the button's showMaximized() slot will be called when
139 state \c s3 is entered, and the button's showMinimized() slot will be called
140 when \c s3 is exited:
141
142 \snippet doc/src/snippets/statemachine/main.cpp 5
143
144 Custom states can reimplement QAbstractState::onEntry() and
145 QAbstractState::onExit().
146
147 \section1 State Machines That Finish
148
149 The state machine defined in the previous section never finishes. In order
150 for a state machine to be able to finish, it needs to have a top-level \e
151 final state (QFinalState object). When the state machine enters a top-level
152 final state, the machine will emit the QStateMachine::finished() signal and
153 halt.
154
155 All you need to do to introduce a final state in the graph is create a
156 QFinalState object and use it as the target of one or more transitions.
157
158 \section1 Sharing Transitions By Grouping States
159
160 Assume we wanted the user to be able to quit the application at any time by
161 clicking a Quit button. In order to achieve this, we need to create a final
162 state and make it the target of a transition associated with the Quit
163 button's clicked() signal. We could add a transition from each of \c s1, \c
164 s2 and \c s3; however, this seems redundant, and one would also have to
165 remember to add such a transition from every new state that is added in the
166 future.
167
168 We can achieve the same behavior (namely that clicking the Quit button quits
169 the state machine, regardless of which state the state machine is in) by
170 grouping states \c s1, \c s2 and \c s3. This is done by creating a new
171 top-level state and making the three original states children of the new
172 state. The following diagram shows the new state machine.
173
174 \img statemachine-button-nested.png
175 \omit
176 \caption This is a caption
177 \endomit
178
179 The three original states have been renamed \c s11, \c s12 and \c s13 to
180 reflect that they are now children of the new top-level state, \c s1. Child
181 states implicitly inherit the transitions of their parent state. This means
182 it is now sufficient to add a single transition from \c s1 to the final
183 state \c s2. New states added to \c s1 will also automatically inherit this
184 transition.
185
186 All that's needed to group states is to specify the proper parent when the
187 state is created. You also need to specify which of the child states is the
188 initial one (i.e. which child state the state machine should enter when the
189 parent state is the target of a transition).
190
191 \snippet doc/src/snippets/statemachine/main2.cpp 0
192
193 \snippet doc/src/snippets/statemachine/main2.cpp 1
194
195 In this case we want the application to quit when the state machine is
196 finished, so the machine's finished() signal is connected to the
197 application's quit() slot.
198
199 A child state can override an inherited transition. For example, the
200 following code adds a transition that effectively causes the Quit button to
201 be ignored when the state machine is in state \c s12.
202
203 \snippet doc/src/snippets/statemachine/main2.cpp 2
204
205 A transition can have any state as its target, i.e. the target state does
206 not have to be on the same level in the state hierarchy as the source state.
207
208 \section1 Using History States to Save and Restore the Current State
209
210 Imagine that we wanted to add an "interrupt" mechanism to the example
211 discussed in the previous section; the user should be able to click a button
212 to have the state machine perform some non-related task, after which the
213 state machine should resume whatever it was doing before (i.e. return to the
214 old state, which is one of \c s11, \c s12 and \c s13 in this case).
215
216 Such behavior can easily be modeled using \e{history states}. A history
217 state (QHistoryState object) is a pseudo-state that represents the child
218 state that the parent state was in the last time the parent state was
219 exited.
220
221 A history state is created as a child of the state for which we wish to
222 record the current child state; when the state machine detects the presence
223 of such a state at runtime, it automatically records the current (real)
224 child state when the parent state is exited. A transition to the history
225 state is in fact a transition to the child state that the state machine had
226 previously saved; the state machine automatically "forwards" the transition
227 to the real child state.
228
229 The following diagram shows the state machine after the interrupt mechanism
230 has been added.
231
232 \img statemachine-button-history.png
233 \omit
234 \caption This is a caption
235 \endomit
236
237 The following code shows how it can be implemented; in this example we
238 simply display a message box when \c s3 is entered, then immediately return
239 to the previous child state of \c s1 via the history state.
240
241 \snippet doc/src/snippets/statemachine/main2.cpp 3
242
243 \section1 Using Parallel States to Avoid a Combinatorial Explosion of States
244
245 Assume that you wanted to model a set of mutually exclusive properties of a
246 car in a single state machine. Let's say the properties we are interested in
247 are Clean vs Dirty, and Moving vs Not moving. It would take four mutually
248 exclusive states and eight transitions to be able to represent and freely
249 move between all possible combinations.
250
251 \img statemachine-nonparallel.png
252 \omit
253 \caption This is a caption
254 \endomit
255
256 If we added a third property (say, Red vs Blue), the total number of states
257 would double, to eight; and if we added a fourth property (say, Enclosed vs
258 Convertible), the total number of states would double again, to 16.
259
260 Using parallel states, the total number of states and transitions grows
261 linearly as we add more properties, instead of exponentially. Furthermore,
262 states can be added to or removed from the parallel state without affecting
263 any of their sibling states.
264
265 \img statemachine-parallel.png
266 \omit
267 \caption This is a caption
268 \endomit
269
270 To create a parallel state group, pass QState::ParallelStates to the QState
271 constructor.
272
273 \snippet doc/src/snippets/statemachine/main3.cpp 0
274
275 When a parallel state group is entered, all its child states will be
276 simultaneously entered. Transitions within the individual child states
277 operate normally. However, any of the child states may take a transition which exits the parent
278 state. When this happens, the parent state and all of its child states are exited.
279
280 The parallelism in the State Machine framework follows an interleaved semantics. All parallel
281 operations will be executed in a single, atomic step of the event processing, so no event can
282 interrupt the parallel operations. However, events will still be processed sequentially, since
283 the machine itself is single threaded. As an example: Consider the situation where there are two
284 transitions that exit the same parallel state group, and their conditions become true
285 simultaneously. In this case, the event that is processed last of the two will not have any
286 effect, since the first event will already have caused the machine to exit from the parallel
287 state.
288
289 \section1 Detecting that a Composite State has Finished
290
291 A child state can be final (a QFinalState object); when a final child state
292 is entered, the parent state emits the QState::finished() signal. The
293 following diagram shows a composite state \c s1 which does some processing
294 before entering a final state:
295
296 \img statemachine-finished.png
297 \omit
298 \caption This is a caption
299 \endomit
300
301 When \c s1 's final state is entered, \c s1 will automatically emit
302 finished(). We use a signal transition to cause this event to trigger a
303 state change:
304
305 \snippet doc/src/snippets/statemachine/main3.cpp 1
306
307 Using final states in composite states is useful when you want to hide the
308 internal details of a composite state; i.e. the only thing the outside world
309 should be able to do is enter the state, and get a notification when the
310 state has completed its work. This is a very powerful abstraction and
311 encapsulation mechanism when building complex (deeply nested) state
312 machines. (In the above example, you could of course create a transition
313 directly from \c s1 's \c done state rather than relying on \c s1 's
314 finished() signal, but with the consequence that implementation details of
315 \c s1 are exposed and depended on).
316
317 For parallel state groups, the QState::finished() signal is emitted when \e
318 all the child states have entered final states.
319
320 \section1 Targetless Transitions
321
322 A transition need not have a target state. A transition without a target can
323 be triggered the same way as any other transition; the difference is that
324 when a targetless transition is triggered, it doesn't cause any state
325 changes. This allows you to react to a signal or event when your machine is
326 in a certain state, without having to leave that state. Example:
327
328 \code
329 QStateMachine machine;
330 QState *s1 = new QState(&machine);
331
332 QPushButton button;
333 QSignalTransition *trans = new QSignalTransition(&button, SIGNAL(clicked()));
334 s1->addTransition(trans);
335
336 QMessageBox msgBox;
337 msgBox.setText("The button was clicked; carry on.");
338 QObject::connect(trans, SIGNAL(triggered()), &msgBox, SLOT(exec()));
339
340 machine.setInitialState(s1);
341 \endcode
342
343 The message box will be displayed each time the button is clicked, but the
344 state machine will remain in its current state (s1). If the target state
345 were explicitly set to s1, however, s1 would be exited and re-entered each
346 time (e.g. the QAbstractState::entered() and QAbstractState::exited()
347 signals would be emitted).
348
349 \section1 Events, Transitions and Guards
350
351 A QStateMachine runs its own event loop. For signal transitions
352 (QSignalTransition objects), QStateMachine automatically posts a
353 QStateMachine::SignalEvent to itself when it intercepts the corresponding
354 signal; similarly, for QObject event transitions (QEventTransition objects)
355 a QStateMachine::WrappedEvent is posted.
356
357 You can post your own events to the state machine using
358 QStateMachine::postEvent().
359
360 When posting a custom event to the state machine, you typically also have
361 one or more custom transitions that can be triggered from events of that
362 type. To create such a transition, you subclass QAbstractTransition and
363 reimplement QAbstractTransition::eventTest(), where you check if an event
364 matches your event type (and optionally other criteria, e.g. attributes of
365 the event object).
366
367 Here we define our own custom event type, \c StringEvent, for posting
368 strings to the state machine:
369
370 \snippet doc/src/snippets/statemachine/main4.cpp 0
371
372 Next, we define a transition that only triggers when the event's string
373 matches a particular string (a \e guarded transition):
374
375 \snippet doc/src/snippets/statemachine/main4.cpp 1
376
377 In the eventTest() reimplementation, we first check if the event type is the
378 desired one; if so, we cast the event to a StringEvent and perform the
379 string comparison.
380
381 The following is a statechart that uses the custom event and transition:
382
383 \img statemachine-customevents.png
384 \omit
385 \caption This is a caption
386 \endomit
387
388 Here's what the implementation of the statechart looks like:
389
390 \snippet doc/src/snippets/statemachine/main4.cpp 2
391
392 Once the machine is started, we can post events to it.
393
394 \snippet doc/src/snippets/statemachine/main4.cpp 3
395
396 An event that is not handled by any relevant transition will be silently
397 consumed by the state machine. It can be useful to group states and provide
398 a default handling of such events; for example, as illustrated in the
399 following statechart:
400
401 \img statemachine-customevents2.png
402 \omit
403 \caption This is a caption
404 \endomit
405
406 For deeply nested statecharts, you can add such "fallback" transitions at
407 the level of granularity that's most appropriate.
408
409 \section1 Using Restore Policy To Automatically Restore Properties
410
411 In some state machines it can be useful to focus the attention on assigning properties in states,
412 not on restoring them when the state is no longer active. If you know that a property should
413 always be restored to its initial value when the machine enters a state that does not explicitly
414 give the property a value, you can set the global restore policy to
415 QStateMachine::RestoreProperties.
416
417 \code
418 QStateMachine machine;
419 machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties);
420 \endcode
421
422 When this restore policy is set, the machine will automatically restore all properties. If it
423 enters a state where a given property is not set, it will first search the hierarchy of ancestors
424 to see if the property is defined there. If it is, the property will be restored to the value
425 defined by the closest ancestor. If not, it will be restored to its initial value (i.e. the
426 value of the property before any property assignments in states were executed.)
427
428 Take the following code:
429
430 \snippet doc/src/snippets/statemachine/main5.cpp 0
431
432 Lets say the property \c fooBar is 0.0 when the machine starts. When the machine is in state
433 \c s1, the property will be 1.0, since the state explicitly assigns this value to it. When the
434 machine is in state \c s2, no value is explicitly defined for the property, so it will implicitly
435 be restored to 0.0.
436
437 If we are using nested states, the parent defines a value for the property which is inherited by
438 all descendants that do not explicitly assign a value to the property.
439
440 \snippet doc/src/snippets/statemachine/main5.cpp 2
441
442 Here \c s1 has two children: \c s2 and \c s3. When \c s2 is entered, the property \c fooBar
443 will have the value 2.0, since this is explicitly defined for the state. When the machine is in
444 state \c s3, no value is defined for the state, but \c s1 defines the property to be 1.0, so this
445 is the value that will be assigned to \c fooBar.
446
447 \section1 Animating Property Assignments
448
449 The State Machine API connects with the Animation API in Qt to allow automatically animating
450 properties as they are assigned in states.
451
452 Say we have the following code:
453
454 \snippet doc/src/snippets/statemachine/main5.cpp 3
455
456 Here we define two states of a user interface. In \c s1 the \c button is small, and in \c s2
457 it is bigger. If we click the button to transition from \c s1 to \c s2, the geometry of the button
458 will be set immediately when a given state has been entered. If we want the transition to be
459 smooth, however, all we need to do is make a QPropertyAnimation and add this to the transition
460 object.
461
462 \snippet doc/src/snippets/statemachine/main5.cpp 4
463
464 Adding an animation for the property in question means that the property assignment will no
465 longer take immediate effect when the state has been entered. Instead, the animation will start
466 playing when the state has been entered and smoothly animate the property assignment. Since we
467 do not set the start value or end value of the animation, these will be set implicitly. The
468 start value of the animation will be the property's current value when the animation starts, and
469 the end value will be set based on the property assignments defined for the state.
470
471 If the global restore policy of the state machine is set to QStateMachine::RestoreProperties,
472 it is possible to also add animations for the property restorations.
473
474 \section1 Detecting That All Properties Have Been Set In A State
475
476 When animations are used to assign properties, a state no longer defines the exact values that a
477 property will have when the machine is in the given state. While the animation is running, the
478 property can potentially have any value, depending on the animation.
479
480 In some cases, it can be useful to be able to detect when the property has actually been assigned
481 the value defined by a state.
482
483 Say we have the following code:
484
485 \snippet doc/src/snippets/statemachine/main5.cpp 5
486
487 When \c button is clicked, the machine will transition into state \c s2, which will set the
488 geometry of the button, and then pop up a message box to alert the user that the geometry has
489 been changed.
490
491 In the normal case, where animations are not used, this will operate as expected. However, if
492 an animation for the \c geometry of \c button is set on the transition between \c s1 and \c s2,
493 the animation will be started when \c s2 is entered, but the \c geometry property will not
494 actually reach its defined value before the animation is finished running. In this case, the
495 message box will pop up before the geometry of the button has actually been set.
496
497 To ensure that the message box does not pop up until the geometry actually reaches its final
498 value, we can use the state's propertiesAssigned() signal. The propertiesAssigned() signal will be
499 emitted when the property is assigned its final value, whether this is done immediately or
500 after the animation has finished playing.
501
502 \snippet doc/src/snippets/statemachine/main5.cpp 6
503
504 In this example, when \c button is clicked, the machine will enter \c s2. It will remain in state
505 \c s2 until the \c geometry property has been set to \c QRect(0, 0, 50, 50). Then it will
506 transition into \c s3. When \c s3 is entered, the message box will pop up. If the transition into
507 \c s2 has an animation for the \c geometry property, then the machine will stay in \c s2 until the
508 animation has finished playing. If there is no such animation, it will simply set the property and
509 immediately enter state \c s3.
510
511 Either way, when the machine is in state \c s3, you are guaranteed that the property \c geometry
512 has been assigned the defined value.
513
514 If the global restore policy is set to QStateMachine::RestoreProperties, the state will not emit
515 the propertiesAssigned() signal until these have been executed as well.
516
517 \section1 What Happens If A State Is Exited Before The Animation Has Finished
518
519 If a state has property assignments, and the transition into the state has animations for the
520 properties, the state can potentially be exited before the properties have been assigned to the
521 values defines by the state. This is true in particular when there are transitions out from the
522 state that do not depend on the propertiesAssigned signal, as described in the previous section.
523
524 The State Machine API guarantees that a property assigned by the state machine either:
525 \list
526 \o Has a value explicitly assigned to the property.
527 \o Is currently being animated into a value explicitly assigned to the property.
528 \endlist
529
530 When a state is exited prior to the animation finishing, the behavior of the state machine depends
531 on the target state of the transition. If the target state explicitly assigns a value to the
532 property, no additional action will be taken. The property will be assigned the value defined by
533 the target state.
534
535 If the target state does not assign any value to the property, there are two
536 options: By default, the property will be assigned the value defined by the state it is leaving
537 (the value it would have been assigned if the animation had been permitted to finish playing). If
538 a global restore policy is set, however, this will take precedence, and the property will be
539 restored as usual.
540
541 \section1 Default Animations
542
543 As described earlier, you can add animations to transitions to make sure property assignments
544 in the target state are animated. If you want a specific animation to be used for a given property
545 regardless of which transition is taken, you can add it as a default animation to the state
546 machine. This is in particular useful when the properties assigned (or restored) by specific
547 states is not known when the machine is constructed.
548
549 \code
550 QState *s1 = new QState();
551 QState *s2 = new QState();
552
553 s2->assignProperty(object, "fooBar", 2.0);
554 s1->addTransition(s2);
555
556 QStateMachine machine;
557 machine.setInitialState(s1);
558 machine.addDefaultAnimation(new QPropertyAnimation(object, "fooBar"));
559 \endcode
560
561 When the machine is in state \c s2, the machine will play the default animation for the
562 property \c fooBar since this property is assigned by \c s2.
563
564 Note that animations explicitly set on transitions will take precedence over any default
565 animation for the given property.
566*/
Note: See TracBrowser for help on using the repository browser.