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