summaryrefslogtreecommitdiffstats
path: root/libqsystemtest/qsystemtest.cpp
blob: 3535df2ddac914f98e318c6040fac5da36bd9dc4 (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
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
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of QtUiTest.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <qsystemtest.h>
#include "qsystemtestmaster_p.h"
#include "qtuitest_config.h"
#include "qtestide.h"
#include "ui_recorddlg.h"

#ifdef QTCREATOR_QTEST
# include "testoutputwindow.h"
#endif

#include <QDir>
#include <QProcess>
#include <QMessageBox>
#include <QTemporaryFile>
#include <QTextEdit>
#include <QSignalSpy>
#include <QSettings>

#include <sys/types.h>
#include <signal.h>
#include <errno.h>

#undef qLog
#define qLog(A) if (0); else (QDebug(QtDebugMsg) << #A ":")
#define OBJECT_EXIST_TIMEOUT 1000

#define BT(message) (\
    message["location"] = QString("%1:%2%3").arg(__FILE__).arg(__LINE__).arg(!message["location"].toString().isEmpty() ? QString("\n") + message["location"].toString() : QString()),\
    message)

#undef QFAIL
#define QFAIL(message) \
do {\
    setQueryError(message);\
    return;\
} while(0)

#define CHECK_FORCED_MANUAL(msg) \
if (m_run_as_manual_test) {\
    m_manual_commands += msg.event() + msg.msgId() + msg.toString() + "\n";\
    QTestMessage reply;\
    reply["status"] = "OK";\
    return reply;\
}

QString quote(const QString &item)
{
    if (item == "MAGIC_DATA" || item.contains("'"))
        return item;
    else
        return "'" + item + "'";
}

QString mouseButtons( QFlags<Qt::MouseButton> buttons )
{
    QString ret;
    if (buttons) {
        ret = "";
        if ((buttons & Qt::LeftButton) > 0)
            ret += "'Left'+ ";
        if ((buttons & Qt::MidButton) > 0)
            ret += "'Mid'+ ";
        if ((buttons & Qt::RightButton) > 0)
            ret += "'Right'+ ";
        if ((buttons & Qt::XButton1) > 0)
            ret += "'X1'+ ";
        if ((buttons & Qt::XButton2) > 0)
            ret += "'X2'+ ";
        ret = ret.left(ret.length()-2);
    }
    return ret;
}

/*!
    \enum QSystemTest::EnterMode

    This enum specifies whether enter() should commit the entered value (eg, by simulating a Select
    keypress) or not.

    \value Commit          Commit the value (default).
    \value NoCommit        Do not commit the value.
*/

/*!
    \enum QSystemTest::StartApplicationFlag

    This enum describes additional behaviour to use when starting applications
    by startApplication().

    \value NoFlag          Don't apply any of the below flags.
    \value WaitForFocus    Wait for the application to gain keyboard focus before returning.
    \value BackgroundCurrentApplication Use multitasking to background the current application.
                            The default behaviour is to exit the current application.
*/

/*!
    \enum QSystemTest::SkipMode

    This enum describes the modes for skipping tests during execution of the test data.
    \value SkipSingle Skip the rest of this test function for the current test data entry, but continue execution of the remaining test data.
    \value SkipAll Skip the rest of this test function, and do not process any further test data for this test function.

    \sa skip(), QTest::SkipMode
*/

/*!
    \enum QSystemTest::LabelOrientation

    This enum is used to indicate the expected position of a label relative to the widget it is
    associated with. Use setLabelOrientation() to change the expected layout.

    \value LabelLeft       Label is located to left of widget.
    \value LabelRight      Label is located to right of widget.
    \value LabelAbove      Label is located above widget.
    \value LabelBelow      Label is located below widget.

    \sa labelOrientation(), setLabelOrientation()
*/

/*!
    \preliminary
    \namespace QSystemTest
    \brief The QSystemTest namespace provides script based system test functionality for Qt.

    \ingroup qtuitest_systemtest
    \inpublicgroup QtUiTestModule

    This documentation describes the API reference for the QtUiTest scripting language. Please read the \l{QtUiTest Manual} for a full description of the system test tool.

*/

/*! \internal */
QMap<QString, int> QSystemTest::filteredMessages() const
{
    return m_filteredMessages;
}

/*! \internal */
void QSystemTest::clearFilteredMessages()
{
    m_filteredMessages.clear();
}

/*! \internal */
bool QSystemTest::shouldFilterMessage(char const *msg)
{
    static QList<QRegExp> filters;
    if (filters.isEmpty()) {
        QStringList defaultFilters;
//        defaultFilters
//            << "^Connected to VFB server"
//            << "^QTimeLine::start: already running$" // Bug
//        ;
        QStringList stringFilters = QSettings("Trolltech", "QtUitest")
                                .value("Logging/Filters", defaultFilters)
                                .toStringList();
        foreach (QString s, stringFilters) {
            filters << QRegExp(s);
        }
    }

    QString message = QString::fromLocal8Bit(msg);
    foreach (QRegExp r, filters) {
        if (-1 != r.indexIn(message)) {
            ++m_filteredMessages[message];
            return true;
        }
    }
    return false;
}

/*!
    \internal
    Creates the test class.
    Generally you would use the \l {QTest}{QTEST_MAIN()} macro rather than create the class directly.
*/
QSystemTest::QSystemTest()
    : QAbstractTest()
    , event_timer(0)
    , m_test_app(0)
    , m_recorded_events_edit(0)
    , recorded_events_as_code(true)
    , record_prompt(false)
    , query_warning_mode(true)
    , fatal_timeouts(1)
    , timeouts(0)
    , m_keyclickhold_key((Qt::Key)0)
    , current_application("")
    , current_app_version("")
    , m_loc_fname("")
    , m_loc_line(-1)
    , m_auto_mode(false)
    , m_run_as_manual_test(false)
    , m_aut_port(DEFAULT_AUT_PORT)
    , m_keep_aut(false)
    , m_silent_aut(false)
    , m_no_aut(false)
    , m_demo_mode(false)
    , m_verbose(false)
    , m_strict_mode(false)
    , m_visible_response_time(4000)
    , recorded_events()
    , m_recorded_code()
    , display_id(0)
    , device()
    , m_mousePreferred(false)
    , screenGeometry()
    , theme()
    , m_config_id()    
    , m_recording_events(false)
    , m_expect_app_close(false)
{
    m_env.clear();
    ssh_param.host = "127.0.0.1";
    ssh_param.port = 22;
    device_controller = 0;

    QTestIDE::instance()->setSystemTest(this);
    (void)qMetaTypeId<RecordEvent>();
    (void)qMetaTypeId< QList<RecordEvent> >();
    qRegisterMetaType<QTestMessage>("QTestMessage");
    qRegisterMetaType<QTestMessage*>("QTestMessage*");
}

/*!
    \internal
    Destroys the test class.
*/
QSystemTest::~QSystemTest()
{
    if (device_controller)
        device_controller->killApplications();

    delete device_controller;
    delete event_timer;
    delete m_test_app;
    while (expected_msg_boxes.count() > 0)
        delete expected_msg_boxes.takeFirst();
}

void QSystemTest::setConnectionParameters( Qt4Test::TestController::TestDeviceType &type,
                                          Core::SshConnectionParameters param )
{
    ssh_param = param;
    device_controller = new Qt4Test::TestController( type, &param);
}

/*!
    Returns the signature of the currently active window.

    \sa {Query Paths}
*/
QString QSystemTest::activeWindow()
{
    if (runAsManualTest()) {
        manualTestData( "the currently active window" );
        return "MAGIC_DATA";
    }

    QString ret;
    return queryWithReturn(ret, "activeWindow", "");
}

/*!
    Returns the signature of the widget that has keyboard focus.

    Example:
    \code
        // Get the currently focused widget in the current app
        print( focusWidget() );
    \endcode

    \sa {Query Paths}
*/
QString QSystemTest::focusWidget()
{
    if (runAsManualTest()) {
        manualTestData( "the currently focused widget" );
        return "MAGIC_DATA";
    }

    QString ret;
    return queryWithReturn(ret, "focusWidget", "");
}


/*!
    Returns the currently selected text from the widget specified by \a {queryPath}.
    If no text is selected, returns all text.
    For list-type widgets, returns the text for the currently selected item.

    Example:
    \code
        // Enter text in two fields, then go back to the first
        // and make sure it still has the right text
        enter("Australia", "Home");
        enter("dog walker", "Occupation");
        compare( getSelectedText("Home"), "Australia" );
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
QString QSystemTest::getSelectedText( const QString &queryPath )
{
    if (runAsManualTest()) {
        manualTestData( "selected text for " + quote(queryPath) );
        return "MAGIC_DATA";
    }

    QString ret = "";
    return queryWithReturn(ret, "getSelectedText", queryPath);
}

/*!
    Returns all text from the widget specified by \a {queryPath}, or the current
    focus widget if \a {queryPath} is not specified.
    For list-type widgets, returns the text for all items separated by newlines.

    Example:
    \code
        // Get current content of "address" field
        print( getText("Address") );
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
QString QSystemTest::getText( const QString &queryPath )
{
    if (runAsManualTest()) {
        manualTestData( "text for " + quote(queryPath) );
        return "MAGIC_DATA";
    }

    QString ret;
    return queryWithReturn(ret, "getText", queryPath);
}

/*!
    Returns the currently selected value from the widget specified by \a {queryPath}.
    If no value is selected, returns all data in a single value.
    For list-type widgets, returns the currently selected value.

    \sa getSelectedText(), {Query Paths}, {Querying Objects}
*/
QVariant QSystemTest::getSelectedValue( const QString &queryPath )
{
    QVariant ret;
    if (runAsManualTest()) {
        manualTestData( "selected value for " + quote(queryPath) );
        ret = "MAGIC_DATA";
        return ret;
    }

    QString msg("getSelectedValue");
    QTestMessage reply;
    QTestMessage testMessage(msg);
    if (!doQuery(testMessage, queryPath, &reply)) return ret;
    if (!reply[msg].isValid()) {
        reply["status"] = QString("ERROR: no data in reply to %1; status: %2").arg(msg).arg(reply["status"].toString());
        setQueryError(reply);
        return ret;
    }
    return reply[msg];
}

/*!
    Returns the value from the widget specified by \a {queryPath}.
    For list-type widgets, returns a list containing all values.

    \sa getText(), {Query Paths}, {Querying Objects}
*/
QVariant QSystemTest::getValue( const QString &queryPath )
{
    QVariant ret;
    if (runAsManualTest()) {
        manualTestData( "value for " + quote(queryPath) );
        ret = "MAGIC_DATA";
        return ret;
    }

    QString msg("getValue");
    QTestMessage reply;
    QTestMessage testMessage(msg);
    if (!doQuery(testMessage, queryPath, &reply)) return ret;
    if (!reply[msg].isValid()) {
        reply["status"] = QString("ERROR: no data in reply to %1; status: %2").arg(msg).arg(reply["status"].toString());        
        setQueryError(reply);
        return ret;
    }
    return reply[msg];
}

/*!
    Returns true if the primary input method is mouse/touchscreen.

    \sa setMousePreferred()
*/
bool QSystemTest::mousePreferred()
{
    if (runAsManualTest()) {
        qDebug() << "QSystemTest::mousePreferred() set to 'true'";
        return true; //FIXME TODO
    }

    bool ret;
    return queryWithReturn(ret, "mousePreferred", "");
}

/*!
    If \a useMouse is true, indicates that QtUiTest should use mouse/touchscreen
    events to select items on the screen. If false, the keyboard will be used.

    The setting will remain active until the application under test closes, or
    until the value is changed by another call to setMousePreferred().

    \sa mousePreferred()
*/
void QSystemTest::setMousePreferred(bool useMouse)
{
    QTestMessage message("setMousePreferred");
    message["useMouse"] = useMouse;
    queryPassed( "OK", "", BT(message));
}

/*!
    Returns the label orientation, used by QtUiTest to assign labels to
    widgets.

    \sa setLabelOrientation()
*/
QSystemTest::LabelOrientation QSystemTest::labelOrientation()
{
    if (runAsManualTest()) {
        qDebug() << "QSystemTest::labelOrientation() set to 'LabelLeft'";
        return LabelLeft; //FIXME TODO
    }

    int ret;
    return static_cast<LabelOrientation>(queryWithReturn(ret, "labelOrientation", ""));
}

/*!
    Set the expected label orientation to \a orientation. This value is used by
    QtUiTest to work out which labels refer to which widgets. By default, this
    value is LabelLeft (on left-to-right locales) or LabelRight (on right-to-left
    locales).

    The setting will remain active until the application under test closes, or
    until the value is changed by another call to setLabelOrientation().

    \sa labelOrientation()
*/
void QSystemTest::setLabelOrientation(LabelOrientation orientation)
{
    QTestMessage message("setLabelOrientation");
    message["orientation"] = orientation;
    queryPassed( "OK", "", BT(message));
}

/*!
    Returns a list of all items from the list-type widget specified by \a {queryPath}.

    The items will be returned in the order they are stored in the widget (for example,
    for a simple list view the items will be returned from top to bottom).

    Example:
    \code
        // Verify that "gender" combobox contains male and female only
        var g = getList("Gender");
        compare( g.length == 2 );
        verify( g.contains("Male") );
        verify( g.contains("Female") );
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
QStringList QSystemTest::getList( const QString &queryPath )
{
    if (runAsManualTest()) {
        manualTestData( "the contents of list " + quote(queryPath) );
        return QStringList("MAGIC_DATA");
    }

    QStringList ret;
    return queryWithReturn(ret, "getList", queryPath);
}

QPoint QSystemTest::getCenter( const QString &item, const QString &queryPath )
{
    if (item.isNull()) return QPoint();

    if (runAsManualTest()) {
        manualTestData( "the center of " + quote(item) );
        return QPoint();
    }

    QTestMessage message("getCenter");
    message["item"] = item;
    queryPassed("OK", "", BT(message), queryPath);
    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), queryPath, &reply )) return QPoint();
    if (!reply["getCenter"].isValid()) {
        fail("Failed to get center for item");
        return QPoint();
    }
    return reply["getCenter"].value<QPoint>();
}
/*!
    Returns a list of all the labels that are visible in the current active window or the widget specified by \a {queryPath}.
    A label is usually a non-editable widget (such as a QLabel) that is associated with an editable field. The label is used to
    give the user a visual clue of the meaning of the editable field. Labels are used by the user, and by QtUitest, to
    navigate to fields.

    The items will be returned in the order they are displayed, i.e. from top left to bottom right.

    Example:
    \code
        // Verify that the current dialogs contains Labels named 'Name' and 'Email'
        var g = getLabels();
        verify( g.length == 2 );
        verify( g.contains("Name") );
        verify( g.contains("Email") );
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
QStringList QSystemTest::getLabels( const QString &queryPath )
{
    QStringList ret;
    if (runAsManualTest()) {
        manualTestData( "all labels for " + quote(queryPath) );
        ret = QStringList() << "MAGIC_DATA";
        return ret;
    }

    return queryWithReturn(ret, "getLabels", queryPath);
}

/*!
    Returns text stored in the clipboard, or an empty string if the clipboard does not contain any text.

    \sa setClipboardText()
*/
QString QSystemTest::getClipboardText( )
{
    if (runAsManualTest()) {
        manualTestData( "the current clipboard text" );
        return "MAGIC_DATA";
    }
    QString ret;
    return queryWithReturn(ret, "getClipboardText", "");
}

/*!
    Copies \a {text} into the clipboard.

    \sa getClipboardText()
*/
void QSystemTest::setClipboardText( const QString& text )
{
    if (runAsManualTest()) {
        manualTest( "save " + quote(text) + " to the clipboard" );
        return;
    }

    QTestMessage message("setClipboardText");
    message["text"] = text;
    queryPassed( "OK", "", BT(message));
}

/*!
    Returns the current window title for the application specified by \a {queryPath}.
    If \a queryPath contains a widget component, it will be ignored.

    Example:
    \code
        startApplication("Contacts") );

        ...

        // Make sure we are still in contacts
        compare( currentTitle(), "Contacts" );
    \endcode

    \sa {Query Paths}
*/
QString QSystemTest::currentTitle( const QString &queryPath )
{
    if (runAsManualTest()) {
        if (queryPath.isEmpty())
            manualTestData( "the current title" );
        else
            manualTestData( "the current title for " + quote(queryPath) );
        return "MAGIC_DATA";
    }

    QString ret;
    return queryWithReturn(ret, "currentTitle", queryPath);
}

/*!
    Returns the window titles for all top level windows in the application.
*/
QStringList QSystemTest::getWindowTitles()
{
    if (runAsManualTest()) {
        manualTestData( "all window titles" );
        return QStringList("MAGIC_DATA");
    }

    QStringList ret;
    return queryWithReturn(ret, "getWindowTitles", "");
}

/*!
    Brings the window specified by \a titleOrSignature to the foreground.
*/
void QSystemTest::activateWindow( const QString &titleOrSignature )
{
    if (runAsManualTest()) {
        manualTest( "activate window " + quote(titleOrSignature) );
        return;
    }

    QTestMessage message("activateWindow");
    message["window"] = titleOrSignature;
    queryPassed( "OK", "", BT(message));
}

/*!
    Returns the name of the application which currently has keyboard focus.
    The name will be the name returned by QCoreApplication::applicationName(),
    which may be an empty string.

    Example:
    \code
        compare( currentApplication(), "addressbook" );
    \endcode

    \sa applicationVersion()
*/
QString QSystemTest::currentApplication()
{
    return m_test_app->appName();
}

/*!
    Returns the version of the application under test. This is the value
    returned by QCoreApplication::applicationVersion(), which may be an
    empty string.

    \sa applicationName()
*/
QString QSystemTest::applicationVersion()
{
    return m_test_app->appVersion();
}

/*!
    Returns the version of Qt used by the application under test.

    \sa applicationName()
*/
QString QSystemTest::qtVersion()
{
    return m_test_app->qtVersion();
}

/*!
    \internal
    Returns the value of the environment variable for \a key set on the test
    system.
*/
QString QSystemTest::getenv(QString const& key)
{
    if (runAsManualTest()) {
        manualTestData( "environment variable " + quote(key) );
        return "MAGIC_DATA";
    }

    QTestMessage message("getenv");
    message["key"] = key;

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply )) return QString();
    if (!reply["getenv"].isValid()) {
        fail("No data in reply to getenv");
        return QString();
    }
    return reply["getenv"].toString();
}

/*!
    Returns true if the test system is running the operating system specified by \a os.

    The supported values are: UNIX, LINUX, MAEMO, MAC, WIN32, WINCE and SYMBIAN.
*/
bool QSystemTest::checkOS(QString const& os)
{
    if (runAsManualTest()) {
        manualTestData( "Operating System equals " + quote(os) );
        return true;
    }

    QTestMessage message("checkOS");
    message["os"] = os;

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply )) return false;
    if (!reply["checkOS"].isValid()) {
        fail("Failed to get details of OS");
        return false;
    }
    return reply["checkOS"].toBool();
}

/*!
  Returns the target identifier is used when needing to uniquely identifying
  the target.
  Default value for target identifier is \bold default unless set changed by
    \list 
        \o the -targetID option to qtuitestrunner
        \o the value of $QTUITEST_TARGETID environment variable when qtuitestrunner is launched
        \o the value set using the function setTargetIdentifier() in the test script
    \endlist

  /sa setTargetIdentifier()
  */
QString QSystemTest::targetIdentifier()
{
    if (m_run_as_manual_test)
        return QString();

    QTestMessage message("targetIdentifier");

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply )) return QString();
    if (!reply["targetIdentifier"].isValid()) {
        fail("No data in reply to targetIdentifier");
        return QString();
    }
    return reply["targetIdentifier"].toString();
}

/*!
  Sets the target identifier is used when needing to uniquely identifying
  the target.

  /sa targetIdentifier()
  */
void QSystemTest::setTargetIdentifier(const QString &id)
{
    if (m_run_as_manual_test)
        return;

    QTestMessage reply;
    QTestMessage message("setTargetIdentifier");
    message["targetIdentifier"] = id;

    queryPassed( "OK", "", BT(message), "", &reply);
}

/*!
    \internal
    Grabs a snapshot of the widget specified by \a {queryPath}, optionally excluding \a maskedWidgets from the snapshot.  Each masked widget is replaced by a black rectangle, and any overlapping widgets will also be concealed.

    To get a snapshot of the entire application window, use the query path "".

    Example:
    \code
        // Get current screenshot and save to disk
        QImage img = grabImage("");
        verify( img.save(currentDataPath() + "/snapshot.png", "PNG") );
    \endcode

    \sa {Query Paths}, verifyImage(), saveScreen()
*/
QImage QSystemTest::grabImage(const QString &queryPath, const QStringList &maskedWidgets )
{
    if (runAsManualTest()) {
        // FIXME TODO
        qDebug() << "QSystemTest::grabImage() skipped";
        return QImage();
    }

    QImage im;

    QTestMessage message("grabPixmap");
    message["mask"] = maskedWidgets;

    QTestMessage reply = query( BT(message), queryPath );
    if (reply["status"] != "OK" || queryFailed()) {
        fail( "Couldn't grab image: " + reply.toString());
    } else {
        if (!reply["grabPixmap"].isValid()) {
            fail( "Test slave returned no image" );
        } else {
            im = reply["grabPixmap"].value<QImage>();
        }
    }

    return im;
}

/*!
    Grabs a snapshot of the widget specified by \a {queryPath}, and compares it against the reference snapshot \a expectedName.

    New snapshots are gathered by running the test in \l {Learn Mode}{learn mode}, and are stored in the \c testdata subdirectory of the directory containing the test script.  When learn mode is used, a failed image comparison will result in a tester being presented with a manual verification dialog.

    If there is a mismatch between the images, the current test fails.

    When in learn mode, if \a comment is provided it will be shown to the user to help in determining whether or not the pixmap should be accepted.

    \a maskedWidgets is a list of query paths specifying widgets to be excluded from the snapshot.  This allows constantly changing widgets to be hidden from view while the snapshot is taken.  Each masked widget is replaced by a black rectangle, and any overlapping widgets will also be concealed.

    Example:
    \code
        verifyImage( "task_completed", "", "Verify that the current task is shown with a green tick indicating completion" );
    \endcode

    \sa saveScreen()
*/
void QSystemTest::verifyImage( const QString &expectedName, const QString &queryPath, const QString &comment, const QStringList &maskedWidgets )
{
    if (runAsManualTest()) {
        if (!comment.isEmpty())
            manualTest( comment );
        else
            manualTest( "verify that " + quote(queryPath) + " looks as expected" );
        return;
    }

    // Determine the filename
    // If the function was passed an explicit filename (indicated by an extension) it will be used directly
    // otherwise system specific values are prepended to the name.
    QString expectedFilename = currentDataPath();
    if ( expectedName.endsWith( ".png" ) ) {
        expectedFilename += "/" + expectedName;
    } else {
        expectedFilename += QString("/%1_%2.png")
            .arg( m_config_id )
            .arg( expectedName );
    }

    // The reference snapshot should exist in the data directory for this testcase.
    // If it's not there, and we're not in learn mode, we will fail.
    if ( (learnMode() == LearnNone || m_auto_mode) && !QFile::exists(expectedFilename) ) {
        fail(QString("Reference snapshot '%1' doesn't exist yet. Please manually run test in learn mode.").arg(expectedFilename));
        return;
    }

    // Now query AUT for the current snapshot
    QImage actualIm( grabImage(queryPath, maskedWidgets) );
    if (actualIm.isNull()) return;

    bool snapshotOk = false;
    QDir("/").mkpath(currentDataPath());
    QImage expectedIm(expectedFilename);

    // Now do the actual comparisons.
    // If we are not in learn mode, a difference in snapshots will cause a failure.
    // If we are in learn mode, a difference will cause a user prompt to accept the new snapshot.
    // If we are in learn-all mode, the prompt will be displayed every time.

    if ( (learnMode() != LearnAll || m_auto_mode) && QFile::exists(expectedFilename) ) {
        snapshotOk = imagesAreEqual(actualIm, expectedIm);
    }

    if ( !m_auto_mode && !snapshotOk && learnMode() != LearnNone ) {
        if ( learnImage(actualIm, expectedIm, comment) ) {
            QFile::remove(expectedFilename);
            if ( !actualIm.save(expectedFilename, "PNG", 0) ) {
                QWARN(QString("Failed to save image to %1!").arg(expectedFilename).toLatin1());
            } else {
                QTestIDE::instance()->newTestData(expectedFilename);
            }
            snapshotOk = true;
        } else {
            fail( "New image not accepted by tester" );
            return;
        }
    }

    if (!snapshotOk) {
        // Failure, so rename the snapshot to identify it for future reference
        expectedFilename.replace(".png", "_failure.png");
        if ( !actualIm.save(expectedFilename, "PNG", 0) ) {
            QWARN(QString("Failed to save failure pixmap to %1!").arg(expectedFilename).toLatin1());
        }
        fail( "Snapshots are not the same" );
        return;
    }

    /* By using compare, we go through the "expected failure" processing. */
    /* Without this, we won't get XPASS */
    QTest::compare_helper( true, "Snapshots are the same", qPrintable(currentFile()), currentLine() );
}

/*!
    Compares the widget specified by \a {queryPath} against the reference snapshot \a expectedName.

    \a maskedWidgets is a list of query paths specifying widgets to be excluded from the snapshot.  This allows constantly changing widgets to be hidden from view while the snapshot is taken.  Each masked widget is replaced by a black rectangle, and any overlapping widgets will also be concealed.

    Returns true if the images match, or false otherwise.

    The reference snapshot can be one previously learned using verifyImage(), or an image saved using saveScreen(), in which case
    the .png filename extension must be specified.

    \sa verifyImage(), saveScreen()
*/
bool QSystemTest::compareImage( const QString &expectedName, const QString &queryPath, const QStringList &maskedWidgets )
{
    if (runAsManualTest()) {
        manualTestData( quote(expectedName) + " looks similar to " + quote(queryPath) );
        return true;
    }

    // Determine the filename
    // If the function was passed an explicit filename (indicated by an extension) it will be used directly
    // otherwise system specific values are prepended to the name.
    QString expectedFilename = currentDataPath();
    if ( expectedName.endsWith( ".png" ) ) {
        expectedFilename += "/" + expectedName;
    } else {
        expectedFilename += QString("/%1_%2.png")
            .arg( m_config_id )
            .arg( expectedName );
    }

    // The reference snapshot should exist in the data directory for this testcase.
    if ( !QFile::exists(expectedFilename) ) {
        fail(QString("Reference snapshot '%1' doesn't exist.").arg(expectedFilename));
        return false;
    }

    // Now query AUT for the current snapshot
    QImage actualIm( grabImage(queryPath, maskedWidgets) );
    if (queryFailed()) return false;

    QImage expectedIm(expectedFilename);

    // Now do the actual comparisons.
    return imagesAreEqual(actualIm, expectedIm);
}

/*!
    Reads \a srcFile from the test system and returns its contents.
    if \a srcFile contains environment variables, they will be expanded on the test system.

    \sa {File Management}, getFile(), putData(), putFile()
*/
QString QSystemTest::getData( const QString &srcFile )
{
    if (runAsManualTest()) {
        manualTestData( "the contents of file " + quote(srcFile) );
        return "MAGIC_DATA";
    }

    QTestMessage message("getFile");
    message["path"] = srcFile;

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply )) return QString();
    if (!reply["getFile"].isValid()) {
        fail("No data in reply to getData");
        return QString();
    }
    return reply["getFile"].toString();
}

/*!
    \internal
    Returns image size of image specified in \a srcFile.
    if \a srcFile contains environment variables, they will be expanded on the test system.

    Note: QSize does not have toString(), see QSize docs for methods returning common types.

    Example:
    \code
        // Find the image size of specified image
        var imgSize = getImageSize( documentsPath() + "image/foo.jpg" );
        prompt( "Image size is: " + imgSize.width() + " by " + imgSize.height() + ".\n" );
    \endcode
*/
QSize QSystemTest::getImageSize( const QString &srcFile)
{
    if (runAsManualTest()) {
        manualTestData( "the image size of " + quote(srcFile) );
        return QSize();
    }

    QTestMessage message("getImageSize");
    message["path"] = srcFile;

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply )) return QSize();
    if (!reply["getImageSize"].isValid()) {
        fail("No data in reply to getImageSize");
        return QSize();
    }
    return reply["getImageSize"].value<QSize>();
}
/*!
    Returns geometry of the widget specified in \a queryPath, with position (x,y) co-ordinates being global.
    Note: QRect does not have toString() method, refer to QRect docs for methods returning common types.

    Example:
    \code
        // pass the test if widgets do not overlap
        var first_widget = getGeometry("Button1");
        var second_widget = getGeometry("Button2");
        // intersects returns true on overlap, false when not; verify causes test to fail on false
        verify( !first_widget.intersects(second_widget), "Specified widgets overlap.");
    \endcode
    Example two - a non-mainstream situation:

        select() may work in an undefined manner with custom widgets/items, implementing custom select() methods isn't ideal - each would require writing and testing.
        On a device with a primary input method of mouse/touchscreen there may not be key code mapping for keys which don't exist - therefore mouse events should be used. However devices may have different geometry, and widget geometry can change between invocations. The example below uses mouseClick() without prior geometry knowledge, though a way is needed to determine where to click, the example shows mouseClick() in the middle of an area defined by the 4th col and 4th row in a uniform grid of the area of the active widget.
    \code
        // mouseClick() a widget or item with a fixed position inside its parent widget
        var geo = getGeometry();
        var select_x = geo.x() + (( geo.width() / 8) * 7);
        var select_y = geo.y() + (( geo.height() / 8) * 7);
        mouseClick(select_x, select_y);
    \endcode

    \sa select(), mouseClick(), QRect
*/
QRect QSystemTest::getGeometry( const QString &queryPath )
{
    if (runAsManualTest()) {
        manualTestData( "the geometry of " + quote(queryPath) );
        return QRect();
    }

    QRect ret;
    return queryWithReturn(ret, "getGeometry", queryPath);
}

/*!
    Retrieves \a srcFile from the test system and copies it to \a destFile on the local machine.
    if \a srcFile contains environment variables, they will be expanded on the test system.

    Example:
    \code
        // Copy a settings file to the local machine
        getFile("$HOME/Settings/foo.conf", "/tmp/foo.conf" );
    \endcode

    \sa {File Management}, getData(), putData(), putFile()
*/
void QSystemTest::getFile( const QString &srcFile, const QString &destFile )
{
    if (runAsManualTest()) {
        manualTest( "copy file " + quote(srcFile) + " from the tested device to " + quote(destFile) + "  on your local machine" );
        return;
    }

    QTestMessage message("getFile");
    message["path"] = srcFile;

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply )) return;
    if (!reply["getFile"].isValid()) {
        reply["status"] = "ERROR_MISSING_DATA";
        QFAIL(reply);
    }
    QByteArray data = reply["getFile"].toByteArray();
    QFile out(destFile);
    if (!out.open(QIODevice::WriteOnly|QIODevice::Truncate))
        QFAIL( "Couldn't open local file '" + destFile + "'");
    qint64 b;
    for (b = out.write(data); b < data.size() && -1 != b; ++b) {
        qint64 this_b = out.write(data.mid(b));
        if (-1 == this_b) b  = -1;
        else              b += this_b;
    }
    if (-1 == b)
        QFAIL( "Couldn't write to local file '" + destFile + "'");
}

/*!
    Transfers \a srcFile from the local machine and copies it to \a destFile on the test system.
    if \a destFile contains environment variables, they will be expanded on the test system.

    By default, the file permissions of the destination file will be set to those of the source
    file. This can be overridden by specifying \a permissions.

    Example:
    \code
        // Force test system to use certain settings
        putFile("testdata/my_settings.conf", "$HOME/Settings/foo.conf");

        // Specify file permissions
        putFile("testdata/my_file", "$HOME/my_file", QFile.WriteOwner | QFile.ReadOwner | QFile.ReadOther);
    \endcode

    \sa {File Management}, putData()
*/
void QSystemTest::putFile( const QString &srcFile, const QString &destFile, QFile::Permissions permissions )
{
    if (runAsManualTest()) {
        QString perm;
        if (permissions == 0) {
            perm = " using the current file permissions";
        } else {
            perm = " using permissions: ";
            if ((permissions & QFile::ReadOwner) > 0) perm += "ReadOwner, ";
            if ((permissions & QFile::WriteOwner) > 0) perm += "WriteOwner, ";
            if ((permissions & QFile::ExeOwner) > 0) perm += "ExeOwner, ";
            if ((permissions & QFile::ReadUser) > 0) perm += "ReadUser, ";
            if ((permissions & QFile::WriteUser) > 0) perm += "WriteUser, ";
            if ((permissions & QFile::ExeUser) > 0) perm += "ExeUser, ";
            if ((permissions & QFile::ReadGroup) > 0) perm += "ReadGroup, ";
            if ((permissions & QFile::WriteGroup) > 0) perm += "WriteGroup, ";
            if ((permissions & QFile::ExeGroup) > 0) perm += "ExeGroup, ";
            if ((permissions & QFile::ReadOther) > 0) perm += "ReadOther, ";
            if ((permissions & QFile::WriteOther) > 0) perm += "WriteOther, ";
            if ((permissions & QFile::ExeOther) > 0) perm += "ExeOther, ";
            if (perm.endsWith(", ")) perm = perm.left(perm.length()-2);
        }
        manualTest( "copy file " + quote(srcFile) + " from your local machine to " + quote(destFile) + "  on the tested device" + perm);
        return;
    }

    QFile f(srcFile);
    if (!f.open(QIODevice::ReadOnly))
        QFAIL( "Couldn't open '" + srcFile + "'" );

    putData(f.readAll(), destFile, permissions ? permissions : f.permissions());
}

/*!
    Reads text from the specified \a file and returns the contents as a QString.

    This can be useful when prompting the user with larger amounts of text.

    \sa {File Management}, prompt()
*/
QString QSystemTest::readLocalFile( const QString &file )
{
    QFile f(file);
    QString ret;
    if (!f.open(QIODevice::ReadOnly)) {
        setQueryError( "Couldn't open '" + file + "'" );
        return ret;
    }
    ret = f.readAll();
    return ret;
}

/*!
    Transfers \a data from the local machine and copies it to \a destFile on the test system.
    if \a destFile contains environment variables, they will be expanded on the test system.
    The file permissions of the destination file can be specified using \a permissions.

    \sa {File Management}, putFile()
*/
void QSystemTest::putData( const QByteArray &data, const QString &destFile, QFile::Permissions permissions )
{
    QTestMessage message("putFile");
    message["path"] = destFile;
    message["data"] = data;
    if (permissions) {
        message["permissions"] = static_cast<int>(permissions);
    }
    queryPassed("OK", "", BT(message));
}

/*!
    Delete \a path from the test system.  Can be a file, or can be a directory
    tree, in which case the entire tree is recursively deleted.
    If \a path contains environment variables, they will be expanded on the
    test system.

    Example:
    \code
        // Force test system to start with clean settings
        deletePath("$HOME/Settings");
    \endcode

    \sa {File Management}
*/
void QSystemTest::deletePath( const QString &path )
{
    if (runAsManualTest()) {
        manualTest( "delete the contents of path " + quote(path) + " on your device" );
        return;
    }

    QTestMessage message("deletePath");
    message["path"] = path;
    queryPassed( "OK", "", BT(message) );
}

/*!
    Invoke method \a method on object \a queryPath on the test system.
    Invokable methods include only Qt signals and slots.

    The method will be invoked using the Qt connection type \a type.  This can
    almost always be Qt::AutoConnection, but in a few cases Qt.QueuedConnection may
    be necessary.

    The optional arguments \a arg0, \a arg1, \a arg2, \a arg3, \a arg4, \a arg5, \a arg6,
    \a arg7, \a arg8 and \a arg9 will be passed to the method if given.

    Returns true if the method could be invoked, false otherwise.

    Example:
    \code
        // Hide this field because it keeps changing and we want a snapshot
        verify( invokeMethod("Time", "setVisible(bool)", Qt.AutoConnection, false) );
        verifyImage("good_snapshot");
        // Put the field back
        verify( invokeMethod("Time", "setVisible(bool)", Qt.AutoConnection, true) );
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
bool QSystemTest::invokeMethod( const QString &queryPath, const QString &method, Qt::ConnectionType type,
                                const QVariant &arg0, const QVariant &arg1, const QVariant &arg2,
                                const QVariant &arg3, const QVariant &arg4, const QVariant &arg5,
                                const QVariant &arg6, const QVariant &arg7, const QVariant &arg8,
                                const QVariant &arg9 )
{
    if (runAsManualTest()) {
        manualTestData( "invoke method " + quote(method) + " on " + quote(queryPath) );
        return true;
    }

    QTestMessage message("invokeMethod");
    message["method"]  = method;
    message["returns"] = false;
    message["conntype"] = (int)type;

    QVariantList argList;
    if (arg0.isValid()) argList << arg0;
    if (arg1.isValid()) argList << arg1;
    if (arg2.isValid()) argList << arg2;
    if (arg3.isValid()) argList << arg3;
    if (arg4.isValid()) argList << arg4;
    if (arg5.isValid()) argList << arg5;
    if (arg6.isValid()) argList << arg6;
    if (arg7.isValid()) argList << arg7;
    if (arg8.isValid()) argList << arg8;
    if (arg9.isValid()) argList << arg9;

    message["args"] = argList;

    QTestMessage reply;
    if (!queryPassed( QStringList("OK"), QStringList()
            << "ERROR_NO_METHOD"
            << "ERROR_METHOD_NOT_INVOKABLE"
            << "ERROR_WRONG_ARG_COUNT"
            << "ERROR_NO_RETURN"
            << "ERROR_IN_INVOKE", BT(message), queryPath, &reply)) return false;

    return true;
}

/*!
    \overload
    Invokes the given method using connection type Qt.AutoConnection.
*/
bool QSystemTest::invokeMethod( const QString &queryPath, const QString &method,
                                const QVariant &arg0, const QVariant &arg1, const QVariant &arg2,
                                const QVariant &arg3, const QVariant &arg4, const QVariant &arg5,
                                const QVariant &arg6, const QVariant &arg7, const QVariant &arg8,
                                const QVariant &arg9 )
{
    return invokeMethod(queryPath, method, Qt::AutoConnection, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 );
}

/*!
    Set the Qt property named \a name on object \a queryPath to value \a value
    on the test system.

    Errors can occur in this function.

    Example:
    \code
        // Set the text of this field without simulating key presses
        setProperty("Name", "text", "Billy Jones");
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
void QSystemTest::setProperty( const QString &queryPath, const QString &name, const QVariant &value )
{
    if (runAsManualTest()) {
        manualTest( "set property " + quote(name) + " to " + quote(value.toString()) );
        return;
    }

    QTestMessage message("setProperty");
    message["property"] = name;
    message["value"] = value;

    queryPassed( "OK", "", BT(message), queryPath );
}

/*!
    Get the value of the Qt property named \a name on object \a queryPath on the test system.

    Example:
    \code
        // Get the text of this field without using getText()
        var t = getProperty("Name", "text").toString();
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
QVariant QSystemTest::getProperty( const QString &queryPath, const QString &name )
{
    if (runAsManualTest()) {
        manualTest( "property " + quote(name) + " from " + quote(queryPath) );
        return QVariant("MAGIC_DATA");
    }

    QTestMessage message("getProperty");
    message["property"] = name;

    QVariant out;

    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), queryPath, &reply)) return out;

    return reply["getProperty"];
}

/*!
    Returns the signatures of the widgets that have \a property matching \a value.
    This can be used to identify widgets that do not have an associated label text.

    In addition to normal QObject properties, "inherits" and "className" may also
    be used, with the class specified as a string.

    Example:
    \code
        // Select the button with the tool tip "Quit"
        // assumes that only one widget will match
        var button = findByProperty("toolTip", "Quit");
        activate(button);
    \endcode

    If more than one widget matches, the list returned is sorted by widget position.
    If no matching widgets are found, the list returned is empty, but the test does
    not fail. Use findWidget() to cause a test failure when no matching widgets are found.

    \sa findWidget(), signature(), {Query Paths}, {Querying Objects}
*/
QStringList QSystemTest::findByProperty( const QString &property, const QVariant &searchValue )
{
    if (runAsManualTest()) {
        manualTest( "the property " + quote(property) + " of " + quote(searchValue.toString()) );
        return QStringList("MAGIC_DATA");
    }

    QTestMessage message("findByProperty");
    message["property"] = property;
    message["searchValue"] = searchValue;

    QStringList out;
    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply)) return out;
    out = reply["findByProperty"].toStringList();
    return out;
}

/*!
    Returns the signatures of the widgets that match all of the property values
    specified in \a searchValues.

    This can be used to identify widgets that do not have an associated label text.

    Example:
    \code
        // Select the button with the tool tip "Quit"
        // assumes that only one widget will match
        var button = findByProperty( {className: "QToolButton",
                                      toolTip:   "Quit"} );
        activate(button);
    \endcode

    If more than one widget matches, the list returned is sorted by widget position.
    If no matching widgets are found, the list returned is empty, but the test does
    not fail. Use findWidget() to cause a test failure when no matching widgets are found.

    \sa findWidget(), signature(), {Query Paths}, {Querying Objects}
*/
QStringList QSystemTest::findByProperty( const QVariantMap &searchValues )
{
    QTestMessage message("findByProperties");
    message["searchValues"] = searchValues;

    QStringList out;
    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply)) return out;
    out = reply["findByProperties"].toStringList();
    return out;
}

/*!
    Returns the signatures of the widgets that have \a property matching \a value.

    This function is the same as findByProperty(), but results in a test failure
    if no matching widgets are found.

    \sa findByProperty()
*/
QStringList QSystemTest::findWidget( const QString &property, const QVariant &searchValue )
{
    QStringList ret = findByProperty(property, searchValue);
    if (ret.isEmpty()) {
        fail("No widget found with specified property.");
    }
    return ret;
}

/*!
    Returns the signatures of the widgets that match all of the property values
    specified in \a searchValues.

    This function is the same as findByProperty(), but results in a test failure
    if no matching widgets are found.

    \sa findByProperty()
*/
QStringList QSystemTest::findWidget( const QVariantMap &searchValues )
{
    QStringList ret = findByProperty(searchValues);
    if (ret.isEmpty()) {
        fail("No widget found with specified properties.");
    }
    return ret;
}

/*!
    Retrieves a QSettings settings value from the test system located in \a file, settings group \a group, key \a key.
    If \a file contains environment variables, they will be expanded on the test system.

    Example:
    \code
        // What's our primary input mode?
        var primaryInput = getSetting("$QPEDIR/etc/defaultbuttons.conf", "Device", "PrimaryInput");
    \endcode

    \sa setSetting(), QSettings
*/
QVariant QSystemTest::getSetting( const QString &file, const QString &group, const QString &key )
{
    return getSetting(QString(), QString(), file, group, key);
}

/*!
    Retrieves a QSettings settings value from the test system located in the settings file for
    organization \a organization and application \a application, as passed to the QSettings
    constructor.  The settings value retrieved will be group \a group, key \a key.

    \sa setSetting(), QSettings
*/
QVariant QSystemTest::getSetting( const QString &organization, const QString &application, const QString &group, const QString &key )
{
    return getSetting(organization, application, QString(), group, key);
}

/*!
    Set a QSettings settings \a value on the test system located in \a file, settings group \a group, key \a key.

    Example:
    \code
        // Turn on english and deutsch input languages
        setSetting("$HOME/Settings/Trolltech/locale.conf", "Language", "InputLanguages", "en_US de" );
    \endcode

    \sa getSetting(), QSettings
*/
void QSystemTest::setSetting( const QString &file, const QString &group, const QString &key, const QVariant &value )
{
    setSetting(QString(), QString(), file, group, key, value);
}

/*!
    Set a QSettings settings \a value on the test system located in the settings file
    for the given \a organization and \a application, as passed to a QSettings constructor.
    The value set will be in settings group \a group, key \a key.

    \sa getSetting(), QSettings
*/
void QSystemTest::setSetting( const QString &organization, const QString &application, const QString &group, const QString &key, const QVariant &value )
{
    setSetting(organization, application, QString(), group, key, value);
}

static QStringList filter = QStringList();


/*! \internal */
void QSystemTest::applicationStandardOutput(QList<QByteArray> const& lines)
{
    foreach (QByteArray const& line, lines)
        QDebug(QtDebugMsg) << line;
}

/*! \internal */
void QSystemTest::applicationStandardError(QList<QByteArray> const& lines)
{
    foreach (QByteArray const& line, lines)
        QDebug(QtDebugMsg) << line;
}

/*!
    Switches the 'strict syntax' checking mode for the System test to \a on.

    In strict mode the following commands are no longer allowed and will cause an immediate failure:
    \list
    \i keyClick()
    \i keyPress()
    \i keyRelease()
    \i keyClickHold()
    \endlist

    Strict mode also verifies that every 'Title' change is covered by a call to waitForTitle(): any
    action that results in a Dialog to be shown (with a different title) will cause a test failure
    unless a waitForTitle() is called on the next line of the test script.
*/
void QSystemTest::strict( bool on )
{
    m_strict_mode = on;
}

/*!
    Simulates a \a key press for the application specified by \a queryPath.
    \a key is a Qt::Key describing the key to be pressed.

    Example:
    \code
        // Press (do not release) F23 key in current app
        keyPress( Qt.Key_F23 );
    \endcode

    \sa {Query Paths}, {Keypad Simulation}
*/
void QSystemTest::keyPress( Qt::Key key, const QString &queryPath )
{
    if (m_strict_mode) QFAIL( "ERROR: keyPress is not allowed in strict mode" );

    QTestMessage message("keyPress");
    message["key"] = (int)key;
    QString qp = queryPath;
    if (qp.isEmpty()) qp = "";
    queryPassed( "OK", "", BT(message), qp );
}

/*!
    Simulates a \a key release for the application specified by \a queryPath.
    \a key is a Qt::Key describing the key to be released.

    Example:
    \code
        // Release Up key in current app
        keyRelease( Qt.Key_Up );
    \endcode

    \sa {Query Paths}, {Keypad Simulation}
*/
void QSystemTest::keyRelease( Qt::Key key, const QString &queryPath )
{
    if (m_strict_mode) QFAIL( "ERROR: keyRelease is not allowed in strict mode" );

    QTestMessage message("keyRelease");
    message["key"] = (int)key;
    QString qp = queryPath;
    if (qp.isEmpty()) qp = "";
    queryPassed( "OK", "", BT(message), qp );
}

/*!
    Simulates a \a key click (press and release) for the application specified by \a queryPath.
    \a key is a string describing the key to be released.

    Example:
    \code
        // Go right 5 times, then select
        for (int i = 0; i < 5; ++i) keyClick( Qt.Key_Right );
        keyClick( Qt.Key_Select );
    \endcode

    \sa {Query Paths}, {Keypad Simulation}
*/
void QSystemTest::keyClick( Qt::Key key, const QString &queryPath )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("click key %1 in application %2")
                    .arg(QKeySequence(key).toString())
                    .arg(quote(queryPath)) );
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: keyClick is not allowed in strict mode" );

    QTestMessage message("keyClick");
    message["key"] = (int)key;
    QString qp = queryPath;
    if (qp.isEmpty()) qp = "";
    queryPassed( "OK", "", BT(message), qp );
}

/*!
    Simulates a \a key click and hold (press + wait + release) for \a queryPath.
    The interval between press and release is set in milliseconds by \a duration.

    Example:
    \code
        // Hold hangup key to bring up shutdown app
        keyClickHold(Qt.Key_Hangup, 3000);
    \endcode

    \sa {Query Paths}, {Keypad Simulation}
*/
void QSystemTest::keyClickHold( Qt::Key key, int duration, const QString &queryPath )
{
    if (m_strict_mode) QFAIL( "ERROR: keyClickHold is not allowed in strict mode" );

    m_keyclickhold_key = key;
    m_keyclickhold_path = queryPath;

    QTestMessage message("keyPress");
    message["key"] = (int)key;
    message["duration"] = duration;
    QString qp = queryPath;
    if (qp.isEmpty()) qp = "";
    queryPassed( "OK", "", BT(message), qp );

    if (queryFailed()) return;

    QTest::qWait(duration);

    if (m_keyclickhold_key) {
        m_keyclickhold_key = (Qt::Key)0;
        m_keyclickhold_path = "";

        keyRelease(key, queryPath);
    }
}

/*!
    Simulates a mouse click / touchscreen tap at co-ordinates ( \a x, \a y ).

    Example:
    \code
        mouseClick(200, 300);
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseClick( int x, int y, QFlags<Qt::MouseButton> buttons )
{
    mouseClick(QPoint(x, y), buttons);
}

/*!
    Simulates a mouse click / touchscreen tap at \a point.

    Example:
    \code
        mouseClick( new QPoint(200, 300) );
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseClick( const QPoint &point, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTestData( QString("position (x,y) %1,%2").arg(point.x()).arg(point.y()), true);
        manualTest( QString("%1 click the mouse on MAGIC_DATA")
                    .arg(mouseButtons(buttons)));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mouseClick is not allowed in strict mode" );
    QTestMessage message("mouseClick");
    message["pos"] = point;
    message["buttons"] = (int)buttons;
    queryPassed( "OK", "", BT(message) );
}

/*!
    Simulates a mouse click / touchscreen tap at the center of the widget
    specified by \a queryPath.

    Example:
    \code
        // Click on Accept button
        mouseClick("Accept");
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseClick( const QString &queryPath, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 click the mouse on %2")
                    .arg(mouseButtons(buttons)).arg(quote(queryPath)));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mouseClick is not allowed in strict mode" );
    QTestMessage message("mouseClick");
    message["buttons"] = (int)buttons;
    queryPassed( "OK", "", BT(message), queryPath );
    wait(200);
}

/*!
    Simulates a mouse click / touchscreen tap at co-ordinates ( \a x, \a y ),
    with a custom \a duration in milliseconds between press and release.

    Example:
    \code
        // Hold at (200, 300) for three seconds
        mouseClickHold(200, 300, 3000);
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseClickHold( int x, int y, int duration, QFlags<Qt::MouseButton> buttons )
{
    mouseClickHold(QPoint(x, y), duration, buttons);
}

/*!
    Simulates a mouse click / touchscreen tap at \a point,
    with a custom \a duration in milliseconds between press and release.

    Example:
    \code
        // Hold at (200, 300) for three seconds
        mouseClickHold( new QPoint(200, 300), 3000 );
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseClickHold( const QPoint &point, int duration, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 click - and HOLD - the mouse on position (x,y) %2,%3 for approximately %4 milliseconds, and then release")
                    .arg(mouseButtons(buttons)).arg(point.x()).arg(point.y()).arg(duration));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mouseClickHold is not allowed in strict mode" );

    mousePress(point, buttons);
    QTest::qWait(duration);
    mouseRelease(point, buttons);
}

/*!
    Simulates a mouse click / touchscreen tap at the center of the widget
    specified by \a queryPath, with a custom \a duration in milliseconds
    between press and release.

    Example:
    \code
        // Hold on the "Shutdown" button for three seconds
        mouseClickHold("Shutdown", 3000);
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseClickHold( const QString &queryPath, int duration, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 click - and HOLD - the mouse on %2 for approximately %3 milliseconds, and then release")
                    .arg(mouseButtons(buttons)).arg(quote(queryPath)).arg(duration));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mouseClickHold is not allowed in strict mode" );

    mousePress(queryPath, buttons);
    QTest::qWait(duration);
    mouseRelease(queryPath, buttons);
}

/*!
    Simulates a mouse / touchscreen press at co-ordinates ( \a x, \a y ).

    Example:
    \code
        mousePress(200, 300);
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mousePress( int x, int y, QFlags<Qt::MouseButton> buttons )
{
    mousePress(QPoint(x, y), buttons);
}

/*!
    Simulates a mouse / touchscreen press at \a point.

    Example:
    \code
        mousePress( new QPoint(200, 300) );
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mousePress( const QPoint &point, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 press - and HOLD - the mouse on position (x,y) %2,%3")
                    .arg(mouseButtons(buttons)).arg(point.x()).arg(point.y()));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mousePress is not allowed in strict mode" );

    QTestMessage message("mousePress");
    message["pos"] = point;
    message["buttons"] = (int)buttons;
    queryPassed( "OK", "", BT(message) );
}

/*!
    Simulates a mouse / touchscreen press at the center of the widget
    specified by \a queryPath.

    Example:
    \code
        // Press "Edit" button
        mousePress("Edit");
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mousePress( const QString &queryPath, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 press - and HOLD - the mouse on %2")
                    .arg(mouseButtons(buttons)).arg(quote(queryPath)));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mousePress is not allowed in strict mode" );

    QTestMessage message("mousePress");
    message["buttons"] = (int)buttons;
    queryPassed( "OK", "", BT(message), queryPath );
}

/*!
    Simulates a mouse / touchscreen release at co-ordinates ( \a x, \a y ).

    Example:
    \code
        mouseRelease(200, 300);
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseRelease( int x, int y, QFlags<Qt::MouseButton> buttons )
{
    mouseRelease(QPoint(x, y), buttons);
}

/*!
    Simulates a mouse / touchscreen release at \a point.

    Example:
    \code
        mouseRelease( new QPoint(200, 300) );
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseRelease( const QPoint &point, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 release the mouse on position (x,y) %2,%3")
                    .arg(mouseButtons(buttons)).arg(point.x()).arg(point.y()));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mouseRelease is not allowed in strict mode" );

    QTestMessage message("mouseRelease");
    message["buttons"] = (int)buttons;
    message["pos"] = point;
    queryPassed( "OK", "", BT(message) );
}

/*!
    Simulates a mouse / touchscreen release at the center of the widget
    specified by \a queryPath.

    Example:
    \code
        // Release mouse over "Edit" button
        mouseRelease("Edit");
    \endcode

    \sa {Query Paths}, {Mouse / Touchscreen Simulation}
*/
void QSystemTest::mouseRelease( const QString &queryPath, QFlags<Qt::MouseButton> buttons )
{
    if (QSystemTest::runAsManualTest()) {
        manualTest( QString("%1 release the mouse on %2")
                    .arg(mouseButtons(buttons)).arg(quote(queryPath)));
        return;
    }

    if (m_strict_mode) QFAIL( "ERROR: mouseRelease is not allowed in strict mode" );

    QTestMessage message("mouseRelease");
    message["buttons"] = (int)buttons;
    queryPassed( "OK", "", BT(message), queryPath );
}

/*!
    Simulates \a value being entered into the widget specified by \a queryPath.

    Some widgets go into an editing mode when entering text and need to be taken
    out of the editing mode by e.g. a Qt::Key_Select or by navigating to
    another field in the dialog. By default, enter() will automatically take whatever
    action is necessary to commit the text and leave edit mode. Set \a mode to NoCommit to
    override this.

    Example:
    \code
        // Enter my job in "Occupation" field
        enter( "Dog Walker", "Occupation" );

        // Enter date of birth in "Birthday" field
        enter( new Date(1985, 11, 10), "Birthday" );

        // Enter start time in "Start" field
        enter( new QTime(11, 30), "Start" );
    \endcode

    \sa {Query Paths}, {Keypad Simulation}
*/
void QSystemTest::enter( const QVariant &value, const QString &queryPath, EnterMode mode )
{
    if (QSystemTest::runAsManualTest()) {
        QString type = value.typeName();
        if (type == "QDate") type = "date";
        else if (type == "QTime" ) type = "time";
        else if (type == "QString" ) type = "string";

        manualTest( QString("enter %1 %2 in field %3")
                    .arg(type)
                    .arg(quote(value.toString()))
                    .arg(quote(queryPath)));
        return;
    }

    if (value.isNull()) return;
    QTestMessage message("enter");
    message["value"] = value;

    switch (mode)
    {
        case NoCommit: message["mode"] = "NoCommit"; break;
        default: message["mode"] = "Commit"; break;
    }

    queryPassed( "OK", "", BT(message), queryPath );
}

/*!
    Selects the \a item from the application/widget specified by \a queryPath.
    This can be used to, e.g., select a certain item from a list widget or combo box.
    select() works with widgets which are conceptually a list, including
    list views, combo boxes and menus.

    When used with a list widget, the specified item is navigated to and no further
    action is taken.

    When used with a combo box, the drop-down list is opened,
    the item is selected, and the drop-down list is closed again.

    Items in submenus are denoted using '/' delimiters (e.g., "View/All" means
    navigate to the "View" submenu, then the "All" item).  Menu items which
    have a '/' in their name can be escaped using '\' (e.g. "Add\\/Remove Words").

    Example:
    \code
        // Select "Female" from "Gender" field
        select("Female", "Gender");
    \endcode

    \sa {Query Paths}, {Keypad Simulation}
*/
void QSystemTest::select( const QString &item, const QString &queryPath )
{
    if (m_run_as_manual_test) {
        manualTest( "select " + quote(item) + " from " + quote(queryPath));
        return;
    }

    if (item.isNull()) return;
    QTestMessage message("select");
    message["text"] = item;
    queryPassed("OK", "", BT(message), queryPath);

    /* FIXME: this wait should be able to be put in the test widgets.
        * Currently it can't because of the new bop problem (bug 194361).
        */
    wait((m_demo_mode) ? 1500 : 150);
}

/*!
    Selects the item with \a index from an indexed widget (such as a QAbstractItemView)
    specified by \a queryPath.

    This function is lower level than using select(), but is more appropriate when there
    are large numbers of items in the view, or the view contains unnamed or ambiguously
    named items.

    The \a index is specified as a list of row and column values.

    Example:
    \code
        // Select item (row 2, column 3) from table view
        select( [2, 3], table );
    \endcode

    The index may be hierarchical, in which case the row and column values should be
    specified as [row, column, parentRow, parentColumn, ...].

    \sa select(), selectedIndex()
*/
void QSystemTest::selectIndex( const QVariantList &index, const QString &queryPath )
{
    if (m_run_as_manual_test) {
        QString index_str = "[";
        for (int i=0; i<index.count(); i++) {
            index_str += index[i].toString() + ", ";
        }
        index_str = index_str.left(index_str.length()-2);
        index_str += "]";

        QString example_str = "item";
        if (index.count() >= 2) {
            example_str = "<row, column";
            if (index.count() == 3) example_str += ", ...";
            if (index.count() >= 4) example_str += ", parentRow, parentColumn";
            if (index.count() == 5) example_str += ", ...";
            if (index.count() >= 6) example_str += ", ...";
            example_str += ">";
        }
        manualTest( "select " + example_str + " " + index_str + " from list " + quote(queryPath) );
        return;
    }

    QTestMessage message("selectIndex");
    message["index"] = index;
    queryPassed("OK", "", BT(message), queryPath);

    /* FIXME: this wait should be able to be put in the test widgets.
        * Currently it can't because of the new bop problem (bug 194361).
        */
    wait((m_demo_mode) ? 1500 : 150);
}


/*!
    Returns the currently selected index of an indexed widget specified by \a queryPath.
    The index is returned as an array to QtScript, in the format required for selectIndex().

    \sa selectIndex()
*/
QVariantList QSystemTest::getSelectedIndex( const QString &queryPath )
{
    if (m_run_as_manual_test) {
        manualTestData( "the contents of list " + quote(queryPath) );
        return QVariantList();
    }

    QVariantList ret;
    return queryWithReturn(ret, "getSelectedIndex", queryPath);
}

/*!
    Activate the widget specified by \a queryPath.
    This is typically used to activate button widgets.

    \sa {Query Paths}
*/
void QSystemTest::activate( const QString &queryPath )
{
    if (m_run_as_manual_test) {
        manualTest( "activate " + quote(queryPath) );
        return;
    }

    QTestMessage message("activate");
    queryPassed("OK", "", BT(message), queryPath);

    /* FIXME: this wait should be able to be put in the test widgets.
        * Currently it can't because of the new bop problem (bug 194361).
        */
    wait((m_demo_mode) ? 1500 : 150);
}

/*!
    Make sure the specified \a item is visible in the widget specified by \a queryPath.
    The action taken depends on the widget, but may for example involve moving the
    widget's scrollbars.

    \sa {Query Paths}
*/
void QSystemTest::ensureVisible( const QString &item, const QString &queryPath )
{
    if (m_run_as_manual_test) {
        manualTest( "verify item " + quote(item) + " is visible in " + quote(queryPath) );
        return;
    }

    if (item.isNull()) return;
    QTestMessage message("ensureVisible");
    message["item"] = item;
    queryPassed("OK", "", BT(message), queryPath);

    /* FIXME: this wait should be able to be put in the test widgets.
        * Currently it can't because of the new bop problem (bug 194361).
        */
    wait((m_demo_mode) ? 1500 : 150);
}

/*!
    Start the specified \a application.

    \a application is the combined path and arguments of a program to launch.
    The application must connect to the test framework within \a timeout ms or
    the test fails.

    \a flags specifies additional behaviour.

    \sa {Application Management}
*/
void QSystemTest::startApplication( const QString &application, const QStringList &arguments, int timeout, StartApplicationFlags flags )
{
    if (m_run_as_manual_test) {
        manualTest( "start application '"
                       + application
                       + "' "
                       + arguments.join(" ") );
        return;
    }

    QString app = application;
    QStringList args = arguments;

    if (!runsOnDevice()) {
        if (!device_controller)
            device_controller = new Qt4Test::TestController(Qt4Test::TestController::Desktop);

        args = processEnvironment(arguments);
        app = processEnvironment(application);
        app = which(app);
        if (app.isEmpty()) {
            fail(QString("Application '%1' not found in PATH (%2)").arg(application).arg(PATH()));
            return;
        }

    } else {
        if (!device_controller)
            device_controller = new Qt4Test::TestController(Qt4Test::TestController::Maemo, &ssh_param);
    }

    if (device_controller)
        device_controller->killApplications();

    // setup configuration for target, used by configTarget() later
    QByteArray defTargetID = qgetenv("QTUITEST_TARGETID");
    if (!defTargetID.isEmpty())
        m_targetID = QString(defTargetID);

    QString reply;
    if (device_controller) {
        device_controller->startApplication(app, args, true, m_env, reply);
#ifdef QTCREATOR_QTEST
        testOutputPane()->append(reply);
#endif
    }

    // Give it a little time for the slave to come up.
    wait(100);

    if (!connectToAut(timeout)) {
        device_controller->killApplications();
        fail(QString("Could not connect to remote process '%1'.").arg(app));
    }
    configTarget();
}

/*!
    Returns true if the widget specified by \a queryPath exists and is currently visible
    to the user.

    The widget is considered to be visible to the user if QWidget::visibleRegion() returns
    a non-empty region.  Thus, isVisible() will return true if even a single pixel of the
    widget is unobscured.

    \sa {Query Paths}, {Querying Objects}
*/
bool QSystemTest::isVisible( const QString &queryPath )
{
    if (m_run_as_manual_test) {
        manualTestData( "'" + queryPath + "' is visible" );
        return true;
    }

    bool ret = false;
    return queryWithReturn(ret, "isVisible", queryPath);
}

/*!
    The function returns whether the widget specified by \a queryPath is enabled.

    Example:
    \code
        // Verify the AM/PM field is disabled when using 24 hour format
        select("24 hour", "Time format");
        verify( !isEnabled("AM-PM"), "AM-PM field still enabled." );
    \endcode

    \sa {Query Paths}, {Querying Objects}
*/
bool QSystemTest::isEnabled( const QString &queryPath )
{
    return getProperty( queryPath, "enabled" ).toBool();
}

/*!
    \internal
    Returns a string of all the visible widgets that are children of the object specified by \a queryPath.
    If only the application part of \a queryPath is defined, then all visible widgets for that application
    are listed. The string is organized in a tree type hierarchy showing the relationship between
    widgets.

    This function is intended to help with the development of testcases.

    \sa {Query Paths}
*/
QString QSystemTest::activeWidgetInfo()
{
    QString ret;
    return queryWithReturn(ret, "activeWidgetInfo", "");
}

/*!
    Returns the checked state of the checkbox-like widget specified by \a queryPath.
    Checkbox-like widgets include QCheckBox and anything inheriting QAbstractButton.

    \sa {Query Paths}, {Querying Objects}, setChecked(), checkState()
*/
bool QSystemTest::isChecked( const QString &queryPath )
{
    bool ret = false;
    return queryWithReturn(ret, "isChecked", queryPath);
}

/*!
    Returns the checked state of \a item in the widget specified by \a queryPath.

    \sa {Query Paths}, {Querying Objects}, setChecked(), checkState()
*/
bool QSystemTest::isChecked( const QString &item, const QString &queryPath )
{
    if (item.isNull()) return false;
    QTestMessage message("isChecked");
    QTestMessage reply;
    message["item"] = item;
    if (!queryPassed("OK", "", BT(message), queryPath, &reply)) return false;
    return reply["isChecked"].toBool();
}

/*!
    Based on the value of \a doCheck checks or un-checks a checkbox-like widget specified by \a queryPath.
    Checkbox-like widgets include QCheckBox and anything inheriting QAbstractButton.

    \sa {Query Paths}, {Querying Objects}, isChecked(), setCheckState()
*/
void QSystemTest::setChecked( bool doCheck, const QString &queryPath)
{
    QTestMessage message("setChecked");
    message["doCheck"] = doCheck;
    queryPassed("OK", "", BT(message), queryPath);
}

/*!
    Based on the value of \a doCheck checks or un-checks \a item in the widget specified by \a queryPath.

    \sa {Query Paths}, {Querying Objects}, isChecked(), setCheckState()
*/
void QSystemTest::setChecked( bool doCheck, const QString &item, const QString &queryPath)
{
    QTestMessage message("setChecked");
    message["doCheck"] = doCheck;
    message["item"] = item;
    queryPassed("OK", "", BT(message), queryPath);
}

/*!
    Returns the checked state of the checkbox-like widget specified by \a queryPath.
    Checkbox-like widgets include QCheckBox and anything inheriting QAbstractButton.

    \sa {Query Paths}, {Querying Objects}, isChecked(), setCheckState()
*/
int QSystemTest::checkState( const QString &queryPath )
{
    int ret = Qt::Unchecked;
    return queryWithReturn(ret, "checkState", queryPath);
}

/*!
    Sets the check state of a checkbox-like widget specified by \a queryPath to \a state.
    Checkbox-like widgets include QCheckBox and anything inheriting QAbstractButton.

    Example:
    \code
        // Set tri-state button to partially checked state
        setCheckState(Qt.PartiallyChecked, "Tri-state button");
    \endcode

    \sa {Query Paths}, {Querying Objects}, checkState(), setChecked()
*/
void QSystemTest::setCheckState( int state, const QString &queryPath)
{
    QTestMessage message("setCheckState");
    message["state"] = state;
    queryPassed("OK", "", BT(message), queryPath);
}

/*!
    Returns the signature of the widget that is associated with \a labelText.

    If \a offset is a number != 0 the query will return the n'th next or previous widget (excluding labels). The widgets are ordered from
    top to bottom, left to right. A positive offset indicates a widget to the right or below, a negative offset indicates a widget to
    the left or above the label.

    This function can be used for situations where a field doesn't have a label associated with it.

    \sa {Query Paths}, {Querying Objects}, {QObject::inherits()}
*/
QString QSystemTest::signature( const QString &labelText, int offset )
{
    QTestMessage message("widget");
    message["offset"] = offset;
    QTestMessage reply;
    if (!queryPassed("OK", "", BT(message), labelText, &reply)) return "";
    return reply["widget"].toString();
}

/*!
    List the contents of directory \a dir on the test system, applying \a filters to the listing.
    If \a dir contains environment variables, they will be expanded on the test system.

    The returned listing will be relative to \a dir.

    Example:
    \code
        // Delete entire contents of Documents directory on the test system
        var list = getDirectoryEntries( documentsPath(), QDir.AllEntries);
        for (var i = 0; i < list.length; ++i) {
            deletePath( documentsPath() + list[i]);
        }
    \endcode

    \sa QDir::entryList(), {File Management}
*/
QStringList QSystemTest::getDirectoryEntries( const QString &dir, QDir::Filters filters )
{
    QTestMessage message("getDirectoryEntries");
    message["path"] = dir;
    message["filters"] = (int)filters;

    QStringList out;
    QTestMessage reply;
    if (!queryPassed( "OK", "", BT(message), "", &reply)) return out;
    if (reply["getDirectoryEntries"].isNull()) {
        setQueryError("Got no data in response to getDirectoryEntries");
        return out;
    }
    out = reply["getDirectoryEntries"].toStringList();
    return out;
}

/*!
    Returns the current date and time of the test system.
*/
QDateTime QSystemTest::getDateTime()
{
    QDateTime ret;
    return queryWithReturn(ret, "systemTime", "");
}

/*!
    Returns true if the test is running on an actual device, and false if it is running locally.
*/
bool QSystemTest::runsOnDevice()
{
    return ssh_param.host != "127.0.0.1";
}

/*!
    Wait for \a msecs milliseconds, while still processing events from the event loop.
*/
void QSystemTest::wait(int msecs)
{
    QTime t;
    t.start();
    while (t.elapsed() < msecs) {
        qApp->processEvents();
    }
}

/*!
    Returns the currently set Visual Response Time. This time is used in QtUiTest to decide whether the User
    Interface is responsive to user events. For instance, after selecting "New Event" from the options menu a user
    expects a dialog in which a new event can be entered. If the Application Under Test does not respond in some
    visible way within the visual response time, the test will fail.

    By default the visual response time is set to 4 seconds, i.e. any UI that doesn't respond to events within this time
    is considered at fault.

    The visibleResponseTime is also used as the default value for some queries such as waitForTitle().

    \sa setVisibleResponseTime(), waitForTitle()
*/
int QSystemTest::visibleResponseTime()
{
    return m_visible_response_time;
}

/*!
    Sets the Visual Response Time to \a time.

    \sa visibleResponseTime(), waitForTitle()
*/
void QSystemTest::setVisibleResponseTime( int time )
{
    if (m_visible_response_time != time) {
        qLog(QtUitest) <<  "Need to set a new visual response time" ;
    }
    m_visible_response_time = time;
}

/*!
    Take a full screenshot and save it as \a name.
    The screenshot will be placed in the test data directory in PNG format,
    and will automatically have .png appended to the name.

    This function is intended to be used as a simple way to automate the
    gathering of screenshots, i.e. to be used in documentation and such.

    If a \a queryPath is specified the snapshot will be limited to the Widget
    that is identified by the queryPath.

    \sa verifyImage()
*/
void QSystemTest::saveScreen(const QString &name, const QString &queryPath)
{
    QString cdp = currentDataPath();
    if (!QDir("/").exists(cdp) && !QDir("/").mkpath(cdp)) QFAIL(QString("Path '' didn't exist and I couldn't create it").arg(cdp));
    QImage img;
    img = grabImage(queryPath);
    if (queryFailed()) return;
    if (img.isNull()) QFAIL( "AUT returned a null screenshot." );
    if (!img.save(cdp + "/" + name + ".png", "PNG")) QFAIL(QString("Couldn't save image '%1' to '%2'").arg(name).arg(cdp) );
}


/*!
    \fn QSystemTest::expectMessageBox(String title, String text, String option, Number timeout)
    Denotes the start of a block of code which, immediately after or during execution, should
    cause a message box to pop up with the given \a title and \a text.  When the message box
    appears, the given menu \a option will be chosen from the message box softmenu bar (if one exists).

    If the message box hasn't appeared by the end of the block of code, the test will
    wait until the \a timeout expires.  If it still doesn't appear, the current test fails.

    If a message box appears which hasn't been marked as expected, the current test fails.

    Example:
    \code
    // Delete a contact - select "Yes" on the popped-up message box
    // If the message box doesn't pop up, the test fails.
    expectMessageBox("Contacts", "Are you sure you want to delete: " + contact_name + "?", "Yes") {
        select("Delete contact", optionsMenu());
    }
    \endcode
*/

/*!
    Indicate to the test framework if the application under test is expected to close.

    If \a value is true, the test framework will not report a failure when it loses its connection to the application.
    If \a value is false, unexpected application terminations will result in a test failure.

    Example:
    \code
    expectApplicationClose( true );
    select( "Close" );                // Selecting this causes the current application to close
    expectApplicationClose( false );  // Resume normal checking
    \endcode
*/
void QSystemTest::expectApplicationClose( bool value )
{
    m_expect_app_close = value;
}

/*!
    \internal
    Processes the command line parameters.
*/
void QSystemTest::processCommandLine( QStringList &args )
{  
    QMutableStringListIterator it(args);
    
    while (it.hasNext()) {
        QString arg = it.next();
        if (!arg.compare("-remote", Qt::CaseInsensitive)) {
            it.remove();          
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            QString host_port = it.next();
            it.remove();
            QStringList host_port_parts = host_port.split(":");

            bool ok = (host_port_parts.count() == 2);
            int port = -1;
            QString host;
            if (ok) port = host_port_parts[1].toInt(&ok);
            if (ok) host = host_port_parts[0];
            ok = ok && port > 0 && port < 65536 && !host.isEmpty();

            if (!ok)
                qFatal("'%s' is not a valid host:port argument", qPrintable(host_port));

            QTestIDE::instance()->openRemote( host, port );
            connect(QTestIDE::instance(), SIGNAL(abort()), this, SLOT(abortTest()));           
        } else if ( !arg.compare("-autip", Qt::CaseInsensitive) || !arg.compare("-authost", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            ssh_param.host = it.next();
            it.remove();
            ssh_param.timeout = 20000;
        } else if ( !arg.compare("-username", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            ssh_param.uname = it.next();
            it.remove();
        } else if ( !arg.compare("-pwd", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            ssh_param.pwd = it.next();
            it.remove();
            ssh_param.authType = Core::SshConnectionParameters::AuthByPwd;
            ssh_param.privateKeyFile = "";
        } else if ( !arg.compare("-private-key", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            ssh_param.privateKeyFile = it.next();
            it.remove();
            ssh_param.pwd = "";
            ssh_param.authType = Core::SshConnectionParameters::AuthByKey;
        } else if ( !arg.compare("-autport", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));            
            bool ok;
            m_aut_port = it.next().toUShort( &ok );
            if (!ok)
                qFatal("%s is not a valid port specifier", qPrintable(it.value()));
            it.remove();
        } else if ( !arg.compare("-keepaut", Qt::CaseInsensitive) ) {
            it.remove();
            m_keep_aut = true;
        } else if ( !arg.compare("-silentaut", Qt::CaseInsensitive) ) {
            it.remove();
            m_silent_aut = true;
        } else if ( !arg.compare("-noaut", Qt::CaseInsensitive) ) {
            it.remove();
            m_no_aut = true;
        } else if ( !arg.compare("-auto", Qt::CaseInsensitive) ) {
            it.remove();
            m_auto_mode = true;
        } else if ( !arg.compare("-force-manual", Qt::CaseInsensitive) ) {
            it.remove();
            m_run_as_manual_test = true;
        } else if ( !arg.compare("-env", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            m_env << it.next();
            it.remove();
        } else if ( !arg.compare("-targetid", Qt::CaseInsensitive) ) {
            it.remove();
            if (!it.hasNext()) qFatal("Expected a value after %s", qPrintable(arg));
            m_targetID = it.next();
            it.remove();
        } else if ( !arg.compare("-demomode", Qt::CaseInsensitive) ) {
            it.remove();
            m_demo_mode = true;
        } else if ( !arg.compare("-verbose-pref", Qt::CaseInsensitive) ) {
            it.remove();
            m_verbose_perf = true;
        } else if ( !arg.compare("-v", Qt::CaseInsensitive) ) {
            it.remove();
            m_verbose = true;
        }
    }
    QAbstractTest::processCommandLine(args);

    if (m_auto_mode && learnMode() != LearnNone) {
        qWarning("Can't learn in auto mode; learn options ignored.");
    }
    if (!m_auto_mode && learnMode() == LearnNone) {
        setLearnMode(LearnNew);
    }
}

/*!
    \internal
    Starts event recording. While event recording is busy a dialog will be visible that shows all recorded events and also
    enables the user to stop the recording session. \a file and \a line specifies the location in a source file where event
    recording commenced.

    If \a manualSteps are specified the dialog will have an additional field showing all the manual steps.

    Don't use this, use prompt() instead.
*/
bool QSystemTest::recordEvents( const QString &manualSteps, bool gui )
{
    if (m_auto_mode && gui) {
        skip("Can't record events in auto mode.", SkipSingle );
        return false;
    }

    m_recorded_events_edit = 0;
    m_recorded_code = QString();
    if (!queryPassed( "OK", "", QTestMessage("startEventRecording"))) return false;
    if (gui) {
        if (QTestIDE::instance()->isConnected()) {
            QTestIDE::instance()->eventRecordingStarted(currentFile(), currentLine(), manualSteps);
            m_recording_events = true;
            while (!QTestIDE::instance()->mustStopEventRecording()) {            
                QTest::qWait( 50 );
            }
            
            m_recording_events = false;
            if (QTestIDE::instance()->eventRecordingAborted()) {            
                skip("Event recording aborted.", SkipSingle );
            }
        } else {
            QDialog recordWindow;
            Ui::RecordDialog ui;
            ui.setupUi(&recordWindow);

            if (!manualSteps.isEmpty()) {
                ui.steps_view->setPlainText( manualSteps );
            } else {
                ui.steps_view->hide();
                ui.steps_label->hide();
            }

            m_recorded_events_edit = ui.codeEdit;

            connect( ui.abort_button, SIGNAL(clicked()), &recordWindow, SLOT(close()) );
            connect( ui.abort_button, SIGNAL(clicked()), this, SLOT(abortPrompt()) );
            abort_prompt = false;

            m_recording_events = true;
            recordWindow.exec();
            m_recording_events = false;
            if (abort_prompt) {
                return false;
            }

        }
        return queryPassed( "OK", "", QTestMessage("stopEventRecording"));
    }
    return true;
}

/*!
    \internal
    Stops recording events, returning the generated code from event recording.
    Used internally for testing event recording.
*/
QString QSystemTest::stopRecordingEvents()
{
    queryPassed( "OK", "", QTestMessage("stopEventRecording"));
    return m_recorded_code;
}

/*!
    Displays a dialog with the \a manualSteps and Pass/Fail/Record buttons, then waits for a response from
    the user.
    \list
    \o If Pass is clicked, the test will continue.
    \o If Fail is clicked, a failure will be generated and the current testcase will abort.
    \o If Record is clicked, event recording will start and recorded events can be appended to the testcase
        once recording is finished.
    \endlist

    This function is intended to be used for verification of testcases that cannot be fully automated.
    Testcases containing this function will be skipped if the test is run with the \c -auto option (i.e.
    when tests are executed in a CI system).

    Example1:
    \code
        prompt( "Did something totally amazing just happen?" );
    \endcode

    When the test is run with \c -force-manual the \a manualSteps are accumulated and the actual prompt dialog is
    not shown until the end of the test function, i.e.
    \list
    \o all automated commands are converted into documented manual steps
    \o all \a manualSteps are added to this list
    \o and the complete set of steps is shown in one go
    \endlist

    For example:
    \code
        startApplication("foobar");
        prompt( "Do something that is difficult to automate" );
        compare( currentTitle(), "blah" );
    \endcode

    When the above example is executed in normal (automated) test execution mode 'startApplication' will
    start application foobar, then show a dialog with the text "Do something that is difficult to automate"
    and wait until the user clicks on Pass or Fail. If the user clicked on Fail the test will be terminated
    and if the user clicked on Pass the execution will continue with the next step, i.e. an automatic
    comparison of the current title against the constant 'blah'.

    If however the test is executed with \c -force-manual all text will be converted into manual steps and
    nothing will be executed automatically, but instead one prompt dialog will be shown at the end of the
    test function with the following steps:
    \code
        1. start application 'foobar'
        2. Do something that is difficult to automate
        3. Verify that the current title is equal to 'blah'
    \endcode

    \sa manualTest
*/
void QSystemTest::prompt( const QString &manualSteps )
{
    if (manualSteps.contains(QRegExp("<.*>.*</.*>")))
    {
        // Contains HTML, don't assume it's a series of steps
        showPromptDialog(manualSteps);
        return;
    }

    QStringList list = manualSteps.split("\n", QString::SkipEmptyParts);
    foreach( QString cmd, list)
        manualTest(cmd);

    if (runAsManualTest()) {
        // just add the manualSteps to whatever we already have, and show prompt at the end.
        return;
    }

    if (m_auto_mode) {
        skip("Manual test skipped", SkipSingle);
        return;
    }

    showPromptDialog();
}

/*! \internal */
void QSystemTest::abortPrompt()
{
    abort_prompt = true;
}

/*!
    \internal
    This function is called when the test IDE wants to abort the current test.
*/
void QSystemTest::abortTest()
{
#ifndef Q_OS_SYMBIAN
    ::raise(SIGINT);
#endif
}

//#ifndef QTCREATOR_QTEST
/*!
    \internal
    Print any special usage information which should be shown when test is launched
    with -help.
*/
void QSystemTest::printUsage() const
{
    QAbstractTest::printUsage();
    qWarning(
        "  System test options:\n"
        "    -authost <host>   : Specify the IP address or host name of the machine on which the AUT is running.\n"
        "                        By default, the system test will connect to 127.0.0.1.\n"
        "    -autport <port>   : Use QTUITEST_DEFAULT_OPTIONS environment variable to specify autport option and value.\n"
        "                        Specify the port on which the AUT is listening for a system test connection.\n"
        "                        Defaults to %d. \n"
        "    -keepaut          : Leave the AUT running after the system test finishes.\n"
        "                        By default, if the system test launches the AUT, it will kill the AUT when testing\n"
        "                        completes.\n"
        "    -silentaut        : Hide the output of the AUT.  By default, if the system test launches the AUT, the AUT's\n"
        "                        standard output and standard error will be mixed with that of the test itself.\n"
        "\n"
        "    -auto             : Run in fully-automated mode.  Any tests which require the presence of a manual\n"
        "                        tester will be skipped.\n"
        "\n"
        "    -force-manual     : Runs all system tests as manual tests. Test cases that contain automated step are translated\n"
        "                        into a set of documented steps.\n"
        "\n"
        "    -verbose-perf     : Output all performance messages from the AUT to the console.  This may be used to run\n"
        "                        a post-processing script on performance logs.\n"
        "\n"
        "    -remote <host:port> : Specify the host and port of a QtUiTest-compatible test IDE, used for manual\n"
        "                          verification steps.  The default is to not use an IDE.\n"
        "    -env VAR=VALUE    : Specify additional environment variables to be applied to tested \n"
        "                        applications.  For example, pass -env DISPLAY=:123 to run tested \n"
        "                        applications on a different X server.\n"
        "    -targetID         : Specify the target identifier for system under test, defaults to \'default\' or $QTUITEST_TARGETID if set\n"
        , DEFAULT_AUT_PORT
    );
}
//#endif

#ifndef Q_QDOC
/*
    Fail returning a bool is for internal use only.
    Hide from documentation.
*/
/*!
    \internal
    Cause a test failure with the given \a message.
    Returns true if the test should continue (e.g., because the failure was expected), false otherwise.
*/
bool QSystemTest::fail(QString const &message)
{
    if (m_expect_app_close &&
        (message.startsWith("ERROR: Connection lost") ||
        message.startsWith("ERROR: no data in reply to") ||
        message.startsWith("reply was missing return value") ||
        message.startsWith("ERROR_NO_CONNECTION")) ) {
        return true;
    }

    static bool saving_screen = false;
    static bool saving_info   = false;
    static QString saving_screen_failed;
    static QString saving_info_failed;
    /* Prevent recursive failure on saving screen/widget info */
    if (saving_screen) {
        saving_screen_failed = "Failed to save failure screenshot: " + message;
        return true;
    }
    if (saving_info) {
        saving_info_failed = "Failed to save widget info on failure: " + message;
        return true;
    }

    bool ret = QTest::compare_helper( false, qPrintable(message), qPrintable(currentFile()), currentLine() );
    if (!ret) {
        saving_screen = true;
        saving_screen_failed = QString();

        QString config = configurationIdentifier();
        saveScreen("failure_" + config);

        saving_screen = false;

        if (saving_screen_failed.isEmpty()) {
            // If we saved it, let the IDE know.
            QFileInfo info(currentDataPath() + "/failure_" + config + ".png");
            if (info.exists()) {
                QTestIDE::instance()->failureScreenshot(info.canonicalFilePath(), currentFile(), currentLine(), QTest::currentTestFunction());
            }
        }

        saving_info = true;
        saving_info_failed = QString();

        QString info = activeWidgetInfo();

        saving_info = false;
        if (!info.isEmpty()) {
            QFile f(currentDataPath() + "/failure_" + config + ".txt");
            if (!f.exists() && f.open(QIODevice::WriteOnly)) {
                QTextStream(&f)
                    <<  message << "\n"
                    << "Location: " << currentFile() << ":" << currentLine() << "\n"
                    << (saving_screen_failed.isEmpty()
                            ? "Also see failure_" + config + ".png for a screenshot."
                            : saving_screen_failed)
                    << "\n"
                    << (saving_info_failed.isEmpty()
                            ? info
                            : saving_info_failed)
                    << "\n";
            }
        }
    }
    return ret;
}
#endif

/*!

    Cause a test to skip with the given \a message and \a mode.

*/
void QSystemTest::skip(const QString& message, SkipMode mode)
{
    m_skip_current_function = true;
    
    // If there is no test data for this function, always use
    // SkipAll to avoid reporting both SKIP and PASS result
    if (currentDataTag().isEmpty())
        mode = SkipAll;

    QTest::qSkip(qPrintable(message), QTest::SkipMode(mode), qPrintable(currentFile()), currentLine());
}

/*!
    \internal
    Returns true if the last executed query has failed.
    If \a message is not null, a failure message is returned in \a message.
    If \a sent is not null, the message sent from the system test which
    caused the failure is returned in \a sent.
*/
bool QSystemTest::queryFailed( QTestMessage *message, QTestMessage *sent )
{
    if (message != 0)
        *message = m_error_msg;
    if (sent != 0)
        *sent = m_error_msg_sent;
    return query_failed;
}

/*!
    \internal
    Informs the testframework that error situations need to be reported as warnings.
*/
void QSystemTest::enableQueryWarnings( bool enable, const QString &file, int line )
{
    setLocation( file, line );

    if (!enable) {
        m_error_msg = QTestMessage();
        query_failed = false;
    }
    query_warning_mode = enable;
}

/*!
    \internal
    Saves the \a file and \a line information for internal usage. Whenever an error situation occurs this data is appended to the error message to improve traceability of the error.

    It is usually not necessery to call this function directly.
*/
void QSystemTest::setLocation( const QString &file, int line )
{
    m_loc_fname = file;
    m_loc_line = line;
}

/*!
    \internal
    Returns the current filename, i.e. the file that was being executed when the error situation occurred.
*/
QString QSystemTest::currentFile()
{
    return m_loc_fname;
}

/*!
    \internal
    Returns the current line number, i.e. the line number that presumably caused the error situation.
*/
int QSystemTest::currentLine()
{
    return m_loc_line;
}

/*!
    \internal
    Saves the error string \a errString for future processing. If warning mode is enabled the error is written directly to std out as a warning.
    Base implementation returns false; subclasses may return true to indicate that the error is not considered "fatal".
*/
bool QSystemTest::setQueryError( const QString &errString )
{
    query_failed = true;
    m_error_msg["status"] = errString;
    m_error_msg_sent = m_last_msg_sent;
    if (query_warning_mode)
        qWarning( errString.toLatin1() );
    return false; // query is NOT successfull
}

/*!
    \internal
    Saves the error specified in the test \a message for future processing. If warning mode is enabled the error is written directly to std out as a warning.
    Base implementation returns false; subclasses may return true to indicate that the error is not considered "fatal".
*/
bool QSystemTest::setQueryError( const QTestMessage &message )
{
    query_failed = true;
    m_error_msg = message;
    m_error_msg_sent = m_last_msg_sent;
    if (query_warning_mode)
        qWarning( QString("%1 %2").arg(message.event()).arg(message.toString()).toLatin1().constData() );
    return false; // query is NOT successfull
}

//#ifndef QTCREATOR_QTEST
/*!
    \internal
    Launch AUT and run the test.
*/
int QSystemTest::runTest(const QString &fname, const QStringList &args,
                               const QStringList &environment)
{
    // Try to launch the aut script, and if successful, start executing the test.
    // QTest::qExec will also start the application event loop, and will not return until the tests have finished.

    return QAbstractTest::runTest(fname, args, environment);
}
//#endif

/*!
    \internal
    Attempts to launch the AUT (Application Under Test), and returns whether it was successful.
    The \c -remote command line argument is appended to the script with the IP set to the address of the
    local machine. This is to allow the test system to connect to the machine the test is running on.

    Any scripts used should support this.
*/
bool QSystemTest::connectToAut(int timeout)
{
    if (!m_test_app)
        m_test_app = new QSystemTestMaster( this );

    QTime t;
    t.start();
    while (t.elapsed() < timeout && !isConnected()) {
        m_test_app->connect( ssh_param.host, m_aut_port );
        m_test_app->waitForConnected(2000);
    }

    if (!m_test_app->isConnected()) {
        qLog(QtUitest) << qPrintable(QString("'%1' while trying to connect to test app on %2:%3. ").arg(m_test_app->errorStr()).arg(ssh_param.host).arg(m_aut_port)) ;
        return false;
    }

    // Don't try to reconnect if connection is lost ... it's pointless
    m_test_app->enableReconnect(false, 0);

    if (m_demo_mode) setDemoMode(true);

    return true;
}

/*!
    \internal
*/
void QSystemTest::disconnectFromAut()
{
    m_test_app->disconnect();
}

/*!
    Returns the username that is running the test on the desktop machine.
*/
QString QSystemTest::userName()
{
    QString user_name;

#if defined Q_OS_TEMP
    user_name = "WinCE";
#elif defined Q_OS_WIN32
    user_name = ::getenv("USERNAME");
#elif defined Q_OS_UNIX
    user_name = ::getenv("USER");
    if (user_name == "")
        user_name = ::getenv( "LOGNAME" );
#elif defined Q_OS_MAC
    user_name = ::getenv();
#endif

    return user_name.toLower();
}

/*!
    Runs \a application with arguments \a args on the local machine,
    with \a input given as standard input. The combined stderr and stdout text will be returned.

    If the process fails to run or returns a non-zero exit code, the current test fails.
*/
QString QSystemTest::runProcess( const QString &application, const QStringList &args, const QString &input )
{
    QString output;
    QProcess p;
    p.setReadChannelMode(QProcess::MergedChannels);
    p.setReadChannel(QProcess::StandardOutput);
    p.start(application, args);
    if (p.waitForStarted()) {
        if (!input.isEmpty()) {
            p.write( input.toLatin1() );
        }
        p.closeWriteChannel();
        while (p.state() == QProcess::Running) {
            while (p.canReadLine()) {
                output += p.readLine();
            }
            wait(10); //important
        }
        while (p.canReadLine()) {
            output += p.readLine();
        }
        if (p.exitStatus() != QProcess::NormalExit) {
            setQueryError("Process didn't exit normally\n" + output);
            return QString();
        }
        int ec = p.exitCode();
        if (0 != ec) {
            QString err_str = QString("Process exited with exit code: %1\n%2").arg(ec).arg(output);
            setQueryError(err_str);
            return QString();
        }
        return output;
    }
    setQueryError("Process didn't start");
    return output;
}

/******************************************************************************
* DOCUMENTATION FOR FUNCTIONS IN builtins.js
******************************************************************************/

/*!
    Compares the \a actual string with the \a expected string and reports a fail
    with a nicely formatted error message in case the strings are not equal.

    Example:
    \code
        var my_variable1 = "Test";
        var my_variable2 = "Test2";
        compare( my_variable1, "Test" ); // passes
        compare( my_variable2, "Test" ); // will fail the test, and test execution will stop at this line
    \endcode

    \sa verify()
*/
#ifdef Q_QDOC
void QSystemTest::compare( const QString &actual, const QString &expected )
{
    // This code is implemented in the QtUiTestrunner bindings
}
#endif

/*!
    Aborts the test with a failure message if \a statement is false.
    The failure messages returned by compare() are generally speaking better readable (more informative) and is preferred when working with strings.

    Example:
    \code
        var my_variable1 = "Test";
        var my_variable2 = "Test2";
        verify( my_variable1 == "Test" ); // passes
        verify( my_variable2 == "Test" ); // will fail the test, and test execution will stop at this line
    \endcode

    \sa compare()
*/
#ifdef Q_QDOC
void QSystemTest::verify( bool statement )
{
    // This code is implemented in the QtUiTestrunner bindings
}
#endif

/*!
    \fn QSystemTest::waitFor(Number timeout, Number intervals, String message)

    Denotes the start of a block of code which should be repeatedly executed
    until it returns true.  If the block of code doesn't return true within
    \a timeout milliseconds, the current test fails with the given \a message.

    \a intervals is the maximum amount of times the block of code should be
    executed; i.e., the code will be executed every \a timeout / \a intervals
    milliseconds.

    Example:
    \code
    waitFor() {
        return getList().length > 0;
    }
    \endcode
*/


/*!
    \fn QSystemTest::verify(Boolean condition, String message)

    Verifies that \a condition is true.  If \a condition is not true, the
    current test fails.  If \a message is given, it will be appended to
    the failure message.

    Example:
    \code
    select("Frank", "Contacts");
    waitForTitle("Details: Frank");
    var details = getText();
    // Verify that Frank's phone number is shown somewhere
    verify( details.contains("12345") );
    // Same, but with more details in error message
    verify( details.contains("12345"), "Frank's phone number is missing!" );
    \endcode
*/

/*!
    \fn QSystemTest::compare(Variant actual, Variant expected)

    Verifies that \a actual is equal to \a expected.  If this is not the case,
    the current test fails.

    Note that the order of \a actual and \a expected is significant, as it
    affects the test failure message.
*/

/*!
    \fn QSystemTest::fail(String message)

    Immediately fail the current test with the specified \a message.
*/

/*!
    Returns the signature of the tabbar widget. If multiple tabbars exist, \a index can be used to
    distinguish between them (sorted in order of position from top left of screen).

    Example:
    \code
        select( "Personal", tabBar() ); // select the tab with text 'Personal' from the tab bar.
        print( tabBar() );              // to print the signature of the tabbar widget.
    \endcode

    The test will fail if no visible tabbar is found.
*/
#ifdef Q_QDOC
void QSystemTest::tabBar( int index )
{
    // This code is implemented in the QtUiTestrunner bindings
}
#endif

/*!
    \internal
    Returns an identifier for the current runtime configuration.
    Includes mousePreferred(), screen size and theme.
*/
QString QSystemTest::configurationIdentifier() const
{
    return m_config_id;
}

/*!
    \internal
*/
void QSystemTest::setConfigurationIdentifier(QString const& config)
{
    m_config_id = config;
}

/*!
    \internal
*/
bool QSystemTest::verbose() const
{
    return m_verbose;
}

/*!
    \internal
*/
bool QSystemTest::doQuery(const QTestMessage& message, const QString& queryPath, QTestMessage* reply, int timeout, const QStringList& pass, const QStringList& fail)
{ return queryPassed(pass, fail, message, queryPath, reply, timeout); }

/*!
    \internal
    Prints \a value.
*/
void QSystemTest::print( QVariant const& value )
{
    QDebug(QtDebugMsg) << qPrintable(value.toString());
}

/*! \internal
    Enables/disables waits and animations for demo purposes.
*/
void QSystemTest::setDemoMode( bool enabled )
{
    QTestMessage queryMsg("enableDemoMode");
    queryMsg["enable"] = enabled;
    queryPassed( "OK", "", queryMsg );
}

/*!
    \internal
*/
bool QSystemTest::demoMode() const
{
    return m_demo_mode;
}

/*!
    \internal
*/
QString QSystemTest::autHost() const
{
    return ssh_param.host;
}

/*!
    \internal
*/
int QSystemTest::autPort() const
{
    return m_aut_port;
}

/*!
    Uses the \a reason to mark the current testfunction as expected to fail.
*/
void QSystemTest::expectFail( const QString &reason )
{
    QEXPECT_FAIL(currentDataTag().toLatin1().constData(), qstrdup(reason.toLatin1().constData()), Abort);
}

/*!
    Returns the translation for \a text, from the application's installed translation files. \a context is
    typically a class name. If no translation is found, the \a text is returned unchanged.

    \a comment is a disambiguating comment, for when the same sourceText is used in different roles
    within the same context. By default, it is null. \a n is used in conjunction with \c %n to support
    plural forms. See QObject::tr() for details.

    When developing test cases that use translations, it will be necessary to refer to the translator
    message files (\c .ts files), either directly or through Qt Linguist, to determine which
    translations are available, and the appropriate \a context to use.

    In some cases, translated phrases will contain argument placeholders (\c %1, etc) which will need
    to be expanded with the correct values.

    Example:
    \code
        // Label translation
        print( translate("QFileDialog", "File &name:") );

        // Replace argument placeholders
        compare( message, translate("QHttp", "Host %1 not found").replace("%1", hostname) );
    \endcode

    \sa QCoreApplication::translate(), getLocale()
*/
QString QSystemTest::translate(const QString &context, const QString &text, const QString &comment, int n)
{
    QTestMessage message("translate");
    message["context"] = context;
    message["text"] = text;
    message["comment"] = comment;
    message["number"] = n;
    QTestMessage reply;

    if (!queryPassed( "OK", "", BT(message), "", &reply )) return false;
    return reply["translate"].toString();
}

/*!
    Returns the system locale.

    \sa QLocale::system(), translate()
*/
QLocale QSystemTest::getLocale()
{
    QTestMessage message("getLocale");
    QTestMessage reply;

    if (!queryPassed( "OK", "", BT(message), "", &reply )) return QLocale();
    return reply["getLocale"].toLocale();
}

/*!
    \internal
*/
void QSystemTest::qtuitest_pre_test_function()
{
    m_query_count = 0;
    m_skip_current_function = false;
}

/*!
    \internal
*/
void QSystemTest::qtuitest_post_test_function()
{
    if (!m_manual_commands.isEmpty() && !QTest::currentTestFailed()) {
        showPromptDialog();
    }

    if (failEmptyTest() && m_query_count == 0 && !m_skip_current_function && !QTest::currentTestFailed()) {
        fail("Nothing tested");
    }
}

/*!
    \internal
*/
bool QSystemTest::runAsManualTest(void)
{
    return m_run_as_manual_test;
}

/*! 
  \internal
  Pass any configuration values to the system under test
   */
void  QSystemTest::configTarget()
{
    if (m_run_as_manual_test)
        return;

    // set the target identifier
    if (!m_targetID.isEmpty())
        setTargetIdentifier(m_targetID);
}

/*! \typedef StringArray
    \relates QSystemTest

    An \l Array object in which every element is a \l String.
*/

/*! \typedef QVariantArray
    \relates QSystemTest

    An \l Array object in which every element is a \l QVariant.
*/

/*! \typedef Function
    \relates QSystemTest

    The Function type as documented in ECMA-262, section 15.3.
*/

/*! \typedef Array
    \relates QSystemTest

    The Array type as documented in ECMA-262, section 15.4.

    The following extensions are provided in QtUiTest.

    \table
    \row \o \tt{\l Boolean Array.prototype.contains(value)}
            \o Returns true if the array contains the given value.
    \endtable
*/

/*! \typedef String
    \relates QSystemTest

    The String type as documented in ECMA-262, section 15.5.

    The following extensions are provided in QtUiTest.

    \table
    \row \o \tt{ \l Boolean String.prototype.contains(String text)}
            \o Returns true if the string contains the given text.
    \row \o \tt{ \l Boolean String.prototype.contains(\l QRegExp regex)}
            \o Returns true if the string is matched by the given regular expression.
    \row \o \tt{ \l Boolean String.prototype.startsWith(String text)}
            \o Returns true if the string starts with the given text.
    \row \o \tt{ String String.prototype.left(\l Number n)}
            \o Returns the first n characters of the string.
    \row \o \tt{ String String.prototype.right(\l Number n)}
            \o Returns the last n characters of the string.
    \endtable
*/


/*! \typedef Boolean
    \relates QSystemTest

    The Boolean type as documented in ECMA-262, section 15.6.
*/

/*! \typedef Number
    \relates QSystemTest

    The Number type as documented in ECMA-262, section 15.7.
*/