summaryrefslogtreecommitdiffstats
path: root/src/scxml/qscxmlstatemachine.cpp
blob: 04d3726c20cd98379be3dd8724d88ed199a59ae6 (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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qscxmlstatemachine_p.h"
#include "qscxmlexecutablecontent_p.h"
#include "qscxmlevent_p.h"
#include "qscxmlinvokableservice.h"
#include "qscxmldatamodel_p.h"

#include <qfile.h>
#include <qhash.h>
#include <qloggingcategory.h>
#include <qstring.h>
#include <qtimer.h>
#include <qthread.h>

#include <functional>

QT_BEGIN_NAMESPACE

Q_LOGGING_CATEGORY(qscxmlLog, "qt.scxml.statemachine")
Q_LOGGING_CATEGORY(scxmlLog, "scxml.statemachine")

/*!
 * \class QScxmlStateMachine
 * \brief The QScxmlStateMachine class provides an interface to the state machines
 * created from SCXML files.
 * \since 5.7
 * \inmodule QtScxml
 *
 * QScxmlStateMachine is an implementation of the
 * \l{SCXML Specification}{State Chart XML (SCXML)}.
 *
 * All states that are defined in the SCXML file
 * are accessible as properties of QScxmlStateMachine.
 * These properties are boolean values and indicate
 * whether the state is active or inactive.
 *
 * \note The QScxmlStateMachine needs a QEventLoop to work correctly. The event loop is used to
 *       implement the \c delay attribute for events and to schedule the processing of a state
 *       machine when events are received from nested (or parent) state machines.
 */

/*!
    \qmltype ScxmlStateMachine
    \instantiates QScxmlStateMachine
    \inqmlmodule QtScxml
    \since 5.7

    \brief Provides an interface to the state machines created from SCXML files.

    The ScxmlStateMachine type is an implementation of the
    \l{SCXML Specification}{State Chart XML (SCXML)}.

    All states that are defined in the SCXML file are accessible as properties
    of this type. These properties are boolean values and indicate whether the
    state is active or inactive.
*/

/*!
    \fn template<typename Functor> QMetaObject::Connection QScxmlStateMachine::connectToEvent(
            const QString &scxmlEventSpec,
            const QObject *context,
            Functor &&functor,
            Qt::ConnectionType type)
    \fn template<typename Functor> QMetaObject::Connection QScxmlStateMachine::connectToEvent(
            const QString &scxmlEventSpec,
            Functor &&functor,
            Qt::ConnectionType type)

    Creates a connection of the given \a type from the event specified by
    \a scxmlEventSpec to \a functor, which can be a functor or a member function of
    the optional \a context object.

    The receiver's \a functor must take a QScxmlEvent as a parameter.

    In contrast to event specifications in SCXML documents, spaces are not
    allowed in the \a scxmlEventSpec here. In order to connect to multiple
    events with different prefixes, connectToEvent() has to be called multiple
    times.

    Returns a handle to the connection, which can be used later to disconnect.
*/

/*!
    \fn template<typename Functor> QMetaObject::Connection QScxmlStateMachine::connectToState(
            const QString &scxmlStateName,
            const QObject *context,
            Functor &&functor,
            Qt::ConnectionType type)
    \fn template<typename Functor> QMetaObject::Connection QScxmlStateMachine::connectToState(
            const QString &scxmlStateName,
            Functor &&functor,
            Qt::ConnectionType type)

    Creates a connection of the given \a type from the state specified by
    \a scxmlStateName to \a functor, which can be a functor or a member function of
    the optional \a context object.

    The receiver's \a functor must take a boolean argument that indicates
    whether the state connected became active or inactive.

    Returns a handle to the connection, which can be used later to disconnect.
*/

/*!
    \fn [onentry] std::function<void(bool)> QScxmlStateMachine::onEntry(
            const QObject *receiver, const char *method)

    Returns a functor that accepts a boolean argument and calls the given
    \a method on \a receiver using QMetaObject::invokeMethod() if that argument
    is \c true and \a receiver has not been deleted, yet.

    The given \a method must not accept any arguments. \a method is the plain
    method name, not enclosed in \c SIGNAL() or \c SLOT().

    This is useful to wrap handlers for connectToState() that should only
    be executed when the state is entered.
 */

/*!
    \fn [onexit] std::function<void(bool)> QScxmlStateMachine::onExit(
            const QObject *receiver, const char *method)

    Returns a functor that accepts a boolean argument and calls the given
    \a method on \a receiver using QMetaObject::invokeMethod() if that argument
    is \c false and \a receiver has not been deleted, yet.

    The given \a method must not accept any arguments. \a method is the plain
    method name, not enclosed in SIGNAL(...) or SLOT(...).

    This is useful to wrap handlers for connectToState() that should only
    be executed when the state is left.
 */

/*!
    \fn [onentry-functor] template<typename Functor> std::function<void(bool)> QScxmlStateMachine::onEntry(
            Functor functor)

    Returns a functor that accepts a boolean argument and calls the given
    \a functor if that argument is \c true. The given \a functor must not
    accept any arguments.

    This is useful to wrap handlers for connectToState() that should only
    be executed when the state is entered.
 */

/*!
    \fn [onexit-functor] template<typename Functor> std::function<void(bool)> QScxmlStateMachine::onExit(Functor functor)

    Returns a functor that accepts a boolean argument and calls the given
    \a functor if that argument is \c false. The given \a functor must not
    accept any arguments.

    This is useful to wrap handlers for connectToState() that should only
    be executed when the state is left.
 */

/*!
    \fn [onentry-template] template<typename PointerToMemberFunction> std::function<void(bool)> QScxmlStateMachine::onEntry(
            const typename QtPrivate::FunctionPointer<PointerToMemberFunction>::Object *receiver,
            PointerToMemberFunction method)

    Returns a functor that accepts a boolean argument and calls the given
    \a method on \a receiver if that argument is \c true and the \a receiver
    has not been deleted, yet. The given \a method must not accept any
    arguments.

    This is useful to wrap handlers for connectToState() that should only
    be executed when the state is entered.
 */

/*!
    \fn [onexit-template] template<typename PointerToMemberFunction> std::function<void(bool)> QScxmlStateMachine::onExit(
            const typename QtPrivate::FunctionPointer<PointerToMemberFunction>::Object *receiver,
            PointerToMemberFunction method)

    Returns a functor that accepts a boolean argument and calls the given
    \a method on \a receiver if that argument is \c false and the \a receiver
    has not been deleted, yet. The given \a method must not accept any
    arguments.

    This is useful to wrap handlers for connectToState() that should only
    be executed when the state is left.
 */

namespace QScxmlInternal {

static int signalIndex(const QMetaObject *meta, const QByteArray &signalName)
{
    Q_ASSERT(meta);

    int signalIndex = meta->indexOfSignal(signalName.constData());

    // If signal doesn't exist, return negative value
    if (signalIndex < 0)
        return signalIndex;

    // signal belongs to class whose meta object was passed, not some derived class.
    Q_ASSERT(meta->methodOffset() <= signalIndex);

    // Duplicate of computeOffsets in qobject.cpp
    const QMetaObject *m = meta->d.superdata;
    while (m) {
        const QMetaObjectPrivate *d = QMetaObjectPrivate::get(m);
        signalIndex = signalIndex - d->methodCount + d->signalCount;
        m = m->d.superdata;
    }

    // Asserting about the signal not being cloned would be nice, too, but not practical.

    return signalIndex;
}

void EventLoopHook::queueProcessEvents()
{
    if (smp->m_isProcessingEvents)
        return;

    QMetaObject::invokeMethod(this, "doProcessEvents", Qt::QueuedConnection);
}

void EventLoopHook::doProcessEvents()
{
    smp->processEvents();
}

void EventLoopHook::timerEvent(QTimerEvent *timerEvent)
{
    const int timerId = timerEvent->timerId();
    for (auto it = smp->m_delayedEvents.begin(), eit = smp->m_delayedEvents.end(); it != eit; ++it) {
        if (it->first == timerId) {
            QScxmlEvent *scxmlEvent = it->second;
            smp->m_delayedEvents.erase(it);
            smp->routeEvent(scxmlEvent);
            killTimer(timerId);
            return;
        }
    }
}

void ScxmlEventRouter::route(const QStringList &segments, QScxmlEvent *event)
{
    emit eventOccurred(*event);
    if (!segments.isEmpty()) {
        auto it = children.find(segments.first());
        if (it != children.end())
            it.value()->route(segments.mid(1), event);
    }
}

static QString nextSegment(const QStringList &segments)
{
    if (segments.isEmpty())
        return QString();

    const QString &segment = segments.first();
    return segment == QLatin1String("*") ? QString() : segment;
}

ScxmlEventRouter *ScxmlEventRouter::child(const QString &segment)
{
    ScxmlEventRouter *&child = children[segment];
    if (child == nullptr)
        child = new ScxmlEventRouter(this);
    return child;
}

void ScxmlEventRouter::disconnectNotify(const QMetaMethod &signal)
{
    Q_UNUSED(signal);

    // Defer the actual work, as this may be called from a destructor, or the signal may not
    // actually be disconnected, yet.
    QTimer::singleShot(0, this, [this] {
        if (!children.isEmpty() || receivers(SIGNAL(eventOccurred(QScxmlEvent))) > 0)
            return;

        ScxmlEventRouter *parentRouter = qobject_cast<ScxmlEventRouter *>(parent());
        if (!parentRouter) // root node
            return;

        QHash<QString, ScxmlEventRouter *>::Iterator it = parentRouter->children.begin(),
                end = parentRouter->children.end();
        for (; it != end; ++it) {
            if (it.value() == this) {
                parentRouter->children.erase(it);
                parentRouter->disconnectNotify(QMetaMethod());
                break;
            }
        }

        deleteLater(); // The parent might delete itself, triggering QObject delete cascades.
    });
}

QMetaObject::Connection ScxmlEventRouter::connectToEvent(const QStringList &segments,
                                                         const QObject *receiver,
                                                         const char *method,
                                                         Qt::ConnectionType type)
{
    QString segment = nextSegment(segments);
    return segment.isEmpty() ?
                connect(this, SIGNAL(eventOccurred(QScxmlEvent)), receiver, method, type) :
                child(segment)->connectToEvent(segments.mid(1), receiver, method, type);
}

QMetaObject::Connection ScxmlEventRouter::connectToEvent(const QStringList &segments,
                                                         const QObject *receiver, void **slot,
                                                         QtPrivate::QSlotObjectBase *method,
                                                         Qt::ConnectionType type)
{
    QString segment = nextSegment(segments);
    if (segment.isEmpty()) {
        const int *types = nullptr;
        if (type == Qt::QueuedConnection || type == Qt::BlockingQueuedConnection)
            types = QtPrivate::ConnectionTypes<QtPrivate::List<QScxmlEvent> >::types();

        const QMetaObject *meta = metaObject();
        static const int eventOccurredIndex = signalIndex(meta, "eventOccurred(QScxmlEvent)");
        return QObjectPrivate::connectImpl(this, eventOccurredIndex, receiver, slot, method, type,
                                           types, meta);
    } else {
        return child(segment)->connectToEvent(segments.mid(1), receiver, slot, method, type);
    }
}

} // namespace QScxmlInternal

QAtomicInt QScxmlStateMachinePrivate::m_sessionIdCounter = QAtomicInt(0);

QScxmlStateMachinePrivate::QScxmlStateMachinePrivate(const QMetaObject *metaObject)
    : QObjectPrivate()
    , m_sessionId(QScxmlStateMachinePrivate::generateSessionId(QStringLiteral("session-")))
    , m_isInvoked(false)
    , m_isProcessingEvents(false)
    , m_executionEngine(nullptr)
    , m_parentStateMachine(nullptr)
    , m_eventLoopHook(this)
    , m_metaObject(metaObject)
    , m_infoSignalProxy(nullptr)
{
    static int metaType = qRegisterMetaType<QScxmlStateMachine *>();
    Q_UNUSED(metaType);
    m_loader.setValueBypassingBindings(&m_defaultLoader);
}

QScxmlStateMachinePrivate::~QScxmlStateMachinePrivate()
{
    for (const InvokedService &invokedService : m_invokedServices)
        delete invokedService.service;
    qDeleteAll(m_cachedFactories);
    delete m_executionEngine;
}

QScxmlStateMachinePrivate::ParserData *QScxmlStateMachinePrivate::parserData()
{
    if (m_parserData.isNull())
        m_parserData.reset(new ParserData);
    return m_parserData.data();
}

void QScxmlStateMachinePrivate::addService(int invokingState)
{
    Q_Q(QScxmlStateMachine);

    const int arrayId = m_stateTable->state(invokingState).serviceFactoryIds;
    if (arrayId == StateTable::InvalidIndex)
        return;

    const auto &ids = m_stateTable->array(arrayId);
    for (int id : ids) {
        auto factory = serviceFactory(id);
        auto service = factory->invoke(q);
        if (service == nullptr)
            continue; // service failed to start
        const QString serviceName = service->name();
        m_invokedServices[size_t(id)] = { invokingState, service, serviceName };
        service->start();
    }
    emitInvokedServicesChanged();
}

void QScxmlStateMachinePrivate::removeService(int invokingState)
{
    const int arrayId = m_stateTable->state(invokingState).serviceFactoryIds;
    if (arrayId == StateTable::InvalidIndex)
        return;

    for (size_t i = 0, ei = m_invokedServices.size(); i != ei; ++i) {
        auto &it = m_invokedServices[i];
        QScxmlInvokableService *service = it.service;
        if (it.invokingState == invokingState && service != nullptr) {
            it.service = nullptr;
            delete service;
        }
    }
    emitInvokedServicesChanged();
}

QScxmlInvokableServiceFactory *QScxmlStateMachinePrivate::serviceFactory(int id)
{
    Q_ASSERT(id <= m_stateTable->maxServiceId && id >= 0);
    QScxmlInvokableServiceFactory *& factory = m_cachedFactories[size_t(id)];
    if (factory == nullptr)
        factory = m_tableData.value()->serviceFactory(id);
    return factory;
}

bool QScxmlStateMachinePrivate::executeInitialSetup()
{
    return m_executionEngine->execute(m_tableData.value()->initialSetup());
}

void QScxmlStateMachinePrivate::routeEvent(QScxmlEvent *event)
{
    Q_Q(QScxmlStateMachine);

    if (!event)
        return;

    QString origin = event->origin();
    if (origin == QStringLiteral("#_parent")) {
        if (auto psm = m_parentStateMachine) {
            qCDebug(qscxmlLog) << q << "routing event" << event->name() << "from" << q->name() << "to parent" << psm->name();
                                 QScxmlStateMachinePrivate::get(psm)->postEvent(event);
        } else {
            qCDebug(qscxmlLog) << this << "is not invoked, so it cannot route a message to #_parent";
            delete event;
        }
    } else if (origin.startsWith(QStringLiteral("#_")) && origin != QStringLiteral("#_internal")) {
        // route to children
        auto originId = QStringView{origin}.mid(2);
        for (const auto &invokedService : m_invokedServices) {
            auto service = invokedService.service;
            if (service == nullptr)
                continue;
            if (service->id() == originId) {
                qCDebug(qscxmlLog) << q << "routing event" << event->name()
                                   << "from" << q->name()
                                   << "to child" << service->id();
                service->postEvent(new QScxmlEvent(*event));
            }
        }
        delete event;
    } else {
        postEvent(event);
    }
}

void QScxmlStateMachinePrivate::postEvent(QScxmlEvent *event)
{
    Q_Q(QScxmlStateMachine);

    if (!event->name().startsWith(QStringLiteral("done.invoke."))) {
        for (int id = 0, end = static_cast<int>(m_invokedServices.size()); id != end; ++id) {
            auto service = m_invokedServices[id].service;
            if (service == nullptr)
                continue;
            auto factory = serviceFactory(id);
            if (event->invokeId() == service->id()) {
                setEvent(event);

                const QScxmlExecutableContent::ContainerId finalize
                        = factory->invokeInfo().finalize;
                if (finalize != QScxmlExecutableContent::NoContainer) {
                    auto psm = service->parentStateMachine();
                    qCDebug(qscxmlLog) << psm << "running finalize on event";
                    auto smp = QScxmlStateMachinePrivate::get(psm);
                    smp->m_executionEngine->execute(finalize);
                }

                resetEvent();
            }
            if (factory->invokeInfo().autoforward) {
                qCDebug(qscxmlLog) << q << "auto-forwarding event" << event->name()
                                   << "from" << q->name()
                                   << "to child" << service->id();
                service->postEvent(new QScxmlEvent(*event));
            }
        }
    }

    if (event->eventType() == QScxmlEvent::ExternalEvent)
        m_router.route(event->name().split(QLatin1Char('.')), event);

    if (event->eventType() == QScxmlEvent::ExternalEvent) {
        qCDebug(qscxmlLog) << q << "posting external event" << event->name();
        m_externalQueue.enqueue(event);
    } else {
        qCDebug(qscxmlLog) << q << "posting internal event" << event->name();
        m_internalQueue.enqueue(event);
    }

    m_eventLoopHook.queueProcessEvents();
}

void QScxmlStateMachinePrivate::submitDelayedEvent(QScxmlEvent *event)
{
    Q_ASSERT(event);
    Q_ASSERT(event->delay() > 0);

    const int timerId = m_eventLoopHook.startTimer(event->delay());
    if (timerId == 0) {
        qWarning("QScxmlStateMachinePrivate::submitDelayedEvent: "
                 "failed to start timer for event '%s' (%p)",
                 qPrintable(event->name()), event);
        delete event;
        return;
    }
    m_delayedEvents.push_back(std::make_pair(timerId, event));

    qCDebug(qscxmlLog) << q_func()
                       << ": delayed event" << event->name()
                       << "(" << event << ") got id:" << timerId;
}

/*!
 * Submits an error event to the external event queue of this state machine.
 *
 * The type of the error is specified by \a type. The value of type has to begin
 * with the string \e error. For example \c {error.execution}. The message,
 * \a message, decribes the error and is passed to the event as the
 * \c errorMessage property. The \a sendId of the message causing the error is specified, if it has
 * one.
 */
void QScxmlStateMachinePrivate::submitError(const QString &type, const QString &message,
                                            const QString &sendId)
{
    Q_Q(QScxmlStateMachine);
    qCDebug(qscxmlLog) << q << "had error" << type << ":" << message;
    if (!type.startsWith(QStringLiteral("error.")))
        qCWarning(qscxmlLog) << q << "Message type of error message does not start with 'error.'!";
    q->submitEvent(QScxmlEventBuilder::errorEvent(q, type, message, sendId));
}

void QScxmlStateMachinePrivate::start()
{
    Q_Q(QScxmlStateMachine);

    if (m_stateTable->binding == StateTable::LateBinding)
        m_isFirstStateEntry.resize(m_stateTable->stateCount, true);

    bool running = isRunnable() && !isPaused();
    m_runningState = Starting;
    Q_ASSERT(m_stateTable->initialTransition != StateTable::InvalidIndex);

    if (!running)
        emit q->runningChanged(true);
}

void QScxmlStateMachinePrivate::pause()
{
    Q_Q(QScxmlStateMachine);

    if (isRunnable() && !isPaused()) {
        m_runningState = Paused;
        emit q->runningChanged(false);
    }
}

void QScxmlStateMachinePrivate::processEvents()
{
    if (m_isProcessingEvents || (!isRunnable() && !isPaused()))
        return;

    m_isProcessingEvents = true;

    Q_Q(QScxmlStateMachine);
    qCDebug(qscxmlLog) << q_func() << "starting macrostep";

    while (isRunnable() && !isPaused()) {
        if (m_runningState == Starting) {
            enterStates({m_stateTable->initialTransition});
            if (m_runningState == Starting)
                m_runningState = Running;
            continue;
        }

        OrderedSet enabledTransitions;
        std::vector<int> configurationInDocumentOrder = m_configuration.list();
        std::sort(configurationInDocumentOrder.begin(), configurationInDocumentOrder.end());
        selectTransitions(enabledTransitions, configurationInDocumentOrder, nullptr);
        if (!enabledTransitions.isEmpty()) {
            microstep(enabledTransitions);
        } else if (!m_internalQueue.isEmpty()) {
            auto event = m_internalQueue.dequeue();
            setEvent(event);
            selectTransitions(enabledTransitions, configurationInDocumentOrder, event);
            if (!enabledTransitions.isEmpty()) {
                microstep(enabledTransitions);
            }
            resetEvent();
            delete event;
        } else if (!m_externalQueue.isEmpty()) {
            auto event = m_externalQueue.dequeue();
            setEvent(event);
            selectTransitions(enabledTransitions, configurationInDocumentOrder, event);
            if (!enabledTransitions.isEmpty()) {
                microstep(enabledTransitions);
            }
            resetEvent();
            delete event;
        } else {
            // nothing to do, so:
            break;
        }
    }

    if (!m_statesToInvoke.empty()) {
        for (int stateId : m_statesToInvoke)
            addService(stateId);
        m_statesToInvoke.clear();
    }

    qCDebug(qscxmlLog) << q_func()
                       << "finished macrostep, runnable:" << isRunnable()
                       << "paused:" << isPaused();
    emit q->reachedStableState();
    if (!isRunnable() && !isPaused()) {
        exitInterpreter();
        emit q->finished();
    }

    m_isProcessingEvents = false;
}

void QScxmlStateMachinePrivate::setEvent(QScxmlEvent *event)
{
    Q_ASSERT(event);
    m_dataModel.value()->setScxmlEvent(*event);
}

void QScxmlStateMachinePrivate::resetEvent()
{
    m_dataModel.value()->setScxmlEvent(QScxmlEvent());
}

void QScxmlStateMachinePrivate::emitStateActive(int stateIndex, bool active)
{
    Q_Q(QScxmlStateMachine);
    void *args[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&active)) };
    const int signalIndex = m_stateIndexToSignalIndex.value(stateIndex, -1);
    if (signalIndex >= 0)
        QMetaObject::activate(q, m_metaObject, signalIndex, args);
}

void QScxmlStateMachinePrivate::emitInvokedServicesChanged()
{
    Q_Q(QScxmlStateMachine);
    m_invokedServicesComputedProperty.notify();
    emit q->invokedServicesChanged(q->invokedServices());
}

void QScxmlStateMachinePrivate::attach(QScxmlStateMachineInfo *info)
{
    Q_Q(QScxmlStateMachine);

    if (!m_infoSignalProxy)
        m_infoSignalProxy = new QScxmlInternal::StateMachineInfoProxy(q);

    QObject::connect(m_infoSignalProxy, &QScxmlInternal::StateMachineInfoProxy::statesEntered,
                     info, &QScxmlStateMachineInfo::statesEntered);
    QObject::connect(m_infoSignalProxy, &QScxmlInternal::StateMachineInfoProxy::statesExited,
                     info, &QScxmlStateMachineInfo::statesExited);
    QObject::connect(m_infoSignalProxy,&QScxmlInternal::StateMachineInfoProxy::transitionsTriggered,
                     info, &QScxmlStateMachineInfo::transitionsTriggered);
}

void QScxmlStateMachinePrivate::updateMetaCache()
{
    // This function creates a mapping from state index/name to their signal indexes.
    // The state index may differ from its signal index as we don't generate history
    // and invalid states, effectively skipping them
    m_stateIndexToSignalIndex.clear();
    m_stateNameToSignalIndex.clear();

    const QScxmlTableData *tableData = m_tableData.valueBypassingBindings();
    if (!tableData)
        return;

    if (!m_stateTable)
        return;

    int signalIndex = 0;
    const int methodOffset = QMetaObjectPrivate::signalOffset(m_metaObject);
    for (int i = 0; i < m_stateTable->stateCount; ++i) {
        const auto &s = m_stateTable->state(i);
        if (!s.isHistoryState() && s.type != StateTable::State::Invalid) {
            m_stateIndexToSignalIndex.insert(i, signalIndex);
            m_stateNameToSignalIndex.insert(tableData->string(s.name),
                                            signalIndex + methodOffset);

            ++signalIndex;
        }
    }
}

QStringList QScxmlStateMachinePrivate::stateNames(const std::vector<int> &stateIndexes) const
{
    QStringList names;
    for (int idx : stateIndexes)
        names.append(m_tableData.value()->string(m_stateTable->state(idx).name));
    return names;
}

std::vector<int> QScxmlStateMachinePrivate::historyStates(int stateIdx) const {
    const StateTable::Array kids = m_stateTable->array(m_stateTable->state(stateIdx).childStates);
    std::vector<int> res;
    if (!kids.isValid()) return res;
    for (int k : kids) {
        if (m_stateTable->state(k).isHistoryState())
            res.push_back(k);
    }
    return res;
}

void QScxmlStateMachinePrivate::exitInterpreter()
{
    qCDebug(qscxmlLog) << q_func() << "exiting SCXML processing";

    for (auto it : m_delayedEvents) {
        m_eventLoopHook.killTimer(it.first);
        delete it.second;
    }
    m_delayedEvents.clear();

    auto statesToExitSorted = m_configuration.list();
    std::sort(statesToExitSorted.begin(), statesToExitSorted.end(), std::greater<int>());
    for (int stateIndex : statesToExitSorted) {
        const auto &state = m_stateTable->state(stateIndex);
        if (state.exitInstructions != StateTable::InvalidIndex) {
            m_executionEngine->execute(state.exitInstructions);
        }
        removeService(stateIndex);
        if (state.type == StateTable::State::Final && state.parentIsScxmlElement()) {
            returnDoneEvent(state.doneData);
        }
    }
}

void QScxmlStateMachinePrivate::returnDoneEvent(QScxmlExecutableContent::ContainerId doneData)
{
    Q_Q(QScxmlStateMachine);

    m_executionEngine->execute(doneData, QVariant());
    if (m_isInvoked) {
        auto e = new QScxmlEvent;
        e->setName(QStringLiteral("done.invoke.") + q->sessionId());
        e->setInvokeId(q->sessionId());
        QScxmlStateMachinePrivate::get(m_parentStateMachine)->postEvent(e);
    }
}

bool QScxmlStateMachinePrivate::nameMatch(const StateTable::Array &patterns,
                                          QScxmlEvent *event) const
{
    const QString eventName = event->name();
    bool selected = false;
    for (int eventSelectorIter = 0; eventSelectorIter < patterns.size(); ++eventSelectorIter) {
        QString eventStr = m_tableData.value()->string(patterns[eventSelectorIter]);
        if (eventStr == QStringLiteral("*")) {
            selected = true;
            break;
        }
        if (eventStr.endsWith(QStringLiteral(".*")))
            eventStr.chop(2);
        if (eventName.startsWith(eventStr)) {
            QChar nextC = QLatin1Char('.');
            if (eventName.size() > eventStr.size())
                nextC = eventName.at(eventStr.size());
            if (nextC == QLatin1Char('.') || nextC == QLatin1Char('(')) {
                selected = true;
                break;
            }
        }
    }
    return selected;
}

void QScxmlStateMachinePrivate::selectTransitions(OrderedSet &enabledTransitions,
                                                  const std::vector<int> &configInDocumentOrder,
                                                  QScxmlEvent *event) const
{
    if (event == nullptr) {
        qCDebug(qscxmlLog) << q_func() << "selectEventlessTransitions";
    } else {
        qCDebug(qscxmlLog) << q_func() << "selectTransitions with event"
                           << QScxmlEventPrivate::debugString(event).constData();
    }

    std::vector<int> states;
    states.reserve(16);
    for (int configStateIdx : configInDocumentOrder) {
        if (m_stateTable->state(configStateIdx).isAtomic()) {
            states.clear();
            states.push_back(configStateIdx);
            getProperAncestors(&states, configStateIdx, -1);
            for (int stateIdx : states) {
                bool finishedWithThisConfigState  = false;

                if (stateIdx == -1) {
                    // the state machine has no transitions (other than the initial one, which has
                    // already been taken at this point)
                    continue;
                }
                const auto &state = m_stateTable->state(stateIdx);
                const StateTable::Array transitions = m_stateTable->array(state.transitions);
                if (!transitions.isValid())
                    continue;
                std::vector<int> sortedTransitions(transitions.size(), -1);
                std::copy(transitions.begin(), transitions.end(), sortedTransitions.begin());
                for (int transitionIndex : sortedTransitions) {
                    const StateTable::Transition &t = m_stateTable->transition(transitionIndex);
                    bool enabled = false;
                    if (event == nullptr) {
                        if (t.events == -1) {
                            if (t.condition == -1) {
                                enabled = true;
                            } else {
                                bool ok = false;
                                enabled = m_dataModel.value()->evaluateToBool(t.condition, &ok) && ok;
                            }
                        }
                    } else {
                        if (t.events != -1 && nameMatch(m_stateTable->array(t.events), event)) {
                            if (t.condition == -1) {
                                enabled = true;
                            } else {
                                bool ok = false;
                                enabled = m_dataModel.value()->evaluateToBool(t.condition, &ok) && ok;
                            }
                        }
                    }
                    if (enabled) {
                        enabledTransitions.add(transitionIndex);
                        finishedWithThisConfigState = true;
                        break; // stop iterating over transitions
                    }
                }

                if (finishedWithThisConfigState)
                    break; // stop iterating over ancestors
            }
        }
    }
    if (!enabledTransitions.isEmpty())
        removeConflictingTransitions(&enabledTransitions);
}

void QScxmlStateMachinePrivate::removeConflictingTransitions(OrderedSet *enabledTransitions) const
{
    Q_ASSERT(enabledTransitions);

    auto sortedTransitions = enabledTransitions->takeList();
    std::sort(sortedTransitions.begin(), sortedTransitions.end(), [this](int t1, int t2) -> bool {
        auto descendantDepth = [this](int state, int ancestor)->int {
            int depth = 0;
            for (int it = state; it != -1; it = m_stateTable->state(it).parent) {
                if (it == ancestor)
                    break;
                ++depth;
            }
            return depth;
        };

        const auto &s1 = m_stateTable->transition(t1).source;
        const auto &s2 = m_stateTable->transition(t2).source;
        if (s1 == s2) {
            return t1 < t2;
        } else if (isDescendant(s1, s2)) {
            return true;
        } else if (isDescendant(s2, s1)) {
            return false;
        } else {
            const int lcca = findLCCA({ s1, s2 });
            const int s1Depth = descendantDepth(s1, lcca);
            const int s2Depth = descendantDepth(s2, lcca);
            if (s1Depth == s2Depth)
                return s1 < s2;
            else
                return s1Depth > s2Depth;
        }
    });

    OrderedSet filteredTransitions;
    for (int t1 : sortedTransitions) {
        OrderedSet transitionsToRemove;
        bool t1Preempted = false;
        OrderedSet exitSetT1;
        computeExitSet({t1}, exitSetT1);
        const int source1 = m_stateTable->transition(t1).source;
        for (int t2 : filteredTransitions) {
            OrderedSet exitSetT2;
            computeExitSet({t2}, exitSetT2);
            if (exitSetT1.intersectsWith(exitSetT2)) {
                const int source2 = m_stateTable->transition(t2).source;
                if (isDescendant(source1, source2)) {
                    transitionsToRemove.add(t2);
                } else {
                    t1Preempted = true;
                    break;
                }
            }
        }
        if (!t1Preempted) {
            for (int t3 : transitionsToRemove) {
                filteredTransitions.remove(t3);
            }
            filteredTransitions.add(t1);
        }
    }
    *enabledTransitions = filteredTransitions;
}

void QScxmlStateMachinePrivate::getProperAncestors(std::vector<int> *ancestors, int state1,
                                                   int state2) const
{
    Q_ASSERT(ancestors);

    if (state1 == -1) {
        return;
    }

    int parent = state1;
    do {
        parent = m_stateTable->state(parent).parent;
        if (parent == state2) {
            break;
        }
        ancestors->push_back(parent);
    } while (parent != -1);
}

void QScxmlStateMachinePrivate::microstep(const OrderedSet &enabledTransitions)
{
    if (qscxmlLog().isDebugEnabled()) {
        qCDebug(qscxmlLog) << q_func()
                           << "starting microstep, configuration:"
                           << stateNames(m_configuration.list());
        qCDebug(qscxmlLog) << q_func() << "enabled transitions:";
        for (int t : enabledTransitions) {
            const auto &transition = m_stateTable->transition(t);
            QString from = QStringLiteral("(none)");
            if (transition.source != StateTable::InvalidIndex)
                from = m_tableData.value()->string(m_stateTable->state(transition.source).name);
            QStringList to;
            if (transition.targets == StateTable::InvalidIndex) {
                to.append(QStringLiteral("(none)"));
            } else {
                for (int t : m_stateTable->array(transition.targets))
                    to.append(m_tableData.value()->string(m_stateTable->state(t).name));
            }
            qCDebug(qscxmlLog) << q_func() << "\t" << t << ":" << from << "->"
                               << to.join(QLatin1Char(','));
        }
    }

    exitStates(enabledTransitions);
    executeTransitionContent(enabledTransitions);
    enterStates(enabledTransitions);

    qCDebug(qscxmlLog) << q_func() << "finished microstep, configuration:"
                       << stateNames(m_configuration.list());
}

void QScxmlStateMachinePrivate::exitStates(const OrderedSet &enabledTransitions)
{
    OrderedSet statesToExit;
    computeExitSet(enabledTransitions, statesToExit);
    auto statesToExitSorted = statesToExit.takeList();
    std::sort(statesToExitSorted.begin(), statesToExitSorted.end(), std::greater<int>());
    qCDebug(qscxmlLog) << q_func() << "exiting states" << stateNames(statesToExitSorted);
    for (int s : statesToExitSorted) {
        const auto &state = m_stateTable->state(s);
        if (state.serviceFactoryIds != StateTable::InvalidIndex)
            m_statesToInvoke.remove(s);
    }
    for (int s : statesToExitSorted) {
        for (int h : historyStates(s)) {
            const auto &hState = m_stateTable->state(h);
            QList<int> history;

            for (int s0 : m_configuration) {
                const auto &s0State = m_stateTable->state(s0);
                if (hState.type == StateTable::State::DeepHistory) {
                    if (s0State.isAtomic() && isDescendant(s0, s))
                        history.append(s0);
                } else {
                    if (s0State.parent == s)
                        history.append(s0);
                }
            }

            m_historyValue[h] = history;
        }
    }
    for (int s : statesToExitSorted) {
        const auto &state = m_stateTable->state(s);
        if (state.exitInstructions != StateTable::InvalidIndex)
            m_executionEngine->execute(state.exitInstructions);
        m_configuration.remove(s);
        emitStateActive(s, false);
        removeService(s);
    }

    if (m_infoSignalProxy) {
        emit m_infoSignalProxy->statesExited(
                QList<QScxmlStateMachineInfo::StateId>(statesToExitSorted.begin(),
                                                         statesToExitSorted.end()));
    }
}

void QScxmlStateMachinePrivate::computeExitSet(const OrderedSet &enabledTransitions,
                                               OrderedSet &statesToExit) const
{
    for (int t : enabledTransitions) {
        const auto &transition = m_stateTable->transition(t);
        if (transition.targets == StateTable::InvalidIndex) {
            // nothing to do here: there is no exit set
        } else {
            const int domain = getTransitionDomain(t);
            for (int s : m_configuration) {
                if (isDescendant(s, domain))
                    statesToExit.add(s);
            }
        }
    }
}

void QScxmlStateMachinePrivate::executeTransitionContent(const OrderedSet &enabledTransitions)
{
    for (int t : enabledTransitions) {
        const auto &transition = m_stateTable->transition(t);
        if (transition.transitionInstructions != StateTable::InvalidIndex)
            m_executionEngine->execute(transition.transitionInstructions);
    }

    if (m_infoSignalProxy) {
        emit m_infoSignalProxy->transitionsTriggered(
                QList<QScxmlStateMachineInfo::TransitionId>(enabledTransitions.list().begin(),
                                                              enabledTransitions.list().end()));
    }
}

void QScxmlStateMachinePrivate::enterStates(const OrderedSet &enabledTransitions)
{
    Q_Q(QScxmlStateMachine);

    OrderedSet statesToEnter, statesForDefaultEntry;
    HistoryContent defaultHistoryContent;
    computeEntrySet(enabledTransitions, &statesToEnter, &statesForDefaultEntry,
                    &defaultHistoryContent);
    auto sortedStates = statesToEnter.takeList();
    std::sort(sortedStates.begin(), sortedStates.end());
    qCDebug(qscxmlLog) << q_func() << "entering states" << stateNames(sortedStates);
    for (int s : sortedStates) {
        const auto &state = m_stateTable->state(s);
        m_configuration.add(s);
        if (state.serviceFactoryIds != StateTable::InvalidIndex)
            m_statesToInvoke.insert(s);
        if (m_stateTable->binding == StateTable::LateBinding && m_isFirstStateEntry[s]) {
            if (state.initInstructions != StateTable::InvalidIndex)
                m_executionEngine->execute(state.initInstructions);
            m_isFirstStateEntry[s] = false;
        }
        if (state.entryInstructions != StateTable::InvalidIndex)
            m_executionEngine->execute(state.entryInstructions);
        if (statesForDefaultEntry.contains(s)) {
            const auto &initialTransition = m_stateTable->transition(state.initialTransition);
            if (initialTransition.transitionInstructions != StateTable::InvalidIndex)
                m_executionEngine->execute(initialTransition.transitionInstructions);
        }
        const int dhc = defaultHistoryContent.value(s);
        if (dhc != StateTable::InvalidIndex)
            m_executionEngine->execute(dhc);
        if (state.type == StateTable::State::Final) {
            if (state.parentIsScxmlElement()) {
                bool running = isRunnable() && !isPaused();
                m_runningState = Finished;
                if (running)
                    emit q->runningChanged(false);
            } else {
                const auto &parent = m_stateTable->state(state.parent);
                m_executionEngine->execute(state.doneData, m_tableData.value()->string(parent.name));
                if (parent.parent != StateTable::InvalidIndex) {
                    const auto &grandParent = m_stateTable->state(parent.parent);
                    if (grandParent.isParallel()) {
                        if (allInFinalStates(getChildStates(grandParent))) {
                            auto e = new QScxmlEvent;
                            e->setEventType(QScxmlEvent::InternalEvent);
                            e->setName(QStringLiteral("done.state.")
                                       + m_tableData.value()->string(grandParent.name));
                            q->submitEvent(e);
                        }
                    }
                }
            }
        }
    }
    for (int s : sortedStates)
        emitStateActive(s, true);
    if (m_infoSignalProxy) {
        emit m_infoSignalProxy->statesEntered(
                QList<QScxmlStateMachineInfo::StateId>(sortedStates.begin(),
                                                         sortedStates.end()));
    }
}

void QScxmlStateMachinePrivate::computeEntrySet(const OrderedSet &enabledTransitions,
                                                OrderedSet *statesToEnter,
                                                OrderedSet *statesForDefaultEntry,
                                                HistoryContent *defaultHistoryContent) const
{
    Q_ASSERT(statesToEnter);
    Q_ASSERT(statesForDefaultEntry);
    Q_ASSERT(defaultHistoryContent);

    for (int t : enabledTransitions) {
        const auto &transition = m_stateTable->transition(t);
        if (transition.targets == StateTable::InvalidIndex)
            // targetless transition, so nothing to do
            continue;
        for (int s : m_stateTable->array(transition.targets))
            addDescendantStatesToEnter(s, statesToEnter, statesForDefaultEntry,
                                       defaultHistoryContent);
        auto ancestor = getTransitionDomain(t);
        OrderedSet targets;
        getEffectiveTargetStates(&targets, t);
        for (auto s : targets)
            addAncestorStatesToEnter(s, ancestor, statesToEnter, statesForDefaultEntry,
                                     defaultHistoryContent);
    }
}

void QScxmlStateMachinePrivate::addDescendantStatesToEnter(
        int stateIndex, OrderedSet *statesToEnter, OrderedSet *statesForDefaultEntry,
        HistoryContent *defaultHistoryContent) const
{
    Q_ASSERT(statesToEnter);
    Q_ASSERT(statesForDefaultEntry);
    Q_ASSERT(defaultHistoryContent);

    const auto &state = m_stateTable->state(stateIndex);
    if (state.isHistoryState()) {
        HistoryValues::const_iterator historyValueIter = m_historyValue.find(stateIndex);
        if (historyValueIter != m_historyValue.end()) {
            auto historyValue = historyValueIter.value();
            for (int s : historyValue)
                addDescendantStatesToEnter(s, statesToEnter, statesForDefaultEntry,
                                           defaultHistoryContent);
            for (int s : historyValue)
                addAncestorStatesToEnter(s, state.parent, statesToEnter, statesForDefaultEntry,
                                         defaultHistoryContent);
        } else {
            int transitionIdx = StateTable::InvalidIndex;
            if (state.transitions == StateTable::InvalidIndex) {
                int parentInitialTransition = m_stateTable->state(state.parent).initialTransition;
                if (parentInitialTransition == StateTable::InvalidIndex)
                    return;
                transitionIdx = parentInitialTransition;
            } else {
                transitionIdx = m_stateTable->array(state.transitions)[0];
            }
            const auto &defaultHistoryTransition = m_stateTable->transition(transitionIdx);
            defaultHistoryContent->operator[](state.parent) =
                    defaultHistoryTransition.transitionInstructions;
            StateTable::Array targetStates = m_stateTable->array(defaultHistoryTransition.targets);
            for (int s : targetStates)
                addDescendantStatesToEnter(s, statesToEnter, statesForDefaultEntry,
                                           defaultHistoryContent);
            for (int s : targetStates)
                addAncestorStatesToEnter(s, state.parent, statesToEnter, statesForDefaultEntry,
                                         defaultHistoryContent);
        }
    } else {
        statesToEnter->add(stateIndex);
        if (state.isCompound()) {
            statesForDefaultEntry->add(stateIndex);
            if (state.initialTransition != StateTable::InvalidIndex) {
                auto initialTransition = m_stateTable->transition(state.initialTransition);
                auto initialTransitionTargets = m_stateTable->array(initialTransition.targets);
                for (int targetStateIndex : initialTransitionTargets)
                    addDescendantStatesToEnter(targetStateIndex, statesToEnter,
                                               statesForDefaultEntry, defaultHistoryContent);
                for (int targetStateIndex : initialTransitionTargets)
                    addAncestorStatesToEnter(targetStateIndex, stateIndex, statesToEnter,
                                             statesForDefaultEntry, defaultHistoryContent);
            }
        } else {
            if (state.isParallel()) {
                for (int child : getChildStates(state)) {
                    if (!hasDescendant(*statesToEnter, child))
                        addDescendantStatesToEnter(child, statesToEnter, statesForDefaultEntry,
                                                   defaultHistoryContent);
                }
            }
        }
    }
}

void QScxmlStateMachinePrivate::addAncestorStatesToEnter(
        int stateIndex, int ancestorIndex, OrderedSet *statesToEnter,
        OrderedSet *statesForDefaultEntry, HistoryContent *defaultHistoryContent) const
{
    Q_ASSERT(statesToEnter);
    Q_ASSERT(statesForDefaultEntry);
    Q_ASSERT(defaultHistoryContent);

    std::vector<int> ancestors;
    getProperAncestors(&ancestors, stateIndex, ancestorIndex);
    for (int anc : ancestors) {
        if (anc == -1) {
            // we can't enter the state machine itself, so:
            continue;
        }
        statesToEnter->add(anc);
        const auto &ancState = m_stateTable->state(anc);
        if (ancState.isParallel()) {
            for (int child : getChildStates(ancState)) {
                if (!hasDescendant(*statesToEnter, child))
                    addDescendantStatesToEnter(child, statesToEnter, statesForDefaultEntry,
                                               defaultHistoryContent);
            }
        }
    }
}

std::vector<int> QScxmlStateMachinePrivate::getChildStates(
        const QScxmlExecutableContent::StateTable::State &state) const
{
    std::vector<int> childStates;
    auto kids = m_stateTable->array(state.childStates);
    if (kids.isValid()) {
        childStates.reserve(kids.size());
        for (int kiddo : kids) {
            switch (m_stateTable->state(kiddo).type) {
            case StateTable::State::Normal:
            case StateTable::State::Final:
            case StateTable::State::Parallel:
                childStates.push_back(kiddo);
                break;
            default:
                break;
            }
        }
    }
    return childStates;
}

bool QScxmlStateMachinePrivate::hasDescendant(const OrderedSet &statesToEnter, int childIdx) const
{
    for (int s : statesToEnter) {
        if (isDescendant(s, childIdx))
            return true;
    }
    return false;
}

bool QScxmlStateMachinePrivate::allDescendants(const OrderedSet &statesToEnter, int childdx) const
{
    for (int s : statesToEnter) {
        if (!isDescendant(s, childdx))
            return false;
    }
    return true;
}

bool QScxmlStateMachinePrivate::isDescendant(int state1, int state2) const
{
    int parent = state1;
    do {
        parent = m_stateTable->state(parent).parent;
        if (parent == state2)
            return true;
    } while (parent != -1);
    return false;
}

bool QScxmlStateMachinePrivate::allInFinalStates(const std::vector<int> &states) const
{
    if (states.empty())
        return false;

    for (int idx : states) {
        if (!isInFinalState(idx))
            return false;
    }

    return true;
}

bool QScxmlStateMachinePrivate::someInFinalStates(const std::vector<int> &states) const
{
    for (int stateIndex : states) {
        const auto &state = m_stateTable->state(stateIndex);
        if (state.type == StateTable::State::Final && m_configuration.contains(stateIndex))
            return true;
    }
    return false;
}

bool QScxmlStateMachinePrivate::isInFinalState(int stateIndex) const
{
    const auto &state = m_stateTable->state(stateIndex);
    if (state.isCompound())
        return someInFinalStates(getChildStates(state)) && m_configuration.contains(stateIndex);
    else if (state.isParallel())
        return allInFinalStates(getChildStates(state));
    else
        return false;
}

int QScxmlStateMachinePrivate::getTransitionDomain(int transitionIndex) const
{
    const auto &transition = m_stateTable->transition(transitionIndex);
    if (transition.source == -1)
        //oooh, we have the initial transition of the state machine.
        return -1;

    OrderedSet tstates;
    getEffectiveTargetStates(&tstates, transitionIndex);
    if (tstates.isEmpty()) {
        return StateTable::InvalidIndex;
    } else {
        const auto &sourceState = m_stateTable->state(transition.source);
        if (transition.type == StateTable::Transition::Internal
                && sourceState.isCompound()
                && allDescendants(tstates, transition.source)) {
            return transition.source;
        } else {
            tstates.add(transition.source);
            return findLCCA(std::move(tstates));
        }
    }
}

int QScxmlStateMachinePrivate::findLCCA(OrderedSet &&states) const
{
    std::vector<int> ancestors;
    const int head = *states.begin();
    OrderedSet tail(std::move(states));
    tail.removeHead();

    getProperAncestors(&ancestors, head, StateTable::InvalidIndex);
    for (int anc : ancestors) {
        if (anc != -1) { // the state machine itself is always compound
            const auto &ancState = m_stateTable->state(anc);
            if (!ancState.isCompound())
                continue;
        }

        if (allDescendants(tail, anc))
            return anc;
    }

    return StateTable::InvalidIndex;
}

void QScxmlStateMachinePrivate::getEffectiveTargetStates(OrderedSet *targets,
                                                         int transitionIndex) const
{
    Q_ASSERT(targets);

    const auto &transition = m_stateTable->transition(transitionIndex);
    for (int s : m_stateTable->array(transition.targets)) {
        const auto &state = m_stateTable->state(s);
        if (state.isHistoryState()) {
            HistoryValues::const_iterator historyValueIter = m_historyValue.find(s);
            if (historyValueIter != m_historyValue.end()) {
                for (int historyState : historyValueIter.value()) {
                    targets->add(historyState);
                }
            } else if (state.transitions != StateTable::InvalidIndex) {
                getEffectiveTargetStates(targets, m_stateTable->array(state.transitions)[0]);
            }
        } else {
            targets->add(s);
        }
    }
}

/*!
 * Creates a state machine from the SCXML file specified by \a fileName.
 *
 * This method will always return a state machine. If errors occur while reading the SCXML file,
 * the state machine cannot be started. The errors can be retrieved by calling the parseErrors()
 * method.
 *
 * \sa parseErrors()
 */
QScxmlStateMachine *QScxmlStateMachine::fromFile(const QString &fileName)
{
    QFile scxmlFile(fileName);
    if (!scxmlFile.open(QIODevice::ReadOnly)) {
        auto stateMachine = new QScxmlStateMachine(&QScxmlStateMachine::staticMetaObject);
        QScxmlError err(scxmlFile.fileName(), 0, 0, QStringLiteral("cannot open for reading"));
        QScxmlStateMachinePrivate::get(stateMachine)->parserData()->m_errors.append(err);
        return stateMachine;
    }

    QScxmlStateMachine *stateMachine = fromData(&scxmlFile, fileName);
    scxmlFile.close();
    return stateMachine;
}

/*!
 * Creates a state machine by reading from the QIODevice specified by \a data.
 *
 * This method will always return a state machine. If errors occur while reading the SCXML file,
 * \a fileName, the state machine cannot be started. The errors can be retrieved by calling the
 * parseErrors() method.
 *
 * \sa parseErrors()
 */
QScxmlStateMachine *QScxmlStateMachine::fromData(QIODevice *data, const QString &fileName)
{
    QXmlStreamReader xmlReader(data);
    QScxmlCompiler compiler(&xmlReader);
    compiler.setFileName(fileName);
    return compiler.compile();
}

QList<QScxmlError> QScxmlStateMachine::parseErrors() const
{
    Q_D(const QScxmlStateMachine);
    return d->m_parserData ? d->m_parserData->m_errors : QList<QScxmlError>();
}

QScxmlStateMachine::QScxmlStateMachine(const QMetaObject *metaObject, QObject *parent)
    : QObject(*new QScxmlStateMachinePrivate(metaObject), parent)
{
    Q_D(QScxmlStateMachine);
    d->m_executionEngine = new QScxmlExecutionEngine(this);
}

QScxmlStateMachine::QScxmlStateMachine(QScxmlStateMachinePrivate &dd, QObject *parent)
    : QObject(dd, parent)
{
    Q_D(QScxmlStateMachine);
    d->m_executionEngine = new QScxmlExecutionEngine(this);
}

/*!
    \property QScxmlStateMachine::running

    \brief the running state of this state machine

    \sa start()
 */

/*!
    \qmlproperty bool ScxmlStateMachine::running

    The running state of this state machine.
*/

/*!
    \property QScxmlStateMachine::dataModel

    \brief The data model to be used for this state machine.

    SCXML data models are described in
    \l {SCXML Specification - 5 Data Model and Data Manipulation}. For more
    information about supported data models, see \l {SCXML Compliance}.

    Changing the data model when the state machine has been \c initialized is
    not specified in the SCXML standard and leads to undefined behavior.

    \sa QScxmlDataModel, QScxmlNullDataModel, QScxmlCppDataModel
*/

/*!
    \qmlproperty ScxmlDataModel ScxmlStateMachine::dataModel

    The data model to be used for this state machine.

    SCXML data models are described in
    \l {SCXML Specification - 5 Data Model and Data Manipulation}. For more
    information about supported data models, see \l {SCXML Compliance}.

    Changing the data model when the state machine has been \l initialized is
    not specified in the SCXML standard and leads to undefined behavior.

    \sa QScxmlDataModel, QScxmlNullDataModel, QScxmlCppDataModel
*/

/*!
    \property QScxmlStateMachine::initialized

    \brief Whether the state machine has been initialized.

    It is \c true if the state machine has been initialized, \c false otherwise.

    \sa QScxmlStateMachine::init(), QScxmlDataModel
*/

/*!
    \qmlproperty bool ScxmlStateMachine::initialized

    This read-only property is set to \c true if the state machine has been
    initialized, \c false otherwise.
*/

/*!
    \property QScxmlStateMachine::initialValues

    \brief The initial values to be used for setting up the data model.

    \sa QScxmlStateMachine::init(), QScxmlDataModel
*/

/*!
    \qmlproperty var ScxmlStateMachine::initialValues

    The initial values to be used for setting up the data model.
*/

/*!
    \property QScxmlStateMachine::sessionId

    \brief The session ID of the current state machine.

    The session ID is used for message routing between parent and child state machines. If a state
    machine is started by an \c <invoke> element, any event it sends will have the \c invokeid field
    set to the session ID. The state machine will use the origin of an event (which is set by the
    \e target or \e targetexpr attribute in a \c <send> element) to dispatch messages to the correct
    child state machine.

    \sa QScxmlEvent::invokeId()
 */

/*!
    \qmlproperty string ScxmlStateMachine::sessionId

    The session ID of the current state machine.

    The session ID is used for message routing between parent and child state
    machines. If a state machine is started by an \c <invoke> element, any event
    it sends will have the \c invokeid field set to the session ID. The state
    machine will use the origin of an event (which is set by the \e target or
    \e targetexpr attribute in a \c <send> element) to dispatch messages to the
    correct child state machine.
*/

/*!
    \property QScxmlStateMachine::name

    \brief The name of the state machine as set by the \e name attribute of the \c <scxml> tag.
 */

/*!
    \qmlproperty string ScxmlStateMachine::name

    The name of the state machine as set by the \e name attribute of the
    \c <scxml> tag.
*/

/*!
    \property QScxmlStateMachine::invoked

    \brief Whether the state machine was invoked from an outer state machine.

    \c true when the state machine was started as a service with the \c <invoke> element,
    \c false otherwise.
 */

/*!
    \qmlproperty bool ScxmlStateMachine::invoked

    Whether the state machine was invoked from an outer state machine.

    This read-only property is set to \c true when the state machine was started
    as a service with the \c <invoke> element, \c false otherwise.
 */

/*!
    \property QScxmlStateMachine::parseErrors

    \brief The list of parse errors that occurred while creating a state machine from an SCXML file.
 */

/*!
    \qmlproperty var ScxmlStateMachine::parseErrors

    The list of parse errors that occurred while creating a state machine from
    an SCXML file.
 */

/*!
    \property QScxmlStateMachine::loader

    \brief The loader that is currently used to resolve and load URIs for the state machine.
 */

/*!
    \qmlproperty Loader ScxmlStateMachine::loader

    The loader that is currently used to resolve and load URIs for the state
    machine.
 */

/*!
    \property QScxmlStateMachine::tableData

    \brief The table data that is used when generating C++ from an SCXML file.

    The class implementing
    the state machine will use this property to assign the generated table
    data. The state machine does not assume ownership of the table data.
 */

QString QScxmlStateMachine::sessionId() const
{
    Q_D(const QScxmlStateMachine);

    return d->m_sessionId;
}

QString QScxmlStateMachinePrivate::generateSessionId(const QString &prefix)
{
    int id = ++QScxmlStateMachinePrivate::m_sessionIdCounter;
    return prefix + QString::number(id);
}

bool QScxmlStateMachine::isInvoked() const
{
    Q_D(const QScxmlStateMachine);
    return d->m_isInvoked;
}

bool QScxmlStateMachine::isInitialized() const
{
    Q_D(const QScxmlStateMachine);
    return d->m_isInitialized;
}

QBindable<bool> QScxmlStateMachine::bindableInitialized() const
{
    Q_D(const QScxmlStateMachine);
    return &d->m_isInitialized;
}

/*!
 * Sets the data model for this state machine to \a model. There is a 1:1
 * relation between state machines and models. After setting the model once you
 * cannot change it anymore. Any further attempts to set the model using this
 * method will be ignored.
 */
void QScxmlStateMachine::setDataModel(QScxmlDataModel *model)
{
    Q_D(QScxmlStateMachine);

    if (d->m_dataModel.valueBypassingBindings() == nullptr && model != nullptr) {
        // the binding is removed only on the first valid set
        // as the later attempts are ignored
        d->m_dataModel.removeBindingUnlessInWrapper();
        d->m_dataModel.setValueBypassingBindings(model);
        model->setStateMachine(this);
        d->m_dataModel.notify();
        emit dataModelChanged(model);
    }
}

/*!
 * Returns the data model used by the state machine.
 */
QScxmlDataModel *QScxmlStateMachine::dataModel() const
{
    Q_D(const QScxmlStateMachine);

    return d->m_dataModel;
}

QBindable<QScxmlDataModel*> QScxmlStateMachine::bindableDataModel()
{
    Q_D(QScxmlStateMachine);
    return &d->m_dataModel;
}

void QScxmlStateMachine::setLoader(QScxmlCompiler::Loader *loader)
{
    Q_D(QScxmlStateMachine);
    d->m_loader.setValue(loader);
}

QScxmlCompiler::Loader *QScxmlStateMachine::loader() const
{
    Q_D(const QScxmlStateMachine);

    return d->m_loader;
}

QBindable<QScxmlCompiler::Loader*> QScxmlStateMachine::bindableLoader()
{
    Q_D(QScxmlStateMachine);
    return &d->m_loader;
}

QScxmlTableData *QScxmlStateMachine::tableData() const
{
    Q_D(const QScxmlStateMachine);

    return d->m_tableData;
}

void QScxmlStateMachine::setTableData(QScxmlTableData *tableData)
{
    Q_D(QScxmlStateMachine);

    d->m_tableData.removeBindingUnlessInWrapper();
    if (d->m_tableData.valueBypassingBindings() == tableData)
        return;

    d->m_tableData.setValueBypassingBindings(tableData);
    if (tableData) {
        d->m_stateTable = reinterpret_cast<const QScxmlExecutableContent::StateTable *>(
                    tableData->stateMachineTable());
        // cannot use objectName() here, because it creates binding loop
        const QString currentObjectName = d->extraData
                ? d->extraData->objectName.valueBypassingBindings() : QString();
        if (currentObjectName.isEmpty()) {
            setObjectName(tableData->name());
        }
        if (d->m_stateTable->maxServiceId != QScxmlExecutableContent::StateTable::InvalidIndex) {
            const size_t serviceCount = size_t(d->m_stateTable->maxServiceId + 1);
            d->m_invokedServices.resize(serviceCount, { -1, nullptr, QString() });
            d->m_cachedFactories.resize(serviceCount, nullptr);
        }

        if (d->m_stateTable->version != Q_QSCXMLC_OUTPUT_REVISION) {
           qFatal("Cannot mix incompatible state table (version 0x%x) with this library "
                  "(version 0x%x)", d->m_stateTable->version, Q_QSCXMLC_OUTPUT_REVISION);
        }
        Q_ASSERT(tableData->stateMachineTable()[d->m_stateTable->arrayOffset +
                                                d->m_stateTable->arraySize]
                == QScxmlExecutableContent::StateTable::terminator);
    }

    d->updateMetaCache();

    d->m_tableData.notify();
    emit tableDataChanged(tableData);
}

QBindable<QScxmlTableData*> QScxmlStateMachine::bindableTableData()
{
    Q_D(QScxmlStateMachine);
    return &d->m_tableData;
}

/*!
    \qmlmethod ScxmlStateMachine::stateNames(bool compress)

    Retrieves a list of state names of all states.

    When \a compress is \c true (the default), the states that contain child
    states is filtered out and only the \e {leaf states} is returned.  When it
    is \c false, the full list of all states is returned.

    The returned list does not contain the states of possible nested state
    machines.

    \note The order of the state names in the list is the order in which the
    states occurred in the SCXML document.
*/

/*!
 * Retrieves a list of state names of all states.
 *
 * When \a compress is \c true (the default), the states that contain child states
 * will be filtered out and only the \e {leaf states} will be returned.
 * When it is \c false, the full list of all states will be returned.
 *
 * The returned list does not contain the states of possible nested state machines.
 *
 * \note The order of the state names in the list is the order in which the states occurred in
 *       the SCXML document.
 */
QStringList QScxmlStateMachine::stateNames(bool compress) const
{
    Q_D(const QScxmlStateMachine);

    QStringList names;
    for (int i = 0; i < d->m_stateTable->stateCount; ++i) {
        const auto &state = d->m_stateTable->state(i);
        if (!compress || state.isAtomic())
            names.append(d->m_tableData.value()->string(state.name));
    }
    return names;
}

/*!
    \qmlmethod ScxmlStateMachine::activeStateNames(bool compress)

    Retrieves a list of state names of all active states.

    When a state is active, all its parent states are active by definition. When
    \a compress is \c true (the default), the parent states are filtered out and
    only the \e {leaf states} are returned. When it is \c false, the full list
    of active states is returned.
*/

/*!
 * Retrieves a list of state names of all active states.
 *
 * When a state is active, all its parent states are active by definition. When \a compress
 * is \c true (the default), the parent states will be filtered out and only the \e {leaf states}
 * will be returned. When it is \c false, the full list of active states will be returned.
 */
QStringList QScxmlStateMachine::activeStateNames(bool compress) const
{
    Q_D(const QScxmlStateMachine);

    QStringList result;
    for (int stateIdx : d->m_configuration) {
        const auto &state = d->m_stateTable->state(stateIdx);
        if (state.isAtomic() || !compress)
            result.append(d->m_tableData.value()->string(state.name));
    }
    return result;
}

/*!
    \qmlmethod ScxmlStateMachine::isActive(string scxmlStateName)

    Returns \c true if the state specified by \a scxmlStateName is active,
    \c false otherwise.
*/

/*!
 * Returns \c true if the state specified by \a scxmlStateName is active, \c false otherwise.
 */
bool QScxmlStateMachine::isActive(const QString &scxmlStateName) const
{
    Q_D(const QScxmlStateMachine);

    for (int stateIndex : d->m_configuration) {
        const auto &state = d->m_stateTable->state(stateIndex);
        if (d->m_tableData.value()->string(state.name) == scxmlStateName)
            return true;
    }

    return false;
}

QMetaObject::Connection QScxmlStateMachine::connectToStateImpl(const QString &scxmlStateName,
                                                               const QObject *receiver, void **slot,
                                                               QtPrivate::QSlotObjectBase *slotObj,
                                                               Qt::ConnectionType type)
{
    const int *types = nullptr;
    if (type == Qt::QueuedConnection || type == Qt::BlockingQueuedConnection)
        types = QtPrivate::ConnectionTypes<QtPrivate::List<bool> >::types();

    Q_D(QScxmlStateMachine);
    const int signalIndex = d->m_stateNameToSignalIndex.value(scxmlStateName, -1);
    return signalIndex < 0 ? QMetaObject::Connection()
                           : QObjectPrivate::connectImpl(this, signalIndex, receiver, slot, slotObj,
                                                         type, types, d->m_metaObject);
}

/*!
    Creates a connection of the given \a type from the state identified by \a scxmlStateName
    to the \a method in the \a receiver object. The receiver's \a method
    may take a boolean argument that indicates whether the state connected
    became active or inactive. For example:

    \code
    void mySlot(bool active);
    \endcode

    Returns a handle to the connection, which can be used later to disconnect.
 */
QMetaObject::Connection QScxmlStateMachine::connectToState(const QString &scxmlStateName,
                                                           const QObject *receiver,
                                                           const char *method,
                                                           Qt::ConnectionType type)
{
    QByteArray signalName = QByteArray::number(QSIGNAL_CODE) + scxmlStateName.toUtf8()
            + "Changed(bool)";
    return QObject::connect(this, signalName.constData(), receiver, method, type);
}

/*!
    Creates a connection of the specified \a type from the event specified by
    \a scxmlEventSpec to the \a method in the \a receiver object. The receiver's
    \a method may take a QScxmlEvent as a parameter. For example:

    \code
    void mySlot(const QScxmlEvent &event);
    \endcode

    In contrast to event specifications in SCXML documents, spaces are not
    allowed in the \a scxmlEventSpec here. In order to connect to multiple
    events with different prefixes, connectToEvent() has to be called multiple
    times.

    Returns a handle to the connection, which can be used later to disconnect.
*/
QMetaObject::Connection QScxmlStateMachine::connectToEvent(const QString &scxmlEventSpec,
                                                           const QObject *receiver,
                                                           const char *method,
                                                           Qt::ConnectionType type)
{
    Q_D(QScxmlStateMachine);
    return d->m_router.connectToEvent(scxmlEventSpec.split(QLatin1Char('.')), receiver, method,
                                      type);
}

QMetaObject::Connection QScxmlStateMachine::connectToEventImpl(const QString &scxmlEventSpec,
                                                               const QObject *receiver, void **slot,
                                                               QtPrivate::QSlotObjectBase *slotObj,
                                                               Qt::ConnectionType type)
{
    Q_D(QScxmlStateMachine);
    return d->m_router.connectToEvent(scxmlEventSpec.split(QLatin1Char('.')), receiver, slot,
                                      slotObj, type);
}

/*!
    \qmlmethod ScxmlStateMachine::init()

    Initializes the state machine by setting the initial values for \c <data>
    elements and executing any \c <script> tags of the \c <scxml> tag. The
    initial data values are taken from the \l initialValues property.

    Returns \c false if parse errors occur or if any of the initialization steps
    fail. Returns \c true otherwise.
*/

/*!
 * Initializes the state machine.
 *
 * State machine initialization consists of calling QScxmlDataModel::setup(), setting the initial
 * values for \c <data> elements, and executing any \c <script> tags of the \c <scxml> tag. The
 * initial data values are taken from the \c initialValues property.
 *
 * Returns \c false if parse errors occur or if any of the initialization steps fail.
 * Returns \c true otherwise.
 */
bool QScxmlStateMachine::init()
{
    Q_D(QScxmlStateMachine);

    if (d->m_isInitialized.value())
        return false;

    if (!parseErrors().isEmpty())
        return false;

    if (!dataModel() || !dataModel()->setup(d->m_initialValues.value()))
        return false;

    if (!d->executeInitialSetup())
        return false;

    d->m_isInitialized.setValue(true);
    return true;
}

/*!
 * Returns \c true if the state machine is running, \c false otherwise.
 *
 * \sa setRunning(), runningChanged()
 */
bool QScxmlStateMachine::isRunning() const
{
    Q_D(const QScxmlStateMachine);

    return d->isRunnable() && !d->isPaused();
}

/*!
 * Starts the state machine if \a running is \c true, or stops it otherwise.
 *
 * \sa start(), stop(), isRunning(), runningChanged()
 */
void QScxmlStateMachine::setRunning(bool running)
{
    if (running)
        start();
    else
        stop();
}

QVariantMap QScxmlStateMachine::initialValues()
{
    Q_D(const QScxmlStateMachine);
    return d->m_initialValues;
}

void QScxmlStateMachine::setInitialValues(const QVariantMap &initialValues)
{
    Q_D(QScxmlStateMachine);
    d->m_initialValues.setValue(initialValues);
}

QBindable<QVariantMap> QScxmlStateMachine::bindableInitialValues()
{
    Q_D(QScxmlStateMachine);
    return &d->m_initialValues;
}

QString QScxmlStateMachine::name() const
{
    return tableData()->name();
}

/*!
    \qmlmethod ScxmlStateMachine::submitEvent(event)

    Submits the SCXML event \a event to the internal or external event queue
    depending on the priority of the event.

    When a delay is set, the event will be queued for delivery after the timeout
    has passed. The state machine takes ownership of the event and deletes it
    after processing.

    \sa QScxmlEvent
 */

/*!
 * Submits the SCXML event \a event to the internal or external event queue depending on the
 * priority of the event.
 *
 * When a delay is set, the event will be queued for delivery after the timeout has passed.
 * The state machine takes ownership of \a event and deletes it after processing.
 */
void QScxmlStateMachine::submitEvent(QScxmlEvent *event)
{
    Q_D(QScxmlStateMachine);

    if (!event)
        return;

    if (event->delay() > 0) {
        qCDebug(qscxmlLog) << this << "submitting event" << event->name()
                           << "with delay" << event->delay() << "ms:"
                           << QScxmlEventPrivate::debugString(event).constData();

        Q_ASSERT(event->eventType() == QScxmlEvent::ExternalEvent);
        d->submitDelayedEvent(event);
    } else {
        qCDebug(qscxmlLog) << this << "submitting event" << event->name()
                           << ":" << QScxmlEventPrivate::debugString(event).constData();

        d->routeEvent(event);
    }
}

/*!
 * A utility method to create and submit an external event with the specified
 * \a eventName as the name.
 */
void QScxmlStateMachine::submitEvent(const QString &eventName)
{
    QScxmlEvent *e = new QScxmlEvent;
    e->setName(eventName);
    e->setEventType(QScxmlEvent::ExternalEvent);
    submitEvent(e);
}
/*!
    \qmlmethod ScxmlStateMachine::submitEvent(string eventName, var data)

    A utility method to create and submit an external event with the specified
    \a eventName as the name and \a data as the payload data (optional).
*/

/*!
 * A utility method to create and submit an external event with the specified
 * \a eventName as the name and \a data as the payload data.
 */
void QScxmlStateMachine::submitEvent(const QString &eventName, const QVariant &data)
{
    QScxmlEvent *e = new QScxmlEvent;
    e->setName(eventName);
    e->setEventType(QScxmlEvent::ExternalEvent);
    e->setData(data);
    submitEvent(e);
}

/*!
    \qmlmethod ScxmlStateMachine::cancelDelayedEvent(string sendId)

    Cancels a delayed event with the specified \a sendId.
*/

/*!
 * Cancels a delayed event with the specified \a sendId.
 */
void QScxmlStateMachine::cancelDelayedEvent(const QString &sendId)
{
    Q_D(QScxmlStateMachine);

    for (auto it = d->m_delayedEvents.begin(), eit = d->m_delayedEvents.end(); it != eit; ++it) {
        if (it->second->sendId() == sendId) {
            qCDebug(qscxmlLog) << this
                               << "canceling event" << sendId
                               << "with timer id" << it->first;
            d->m_eventLoopHook.killTimer(it->first);
            delete it->second;
            d->m_delayedEvents.erase(it);
            return;
        }
    }
}

/*!
    \qmlmethod ScxmlStateMachine::isDispatchableTarget(string target)

    Returns \c true if a message to \a target can be dispatched by this state
    machine.

    Valid targets are:
    \list
    \li \c #_parent for the parent state machine if the current state machine
        is started by \c <invoke>
    \li \c #_internal for the current state machine
    \li \c #_scxml_sessionid, where \c sessionid is the session ID of the
        current state machine
    \li \c #_servicename, where \c servicename is the ID or name of a service
        started with \c <invoke> by this state machine
    \endlist
 */

/*!
 * Returns \c true if a message to \a target can be dispatched by this state machine.
 *
 * Valid targets are:
 * \list
 * \li  \c #_parent for the parent state machine if the current state machine is started by
 *      \c <invoke>
 * \li  \c #_internal for the current state machine
 * \li  \c #_scxml_sessionid, where \c sessionid is the session ID of the current state machine
 * \li  \c #_servicename, where \c servicename is the ID or name of a service started with
 *      \c <invoke> by this state machine
 * \endlist
 */
bool QScxmlStateMachine::isDispatchableTarget(const QString &target) const
{
    Q_D(const QScxmlStateMachine);

    if (isInvoked() && target == QStringLiteral("#_parent"))
        return true; // parent state machine, if we're <invoke>d.
    if (target == QStringLiteral("#_internal")
            || target == QStringLiteral("#_scxml_%1").arg(sessionId()))
        return true; // that's the current state machine

    if (target.startsWith(QStringLiteral("#_"))) {
        QStringView targetId = QStringView{target}.mid(2);
        for (auto invokedService : d->m_invokedServices) {
            if (invokedService.service && invokedService.service->id() == targetId)
                return true;
        }
    }

    return false;
}

/*!
    \qmlproperty list ScxmlStateMachine::invokedServices

    A list of SCXML services that were invoked from the main state machine
    (possibly recursively).
*/

/*!
    \property QScxmlStateMachine::invokedServices
    \brief A list of SCXML services that were invoked from the main
    state machine (possibly recursively).
*/

QList<QScxmlInvokableService *> QScxmlStateMachine::invokedServices() const
{
    Q_D(const QScxmlStateMachine);
    return d->m_invokedServicesComputedProperty;
}

QBindable<QList<QScxmlInvokableService*>> QScxmlStateMachine::bindableInvokedServices()
{
    Q_D(QScxmlStateMachine);
    return &d->m_invokedServicesComputedProperty;
}

/*!
  \fn QScxmlStateMachine::runningChanged(bool running)

  This signal is emitted when the \c running property is changed with \a running as argument.
*/

/*!
  \fn QScxmlStateMachine::log(const QString &label, const QString &msg)

  This signal is emitted if a \c <log> tag is used in the SCXML. \a label is the value of the
  \e label attribute of the \c <log> tag. \a msg is the value of the evaluated \e expr attribute
  of the \c <log> tag. If there is no \e expr attribute, a null string will be returned.
*/

/*!
    \qmlsignal ScxmlStateMachine::log(string label, string msg)

    This signal is emitted if a \c <log> tag is used in the SCXML. \a label is
    the value of the \e label attribute of the \c <log> tag. \a msg is the value
    of the evaluated \e expr attribute of the \c <log> tag. If there is no
    \e expr attribute, a null string will be returned.

    The corresponding signal handler is \c onLog().
*/

/*!
  \fn QScxmlStateMachine::reachedStableState()

  This signal is emitted when the event queue is empty at the end of a macro step or when a final
  state is reached.
*/

/*!
    \qmlsignal ScxmlStateMachine::reachedStableState()

    This signal is emitted when the event queue is empty at the end of a macro
    step or when a final state is reached.

    The corresponding signal handler is \c onreachedStableState().
*/

/*!
  \fn QScxmlStateMachine::finished()

  This signal is emitted when the state machine reaches a top-level final state.

  \sa running
*/

/*!
    \qmlsignal ScxmlStateMachine::finished()

    This signal is emitted when the state machine reaches a top-level final
    state.

    The corresponding signal handler is \c onFinished().
*/

/*!
    \qmlmethod ScxmlStateMachine::start()

    Starts this state machine. The machine resets its configuration and
    transitions to the initial state. When a final top-level state
    is entered, the machine emits the finished() signal.

    \sa stop(), finished()
*/

/*!
  Starts this state machine. When a final top-level state
  is entered, the machine will emit the finished() signal.

  \note A state machine will not run without a running event loop, such as
  the main application event loop started with QCoreApplication::exec() or
  QApplication::exec().

  \note Calling start() after stop() will not result in a full reset of its
  configuration yet, hence it is strongly advised not to do it.

  \note Starting a finished machine yields a warning.

  \sa runningChanged(), setRunning(), stop(), finished()
*/
void QScxmlStateMachine::start()
{
    Q_D(QScxmlStateMachine);

    if (d->isFinished()) {
        qCWarning(qscxmlLog) << this << "Can't start finished machine";
    }

    if (!parseErrors().isEmpty())
        return;

    // Failure to initialize doesn't prevent start(). See w3c-ecma/test487 in the scion test suite.
    if (!isInitialized() && !init())
        qCDebug(qscxmlLog) << this << "cannot be initialized on start(). Starting anyway ...";

    d->start();
    d->m_eventLoopHook.queueProcessEvents();
}

/*!
    \qmlmethod ScxmlStateMachine::stop()

    Stops this state machine. The machine will not execute any further state
    transitions. Its \l running property is set to \c false.

    \sa start(), finished()
*/

/*!
  Stops this state machine. The machine will not execute any further state
  transitions. Its \c running property is set to \c false.

  \sa runningChanged(), start(), setRunning()
 */
void QScxmlStateMachine::stop()
{
    Q_D(QScxmlStateMachine);
    d->pause();
}

/*!
  Returns \c true if the state with the ID \a stateIndex is active.

  This method is part of the interface to the compiled representation of SCXML
  state machines. It should only be used internally and by state machines
  compiled from SCXML documents.
 */
bool QScxmlStateMachine::isActive(int stateIndex) const
{
    Q_D(const QScxmlStateMachine);
    // Here we need to find the actual internal state index that corresponds with the
    // index of the compiled metaobject (which is same as its mapped signal index).
    // See updateMetaCache()
    const int mappedStateIndex = d->m_stateIndexToSignalIndex.key(stateIndex, -1);
    return d->m_configuration.contains(mappedStateIndex);
}

QT_END_NAMESPACE