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
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "qmlengine.h"
#include "interactiveinterpreter.h"
#include "qmlinspectoragent.h"
#include "qmlv8debuggerclientconstants.h"
#include "qmlengineutils.h"
#include <debugger/breakhandler.h>
#include <debugger/debuggeractions.h>
#include <debugger/debuggercore.h>
#include <debugger/debuggerinternalconstants.h>
#include <debugger/debuggerruncontrol.h>
#include <debugger/debuggertooltipmanager.h>
#include <debugger/sourcefileshandler.h>
#include <debugger/stackhandler.h>
#include <debugger/threaddata.h>
#include <debugger/watchhandler.h>
#include <debugger/watchwindow.h>
#include <debugger/console/console.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/helpmanager.h>
#include <coreplugin/icore.h>
#include <projectexplorer/applicationlauncher.h>
#include <projectexplorer/runnables.h>
#include <qmljseditor/qmljseditorconstants.h>
#include <qmljs/qmljsmodelmanagerinterface.h>
#include <qmldebug/qpacketprotocol.h>
#include <texteditor/textdocument.h>
#include <texteditor/texteditor.h>
#include <utils/treemodel.h>
#include <utils/basetreeview.h>
#include <utils/qtcassert.h>
#include <QDebug>
#include <QDir>
#include <QDockWidget>
#include <QFileInfo>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QTimer>
#define DEBUG_QML 0
#if DEBUG_QML
# define SDEBUG(s) qDebug() << s
#else
# define SDEBUG(s)
#endif
# define XSDEBUG(s) qDebug() << s
#define CB(callback) [this](const QVariantMap &r) { callback(r); }
using namespace Core;
using namespace ProjectExplorer;
using namespace QmlDebug;
using namespace QmlJS;
using namespace TextEditor;
using namespace Utils;
namespace Debugger {
namespace Internal {
enum Exceptions
{
NoExceptions,
UncaughtExceptions,
AllExceptions
};
enum StepAction
{
Continue,
StepIn,
StepOut,
Next
};
struct QmlV8ObjectData
{
int handle = -1;
QString name;
QString type;
QVariant value;
QVariantList properties;
};
typedef std::function<void(const QVariantMap &)> QmlCallback;
struct LookupData
{
QString iname;
QString name;
QString exp;
};
typedef QHash<int, LookupData> LookupItems; // id -> (iname, exp)
class QmlEnginePrivate : QmlDebugClient
{
public:
QmlEnginePrivate(QmlEngine *engine_, QmlDebugConnection *connection_)
: QmlDebugClient("V8Debugger", connection_),
engine(engine_),
inspectorAgent(engine, connection_),
connection(connection_)
{}
void messageReceived(const QByteArray &data);
void stateChanged(State state);
void continueDebugging(StepAction stepAction);
void evaluate(const QString expr, const QmlCallback &cb);
void lookup(const LookupItems &items);
void backtrace();
void updateLocals();
void scope(int number, int frameNumber = -1);
void scripts(int types = 4, const QList<int> ids = QList<int>(),
bool includeSource = false, const QVariant filter = QVariant());
void setBreakpoint(const QString type, const QString target,
bool enabled = true,int line = 0, int column = 0,
const QString condition = QString(), int ignoreCount = -1);
void clearBreakpoint(int breakpoint);
void setExceptionBreak(Exceptions type, bool enabled = false);
void flushSendBuffer();
void handleBacktrace(const QVariantMap &response);
void handleLookup(const QVariantMap &response);
void handleExecuteDebuggerCommand(const QVariantMap &response);
void handleEvaluateExpression(const QVariantMap &response, const QString &iname, const QString &expr);
void handleFrame(const QVariantMap &response);
void handleScope(const QVariantMap &response);
void handleVersion(const QVariantMap &response);
StackFrame extractStackFrame(const QVariant &bodyVal);
bool canEvaluateScript(const QString &script);
void updateScriptSource(const QString &fileName, int lineOffset, int columnOffset, const QString &source);
void runCommand(const DebuggerCommand &command, const QmlCallback &cb = QmlCallback());
void runDirectCommand(const QString &type, const QByteArray &msg = QByteArray());
void clearRefs() { refVals.clear(); }
void memorizeRefs(const QVariant &refs);
QmlV8ObjectData extractData(const QVariant &data) const;
void insertSubItems(WatchItem *parent, const QVariantList &properties);
void checkForFinishedUpdate();
ConsoleItem *constructLogItemTree(const QmlV8ObjectData &objectData);
public:
QHash<int, QmlV8ObjectData> refVals; // The mapping of target object handles to retrieved values.
int sequence = -1;
QmlEngine *engine;
QHash<BreakpointModelId, int> breakpoints;
QHash<int, BreakpointModelId> breakpointsSync;
QList<int> breakpointsTemp;
LookupItems currentlyLookingUp; // Id -> inames
//Cache
QList<int> currentFrameScopes;
QHash<int, int> stackIndexLookup;
StepAction previousStepAction = Continue;
QList<QByteArray> sendBuffer;
QHash<QString, QTextDocument*> sourceDocuments;
QHash<QString, QWeakPointer<BaseTextEditor> > sourceEditors;
InteractiveInterpreter interpreter;
ApplicationLauncher applicationLauncher;
QmlInspectorAgent inspectorAgent;
QmlOutputParser outputParser;
QTimer noDebugOutputTimer;
QList<quint32> queryIds;
bool retryOnConnectFail = false;
bool automaticConnect = false;
bool unpausedEvaluate = false;
QTimer connectionTimer;
QmlDebug::QmlDebugConnection *connection;
QmlDebug::QDebugMessageClient *msgClient = 0;
QHash<int, QmlCallback> callbackForToken;
private:
ConsoleItem *constructLogItemTree(const QmlV8ObjectData &objectData, QList<int> &seenHandles);
void constructChildLogItems(ConsoleItem *item, const QmlV8ObjectData &objectData,
QList<int> &seenHandles);
};
static void updateDocument(IDocument *document, const QTextDocument *textDocument)
{
if (auto baseTextDocument = qobject_cast<TextDocument *>(document))
baseTextDocument->document()->setPlainText(textDocument->toPlainText());
}
///////////////////////////////////////////////////////////////////////
//
// QmlEngine
//
///////////////////////////////////////////////////////////////////////
QmlEngine::QmlEngine(const DebuggerRunParameters &startParameters, DebuggerEngine *masterEngine)
: DebuggerEngine(startParameters),
d(new QmlEnginePrivate(this, new QmlDebugConnection(this)))
{
setObjectName("QmlEngine");
if (masterEngine)
setMasterEngine(masterEngine);
connect(stackHandler(), &StackHandler::stackChanged,
this, &QmlEngine::updateCurrentContext);
connect(stackHandler(), &StackHandler::currentIndexChanged,
this, &QmlEngine::updateCurrentContext);
connect(inspectorView(), &WatchTreeView::currentIndexChanged,
this, &QmlEngine::updateCurrentContext);
connect(&d->applicationLauncher, &ApplicationLauncher::processExited,
this, &QmlEngine::disconnected);
connect(&d->applicationLauncher, &ApplicationLauncher::appendMessage,
this, &QmlEngine::appendMessage);
connect(&d->applicationLauncher, &ApplicationLauncher::processStarted,
&d->noDebugOutputTimer, static_cast<void(QTimer::*)()>(&QTimer::start));
d->outputParser.setNoOutputText(ApplicationLauncher::msgWinCannotRetrieveDebuggingOutput());
connect(&d->outputParser, &QmlOutputParser::waitingForConnectionOnPort,
this, &QmlEngine::beginConnection);
connect(&d->outputParser, &QmlOutputParser::noOutputMessage,
this, [this] { tryToConnect(); });
connect(&d->outputParser, &QmlOutputParser::errorMessage,
this, &QmlEngine::appStartupFailed);
// Only wait 8 seconds for the 'Waiting for connection' on application output,
// then just try to connect (application output might be redirected / blocked)
d->noDebugOutputTimer.setSingleShot(true);
d->noDebugOutputTimer.setInterval(8000);
connect(&d->noDebugOutputTimer, &QTimer::timeout,
this, [this] { tryToConnect(); });
// we won't get any debug output
if (startParameters.useTerminal) {
d->noDebugOutputTimer.setInterval(0);
d->retryOnConnectFail = true;
d->automaticConnect = true;
}
debuggerConsole()->setScriptEvaluator([this](const QString &expr) {
executeDebuggerCommand(expr, QmlLanguage);
});
d->connectionTimer.setInterval(4000);
d->connectionTimer.setSingleShot(true);
connect(&d->connectionTimer, &QTimer::timeout,
this, &QmlEngine::checkConnectionState);
connect(d->connection, &QmlDebugConnection::logStateChange,
this, &QmlEngine::showConnectionStateMessage);
connect(d->connection, &QmlDebugConnection::logError, this,
[this](const QString &error) { showMessage("QML Debugger: " + error, StatusBar); });
connect(d->connection, &QmlDebugConnection::connectionFailed,
this, &QmlEngine::connectionFailed);
connect(d->connection, &QmlDebugConnection::connected,
&d->connectionTimer, &QTimer::stop);
connect(d->connection, &QmlDebugConnection::connected,
this, &QmlEngine::connectionEstablished);
connect(d->connection, &QmlDebugConnection::disconnected,
this, &QmlEngine::disconnected);
d->msgClient = new QDebugMessageClient(d->connection);
connect(d->msgClient, &QDebugMessageClient::newState,
this, [this](QmlDebugClient::State state) {
logServiceStateChange(d->msgClient->name(), d->msgClient->serviceVersion(), state);
});
connect(d->msgClient, &QDebugMessageClient::message,
this, &appendDebugOutput);
}
QmlEngine::~QmlEngine()
{
QSet<IDocument *> documentsToClose;
QHash<QString, QWeakPointer<BaseTextEditor> >::iterator iter;
for (iter = d->sourceEditors.begin(); iter != d->sourceEditors.end(); ++iter) {
QWeakPointer<BaseTextEditor> textEditPtr = iter.value();
if (textEditPtr)
documentsToClose << textEditPtr.data()->document();
}
EditorManager::closeDocuments(documentsToClose.toList());
delete d;
}
void QmlEngine::setupInferior()
{
QTC_ASSERT(state() == InferiorSetupRequested, qDebug() << state());
notifyInferiorSetupOk();
if (d->automaticConnect)
beginConnection();
}
void QmlEngine::appendMessage(const QString &msg, Utils::OutputFormat /* format */)
{
showMessage(msg, AppOutput); // FIXME: Redirect to RunControl
}
void QmlEngine::connectionEstablished()
{
attemptBreakpointSynchronization();
if (state() == EngineRunRequested)
notifyEngineRunAndInferiorRunOk();
}
void QmlEngine::tryToConnect(Utils::Port port)
{
showMessage("QML Debugger: No application output received in time, trying to connect ...", LogStatus);
d->retryOnConnectFail = true;
if (state() == EngineRunRequested) {
if (isSlaveEngine()) {
// Probably cpp is being debugged and hence we did not get the output yet.
if (!masterEngine()->isDying())
beginConnection(port);
else
appStartupFailed(tr("No application output received in time"));
} else {
beginConnection(port);
}
} else {
d->automaticConnect = true;
}
}
void QmlEngine::beginConnection(Utils::Port port)
{
d->noDebugOutputTimer.stop();
if (state() != EngineRunRequested && d->retryOnConnectFail)
return;
QTC_ASSERT(state() == EngineRunRequested, return);
QString host = runParameters().qmlServer.host;
// Use localhost as default
if (host.isEmpty())
host = "localhost";
/*
* Let plugin-specific code override the port printed by the application. This is necessary
* in the case of port forwarding, when the port the application listens on is not the same that
* we want to connect to.
* NOTE: It is still necessary to wait for the output in that case, because otherwise we cannot
* be sure that the port is already open. The usual method of trying to connect repeatedly
* will not work, because the intermediate port is already open. So the connection
* will be accepted on that port but the forwarding to the target port will fail and
* the connection will be closed again (instead of returning the "connection refused"
* error that we expect).
*/
if (runParameters().qmlServer.port.isValid())
port = runParameters().qmlServer.port;
if (!d->connection || d->connection->isConnected())
return;
d->connection->connectToHost(host, port.number());
//A timeout to check the connection state
d->connectionTimer.start();
}
void QmlEngine::connectionStartupFailed()
{
if (d->retryOnConnectFail) {
// retry after 3 seconds ...
QTimer::singleShot(3000, this, [this] { beginConnection(); });
return;
}
QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
infoBox->setIcon(QMessageBox::Critical);
infoBox->setWindowTitle(tr("Qt Creator"));
infoBox->setText(tr("Could not connect to the in-process QML debugger."
"\nDo you want to retry?"));
infoBox->setStandardButtons(QMessageBox::Retry | QMessageBox::Cancel |
QMessageBox::Help);
infoBox->setDefaultButton(QMessageBox::Retry);
infoBox->setModal(true);
connect(infoBox, &QDialog::finished,
this, &QmlEngine::errorMessageBoxFinished);
infoBox->show();
}
void QmlEngine::appStartupFailed(const QString &errorMessage)
{
QString error = tr("Could not connect to the in-process QML debugger. %1").arg(errorMessage);
if (isMasterEngine()) {
QMessageBox *infoBox = new QMessageBox(ICore::mainWindow());
infoBox->setIcon(QMessageBox::Critical);
infoBox->setWindowTitle(tr("Qt Creator"));
infoBox->setText(error);
infoBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Help);
infoBox->setDefaultButton(QMessageBox::Ok);
connect(infoBox, &QDialog::finished,
this, &QmlEngine::errorMessageBoxFinished);
infoBox->show();
} else {
debuggerConsole()->printItem(ConsoleItem::WarningType, error);
}
notifyEngineRunFailed();
}
void QmlEngine::errorMessageBoxFinished(int result)
{
switch (result) {
case QMessageBox::Retry: {
beginConnection();
break;
}
case QMessageBox::Help: {
HelpManager::handleHelpRequest("qthelp://org.qt-project.qtcreator/doc/creator-debugging-qml.html");
// fall through
}
default:
if (state() == InferiorRunOk) {
notifyInferiorSpontaneousStop();
notifyInferiorIll();
} else if (state() == EngineRunRequested) {
notifyEngineRunFailed();
}
break;
}
}
void QmlEngine::filterApplicationMessage(const QString &output, int /*channel*/) const
{
d->outputParser.processOutput(output);
}
void QmlEngine::showMessage(const QString &msg, int channel, int timeout) const
{
if (channel == AppOutput || channel == AppError)
filterApplicationMessage(msg, channel);
DebuggerEngine::showMessage(msg, channel, timeout);
}
void QmlEngine::gotoLocation(const Location &location)
{
const QString fileName = location.fileName();
if (QUrl(fileName).isLocalFile()) {
// internal file from source files -> show generated .js
QTC_ASSERT(d->sourceDocuments.contains(fileName), return);
QString titlePattern = tr("JS Source for %1").arg(fileName);
//Check if there are open documents with the same title
foreach (IDocument *document, DocumentModel::openedDocuments()) {
if (document->displayName() == titlePattern) {
EditorManager::activateEditorForDocument(document);
return;
}
}
IEditor *editor = EditorManager::openEditorWithContents(
QmlJSEditor::Constants::C_QMLJSEDITOR_ID, &titlePattern);
if (editor) {
editor->document()->setProperty(Constants::OPENED_BY_DEBUGGER, true);
if (auto plainTextEdit = qobject_cast<QPlainTextEdit *>(editor->widget()))
plainTextEdit->setReadOnly(true);
updateDocument(editor->document(), d->sourceDocuments.value(fileName));
}
} else {
DebuggerEngine::gotoLocation(location);
}
}
void QmlEngine::closeConnection()
{
if (d->connectionTimer.isActive()) {
d->connectionTimer.stop();
} else {
if (d->connection)
d->connection->close();
}
}
void QmlEngine::runEngine()
{
QTC_ASSERT(state() == EngineRunRequested, qDebug() << state());
if (!isSlaveEngine()) {
if (runParameters().startMode == AttachToRemoteServer)
d->noDebugOutputTimer.start();
else if (runParameters().startMode == AttachToRemoteProcess)
beginConnection();
else
startApplicationLauncher();
} else {
d->noDebugOutputTimer.start();
}
}
void QmlEngine::startApplicationLauncher()
{
if (!d->applicationLauncher.isRunning()) {
StandardRunnable runnable = runParameters().inferior;
appendMessage(tr("Starting %1 %2").arg(
QDir::toNativeSeparators(runnable.executable),
runnable.commandLineArguments) + '\n',
Utils::NormalMessageFormat);
d->applicationLauncher.start(runnable);
}
}
void QmlEngine::stopApplicationLauncher()
{
if (d->applicationLauncher.isRunning()) {
disconnect(&d->applicationLauncher, &ApplicationLauncher::processExited,
this, &QmlEngine::disconnected);
d->applicationLauncher.stop();
}
}
void QmlEngine::notifyEngineRemoteSetupFinished(const RemoteSetupResult &result)
{
DebuggerEngine::notifyEngineRemoteSetupFinished(result);
if (result.success) {
if (result.qmlServerPort.isValid())
runParameters().qmlServer.port = result.qmlServerPort;
notifyEngineSetupOk();
// The remote setup can take while especialy with mixed debugging.
// Just waiting for 8 seconds is not enough. Increase the timeout
// to 60 s
// In case we get an output the d->outputParser will start the connection.
d->noDebugOutputTimer.setInterval(60000);
}
else {
if (isMasterEngine())
QMessageBox::critical(ICore::dialogParent(), tr("Failed to start application"),
tr("Application startup failed: %1").arg(result.reason));
notifyEngineSetupFailed();
}
}
void QmlEngine::notifyEngineRemoteServerRunning(const QString &serverChannel, int pid)
{
bool ok = false;
quint16 qmlPort = serverChannel.toUInt(&ok);
if (ok)
runParameters().qmlServer.port = Utils::Port(qmlPort);
else
qWarning() << tr("QML debugging port not set: Unable to convert %1 to unsigned int.").arg(serverChannel);
DebuggerEngine::notifyEngineRemoteServerRunning(serverChannel, pid);
notifyEngineSetupOk();
// The remote setup can take a while especially with mixed debugging.
// Just waiting for 8 seconds is not enough. Increase the timeout to 60 s.
// In case we get an output the d->outputParser will start the connection.
d->noDebugOutputTimer.setInterval(60000);
}
void QmlEngine::shutdownInferior()
{
// End session.
// { "seq" : <number>,
// "type" : "request",
// "command" : "disconnect",
// }
d->runCommand({DISCONNECT});
if (isSlaveEngine())
resetLocation();
stopApplicationLauncher();
closeConnection();
notifyInferiorShutdownOk();
}
void QmlEngine::shutdownEngine()
{
clearExceptionSelection();
debuggerConsole()->setScriptEvaluator(ScriptEvaluator());
d->noDebugOutputTimer.stop();
// double check (ill engine?):
stopApplicationLauncher();
notifyEngineShutdownOk();
if (!isSlaveEngine())
showMessage(QString(), StatusBar);
}
void QmlEngine::setupEngine()
{
if (runParameters().remoteSetupNeeded) {
// we need to get the port first
notifyEngineRequestRemoteSetup();
} else {
// We can't do this in the constructore because runControl() isn't yet defined
connect(&d->applicationLauncher, &ApplicationLauncher::bringToForegroundRequested,
runControl(), &RunControl::bringApplicationToForeground,
Qt::UniqueConnection);
notifyEngineSetupOk();
}
}
void QmlEngine::continueInferior()
{
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
clearExceptionSelection();
d->continueDebugging(Continue);
resetLocation();
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::interruptInferior()
{
showMessage(INTERRUPT, LogInput);
d->runDirectCommand(INTERRUPT);
showStatusMessage(tr("Waiting for JavaScript engine to interrupt on next statement."));
}
void QmlEngine::executeStep()
{
clearExceptionSelection();
d->continueDebugging(StepIn);
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeStepI()
{
clearExceptionSelection();
d->continueDebugging(StepIn);
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeStepOut()
{
clearExceptionSelection();
d->continueDebugging(StepOut);
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeNext()
{
clearExceptionSelection();
d->continueDebugging(Next);
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeNextI()
{
executeNext();
}
void QmlEngine::executeRunToLine(const ContextData &data)
{
QTC_ASSERT(state() == InferiorStopOk, qDebug() << state());
showStatusMessage(tr("Run to line %1 (%2) requested...").arg(data.lineNumber).arg(data.fileName), 5000);
d->setBreakpoint(SCRIPTREGEXP, data.fileName, true, data.lineNumber);
clearExceptionSelection();
d->continueDebugging(Continue);
notifyInferiorRunRequested();
notifyInferiorRunOk();
}
void QmlEngine::executeRunToFunction(const QString &functionName)
{
Q_UNUSED(functionName)
XSDEBUG("FIXME: QmlEngine::executeRunToFunction()");
}
void QmlEngine::executeJumpToLine(const ContextData &data)
{
Q_UNUSED(data)
XSDEBUG("FIXME: QmlEngine::executeJumpToLine()");
}
void QmlEngine::activateFrame(int index)
{
if (state() != InferiorStopOk && state() != InferiorUnrunnable)
return;
stackHandler()->setCurrentIndex(index);
gotoLocation(stackHandler()->frames().value(index));
d->updateLocals();
}
void QmlEngine::selectThread(ThreadId threadId)
{
Q_UNUSED(threadId)
}
void QmlEngine::insertBreakpoint(Breakpoint bp)
{
BreakpointState state = bp.state();
QTC_ASSERT(state == BreakpointInsertRequested, qDebug() << bp << this << state);
bp.notifyBreakpointInsertProceeding();
const BreakpointParameters ¶ms = bp.parameters();
if (params.type == BreakpointAtJavaScriptThrow) {
BreakpointResponse br = bp.response();
br.pending = false;
bp.setResponse(br);
bp.notifyBreakpointInsertOk();
d->setExceptionBreak(AllExceptions, params.enabled);
} else if (params.type == BreakpointByFileAndLine) {
d->setBreakpoint(SCRIPTREGEXP, params.fileName,
params.enabled, params.lineNumber, 0,
params.condition, params.ignoreCount);
} else if (params.type == BreakpointOnQmlSignalEmit) {
d->setBreakpoint(EVENT, params.functionName, params.enabled);
BreakpointResponse br = bp.response();
br.pending = false;
bp.setResponse(br);
bp.notifyBreakpointInsertOk();
}
d->breakpointsSync.insert(d->sequence, bp.id());
}
void QmlEngine::resetLocation()
{
DebuggerEngine::resetLocation();
d->currentlyLookingUp.clear();
}
void QmlEngine::removeBreakpoint(Breakpoint bp)
{
const BreakpointParameters ¶ms = bp.parameters();
BreakpointState state = bp.state();
QTC_ASSERT(state == BreakpointRemoveRequested, qDebug() << bp << this << state);
bp.notifyBreakpointRemoveProceeding();
int breakpoint = d->breakpoints.value(bp.id());
d->breakpoints.remove(bp.id());
if (params.type == BreakpointAtJavaScriptThrow)
d->setExceptionBreak(AllExceptions);
else if (params.type == BreakpointOnQmlSignalEmit)
d->setBreakpoint(EVENT, params.functionName, false);
else
d->clearBreakpoint(breakpoint);
if (bp.state() == BreakpointRemoveProceeding)
bp.notifyBreakpointRemoveOk();
}
void QmlEngine::changeBreakpoint(Breakpoint bp)
{
BreakpointState state = bp.state();
QTC_ASSERT(state == BreakpointChangeRequested, qDebug() << bp << this << state);
bp.notifyBreakpointChangeProceeding();
const BreakpointParameters ¶ms = bp.parameters();
BreakpointResponse br = bp.response();
if (params.type == BreakpointAtJavaScriptThrow) {
d->setExceptionBreak(AllExceptions, params.enabled);
br.enabled = params.enabled;
bp.setResponse(br);
} else if (params.type == BreakpointOnQmlSignalEmit) {
d->setBreakpoint(EVENT, params.functionName, params.enabled);
br.enabled = params.enabled;
bp.setResponse(br);
} else {
//V8 supports only minimalistic changes in breakpoint
//Remove the breakpoint and add again
bp.notifyBreakpointChangeOk();
bp.removeBreakpoint();
BreakHandler *handler = d->engine->breakHandler();
handler->appendBreakpoint(params);
}
if (bp.state() == BreakpointChangeProceeding)
bp.notifyBreakpointChangeOk();
}
void QmlEngine::attemptBreakpointSynchronization()
{
if (!stateAcceptsBreakpointChanges()) {
showMessage("BREAKPOINT SYNCHRONIZATION NOT POSSIBLE IN CURRENT STATE");
return;
}
BreakHandler *handler = breakHandler();
DebuggerEngine *bpOwner = isSlaveEngine() ? masterEngine() : this;
foreach (Breakpoint bp, handler->unclaimedBreakpoints()) {
// Take ownership of the breakpoint. Requests insertion.
if (acceptsBreakpoint(bp))
bp.setEngine(bpOwner);
}
foreach (Breakpoint bp, handler->engineBreakpoints(bpOwner)) {
switch (bp.state()) {
case BreakpointNew:
// Should not happen once claimed.
QTC_CHECK(false);
continue;
case BreakpointInsertRequested:
insertBreakpoint(bp);
continue;
case BreakpointChangeRequested:
changeBreakpoint(bp);
continue;
case BreakpointRemoveRequested:
removeBreakpoint(bp);
continue;
case BreakpointChangeProceeding:
case BreakpointInsertProceeding:
case BreakpointRemoveProceeding:
case BreakpointInserted:
case BreakpointDead:
continue;
}
QTC_ASSERT(false, qDebug() << "UNKNOWN STATE" << bp << state());
}
DebuggerEngine::attemptBreakpointSynchronization();
}
bool QmlEngine::acceptsBreakpoint(Breakpoint bp) const
{
if (!bp.parameters().isCppBreakpoint())
return true;
//If it is a Cpp Breakpoint query if the type can be also handled by the debugger client
//TODO: enable setting of breakpoints before start of debug session
//For now, the event breakpoint can be set after the activeDebuggerClient is known
//This is because the older client does not support BreakpointOnQmlSignalHandler
BreakpointType type = bp.type();
return type == BreakpointOnQmlSignalEmit
|| type == BreakpointByFileAndLine
|| type == BreakpointAtJavaScriptThrow;
}
void QmlEngine::loadSymbols(const QString &moduleName)
{
Q_UNUSED(moduleName)
}
void QmlEngine::loadAllSymbols()
{
}
void QmlEngine::reloadModules()
{
}
void QmlEngine::reloadSourceFiles()
{
d->scripts(4, QList<int>(), true, QVariant());
}
void QmlEngine::updateAll()
{
d->updateLocals();
}
void QmlEngine::requestModuleSymbols(const QString &moduleName)
{
Q_UNUSED(moduleName)
}
bool QmlEngine::canHandleToolTip(const DebuggerToolTipContext &) const
{
// This is processed by QML inspector, which has dependencies to
// the qml js editor. Makes life easier.
// FIXME: Except that there isn't any attached.
return true;
}
void QmlEngine::assignValueInDebugger(WatchItem *item,
const QString &expression, const QVariant &value)
{
if (!expression.isEmpty()) {
if (item->isInspect()) {
d->inspectorAgent.assignValue(item, expression, value);
} else {
StackHandler *handler = stackHandler();
QString exp = QString("%1 = %2;").arg(expression).arg(value.toString());
if (handler->isContentsValid() && handler->currentFrame().isUsable()) {
d->evaluate(exp, [this](const QVariantMap &) { d->updateLocals(); });
} else {
showMessage(QString("Cannot evaluate %1 in current stack frame")
.arg(expression), ConsoleOutput);
}
}
}
}
void QmlEngine::expandItem(const QString &iname)
{
const WatchItem *item = watchHandler()->findItem(iname);
QTC_ASSERT(item, return);
if (item->isInspect()) {
d->inspectorAgent.updateWatchData(*item);
} else {
LookupItems items;
items.insert(int(item->id), {item->iname, item->name, item->exp});
d->lookup(items);
}
}
void QmlEngine::updateItem(const QString &iname)
{
const WatchItem *item = watchHandler()->findItem(iname);
QTC_ASSERT(item, return);
if (state() == InferiorStopOk) {
// The Qt side Q_ASSERTs otherwise. So postpone the evaluation,
// it will be triggered from from upateLocals() later.
QString exp = item->exp;
d->evaluate(exp, [this, iname, exp](const QVariantMap &response) {
d->handleEvaluateExpression(response, iname, exp);
});
}
}
void QmlEngine::selectWatchData(const QString &iname)
{
const WatchItem *item = watchHandler()->findItem(iname);
if (item && item->isInspect())
d->inspectorAgent.watchDataSelected(item->id);
}
bool compareConsoleItems(const ConsoleItem *a, const ConsoleItem *b)
{
if (a == 0)
return true;
if (b == 0)
return false;
return a->text() < b->text();
}
static ConsoleItem *constructLogItemTree(const QVariant &result,
const QString &key = QString())
{
bool sorted = boolSetting(SortStructMembers);
if (!result.isValid())
return 0;
QString text;
ConsoleItem *item = 0;
if (result.type() == QVariant::Map) {
if (key.isEmpty())
text = "Object";
else
text = key + " : Object";
QMap<QString, QVariant> resultMap = result.toMap();
QVarLengthArray<ConsoleItem *> children(resultMap.size());
QMapIterator<QString, QVariant> i(result.toMap());
auto it = children.begin();
while (i.hasNext()) {
i.next();
*(it++) = constructLogItemTree(i.value(), i.key());
}
// Sort before inserting as ConsoleItem::sortChildren causes a whole cascade of changes we
// may not want to handle here.
if (sorted)
std::sort(children.begin(), children.end(), compareConsoleItems);
item = new ConsoleItem(ConsoleItem::DefaultType, text);
foreach (ConsoleItem *child, children) {
if (child)
item->appendChild(child);
}
} else if (result.type() == QVariant::List) {
if (key.isEmpty())
text = "List";
else
text = QString("[%1] : List").arg(key);
QVariantList resultList = result.toList();
QVarLengthArray<ConsoleItem *> children(resultList.size());
for (int i = 0; i < resultList.count(); i++)
children[i] = constructLogItemTree(resultList.at(i), QString::number(i));
if (sorted)
std::sort(children.begin(), children.end(), compareConsoleItems);
item = new ConsoleItem(ConsoleItem::DefaultType, text);
foreach (ConsoleItem *child, children) {
if (child)
item->appendChild(child);
}
} else if (result.canConvert(QVariant::String)) {
item = new ConsoleItem(ConsoleItem::DefaultType, result.toString());
} else {
item = new ConsoleItem(ConsoleItem::DefaultType, "Unknown Value");
}
return item;
}
void QmlEngine::expressionEvaluated(quint32 queryId, const QVariant &result)
{
if (d->queryIds.contains(queryId)) {
d->queryIds.removeOne(queryId);
if (ConsoleItem *item = constructLogItemTree(result))
debuggerConsole()->printItem(item);
}
}
bool QmlEngine::hasCapability(unsigned cap) const
{
return cap & (AddWatcherCapability
| AddWatcherWhileRunningCapability
| RunToLineCapability);
/*ReverseSteppingCapability | SnapshotCapability
| AutoDerefPointersCapability | DisassemblerCapability
| RegisterCapability | ShowMemoryCapability
| JumpToLineCapability | ReloadModuleCapability
| ReloadModuleSymbolsCapability | BreakOnThrowAndCatchCapability
| ReturnFromFunctionCapability
| CreateFullBacktraceCapability
| WatchpointCapability
| AddWatcherCapability;*/
}
void QmlEngine::quitDebugger()
{
d->noDebugOutputTimer.stop();
d->automaticConnect = false;
d->retryOnConnectFail = false;
shutdownInferior();
}
void QmlEngine::doUpdateLocals(const UpdateParameters ¶ms)
{
Q_UNUSED(params);
d->updateLocals();
}
void QmlEngine::disconnected()
{
showMessage(tr("QML Debugger disconnected."), StatusBar);
notifyInferiorExited();
}
void QmlEngine::updateCurrentContext()
{
QString context;
if (state() == InferiorStopOk) {
context = stackHandler()->currentFrame().function;
} else {
QModelIndex currentIndex = inspectorView()->currentIndex();
const WatchItem *currentData = watchHandler()->watchItem(currentIndex);
if (!currentData)
return;
const WatchItem *parentData = watchHandler()->watchItem(currentIndex.parent());
const WatchItem *grandParentData = watchHandler()->watchItem(currentIndex.parent().parent());
if (currentData->id != parentData->id)
context = currentData->name;
else if (parentData->id != grandParentData->id)
context = parentData->name;
else
context = grandParentData->name;
}
}
void QmlEngine::executeDebuggerCommand(const QString &command, DebuggerLanguages languages)
{
if (!(languages & QmlLanguage))
return;
if (state() == InferiorStopOk) {
StackHandler *handler = stackHandler();
if (handler->isContentsValid() && handler->currentFrame().isUsable()) {
d->evaluate(command, CB(d->handleExecuteDebuggerCommand));
} else {
// Paused but no stack? Something is wrong
d->engine->showMessage(QString("Cannot evaluate %1. The stack trace is broken.").arg(command),
ConsoleOutput);
}
} else if (d->unpausedEvaluate) {
d->evaluate(command, CB(d->handleExecuteDebuggerCommand));
} else {
QModelIndex currentIndex = inspectorView()->currentIndex();
quint32 queryId = d->inspectorAgent.queryExpressionResult(
watchHandler()->watchItem(currentIndex)->id, command);
if (queryId) {
d->queryIds.append(queryId);
} else {
d->engine->showMessage("The application has to be stopped in a breakpoint in order to"
" evaluate expressions", ConsoleOutput);
}
}
}
void QmlEnginePrivate::updateScriptSource(const QString &fileName, int lineOffset, int columnOffset,
const QString &source)
{
QTextDocument *document = 0;
if (sourceDocuments.contains(fileName)) {
document = sourceDocuments.value(fileName);
} else {
document = new QTextDocument(this);
sourceDocuments.insert(fileName, document);
}
// We're getting an unordered set of snippets that can even interleave
// Therefore we've to carefully update the existing document
QTextCursor cursor(document);
for (int i = 0; i < lineOffset; ++i) {
if (!cursor.movePosition(QTextCursor::NextBlock))
cursor.insertBlock();
}
QTC_CHECK(cursor.blockNumber() == lineOffset);
for (int i = 0; i < columnOffset; ++i) {
if (!cursor.movePosition(QTextCursor::NextCharacter))
cursor.insertText(" ");
}
QTC_CHECK(cursor.positionInBlock() == columnOffset);
QStringList lines = source.split('\n');
foreach (QString line, lines) {
if (line.endsWith('\r'))
line.remove(line.size() -1, 1);
// line already there?
QTextCursor existingCursor(cursor);
existingCursor.movePosition(QTextCursor::EndOfBlock, QTextCursor::KeepAnchor);
if (existingCursor.selectedText() != line)
cursor.insertText(line);
if (!cursor.movePosition(QTextCursor::NextBlock))
cursor.insertBlock();
}
//update open editors
QString titlePattern = QCoreApplication::translate("QmlEngine", "JS Source for %1").arg(fileName);
//Check if there are open editors with the same title
foreach (IDocument *doc, DocumentModel::openedDocuments()) {
if (doc->displayName() == titlePattern) {
updateDocument(doc, document);
break;
}
}
}
bool QmlEnginePrivate::canEvaluateScript(const QString &script)
{
interpreter.clearText();
interpreter.appendText(script);
return interpreter.canEvaluate();
}
void QmlEngine::connectionFailed()
{
// this is only an error if we are already connected and something goes wrong.
if (isConnected()) {
if (!isSlaveEngine()) { // normal flow for slave engine when gdb exits
notifyInferiorSpontaneousStop();
notifyInferiorIll();
}
} else {
d->connectionTimer.stop();
connectionStartupFailed();
}
}
void QmlEngine::checkConnectionState()
{
if (!isConnected()) {
closeConnection();
connectionStartupFailed();
}
}
bool QmlEngine::isConnected() const
{
return d->connection->isConnected();
}
void QmlEngine::showConnectionStateMessage(const QString &message)
{
showMessage("QML Debugger: " + message, LogStatus);
}
void QmlEngine::logServiceStateChange(const QString &service, float version,
QmlDebugClient::State newState)
{
switch (newState) {
case QmlDebugClient::Unavailable: {
showConnectionStateMessage(QString("Status of \"%1\" Version: %2 changed to 'unavailable'.").
arg(service).arg(version));
break;
}
case QmlDebugClient::Enabled: {
showConnectionStateMessage(QString("Status of \"%1\" Version: %2 changed to 'enabled'.").
arg(service).arg(version));
break;
}
case QmlDebugClient::NotConnected: {
showConnectionStateMessage(QString("Status of \"%1\" Version: %2 changed to 'not connected'.").
arg(service).arg(version));
break;
}
}
}
void QmlEngine::logServiceActivity(const QString &service, const QString &logMessage)
{
showMessage(service + ' ' + logMessage, LogDebug);
}
void QmlEnginePrivate::continueDebugging(StepAction action)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "continue",
// "arguments" : { "stepaction" : <"in", "next" or "out">,
// "stepcount" : <number of steps (default 1)>
// }
// }
DebuggerCommand cmd(CONTINEDEBUGGING);
if (action == StepIn)
cmd.arg(STEPACTION, IN);
else if (action == StepOut)
cmd.arg(STEPACTION, OUT);
else if (action == Next)
cmd.arg(STEPACTION, NEXT);
runCommand(cmd);
previousStepAction = action;
}
void QmlEnginePrivate::evaluate(const QString expr, const QmlCallback &cb)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "evaluate",
// "arguments" : { "expression" : <expression to evaluate>,
// "frame" : <number>,
// "global" : <boolean>,
// "disable_break" : <boolean>,
// "additional_context" : [
// { "name" : <name1>, "handle" : <handle1> },
// { "name" : <name2>, "handle" : <handle2> },
// ...
// ]
// }
// }
// The Qt side Q_ASSERTs otherwise. So ignore the request and hope
// it will be repeated soon enough (which it will, e.g. in updateLocals)
QTC_ASSERT(unpausedEvaluate || engine->state() == InferiorStopOk, return);
DebuggerCommand cmd(EVALUATE);
cmd.arg(EXPRESSION, expr);
StackHandler *handler = engine->stackHandler();
if (handler->currentFrame().isUsable())
cmd.arg(FRAME, handler->currentIndex());
runCommand(cmd, cb);
}
void QmlEnginePrivate::handleEvaluateExpression(const QVariantMap &response,
const QString &iname,
const QString &exp)
{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "evaluate",
// "body" : ...
// "running" : <is the VM running after sending this response>
// "success" : true
// }
QVariant bodyVal = response.value(BODY).toMap();
QmlV8ObjectData body = extractData(bodyVal);
WatchHandler *watchHandler = engine->watchHandler();
auto item = new WatchItem;
item->iname = iname;
item->name = exp;
item->exp = exp;
item->id = body.handle;
bool success = response.value("success").toBool();
if (success) {
item->type = body.type;
item->value = body.value.toString();
item->wantsChildren = body.properties.count();
} else {
//Do not set type since it is unknown
item->setError(body.value.toString());
}
insertSubItems(item, body.properties);
watchHandler->insertItem(item);
}
void QmlEnginePrivate::lookup(const LookupItems &items)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "lookup",
// "arguments" : { "handles" : <array of handles>,
// "includeSource" : <boolean indicating whether
// the source will be included when
// script objects are returned>,
// }
// }
if (items.isEmpty())
return;
QList<int> handles;
for (auto it = items.begin(); it != items.end(); ++it) {
const int handle = it.key();
if (!currentlyLookingUp.contains(handle)) {
currentlyLookingUp.insert(handle, it.value());
handles.append(handle);
}
}
DebuggerCommand cmd(LOOKUP);
cmd.arg(HANDLES, handles);
runCommand(cmd, CB(handleLookup));
}
void QmlEnginePrivate::backtrace()
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "backtrace",
// "arguments" : { "fromFrame" : <number>
// "toFrame" : <number>
// "bottom" : <boolean, set to true if the bottom of the
// stack is requested>
// }
// }
DebuggerCommand cmd(BACKTRACE);
runCommand(cmd, CB(handleBacktrace));
}
void QmlEnginePrivate::updateLocals()
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "frame",
// "arguments" : { "number" : <frame number> }
// }
DebuggerCommand cmd(FRAME);
cmd.arg(NUMBER, stackIndexLookup.value(engine->stackHandler()->currentIndex()));
runCommand(cmd, CB(handleFrame));
}
void QmlEnginePrivate::scope(int number, int frameNumber)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "scope",
// "arguments" : { "number" : <scope number>
// "frameNumber" : <frame number, optional uses selected
// frame if missing>
// }
// }
DebuggerCommand cmd(SCOPE);
cmd.arg(NUMBER, number);
if (frameNumber != -1)
cmd.arg(FRAMENUMBER, frameNumber);
runCommand(cmd, CB(handleScope));
}
void QmlEnginePrivate::scripts(int types, const QList<int> ids, bool includeSource,
const QVariant filter)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "scripts",
// "arguments" : { "types" : <types of scripts to retrieve
// set bit 0 for native scripts
// set bit 1 for extension scripts
// set bit 2 for normal scripts
// (default is 4 for normal scripts)>
// "ids" : <array of id's of scripts to return. If this is not specified all scripts are requrned>
// "includeSource" : <boolean indicating whether the source code should be included for the scripts returned>
// "filter" : <string or number: filter string or script id.
// If a number is specified, then only the script with the same number as its script id will be retrieved.
// If a string is specified, then only scripts whose names contain the filter string will be retrieved.>
// }
// }
DebuggerCommand cmd(SCRIPTS);
cmd.arg(TYPES, types);
if (ids.count())
cmd.arg(IDS, ids);
if (includeSource)
cmd.arg(INCLUDESOURCE, includeSource);
if (filter.type() == QVariant::String)
cmd.arg(FILTER, filter.toString());
else if (filter.type() == QVariant::Int)
cmd.arg(FILTER, filter.toInt());
else
QTC_CHECK(!filter.isValid());
runCommand(cmd);
}
void QmlEnginePrivate::setBreakpoint(const QString type, const QString target,
bool enabled, int line, int column,
const QString condition, int ignoreCount)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "setbreakpoint",
// "arguments" : { "type" : <"function" or "script" or "scriptId" or "scriptRegExp">
// "target" : <function expression or script identification>
// "line" : <line in script or function>
// "column" : <character position within the line>
// "enabled" : <initial enabled state. True or false, default is true>
// "condition" : <string with break point condition>
// "ignoreCount" : <number specifying the number of break point hits to ignore, default value is 0>
// }
// }
if (type == EVENT) {
QPacket rs(connection->currentDataStreamVersion());
rs << target.toUtf8() << enabled;
engine->showMessage(QString("%1 %2 %3")
.arg(BREAKONSIGNAL, target, QLatin1String(enabled ? "enabled" : "disabled")), LogInput);
runDirectCommand(BREAKONSIGNAL, rs.data());
} else {
DebuggerCommand cmd(SETBREAKPOINT);
cmd.arg(TYPE, type);
cmd.arg(ENABLED, enabled);
if (type == SCRIPTREGEXP)
cmd.arg(TARGET, Utils::FileName::fromString(target).fileName());
else
cmd.arg(TARGET, target);
if (line)
cmd.arg(LINE, line - 1);
if (column)
cmd.arg(COLUMN, column - 1);
if (!condition.isEmpty())
cmd.arg(CONDITION, condition);
if (ignoreCount != -1)
cmd.arg(IGNORECOUNT, ignoreCount);
runCommand(cmd);
}
}
void QmlEnginePrivate::clearBreakpoint(int breakpoint)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "clearbreakpoint",
// "arguments" : { "breakpoint" : <number of the break point to clear>
// }
// }
DebuggerCommand cmd(CLEARBREAKPOINT);
cmd.arg(BREAKPOINT, breakpoint);
runCommand(cmd);
}
void QmlEnginePrivate::setExceptionBreak(Exceptions type, bool enabled)
{
// { "seq" : <number>,
// "type" : "request",
// "command" : "setexceptionbreak",
// "arguments" : { "type" : <string: "all", or "uncaught">,
// "enabled" : <optional bool: enables the break type if true>
// }
// }
DebuggerCommand cmd(SETEXCEPTIONBREAK);
if (type == AllExceptions)
cmd.arg(TYPE, ALL);
//Not Supported:
// else if (type == UncaughtExceptions)
// cmd.args(TYPE, UNCAUGHT);
if (enabled)
cmd.arg(ENABLED, enabled);
runCommand(cmd);
}
QmlV8ObjectData QmlEnginePrivate::extractData(const QVariant &data) const
{
// { "handle" : <handle>,
// "type" : <"undefined", "null", "boolean", "number", "string", "object", "function" or "frame">
// }
// {"handle":<handle>,"type":"undefined"}
// {"handle":<handle>,"type":"null"}
// { "handle":<handle>,
// "type" : <"boolean", "number" or "string">
// "value" : <JSON encoded value>
// }
// {"handle":7,"type":"boolean","value":true}
// {"handle":8,"type":"number","value":42}
// { "handle" : <handle>,
// "type" : "object",
// "className" : <Class name, ECMA-262 property [[Class]]>,
// "constructorFunction" : {"ref":<handle>},
// "protoObject" : {"ref":<handle>},
// "prototypeObject" : {"ref":<handle>},
// "properties" : [ {"name" : <name>,
// "ref" : <handle>
// },
// ...
// ]
// }
// { "handle" : <handle>,
// "type" : "function",
// "className" : "Function",
// "constructorFunction" : {"ref":<handle>},
// "protoObject" : {"ref":<handle>},
// "prototypeObject" : {"ref":<handle>},
// "name" : <function name>,
// "inferredName" : <inferred function name for anonymous functions>
// "source" : <function source>,
// "script" : <reference to function script>,
// "scriptId" : <id of function script>,
// "position" : <function begin position in script>,
// "line" : <function begin source line in script>,
// "column" : <function begin source column in script>,
// "properties" : [ {"name" : <name>,
// "ref" : <handle>
// },
// ...
// ]
// }
QmlV8ObjectData objectData;
const QVariantMap dataMap = data.toMap();
objectData.name = dataMap.value(NAME).toString();
if (dataMap.contains(REF)) {
objectData.handle = dataMap.value(REF).toInt();
if (refVals.contains(objectData.handle)) {
QmlV8ObjectData data = refVals.value(objectData.handle);
objectData.type = data.type;
objectData.value = data.value;
objectData.properties = data.properties;
}
} else {
objectData.handle = dataMap.value(HANDLE).toInt();
QString type = dataMap.value(TYPE).toString();
if (type == "undefined") {
objectData.type = "undefined";
objectData.value = "undefined";
} else if (type == "null") { // Deprecated. typeof(null) == "object" in JavaScript
objectData.type = "object";
objectData.value = "null";
} else if (type == "boolean") {
objectData.type = "boolean";
objectData.value = dataMap.value(VALUE);
} else if (type == "number") {
objectData.type = "number";
objectData.value = dataMap.value(VALUE);
} else if (type == "string") {
QLatin1Char quote('"');
objectData.type = "string";
objectData.value = QString(quote + dataMap.value(VALUE).toString() + quote);
} else if (type == "object") {
objectData.type = "object";
// ignore "className": it doesn't make any sense.
if (dataMap.contains("properties"))
objectData.properties = dataMap.value("properties").toList();
else if (dataMap.value("value").isNull())
objectData.value = "null"; // Yes, null is an object.
} else if (type == "function") {
objectData.type = "function";
objectData.value = dataMap.value(NAME);
objectData.properties = dataMap.value("properties").toList();
} else if (type == "script") {
objectData.type = "script";
objectData.value = dataMap.value(NAME);
}
}
return objectData;
}
void QmlEnginePrivate::runCommand(const DebuggerCommand &command, const QmlCallback &cb)
{
QJsonObject object;
object.insert("seq", ++sequence);
object.insert("type", "request");
object.insert("command", command.function);
object.insert("arguments", command.args);
if (cb)
callbackForToken[sequence] = cb;
runDirectCommand(V8REQUEST, QJsonDocument(object).toJson(QJsonDocument::Compact));
}
void QmlEnginePrivate::runDirectCommand(const QString &type, const QByteArray &msg)
{
// Leave item as variable, serialization depends on it.
QByteArray cmd = V8DEBUG;
engine->showMessage(QString("%1 %2").arg(type, QString::fromLatin1(msg)), LogInput);
QPacket rs(connection->currentDataStreamVersion());
rs << cmd << type.toLatin1() << msg;
if (state() == Enabled)
sendMessage(rs.data());
else
sendBuffer.append(rs.data());
}
void QmlEnginePrivate::memorizeRefs(const QVariant &refs)
{
if (refs.isValid()) {
foreach (const QVariant &ref, refs.toList()) {
const QVariantMap refData = ref.toMap();
int handle = refData.value(HANDLE).toInt();
refVals[handle] = extractData(refData);
}
}
}
void QmlEnginePrivate::messageReceived(const QByteArray &data)
{
QPacket ds(connection->currentDataStreamVersion(), data);
QByteArray command;
ds >> command;
if (command == V8DEBUG) {
QByteArray type;
QByteArray response;
ds >> type >> response;
engine->showMessage(QLatin1String(type), LogOutput);
if (type == CONNECT) {
//debugging session started
} else if (type == INTERRUPT) {
//debug break requested
} else if (type == BREAKONSIGNAL) {
//break on signal handler requested
} else if (type == V8MESSAGE) {
SDEBUG(response);
engine->showMessage(QString(V8MESSAGE) + ' ' + QString::fromLatin1(response), LogOutput);
const QVariantMap resp = QJsonDocument::fromJson(response).toVariant().toMap();
const QString type = resp.value(TYPE).toString();
if (type == "response") {
const QString debugCommand(resp.value(COMMAND).toString());
memorizeRefs(resp.value(REFS));
bool success = resp.value("success").toBool();
if (!success) {
SDEBUG("Request was unsuccessful");
}
int requestSeq = resp.value("request_seq").toInt();
if (callbackForToken.contains(requestSeq)) {
callbackForToken[requestSeq](resp);
} else if (debugCommand == DISCONNECT) {
//debugging session ended
} else if (debugCommand == CONTINEDEBUGGING) {
//do nothing, wait for next break
} else if (debugCommand == SETBREAKPOINT) {
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "setbreakpoint",
// "body" : { "type" : <"function" or "script">
// "breakpoint" : <break point number of the new break point>
// }
// "running" : <is the VM running after sending this response>
// "success" : true
// }
int seq = resp.value("request_seq").toInt();
const QVariantMap breakpointData = resp.value(BODY).toMap();
int index = breakpointData.value("breakpoint").toInt();
if (breakpointsSync.contains(seq)) {
BreakpointModelId id = breakpointsSync.take(seq);
breakpoints.insert(id, index);
//Is actual position info present? Then breakpoint was
//accepted
const QVariantList actualLocations =
breakpointData.value("actual_locations").toList();
if (actualLocations.count()) {
//The breakpoint requested line should be same as
//actual line
BreakHandler *handler = engine->breakHandler();
Breakpoint bp = handler->breakpointById(id);
if (bp.state() != BreakpointInserted) {
BreakpointResponse br = bp.response();
br.lineNumber = breakpointData.value("line").toInt() + 1;
br.pending = false;
bp.setResponse(br);
bp.notifyBreakpointInsertOk();
}
}
} else {
breakpointsTemp.append(index);
}
} else if (debugCommand == CLEARBREAKPOINT) {
// DO NOTHING
} else if (debugCommand == SETEXCEPTIONBREAK) {
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "setexceptionbreak",
// "body" : { "type" : <string: "all" or "uncaught" corresponding to the request.>,
// "enabled" : <bool: true if the break type is currently enabled as a result of the request>
// }
// "running" : true
// "success" : true
// }
} else if (debugCommand == SCRIPTS) {
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "scripts",
// "body" : [ { "name" : <name of the script>,
// "id" : <id of the script>
// "lineOffset" : <line offset within the containing resource>
// "columnOffset" : <column offset within the containing resource>
// "lineCount" : <number of lines in the script>
// "data" : <optional data object added through the API>
// "source" : <source of the script if includeSource was specified in the request>
// "sourceStart" : <first 80 characters of the script if includeSource was not specified in the request>
// "sourceLength" : <total length of the script in characters>
// "scriptType" : <script type (see request for values)>
// "compilationType" : < How was this script compiled:
// 0 if script was compiled through the API
// 1 if script was compiled through eval
// >
// "evalFromScript" : <if "compilationType" is 1 this is the script from where eval was called>
// "evalFromLocation" : { line : < if "compilationType" is 1 this is the line in the script from where eval was called>
// column : < if "compilationType" is 1 this is the column in the script from where eval was called>
// ]
// "running" : <is the VM running after sending this response>
// "success" : true
// }
if (success) {
const QVariantList body = resp.value(BODY).toList();
QStringList sourceFiles;
for (int i = 0; i < body.size(); ++i) {
const QVariantMap entryMap = body.at(i).toMap();
const int lineOffset = entryMap.value("lineOffset").toInt();
const int columnOffset = entryMap.value("columnOffset").toInt();
const QString name = entryMap.value("name").toString();
const QString source = entryMap.value("source").toString();
if (name.isEmpty())
continue;
if (!sourceFiles.contains(name))
sourceFiles << name;
updateScriptSource(name, lineOffset, columnOffset, source);
}
QMap<QString,QString> files;
foreach (const QString &file, sourceFiles) {
QString shortName = file;
QString fullName = engine->toFileInProject(file);
files.insert(shortName, fullName);
}
engine->sourceFilesHandler()->setSourceFiles(files);
//update open editors
}
} else {
// DO NOTHING
}
} else if (type == EVENT) {
const QString eventType(resp.value(EVENT).toString());
if (eventType == "break") {
clearRefs();
const QVariantMap breakData = resp.value(BODY).toMap();
const QString invocationText = breakData.value("invocationText").toString();
const QString scriptUrl = breakData.value("script").toMap().value("name").toString();
const QString sourceLineText = breakData.value("sourceLineText").toString();
bool inferiorStop = true;
QList<int> v8BreakpointIds;
{
const QVariantList v8BreakpointIdList = breakData.value("breakpoints").toList();
foreach (const QVariant &breakpointId, v8BreakpointIdList)
v8BreakpointIds << breakpointId.toInt();
}
if (!v8BreakpointIds.isEmpty() && invocationText.startsWith("[anonymous]()")
&& scriptUrl.endsWith(".qml")
&& sourceLineText.trimmed().startsWith('(')) {
// we hit most likely the anonymous wrapper function automatically generated for bindings
// -> relocate the breakpoint to column: 1 and continue
int newColumn = sourceLineText.indexOf('(') + 1;
BreakHandler *handler = engine->breakHandler();
foreach (int v8Id, v8BreakpointIds) {
const BreakpointModelId id = breakpoints.key(v8Id);
Breakpoint bp = handler->breakpointById(id);
if (bp.isValid()) {
const BreakpointParameters ¶ms = bp.parameters();
clearBreakpoint(v8Id);
setBreakpoint(SCRIPTREGEXP,
params.fileName,
params.enabled,
params.lineNumber,
newColumn,
params.condition,
params.ignoreCount);
breakpointsSync.insert(sequence, id);
}
}
continueDebugging(Continue);
inferiorStop = false;
}
//Skip debug break if this is an internal function
if (sourceLineText == INTERNAL_FUNCTION) {
continueDebugging(previousStepAction);
inferiorStop = false;
}
if (inferiorStop) {
//Update breakpoint data
BreakHandler *handler = engine->breakHandler();
foreach (int v8Id, v8BreakpointIds) {
const BreakpointModelId id = breakpoints.key(v8Id);
Breakpoint bp = handler->breakpointById(id);
if (bp) {
BreakpointResponse br = bp.response();
if (br.functionName.isEmpty()) {
br.functionName = invocationText;
bp.setResponse(br);
}
if (bp.state() != BreakpointInserted) {
br.lineNumber = breakData.value("sourceLine").toInt() + 1;
br.pending = false;
bp.setResponse(br);
bp.notifyBreakpointInsertOk();
}
}
}
if (engine->state() == InferiorRunOk) {
foreach (const QVariant &breakpointId, v8BreakpointIds) {
if (breakpointsTemp.contains(breakpointId.toInt()))
clearBreakpoint(breakpointId.toInt());
}
engine->notifyInferiorSpontaneousStop();
backtrace();
} else if (engine->state() == InferiorStopRequested) {
engine->notifyInferiorStopOk();
backtrace();
}
}
} else if (eventType == "exception") {
const QVariantMap body = resp.value(BODY).toMap();
int lineNumber = body.value("sourceLine").toInt() + 1;
const QVariantMap script = body.value("script").toMap();
QUrl fileUrl(script.value(NAME).toString());
QString filePath = engine->toFileInProject(fileUrl);
const QVariantMap exception = body.value("exception").toMap();
QString errorMessage = exception.value("text").toString();
QStringList messages = highlightExceptionCode(lineNumber, filePath, errorMessage);
foreach (const QString msg, messages)
engine->showMessage(msg, ConsoleOutput);
if (engine->state() == InferiorRunOk) {
engine->notifyInferiorSpontaneousStop();
backtrace();
}
if (engine->state() == InferiorStopOk)
backtrace();
} else if (eventType == "afterCompile") {
//Currently break point relocation is disabled.
//Uncomment the line below when it will be enabled.
// listBreakpoints();
}
//Sometimes we do not get event type!
//This is most probably due to a wrong eval expression.
//Redirect output to console.
if (eventType.isEmpty()) {
debuggerConsole()->printItem(new ConsoleItem(
ConsoleItem::ErrorType,
resp.value(MESSAGE).toString()));
}
} //EVENT
} //V8MESSAGE
} else {
//DO NOTHING
}
}
void QmlEnginePrivate::handleBacktrace(const QVariantMap &response)
{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "backtrace",
// "body" : { "fromFrame" : <number>
// "toFrame" : <number>
// "totalFrames" : <number>
// "frames" : <array of frames - see frame request for details>
// }
// "running" : <is the VM running after sending this response>
// "success" : true
// }
const QVariantMap body = response.value(BODY).toMap();
const QVariantList frames = body.value("frames").toList();
int fromFrameIndex = body.value("fromFrame").toInt();
QTC_ASSERT(0 == fromFrameIndex, return);
StackHandler *stackHandler = engine->stackHandler();
StackFrames stackFrames;
int i = 0;
stackIndexLookup.clear();
foreach (const QVariant &frame, frames) {
StackFrame stackFrame = extractStackFrame(frame);
if (stackFrame.level.isEmpty())
continue;
stackIndexLookup.insert(i, stackFrame.level.toInt());
stackFrames << stackFrame;
i++;
}
stackHandler->setFrames(stackFrames);
stackHandler->setCurrentIndex(0);
updateLocals();
}
StackFrame QmlEnginePrivate::extractStackFrame(const QVariant &bodyVal)
{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "frame",
// "body" : { "index" : <frame number>,
// "receiver" : <frame receiver>,
// "func" : <function invoked>,
// "script" : <script for the function>,
// "constructCall" : <boolean indicating whether the function was called as constructor>,
// "debuggerFrame" : <boolean indicating whether this is an internal debugger frame>,
// "arguments" : [ { name: <name of the argument - missing of anonymous argument>,
// value: <value of the argument>
// },
// ... <the array contains all the arguments>
// ],
// "locals" : [ { name: <name of the local variable>,
// value: <value of the local variable>
// },
// ... <the array contains all the locals>
// ],
// "position" : <source position>,
// "line" : <source line>,
// "column" : <source column within the line>,
// "sourceLineText" : <text for current source line>,
// "scopes" : [ <array of scopes, see scope request below for format> ],
// }
// "running" : <is the VM running after sending this response>
// "success" : true
// }
const QVariantMap body = bodyVal.toMap();
StackFrame stackFrame;
stackFrame.level = body.value("index").toString();
//Do not insert the frame corresponding to the internal function
if (body.value("sourceLineText") == INTERNAL_FUNCTION) {
stackFrame.level.clear();
return stackFrame;
}
QmlV8ObjectData objectData = extractData(body.value("func"));
QString functionName = objectData.value.toString();
if (functionName.isEmpty())
functionName = QCoreApplication::translate("QmlEngine", "Anonymous Function");
stackFrame.function = functionName;
objectData = extractData(body.value("script"));
stackFrame.file = engine->toFileInProject(objectData.value.toString());
stackFrame.usable = QFileInfo(stackFrame.file).isReadable();
objectData = extractData(body.value("receiver"));
stackFrame.receiver = objectData.value.toString();
stackFrame.line = body.value("line").toInt() + 1;
return stackFrame;
}
void QmlEnginePrivate::handleFrame(const QVariantMap &response)
{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "frame",
// "body" : { "index" : <frame number>,
// "receiver" : <frame receiver>,
// "func" : <function invoked>,
// "script" : <script for the function>,
// "constructCall" : <boolean indicating whether the function was called as constructor>,
// "debuggerFrame" : <boolean indicating whether this is an internal debugger frame>,
// "arguments" : [ { name: <name of the argument - missing of anonymous argument>,
// value: <value of the argument>
// },
// ... <the array contains all the arguments>
// ],
// "locals" : [ { name: <name of the local variable>,
// value: <value of the local variable>
// },
// ... <the array contains all the locals>
// ],
// "position" : <source position>,
// "line" : <source line>,
// "column" : <source column within the line>,
// "sourceLineText" : <text for current source line>,
// "scopes" : [ <array of scopes, see scope request below for format> ],
// }
// "running" : <is the VM running after sending this response>
// "success" : true
// }
QVariantMap body = response.value(BODY).toMap();
StackHandler *stackHandler = engine->stackHandler();
WatchHandler * watchHandler = engine->watchHandler();
watchHandler->notifyUpdateStarted();
const int frameIndex = stackHandler->currentIndex();
if (frameIndex < 0)
return;
const StackFrame frame = stackHandler->currentFrame();
if (!frame.isUsable())
return;
// Always add a "this" variable
{
QString iname = "local.this";
QString exp = "this";
QmlV8ObjectData objectData = extractData(body.value("receiver"));
auto item = new WatchItem;
item->iname = iname;
item->name = exp;
item->id = objectData.handle;
item->type = objectData.type;
item->value = objectData.value.toString();
item->setHasChildren(objectData.properties.count());
// In case of global object, we do not get children
// Set children nevertheless and query later.
if (item->value == "global") {
item->setHasChildren(true);
item->id = 0;
}
watchHandler->insertItem(item);
evaluate(exp, [this, iname, exp](const QVariantMap &response) {
handleEvaluateExpression(response, iname, exp);
});
}
currentFrameScopes.clear();
const QVariantList scopes = body.value("scopes").toList();
foreach (const QVariant &scope, scopes) {
//Do not query for global types (0)
//Showing global properties increases clutter.
if (scope.toMap().value("type").toInt() == 0)
continue;
int scopeIndex = scope.toMap().value("index").toInt();
currentFrameScopes.append(scopeIndex);
this->scope(scopeIndex);
}
engine->gotoLocation(stackHandler->currentFrame());
// Send watchers list
if (stackHandler->isContentsValid() && stackHandler->currentFrame().isUsable()) {
QStringList watchers = watchHandler->watchedExpressions();
foreach (const QString &exp, watchers) {
const QString iname = watchHandler->watcherName(exp);
evaluate(exp, [this, iname, exp](const QVariantMap &response) {
handleEvaluateExpression(response, iname, exp);
});
}
}
}
void QmlEnginePrivate::handleScope(const QVariantMap &response)
{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "scope",
// "body" : { "index" : <index of this scope in the scope chain. Index 0 is the top scope
// and the global scope will always have the highest index for a
// frame>,
// "frameIndex" : <index of the frame>,
// "type" : <type of the scope:
// 0: Global
// 1: Local
// 2: With
// 3: Closure
// 4: Catch >,
// "object" : <the scope object defining the content of the scope.
// For local and closure scopes this is transient objects,
// which has a negative handle value>
// }
// "running" : <is the VM running after sending this response>
// "success" : true
// }
QVariantMap bodyMap = response.value(BODY).toMap();
//Check if the frameIndex is same as current Stack Index
StackHandler *stackHandler = engine->stackHandler();
if (bodyMap.value("frameIndex").toInt() != stackHandler->currentIndex())
return;
QmlV8ObjectData objectData = extractData(bodyMap.value("object"));
LookupItems itemsToLookup;
foreach (const QVariant &property, objectData.properties) {
QmlV8ObjectData localData = extractData(property);
auto item = new WatchItem;
item->exp = localData.name;
//Check for v8 specific local data
if (item->exp.startsWith('.') || item->exp.isEmpty())
continue;
item->name = item->exp;
item->iname = "local." + item->exp;
item->id = localData.handle;
if (localData.value.isValid()) {
item->type = localData.type;
item->value = localData.value.toString();
item->setHasChildren(localData.properties.count());
engine->watchHandler()->insertItem(item);
} else {
itemsToLookup.insert(int(item->id), {item->iname, item->name, item->exp});
}
}
lookup(itemsToLookup);
checkForFinishedUpdate();
}
void QmlEnginePrivate::checkForFinishedUpdate()
{
if (currentlyLookingUp.isEmpty())
engine->watchHandler()->notifyUpdateFinished();
}
ConsoleItem *QmlEnginePrivate::constructLogItemTree(const QmlV8ObjectData &objectData)
{
QList<int> handles;
return constructLogItemTree(objectData, handles);
}
void QmlEnginePrivate::constructChildLogItems(ConsoleItem *item, const QmlV8ObjectData &objectData,
QList<int> &seenHandles)
{
// We cannot sort the children after attaching them to the parent as that would cause layout
// changes, invalidating cached indices. So we presort them before inserting.
QVarLengthArray<ConsoleItem *> children(objectData.properties.size());
auto it = children.begin();
foreach (const QVariant &property, objectData.properties)
*(it++) = constructLogItemTree(extractData(property), seenHandles);
if (boolSetting(SortStructMembers))
std::sort(children.begin(), children.end(), compareConsoleItems);
foreach (ConsoleItem *child, children)
item->appendChild(child);
}
ConsoleItem *QmlEnginePrivate::constructLogItemTree(const QmlV8ObjectData &objectData,
QList<int> &seenHandles)
{
QString text;
if (objectData.value.isValid()) {
text = objectData.value.toString();
} else if (!objectData.type.isEmpty()) {
text = objectData.type;
} else {
int handle = objectData.handle;
ConsoleItem *item = new ConsoleItem(ConsoleItem::DefaultType,
objectData.name,
[this, handle](ConsoleItem *item)
{
DebuggerCommand cmd(LOOKUP);
cmd.arg(HANDLES, QList<int>() << handle);
runCommand(cmd, [this, item, handle](const QVariantMap &response) {
const QVariantMap body = response.value(BODY).toMap();
QStringList handlesList = body.keys();
foreach (const QString &handleString, handlesList) {
if (handle != handleString.toInt())
continue;
QmlV8ObjectData objectData = extractData(body.value(handleString));
// keep original name, if possible
QString name = item->expression();
if (name.isEmpty())
name = objectData.name;
QString value = objectData.value.isValid() ?
objectData.value.toString() : objectData.type;
// We can do setData() and cause dataChanged() here, but only because this
// callback is executed after fetchMore() has returned.
item->model()->setData(item->index(),
QString("%1: %2").arg(name, value),
ConsoleItem::ExpressionRole);
QList<int> newHandles;
constructChildLogItems(item, objectData, newHandles);
break;
}
});
});
return item;
}
if (!objectData.name.isEmpty())
text = QString("%1: %2").arg(objectData.name, text);
if (objectData.properties.isEmpty())
return new ConsoleItem(ConsoleItem::DefaultType, text);
if (seenHandles.contains(objectData.handle)) {
ConsoleItem *item = new ConsoleItem(ConsoleItem::DefaultType, text,
[this, objectData](ConsoleItem *item)
{
QList<int> newHandles;
constructChildLogItems(item, objectData, newHandles);
});
return item;
}
seenHandles.append(objectData.handle);
ConsoleItem *item = new ConsoleItem(ConsoleItem::DefaultType, text);
constructChildLogItems(item, objectData, seenHandles);
seenHandles.removeLast();
return item;
}
void QmlEnginePrivate::insertSubItems(WatchItem *parent, const QVariantList &properties)
{
QTC_ASSERT(parent, return);
LookupItems itemsToLookup;
const QSet<QString> expandedINames = engine->watchHandler()->expandedINames();
foreach (const QVariant &property, properties) {
QmlV8ObjectData propertyData = extractData(property);
auto item = new WatchItem;
item->name = propertyData.name;
// Check for v8 specific local data
if (item->name.startsWith('.') || item->name.isEmpty())
continue;
if (parent->type == "object") {
if (parent->value == "Array")
item->exp = parent->exp + '[' + item->name + ']';
else if (parent->value == "Object")
item->exp = parent->exp + '.' + item->name;
} else {
item->exp = item->name;
}
item->iname = parent->iname + '.' + item->name;
item->id = propertyData.handle;
item->type = propertyData.type;
item->value = propertyData.value.toString();
if (item->type.isEmpty() || expandedINames.contains(item->iname))
itemsToLookup.insert(propertyData.handle, {item->iname, item->name, item->exp});
item->setHasChildren(propertyData.properties.count() > 0);
parent->appendChild(item);
}
if (boolSetting(SortStructMembers)) {
parent->sortChildren([](const WatchItem *item1, const WatchItem *item2) {
return item1->name < item2->name;
});
}
lookup(itemsToLookup);
}
void QmlEnginePrivate::handleExecuteDebuggerCommand(const QVariantMap &response)
{
auto it = response.constFind(SUCCESS);
if (it != response.constEnd() && it.value().toBool()) {
debuggerConsole()->printItem(constructLogItemTree(extractData(response.value(BODY))));
// Update the locals
foreach (int index, currentFrameScopes)
scope(index);
} else {
debuggerConsole()->printItem(new ConsoleItem(ConsoleItem::ErrorType,
response.value(MESSAGE).toString()));
}
}
void QmlEnginePrivate::handleLookup(const QVariantMap &response)
{
// { "seq" : <number>,
// "type" : "response",
// "request_seq" : <number>,
// "command" : "lookup",
// "body" : <array of serialized objects indexed using their handle>
// "running" : <is the VM running after sending this response>
// "success" : true
// }
const QVariantMap body = response.value(BODY).toMap();
QStringList handlesList = body.keys();
foreach (const QString &handleString, handlesList) {
int handle = handleString.toInt();
QmlV8ObjectData bodyObjectData = extractData(body.value(handleString));
QList<LookupData> vals = currentlyLookingUp.values(handle);
currentlyLookingUp.remove(handle);
foreach (const LookupData &res, vals) {
auto item = new WatchItem;
item->exp = res.exp;
item->iname = res.iname;
item->name = res.name;
item->id = handle;
item->type = bodyObjectData.type;
item->value = bodyObjectData.value.toString();
item->setHasChildren(bodyObjectData.properties.count());
insertSubItems(item, bodyObjectData.properties);
engine->watchHandler()->insertItem(item);
}
}
checkForFinishedUpdate();
}
void QmlEnginePrivate::stateChanged(State state)
{
engine->logServiceStateChange(name(), serviceVersion(), state);
if (state == QmlDebugClient::Enabled) {
/// Start session.
flushSendBuffer();
runDirectCommand(CONNECT);
runCommand({VERSION}, CB(handleVersion));
}
}
void QmlEnginePrivate::handleVersion(const QVariantMap &response)
{
unpausedEvaluate = response.value(BODY).toMap().value("UnpausedEvaluate", false).toBool();
}
void QmlEnginePrivate::flushSendBuffer()
{
QTC_ASSERT(state() == Enabled, return);
foreach (const QByteArray &msg, sendBuffer)
sendMessage(msg);
sendBuffer.clear();
}
DebuggerEngine *createQmlEngine(const DebuggerRunParameters &sp)
{
return new QmlEngine(sp);
}
} // Internal
} // Debugger
|