native-gui-mock 1.0.0

Headless Mock backend and in-process E2E testing framework for Native GUI
Documentation
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
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
//! In-process end-to-end test driver.
//!
//! This first implementation is gated by the `e2e` feature and currently
//! supports simulated Mock actions and capability-gated native actions.
//! Capture, dialogs, hardware input, and backend parity remain separate gates.

pub mod dialog;
pub mod gallery;
pub mod harness;
pub mod remote;
pub mod visual;

pub use dialog::*;
pub use gallery::*;
pub use harness::*;
pub use remote::*;
pub use visual::*;

use std::collections::{HashMap, HashSet};
use std::marker::PhantomData;
use std::rc::{Rc, Weak};
use std::time::{Duration, Instant};

use crate::MockBackend;
use native_gui_core::access::AccessibleRole;
use native_gui_core::error::{GuiError, GuiResult};
use native_gui_core::events::UiEvent;
use native_gui_core::ui::{Backend, LoopFlow, Ui};
use native_gui_core::widgets::{WidgetId, WidgetKind, WidgetProperty, WidgetSpec};

/// Compatibility bound for the driver; capabilities are supplied by `Backend`.
#[doc(hidden)]
pub trait E2eBackend: Backend + 'static {}
impl<B: Backend + 'static> E2eBackend for B {}

fn parse_key_chord(chord: &str) -> GuiResult<(String, bool, bool, bool)> {
    if chord.is_empty() {
        return Err(GuiError::Backend(
            "e2e.invalid_argument: key chord must not be empty".into(),
        ));
    }
    let parts: Vec<&str> = chord.split('+').map(str::trim).collect();
    let mut ctrl = false;
    let mut shift = false;
    let mut alt = false;
    let mut key = String::new();

    for (i, part) in parts.iter().enumerate() {
        if i == parts.len() - 1 && !part.is_empty() {
            key = (*part).to_owned();
        } else {
            match part.to_ascii_lowercase().as_str() {
                "ctrl" | "control" => ctrl = true,
                "shift" => shift = true,
                "alt" => alt = true,
                _ => {
                    if i == parts.len() - 1 {
                        key = (*part).to_owned();
                    } else {
                        return Err(GuiError::Backend(format!(
                            "e2e.invalid_argument: unknown modifier in key chord: {part}"
                        )));
                    }
                }
            }
        }
    }

    if key.is_empty() {
        return Err(GuiError::Backend(
            "e2e.invalid_argument: key chord has no main key".into(),
        ));
    }

    Ok((key, ctrl, shift, alt))
}

impl MockBackend {
    pub(crate) fn e2e_mock_type_text(&mut self, widget_id: WidgetId, text: &str) -> GuiResult<()> {
        let new_text = {
            let spec = self
                .created
                .get_mut(&widget_id)
                .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
            spec.ensure_property(WidgetProperty::TextSelection)?;

            let current = spec.text.as_deref().unwrap_or_default();
            let chars: Vec<char> = current.chars().collect();
            let (start, end) = spec.text_selection.unwrap_or((chars.len(), chars.len()));
            let (start, end) = (start.min(chars.len()), end.min(chars.len()));
            if start > end {
                return Err(GuiError::Backend(
                    "E2E text selection is outside the current text".to_owned(),
                ));
            }

            let inserted: Vec<char> = text.chars().collect();
            let mut updated = Vec::with_capacity(chars.len() - (end - start) + inserted.len());
            updated.extend_from_slice(&chars[..start]);
            updated.extend(inserted.iter().copied());
            updated.extend_from_slice(&chars[end..]);
            let caret = start + inserted.len();
            let new_text: String = updated.into_iter().collect();
            spec.text = Some(new_text.clone());
            spec.text_selection = Some((caret, caret));
            new_text
        };
        self.events.push_back(UiEvent::TextChanged {
            widget_id,
            text: new_text.clone(),
        });
        Ok(())
    }

    pub(crate) fn e2e_mock_check(&mut self, widget_id: WidgetId, checked: bool) -> GuiResult<()> {
        let changed = {
            let spec = self
                .created
                .get_mut(&widget_id)
                .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
            spec.ensure_property(WidgetProperty::Checked)?;
            let changed = spec.checked.unwrap_or(false) != checked;
            spec.checked = Some(checked);
            changed
        };
        if changed {
            self.events
                .push_back(UiEvent::Toggled { widget_id, checked });
        }
        Ok(())
    }

    pub(crate) fn e2e_mock_press(&mut self, widget_id: WidgetId, chord: &str) -> GuiResult<()> {
        let (key, ctrl, shift, alt) = parse_key_chord(chord)?;
        self.events.push_back(UiEvent::KeyDown {
            widget_id,
            key: key.clone(),
            ctrl,
            shift,
            alt,
        });
        if !ctrl && !alt && key.chars().count() == 1 {
            self.events.push_back(UiEvent::Char {
                widget_id,
                text: key.clone(),
            });
        }
        self.events.push_back(UiEvent::KeyUp {
            widget_id,
            key,
            ctrl,
            shift,
            alt,
        });
        Ok(())
    }

    pub(crate) fn e2e_mock_select(&mut self, widget_id: WidgetId, index: usize) -> GuiResult<()> {
        let (selected_text, changed) = {
            let spec = self
                .created
                .get_mut(&widget_id)
                .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
            spec.ensure_property(WidgetProperty::SelectedIndex)?;
            let old = spec.selected_index;
            spec.selected_index = Some(index);
            let item_text = if !spec.data_list_items.is_empty() {
                spec.data_list_items.get(index).cloned()
            } else if !spec.tab_items.is_empty() {
                spec.tab_items.get(index).cloned()
            } else {
                None
            };
            (item_text, old != Some(index))
        };
        if changed {
            self.events.push_back(UiEvent::SelectionChanged {
                widget_id,
                selected: selected_text,
                index: Some(index),
            });
        }
        Ok(())
    }

    pub(crate) fn e2e_mock_select_text(
        &mut self,
        widget_id: WidgetId,
        start: usize,
        end: usize,
    ) -> GuiResult<()> {
        let spec = self
            .created
            .get_mut(&widget_id)
            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
        spec.ensure_property(WidgetProperty::TextSelection)?;
        let len = spec.text.as_deref().unwrap_or_default().chars().count();
        if start > end || end > len {
            return Err(GuiError::Backend(
                "e2e.invalid_argument: text selection is out of bounds".into(),
            ));
        }
        spec.text_selection = Some((start, end));
        Ok(())
    }

    pub(crate) fn e2e_mock_set_value(&mut self, widget_id: WidgetId, value: i32) -> GuiResult<()> {
        let changed = {
            let spec = self
                .created
                .get_mut(&widget_id)
                .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
            spec.ensure_property(WidgetProperty::Value)?;
            if let Some((min, max)) = spec.range {
                if value < min {
                    return Err(GuiError::Backend(format!(
                        "e2e.invalid_argument: value {value} is below min {min}"
                    )));
                }
                if value > max {
                    return Err(GuiError::Backend(format!(
                        "e2e.invalid_argument: value {value} is above max {max}"
                    )));
                }
            }
            let changed = spec.value != Some(value);
            spec.value = Some(value);
            changed
        };
        if changed {
            self.events
                .push_back(UiEvent::ValueChanged { widget_id, value });
        }
        Ok(())
    }

    pub(crate) fn e2e_mock_scroll(
        &mut self,
        widget_id: WidgetId,
        _delta_x: f64,
        delta_y: f64,
    ) -> GuiResult<()> {
        let spec = self
            .created
            .get_mut(&widget_id)
            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
        let supported = match spec.kind {
            WidgetKind::Container => true,
            #[cfg(feature = "widgets-text")]
            WidgetKind::TextArea => true,
            #[cfg(feature = "widgets-data")]
            WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => true,
            _ => false,
        };
        if supported {
            let row_offset = (delta_y.round() as i32).max(0) as usize;
            self.scroll_anchors.insert(widget_id, row_offset);
            Ok(())
        } else {
            Err(GuiError::UnsupportedWidget("e2e.scroll"))
        }
    }

    pub(crate) fn e2e_mock_drag_to(
        &mut self,
        source_id: WidgetId,
        target_id: WidgetId,
    ) -> GuiResult<()> {
        if !self.created.contains_key(&source_id) {
            return Err(GuiError::WidgetNotFound(source_id.0));
        }
        if !self.created.contains_key(&target_id) {
            return Err(GuiError::WidgetNotFound(target_id.0));
        }
        self.events.push_back(UiEvent::DragStarted {
            widget_id: source_id,
            indices: vec![0],
        });
        self.events.push_back(UiEvent::Dropped {
            widget_id: target_id,
            target_index: 0,
            source_indices: vec![0],
        });
        Ok(())
    }

    pub(crate) fn e2e_mock_close(&mut self, widget_id: WidgetId) -> GuiResult<()> {
        let spec = self
            .created
            .get_mut(&widget_id)
            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
        if !spec.kind.is_window_like() {
            return Err(GuiError::UnsupportedWidget("e2e.close"));
        }
        if self.close_guards.get(&widget_id).copied().unwrap_or(false) {
            self.events.push_back(UiEvent::CloseRequested { widget_id });
        } else {
            self.events.push_back(UiEvent::WindowClosed { widget_id });
            self.shown.retain(|id| id != &widget_id);
        }
        Ok(())
    }

    pub(crate) fn e2e_mock_value(&self, widget_id: WidgetId) -> GuiResult<i32> {
        let spec = self
            .created
            .get(&widget_id)
            .ok_or(GuiError::WidgetNotFound(widget_id.0))?;
        spec.value
            .ok_or_else(|| GuiError::Backend(format!("widget {} has no value", widget_id.0)))
    }
}

pub use native_gui_core::{Capability, InputMode, Operation};

/// Options for a bounded E2E wait.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct WaitOptions {
    /// Maximum time to wait.
    pub timeout: Duration,
    /// Delay between predicate checks; waits cap each sleep at 25 ms.
    pub poll_interval: Duration,
}

impl WaitOptions {
    /// Creates wait options with a 10 ms polling interval.
    pub fn new(timeout: Duration) -> Self {
        Self {
            timeout,
            poll_interval: Duration::from_millis(10),
        }
    }

    /// Replaces the polling interval.
    pub fn poll_interval(mut self, interval: Duration) -> Self {
        self.poll_interval = interval;
        self
    }
}

impl Default for WaitOptions {
    fn default() -> Self {
        Self::new(Duration::from_secs(5))
    }
}

/// A query over the owning UI's shared widget graph.
#[derive(Debug, Clone, Default)]
pub struct Locator {
    selectors: Vec<Selector>,
    relations: Vec<Relation>,
}

impl Locator {
    /// Matches one exact widget identifier.
    pub fn id(widget_id: WidgetId) -> Self {
        Self::with_selector(Selector::Id(widget_id))
    }

    /// Matches an explicit driver-bound automation name.
    pub fn name(name: impl Into<String>) -> Self {
        Self::with_selector(Selector::Name(name.into()))
    }

    /// Matches an explicit driver-bound test identifier.
    pub fn test_id(test_id: impl Into<String>) -> Self {
        Self::with_selector(Selector::TestId(test_id.into()))
    }

    /// Matches the shared accessibility role and effective accessible label.
    pub fn role(role: AccessibleRole, label: impl Into<String>) -> Self {
        Self::with_selector(Selector::Role(role, label.into()))
    }

    /// Matches a shared widget kind.
    pub fn kind(kind: WidgetKind) -> Self {
        Self::with_selector(Selector::Kind(kind))
    }

    /// Matches any top-level window widget (`WidgetKind::Window`).
    pub fn window() -> Self {
        Self::kind(WidgetKind::Window)
    }

    /// Matches any standard dialog widget (`AlertDialog`, `FileChooserDialog`, `ColorDialog`, `FontDialog`).
    pub fn dialog() -> Self {
        Self::with_selector(Selector::Dialog)
    }

    /// Matches any top-level surface (window or dialog).
    pub fn top_level() -> Self {
        Self::with_selector(Selector::TopLevel)
    }

    /// Matches the exact shared text projection.
    pub fn text(text: impl Into<String>) -> Self {
        Self::with_selector(Selector::Text(text.into()))
    }

    /// Restricts matches to widgets whose immediate parent matches `parent`.
    pub fn child_of(mut self, parent: Locator) -> Self {
        self.relations.push(Relation::ChildOf(Box::new(parent)));
        self
    }

    /// Restricts matches to descendants of `ancestor`.
    pub fn descendant_of(mut self, ancestor: Locator) -> Self {
        self.relations
            .push(Relation::DescendantOf(Box::new(ancestor)));
        self
    }

    /// Restricts matches to a window and its descendants.
    pub fn in_window(mut self, window: Locator) -> Self {
        self.relations.push(Relation::InWindow(Box::new(window)));
        self
    }

    /// Adds an additional kind requirement to this locator.
    pub fn with_kind(mut self, kind: WidgetKind) -> Self {
        self.selectors.push(Selector::Kind(kind));
        self
    }

    /// Adds an additional text requirement to this locator.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.selectors.push(Selector::Text(text.into()));
        self
    }

    /// Adds an additional name requirement to this locator.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.selectors.push(Selector::Name(name.into()));
        self
    }

    /// Adds an additional test_id requirement to this locator.
    pub fn with_test_id(mut self, test_id: impl Into<String>) -> Self {
        self.selectors.push(Selector::TestId(test_id.into()));
        self
    }

    /// Adds an additional accessible role requirement to this locator.
    pub fn with_role(mut self, role: AccessibleRole, label: impl Into<String>) -> Self {
        self.selectors.push(Selector::Role(role, label.into()));
        self
    }

    fn with_selector(selector: Selector) -> Self {
        Self {
            selectors: vec![selector],
            relations: Vec::new(),
        }
    }
}

#[derive(Debug, Clone)]
enum Selector {
    Id(WidgetId),
    Name(String),
    TestId(String),
    Role(AccessibleRole, String),
    Kind(WidgetKind),
    Text(String),
    Dialog,
    TopLevel,
}

#[derive(Debug, Clone)]
enum Relation {
    ChildOf(Box<Locator>),
    DescendantOf(Box<Locator>),
    InWindow(Box<Locator>),
}

/// Target surface for an in-process E2E screenshot capture.
#[derive(Debug, Clone)]
pub enum CaptureTarget {
    /// A specific top-level window or dialog by widget ID.
    Window(WidgetId),
    /// A specific element resolved by locator query.
    Element(Locator),
    /// The overall application viewport / active window canvas.
    Viewport,
    /// A backend-owned prompt that has no widget of its own, addressed by the
    /// token `Ui::show_confirm_dialog` or `Ui::show_file_dialog` returned.
    ///
    /// Mock renders the pending request (title, message or file-dialog
    /// summary, and its buttons). Native backends do not expose these system
    /// prompts to capture and return [`GuiError::UnsupportedCapability`].
    Prompt(u64),
}

/// In-memory RGBA8 raster image produced by an E2E screenshot capture.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaptureImage {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Raw RGBA8 pixel bytes (row-major, top-to-bottom, 4 bytes per pixel: R, G, B, A).
    pub data: Vec<u8>,
}

/// Alias for [`CaptureImage`].
pub type RgbaImage = CaptureImage;

impl CaptureImage {
    /// Creates a new `CaptureImage` from pixel dimensions and raw RGBA8 data.
    pub fn new(width: u32, height: u32, data: Vec<u8>) -> Self {
        Self {
            width,
            height,
            data,
        }
    }

    /// Returns the image width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Returns the image height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Returns a slice over the raw RGBA8 pixel bytes.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Returns a slice over the raw RGBA8 pixel bytes (alias for data).
    pub fn pixels(&self) -> &[u8] {
        &self.data
    }

    /// Reads the RGBA8 color of a pixel at `(x, y)`.
    pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
        if x < self.width && y < self.height {
            let idx = ((y * self.width + x) * 4) as usize;
            if idx + 4 <= self.data.len() {
                return Some([
                    self.data[idx],
                    self.data[idx + 1],
                    self.data[idx + 2],
                    self.data[idx + 3],
                ]);
            }
        }
        None
    }

    /// Encodes this RGBA image into PNG bytes without external dependencies.
    pub fn to_png(&self) -> GuiResult<Vec<u8>> {
        encode_png_rgba(self.width, self.height, &self.data)
    }

    /// Saves this RGBA image to a PNG file on disk.
    pub fn save_png(&self, path: impl AsRef<std::path::Path>) -> GuiResult<()> {
        let bytes = self.to_png()?;
        std::fs::write(path, bytes)
            .map_err(|e| GuiError::Backend(format!("e2e.screenshot: failed to save PNG: {e}")))
    }

    /// Decodes a PNG byte slice into a `CaptureImage`.
    pub fn from_png(bytes: &[u8]) -> GuiResult<Self> {
        decode_png_rgba(bytes)
    }

    /// Reads and decodes a PNG file from disk into a `CaptureImage`.
    pub fn load_png(path: impl AsRef<std::path::Path>) -> GuiResult<Self> {
        let bytes = std::fs::read(path.as_ref()).map_err(|e| {
            GuiError::Backend(format!(
                "e2e.screenshot: failed to read PNG '{}': {e}",
                path.as_ref().display()
            ))
        })?;
        Self::from_png(&bytes)
    }

    /// Compares this image with an expected baseline image using visual diff options.
    pub fn diff(&self, expected: &Self, options: &ImageDiffOptions) -> GuiResult<ImageDiffResult> {
        compare_images(self, expected, options, &[])
    }
}

const CRC_TABLE: [u32; 256] = {
    let mut table = [0u32; 256];
    let mut i = 0;
    while i < 256 {
        let mut c = i as u32;
        let mut k = 0;
        while k < 8 {
            if c & 1 != 0 {
                c = 0xEDB8_8320 ^ (c >> 1);
            } else {
                c >>= 1;
            }
            k += 1;
        }
        table[i] = c;
        i += 1;
    }
    table
};

fn crc32_update(mut crc: u32, data: &[u8]) -> u32 {
    for &byte in data {
        crc = CRC_TABLE[((crc ^ (byte as u32)) & 0xFF) as usize] ^ (crc >> 8);
    }
    crc
}

fn adler32(data: &[u8]) -> u32 {
    let mut s1 = 1u32;
    let mut s2 = 0u32;
    for &byte in data {
        s1 = (s1 + byte as u32) % 65521;
        s2 = (s2 + s1) % 65521;
    }
    (s2 << 16) | s1
}

fn write_png_chunk(out: &mut Vec<u8>, chunk_type: &[u8; 4], data: &[u8]) {
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(chunk_type);
    out.extend_from_slice(data);
    let mut crc = 0xFFFF_FFFFu32;
    crc = crc32_update(crc, chunk_type);
    crc = crc32_update(crc, data);
    out.extend_from_slice(&(!crc).to_be_bytes());
}

fn encode_png_rgba(width: u32, height: u32, rgba_data: &[u8]) -> GuiResult<Vec<u8>> {
    let expected_len = (width as usize)
        .checked_mul(height as usize)
        .and_then(|px| px.checked_mul(4))
        .ok_or_else(|| GuiError::Backend("e2e.png: dimensions overflow".to_owned()))?;
    if rgba_data.len() != expected_len {
        return Err(GuiError::Backend(format!(
            "e2e.png: pixel buffer length {} does not match dimensions {}x{} (expected {})",
            rgba_data.len(),
            width,
            height,
            expected_len
        )));
    }

    let mut out = Vec::new();
    out.extend_from_slice(&[137, 80, 78, 71, 13, 10, 26, 10]);

    // IHDR chunk
    let mut ihdr_data = Vec::with_capacity(13);
    ihdr_data.extend_from_slice(&width.to_be_bytes());
    ihdr_data.extend_from_slice(&height.to_be_bytes());
    ihdr_data.push(8); // bit depth: 8
    ihdr_data.push(6); // color type: 6 (RGBA)
    ihdr_data.push(0); // compression method: 0 (deflate)
    ihdr_data.push(0); // filter method: 0 (standard)
    ihdr_data.push(0); // interlace method: 0 (no interlace)
    write_png_chunk(&mut out, b"IHDR", &ihdr_data);

    // IDAT chunk: filtered scanlines (filter type 0 = None)
    let stride = (width as usize) * 4;
    let filtered_len = (height as usize) * (1 + stride);
    let mut filtered = Vec::with_capacity(filtered_len);
    for y in 0..(height as usize) {
        filtered.push(0); // filter: None
        let start = y * stride;
        filtered.extend_from_slice(&rgba_data[start..start + stride]);
    }

    // Deflate stream: zlib header + stored (uncompressed) blocks + adler32
    let mut zlib_stream = Vec::new();
    zlib_stream.push(0x78); // CMF: deflate, 32k window
    zlib_stream.push(0x01); // FLG: FCHECK=1 (0x7801 % 31 == 0), no dict

    let mut offset = 0;
    let total = filtered.len();
    if total == 0 {
        zlib_stream.push(0x01);
        zlib_stream.extend_from_slice(&0u16.to_le_bytes());
        zlib_stream.extend_from_slice(&0xFFFFu16.to_le_bytes());
    } else {
        while offset < total {
            let chunk_len = (total - offset).min(65535);
            let is_final = (offset + chunk_len) == total;
            zlib_stream.push(if is_final { 0x01 } else { 0x00 });
            let len_u16 = chunk_len as u16;
            let nlen_u16 = !len_u16;
            zlib_stream.extend_from_slice(&len_u16.to_le_bytes());
            zlib_stream.extend_from_slice(&nlen_u16.to_le_bytes());
            zlib_stream.extend_from_slice(&filtered[offset..offset + chunk_len]);
            offset += chunk_len;
        }
    }

    let checksum = adler32(&filtered);
    zlib_stream.extend_from_slice(&checksum.to_be_bytes());

    write_png_chunk(&mut out, b"IDAT", &zlib_stream);

    // IEND chunk
    write_png_chunk(&mut out, b"IEND", &[]);

    Ok(out)
}

/// A writable RGBA8 pixel canvas used by the Mock screenshot raster painters.
///
/// Keeping the buffer and its dimensions together removes the repeated
/// `(canvas_w, canvas_h)` pairs that pushed the painter helpers past the
/// argument-count limit.
struct RasterCanvas<'a> {
    buffer: &'a mut [u8],
    width: u32,
    height: u32,
}

impl RasterCanvas<'_> {
    /// Wraps an RGBA8 pixel buffer holding `width * height` pixels.
    fn new(buffer: &mut [u8], width: u32, height: u32) -> RasterCanvas<'_> {
        RasterCanvas {
            buffer,
            width,
            height,
        }
    }

    /// Fills the `w * h` rectangle at `(x, y)` with `color`, clamped to the canvas.
    fn draw_rect(&mut self, x: i32, y: i32, w: u32, h: u32, color: [u8; 4]) {
        let x_start = x.max(0) as u32;
        let y_start = y.max(0) as u32;
        let x_end = ((x + w as i32).max(0) as u32).min(self.width);
        let y_end = ((y + h as i32).max(0) as u32).min(self.height);

        for cy in y_start..y_end {
            for cx in x_start..x_end {
                let idx = ((cy * self.width + cx) * 4) as usize;
                self.buffer[idx..idx + 4].copy_from_slice(&color);
            }
        }
    }

    /// Outlines the `w * h` rectangle at `(x, y)` with `color`.
    fn draw_border(&mut self, x: i32, y: i32, w: u32, h: u32, color: [u8; 4]) {
        if w == 0 || h == 0 {
            return;
        }
        // Top & bottom lines
        self.draw_rect(x, y, w, 1, color);
        self.draw_rect(x, y + h as i32 - 1, w, 1, color);
        // Left & right lines
        self.draw_rect(x, y, 1, h, color);
        self.draw_rect(x + w as i32 - 1, y, 1, h, color);
    }

    /// Paints a stand-in text bar centred in the given widget rectangle.
    fn draw_text_indicator(&mut self, x: i32, y: i32, w: u32, h: u32, text: &str, color: [u8; 4]) {
        if text.is_empty() || w < 8 || h < 4 {
            return;
        }
        let text_len = text.chars().count();
        let line_len = (text_len * 6).min((w as usize).saturating_sub(8)).max(4) as u32;
        let cy = y + (h as i32) / 2;
        let cx = x + 4;
        self.draw_rect(cx, cy, line_len, 2.min(h), color);
    }

    /// Copies the `src_w * src_h` RGBA block from `src` into the canvas at `(x, y)`.
    fn blit(&mut self, x: i32, y: i32, src: &[u8], src_w: u32, src_h: u32) {
        let x_start = x.max(0) as u32;
        let y_start = y.max(0) as u32;
        let x_end = ((x + src_w as i32).max(0) as u32).min(self.width);
        let y_end = ((y + src_h as i32).max(0) as u32).min(self.height);

        for dy in y_start..y_end {
            let sy = (dy as i32 - y) as u32;
            let dst_row_start = ((dy * self.width + x_start) * 4) as usize;
            let src_row_start = ((sy * src_w + (x_start as i32 - x) as u32) * 4) as usize;
            let copy_len = ((x_end - x_start) * 4) as usize;
            if dst_row_start + copy_len <= self.buffer.len()
                && src_row_start + copy_len <= src.len()
            {
                self.buffer[dst_row_start..dst_row_start + copy_len]
                    .copy_from_slice(&src[src_row_start..src_row_start + copy_len]);
            }
        }
    }

    /// Paints a schematic stand-in for `spec` at `(x, y)` sized `w * h`.
    fn render_mock_widget_raster(&mut self, x: i32, y: i32, w: u32, h: u32, spec: &WidgetSpec) {
        let bg_color = if let Some(c) = spec.background_color {
            [c.r, c.g, c.b, 255]
        } else {
            match spec.kind {
                WidgetKind::Button => [66, 133, 244, 255],
                #[cfg(feature = "widgets-text")]
                WidgetKind::LinkLabel => [240, 244, 255, 255],
                #[cfg(feature = "widgets-text")]
                WidgetKind::TextInput | WidgetKind::TextArea => [255, 255, 255, 255],
                #[cfg(feature = "widgets-choice")]
                WidgetKind::Checkbox | WidgetKind::RadioButton => [245, 245, 245, 255],
                #[cfg(feature = "widgets-range")]
                WidgetKind::Slider | WidgetKind::ProgressBar => [52, 168, 83, 255],
                WidgetKind::Label => [235, 235, 238, 255],
                WidgetKind::Container => [240, 242, 245, 255],
                #[cfg(feature = "widgets-containers")]
                WidgetKind::GroupBox => [240, 242, 245, 255],
                #[cfg(feature = "widgets-data")]
                WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => {
                    [250, 250, 250, 255]
                }
                _ => [220, 222, 226, 255],
            }
        };

        let border_color = match spec.kind {
            WidgetKind::Button => [40, 100, 200, 255],
            #[cfg(feature = "widgets-text")]
            WidgetKind::TextInput | WidgetKind::TextArea => [180, 184, 192, 255],
            _ => [170, 175, 185, 255],
        };

        self.draw_rect(x, y, w, h, bg_color);
        self.draw_border(x, y, w, h, border_color);

        #[cfg(feature = "widgets-choice")]
        if spec.kind == WidgetKind::Checkbox {
            let box_size = 14u32.min(h.saturating_sub(4));
            let bx = x + 4;
            let by = y + ((h as i32) - box_size as i32) / 2;
            self.draw_rect(bx, by, box_size, box_size, [255, 255, 255, 255]);
            self.draw_border(bx, by, box_size, box_size, [100, 100, 100, 255]);
            if spec.checked == Some(true) {
                let inner_size = box_size.saturating_sub(4);
                self.draw_rect(bx + 2, by + 2, inner_size, inner_size, [30, 140, 30, 255]);
            }
        }

        if let Some(text) = &spec.text {
            let text_color = match spec.kind {
                WidgetKind::Button => [255, 255, 255, 255],
                #[cfg(feature = "widgets-text")]
                WidgetKind::LinkLabel => [25, 103, 210, 255],
                _ => [40, 44, 52, 255],
            };
            #[cfg(feature = "widgets-choice")]
            let is_checkbox = spec.kind == WidgetKind::Checkbox;
            #[cfg(not(feature = "widgets-choice"))]
            let is_checkbox = false;
            let text_x = if is_checkbox { x + 24 } else { x + 6 };
            self.draw_text_indicator(text_x, y, w.saturating_sub(12), h, text, text_color);
        }
    }
}

/// An owned driver for one UI and its application event handler.
///
/// Elements are session-bound, non-thread-safe handles. This first driver
/// queries each backend's action and readback capabilities independently.
pub struct Driver<B: E2eBackend, H> {
    ui: Ui<B>,
    handler: H,
    names: HashMap<String, WidgetId>,
    test_ids: HashMap<String, WidgetId>,
    session: Rc<()>,
    requested_mode: Option<InputMode>,
    exited: bool,
    action_timeout: Duration,
    active_modal: Option<WidgetId>,
}

impl<B: E2eBackend, H> Driver<B, H> {
    /// Creates a driver that owns `ui` and the application's event handler.
    pub fn new(ui: Ui<B>, handler: H) -> Self
    where
        H: FnMut(&mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        Self {
            ui,
            handler,
            names: HashMap::new(),
            test_ids: HashMap::new(),
            session: Rc::new(()),
            requested_mode: None,
            exited: false,
            action_timeout: Duration::from_millis(100),
            active_modal: None,
        }
    }

    /// Requires an exact input fidelity for subsequent actions; never downgrades.
    pub fn with_input_mode(mut self, mode: InputMode) -> Self {
        self.requested_mode = Some(mode);
        self
    }

    /// Sets the timeout for bounded action readiness auto-wait and completion.
    pub fn with_action_timeout(mut self, timeout: Duration) -> Self {
        self.action_timeout = timeout;
        self
    }

    /// Returns the current action readiness auto-wait timeout.
    pub fn action_timeout(&self) -> Duration {
        self.action_timeout
    }

    /// Designates an active modal window or dialog surface.
    pub fn set_active_modal(&mut self, modal_id: Option<WidgetId>) {
        self.active_modal = modal_id;
    }

    /// Returns the currently active modal surface, if any.
    pub fn active_modal(&self) -> Option<WidgetId> {
        self.active_modal
    }

    /// Checks if a widget is eligible to receive input under the current modal state.
    pub fn is_modal_eligible(&self, widget_id: WidgetId) -> GuiResult<bool> {
        if let Some(modal_id) = self.active_modal {
            let mut cursor = Some(widget_id);
            let mut visited = HashSet::new();
            while let Some(id) = cursor {
                if id == modal_id {
                    return Ok(true);
                }
                if !visited.insert(id) {
                    return Err(GuiError::Backend(
                        "E2E widget graph contains a parent cycle".to_owned(),
                    ));
                }
                let spec = self.ui.widget(id).ok_or(GuiError::WidgetNotFound(id.0))?;
                cursor = spec.parent;
            }
            return Ok(false);
        }
        Ok(true)
    }

    /// Queries support without performing input or changing widget state.
    pub fn capability(&self, element: &Element, operation: Operation) -> GuiResult<Capability> {
        let spec = self.validate_element(element)?;
        let backend_cap = self
            .ui
            .backend()
            .e2e_capability(element.widget_id, operation)?;
        if matches!(backend_cap, Capability::Supported { .. }) {
            return Ok(backend_cap);
        }
        self.extended_capability(element.widget_id, spec, operation)
    }

    fn extended_capability(
        &self,
        _widget_id: WidgetId,
        spec: &WidgetSpec,
        operation: Operation,
    ) -> GuiResult<Capability> {
        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let supported = match operation {
                Operation::Click => {
                    #[cfg(feature = "widgets-text")]
                    let is_link = spec.kind == WidgetKind::LinkLabel;
                    #[cfg(not(feature = "widgets-text"))]
                    let is_link = false;
                    spec.kind == WidgetKind::Button || is_link
                }
                Operation::TypeText => {
                    #[cfg(feature = "widgets-text")]
                    let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
                    #[cfg(not(feature = "widgets-text"))]
                    let is_text = false;
                    is_text
                }
                Operation::Check | Operation::Checked => {
                    #[cfg(feature = "widgets-choice")]
                    {
                        spec.kind == WidgetKind::Checkbox
                    }
                    #[cfg(not(feature = "widgets-choice"))]
                    {
                        false
                    }
                }
                Operation::Text => true,
                Operation::Press => {
                    #[cfg(feature = "widgets-text")]
                    let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
                    #[cfg(not(feature = "widgets-text"))]
                    let is_text = false;
                    is_text
                }
                Operation::Select => match spec.kind {
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextInput | WidgetKind::TextArea => true,
                    #[cfg(feature = "widgets-containers")]
                    WidgetKind::Tabs => true,
                    #[cfg(feature = "widgets-choice")]
                    WidgetKind::ComboBox | WidgetKind::MultiSelect => true,
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::ListView
                    | WidgetKind::TreeView
                    | WidgetKind::DataList
                    | WidgetKind::DataGrid => true,
                    _ => false,
                },
                Operation::SetValue => {
                    #[cfg(feature = "widgets-range")]
                    {
                        matches!(
                            spec.kind,
                            WidgetKind::Slider | WidgetKind::SpinBox | WidgetKind::ProgressBar
                        )
                    }
                    #[cfg(not(feature = "widgets-range"))]
                    {
                        false
                    }
                }
                Operation::Scroll => match spec.kind {
                    WidgetKind::Container => true,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextArea => true,
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => true,
                    _ => false,
                },
                Operation::DragTo | Operation::Screenshot => true,
                Operation::Close => spec.kind.is_window_like(),
            };
            return Ok(if supported {
                Capability::Supported {
                    mode: InputMode::Simulated,
                }
            } else {
                Capability::Unsupported {
                    reason: format!(
                        "{} is not implemented for {:?}",
                        operation.name(),
                        spec.kind
                    ),
                }
            });
        }

        if self.backend_name() == "win32" {
            let supported = match operation {
                Operation::Click => spec.kind == WidgetKind::Button,
                Operation::Text => {
                    #[cfg(feature = "widgets-text")]
                    let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
                    #[cfg(not(feature = "widgets-text"))]
                    let is_text = false;
                    #[cfg(feature = "widgets-choice")]
                    let is_checkbox = spec.kind == WidgetKind::Checkbox;
                    #[cfg(not(feature = "widgets-choice"))]
                    let is_checkbox = false;
                    matches!(
                        spec.kind,
                        WidgetKind::Button | WidgetKind::Label | WidgetKind::Window
                    ) || is_checkbox
                        || is_text
                }
                Operation::Check | Operation::Checked => {
                    #[cfg(feature = "widgets-choice")]
                    {
                        spec.kind == WidgetKind::Checkbox
                    }
                    #[cfg(not(feature = "widgets-choice"))]
                    {
                        false
                    }
                }
                Operation::TypeText => {
                    #[cfg(feature = "widgets-text")]
                    let is_text = matches!(spec.kind, WidgetKind::TextInput | WidgetKind::TextArea);
                    #[cfg(not(feature = "widgets-text"))]
                    let is_text = false;
                    is_text
                }
                Operation::Close => spec.kind == WidgetKind::Window,
                Operation::SetValue => {
                    #[cfg(feature = "widgets-range")]
                    {
                        matches!(spec.kind, WidgetKind::Slider | WidgetKind::SpinBox)
                    }
                    #[cfg(not(feature = "widgets-range"))]
                    {
                        false
                    }
                }
                _ => false,
            };
            return Ok(if supported {
                Capability::Supported {
                    mode: InputMode::SemanticNative,
                }
            } else {
                Capability::Unsupported {
                    reason: format!(
                        "{} has no Win32 E2E mapping for {:?}",
                        operation.name(),
                        spec.kind
                    ),
                }
            });
        }

        if self.backend_name() == "gtk" {
            let supported = match operation {
                Operation::Close => spec.kind == WidgetKind::Window,
                _ => false,
            };
            if supported {
                return Ok(Capability::Supported {
                    mode: InputMode::SemanticNative,
                });
            }
        }

        Ok(Capability::Unsupported {
            reason: format!(
                "{} has no E2E mapping for {:?}",
                operation.name(),
                spec.kind
            ),
        })
    }

    fn require_operation(&self, element: &Element, operation: Operation) -> GuiResult<()> {
        self.ensure_running()?;
        match self.capability(element, operation)? {
            Capability::Supported { mode }
                if self
                    .requested_mode
                    .is_none_or(|requested| requested == mode) =>
            {
                Ok(())
            }
            _ => Err(GuiError::UnsupportedWidget(operation.name())),
        }
    }

    fn ensure_running(&self) -> GuiResult<()> {
        if self.exited {
            Err(GuiError::Backend(
                "e2e.session: application handler exited".into(),
            ))
        } else {
            Ok(())
        }
    }

    /// Returns the owned UI for read-only inspection between driver steps.
    pub fn ui(&self) -> &Ui<B> {
        &self.ui
    }

    /// Returns the owned UI for application setup between driver steps.
    ///
    /// Removing a widget through this reference invalidates its existing
    /// elements. Locator bindings to removed widgets do not match.
    pub fn ui_mut(&mut self) -> &mut Ui<B> {
        &mut self.ui
    }

    /// Binds an explicit automation name to a live widget.
    pub fn bind_name(&mut self, widget_id: WidgetId, name: impl Into<String>) -> GuiResult<()> {
        self.bind(widget_id, name.into(), false)
    }

    /// Binds an explicit test identifier to a live widget.
    pub fn bind_test_id(
        &mut self,
        widget_id: WidgetId,
        test_id: impl Into<String>,
    ) -> GuiResult<()> {
        self.bind(widget_id, test_id.into(), true)
    }

    /// Returns every matching element in ascending `WidgetId` order.
    pub fn find_all(&self, locator: &Locator) -> GuiResult<Vec<Element>> {
        let mut matches = Vec::new();
        for spec in self.ui.e2e_widget_specs() {
            if self.matches_locator(spec.id, locator)? {
                matches.push(spec.id);
            }
        }
        matches.sort_by_key(|id| id.0);
        Ok(matches
            .into_iter()
            .map(|widget_id| self.element(widget_id))
            .collect())
    }

    /// Returns no element for zero matches and errors when the locator is ambiguous.
    pub fn find(&self, locator: &Locator) -> GuiResult<Option<Element>> {
        let mut matches = self.find_all(locator)?;
        match matches.len() {
            0 => Ok(None),
            1 => Ok(matches.pop()),
            count => Err(GuiError::Backend(format!(
                "E2E locator matched {count} widgets; expected at most one"
            ))),
        }
    }

    /// Requires exactly one match.
    pub fn expect_one(&self, locator: &Locator) -> GuiResult<Element> {
        self.find(locator)?.ok_or_else(|| {
            GuiError::Backend("E2E locator matched no widgets; expected exactly one".to_owned())
        })
    }

    /// Waits for exactly one match, failing immediately if the locator is ambiguous.
    pub fn wait_for(&mut self, locator: &Locator, options: WaitOptions) -> GuiResult<Element>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        self.ensure_running()?;
        let deadline = self.deadline(options)?;
        loop {
            if let Some(element) = self.find(locator)? {
                return Ok(element);
            }
            if Instant::now() >= deadline {
                return Err(GuiError::Backend(
                    "e2e.timeout: locator wait timed out".to_owned(),
                ));
            }
            self.pump()?;
            self.ensure_running()?;
            self.pause_until(deadline, options)?;
        }
    }

    /// Rechecks a predicate until it succeeds or its finite deadline expires.
    pub fn wait_until<F>(&mut self, options: WaitOptions, mut predicate: F) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
        F: FnMut(&mut Self) -> GuiResult<bool>,
    {
        self.ensure_running()?;
        let deadline = self.deadline(options)?;
        loop {
            if predicate(self)? {
                return Ok(());
            }
            if Instant::now() >= deadline {
                return Err(GuiError::Backend(
                    "e2e.timeout: predicate wait timed out".to_owned(),
                ));
            }
            self.pump()?;
            self.ensure_running()?;
            self.pause_until(deadline, options)?;
        }
    }

    /// Captures an in-memory RGBA8 screenshot for the given target surface.
    ///
    /// For headless testing ([`MockBackend`]), renders deterministic synthetic
    /// widget and window layouts via the Mock renderer.
    ///
    /// For native backends (`gtk`, `win32`, `cocoa`), delegates directly to the
    /// shared [`Backend::capture_window_rgba`] and [`Backend::capture_widget_rgba`]
    /// trait methods. Window captures include frame decorations where
    /// appropriate (e.g. on Win32, or for Viewport targets), matching live window
    /// borders and titlebars.
    pub fn screenshot(&mut self, target: CaptureTarget) -> GuiResult<CaptureImage> {
        self.ensure_running()?;
        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            return self.mock_screenshot(target);
        }

        let bname = self.backend_name();
        if bname == "gtk" || bname == "win32" || bname == "cocoa" {
            let (w, h, data) = match target {
                CaptureTarget::Window(wid) => {
                    let include_decorations = bname == "win32";
                    self.ui
                        .backend()
                        .capture_window_rgba(wid, include_decorations)?
                }
                CaptureTarget::Element(loc) => {
                    let elem = self.expect_one(&loc)?;
                    self.ui.backend().capture_widget_rgba(elem.widget_id)?
                }
                CaptureTarget::Viewport => {
                    let window_id = self
                        .ui
                        .e2e_widget_specs()
                        .find(|s| s.kind == WidgetKind::Window && self.ui.is_visible(s.id))
                        .map(|s| s.id)
                        .ok_or_else(|| {
                            GuiError::Backend(format!(
                                "{bname} capture: no active window for Viewport target"
                            ))
                        })?;
                    self.ui.backend().capture_window_rgba(window_id, true)?
                }
                CaptureTarget::Prompt(_) => {
                    return Err(GuiError::UnsupportedCapability(format!(
                        "e2e.screenshot.prompt: {bname} system prompts cannot be captured"
                    )));
                }
            };
            return Ok(CaptureImage::new(w, h, data));
        }

        Err(GuiError::UnsupportedCapability("e2e.screenshot".to_owned()))
    }

    fn mock_screenshot(&mut self, target: CaptureTarget) -> GuiResult<CaptureImage> {
        match target {
            CaptureTarget::Prompt(token) => self.mock_prompt_screenshot(token),
            CaptureTarget::Element(locator) => {
                let element = self.expect_one(&locator)?;
                let spec = self
                    .ui
                    .widget(element.widget_id)
                    .ok_or(GuiError::WidgetNotFound(element.widget_id.0))?
                    .clone();
                if !self.ui.is_visible(element.widget_id) {
                    return Err(GuiError::Backend(format!(
                        "e2e.screenshot: widget {} is not visible",
                        element.widget_id.0
                    )));
                }
                let (w, h) = Self::mock_widget_dimensions(&spec);
                let mut buffer = vec![0u8; (w * h * 4) as usize];
                let mut canvas = RasterCanvas::new(&mut buffer, w, h);
                canvas.render_mock_widget_raster(0, 0, w, h, &spec);
                let children: Vec<WidgetSpec> = self
                    .ui
                    .e2e_widget_specs()
                    .filter(|s| s.parent == Some(element.widget_id) && self.ui.is_visible(s.id))
                    .cloned()
                    .collect();
                for (idx, child_spec) in children.iter().enumerate() {
                    let (cw, ch) = Self::mock_widget_dimensions(child_spec);
                    let (cx, cy) = child_spec.position.unwrap_or((10, 10 + (idx as i32) * 36));
                    canvas.render_mock_widget_raster(cx, cy, cw, ch, child_spec);
                }
                Ok(CaptureImage::new(w, h, buffer))
            }
            CaptureTarget::Window(window_id) => {
                let win_spec = self
                    .ui
                    .widget(window_id)
                    .ok_or(GuiError::WidgetNotFound(window_id.0))?
                    .clone();
                if !win_spec.kind.is_window_like() {
                    return Err(GuiError::UnsupportedWidget("e2e.screenshot.window"));
                }
                if !self.ui.is_visible(window_id) {
                    return Err(GuiError::Backend(format!(
                        "e2e.screenshot: window {} is not visible",
                        window_id.0
                    )));
                }
                let (win_w, win_h) = Self::mock_widget_dimensions(&win_spec);
                let mut buffer = vec![0u8; (win_w * win_h * 4) as usize];

                let bg_color = win_spec
                    .background_color
                    .map(|c| [c.r, c.g, c.b, 255])
                    .unwrap_or([245, 245, 247, 255]);
                let mut canvas = RasterCanvas::new(&mut buffer, win_w, win_h);
                canvas.draw_rect(0, 0, win_w, win_h, bg_color);

                if win_h >= 28 {
                    canvas.draw_rect(0, 0, win_w, 28, [225, 227, 232, 255]);
                    canvas.draw_border(0, 0, win_w, 28, [200, 202, 208, 255]);
                    if let Some(title) = &win_spec.text {
                        canvas.draw_text_indicator(
                            12,
                            4,
                            win_w.saturating_sub(24),
                            20,
                            title,
                            [50, 50, 50, 255],
                        );
                    }
                }
                canvas.draw_border(0, 0, win_w, win_h, [160, 164, 172, 255]);

                let descendants = self.collect_visible_descendants(window_id)?;
                for (idx, child_spec) in descendants.iter().enumerate() {
                    let (cw, ch) = Self::mock_widget_dimensions(child_spec);
                    let (rel_x, rel_y) = self
                        .relative_position(child_spec.id, window_id)?
                        .unwrap_or((16, 36 + (idx as i32) * 40));
                    canvas.render_mock_widget_raster(rel_x, rel_y, cw, ch, child_spec);
                }

                Ok(CaptureImage::new(win_w, win_h, buffer))
            }
            CaptureTarget::Viewport => {
                let visible_windows: Vec<WidgetSpec> = self
                    .ui
                    .e2e_widget_specs()
                    .filter(|s| s.kind.is_window_like() && self.ui.is_visible(s.id))
                    .cloned()
                    .collect();

                let mut vp_w = 800u32;
                let mut vp_h = 600u32;
                for win in &visible_windows {
                    let (ww, wh) = Self::mock_widget_dimensions(win);
                    let (wx, wy) = win.position.unwrap_or((0, 0));
                    let right = (wx.max(0) as u32) + ww;
                    let bottom = (wy.max(0) as u32) + wh;
                    vp_w = vp_w.max(right);
                    vp_h = vp_h.max(bottom);
                }

                let mut buffer = vec![0u8; (vp_w * vp_h * 4) as usize];
                let mut canvas = RasterCanvas::new(&mut buffer, vp_w, vp_h);
                canvas.draw_rect(0, 0, vp_w, vp_h, [38, 42, 51, 255]);

                for win in &visible_windows {
                    let (wx, wy) = win.position.unwrap_or((10, 10));
                    let win_capture = self.mock_screenshot(CaptureTarget::Window(win.id))?;
                    canvas.blit(
                        wx,
                        wy,
                        &win_capture.data,
                        win_capture.width,
                        win_capture.height,
                    );
                }

                Ok(CaptureImage::new(vp_w, vp_h, buffer))
            }
        }
    }

    /// Renders a pending Mock confirm or file-dialog request as a dialog card.
    fn mock_prompt_screenshot(&self, token: u64) -> GuiResult<CaptureImage> {
        let any_backend: &dyn std::any::Any = self.ui.backend();
        let mock = any_backend
            .downcast_ref::<MockBackend>()
            .ok_or_else(|| GuiError::UnsupportedCapability("e2e.screenshot.prompt".to_owned()))?;
        let (title, lines, buttons): (String, Vec<String>, [&str; 2]) =
            if let Some((_, title, message)) = mock
                .confirm_requests
                .iter()
                .find(|(pending, _, _)| *pending == token)
            {
                (
                    title.clone(),
                    message.lines().map(str::to_owned).collect(),
                    ["Cancel", "OK"],
                )
            } else if let Some((_, request)) = mock
                .file_dialog_requests
                .iter()
                .find(|(pending, _)| *pending == token)
            {
                let mut lines = vec![format!("{:?}", request.mode)];
                if let Some(folder) = &request.folder {
                    lines.push(folder.display().to_string());
                }
                if let Some(name) = &request.suggested_name {
                    lines.push(name.clone());
                }
                for filter in &request.filters {
                    lines.push(format!("{} ({})", filter.name, filter.patterns.join(", ")));
                }
                (
                    request.title.clone().unwrap_or_else(|| "File".to_owned()),
                    lines,
                    ["Cancel", "Open"],
                )
            } else {
                return Err(GuiError::Backend(format!(
                    "e2e.screenshot: no pending prompt with token {token}"
                )));
            };

        let (w, h) = (420u32, 240u32);
        let mut buffer = vec![0u8; (w * h * 4) as usize];
        let mut canvas = RasterCanvas::new(&mut buffer, w, h);
        canvas.draw_rect(0, 0, w, h, [250, 250, 252, 255]);
        canvas.draw_rect(0, 0, w, 28, [225, 227, 232, 255]);
        canvas.draw_border(0, 0, w, 28, [200, 202, 208, 255]);
        canvas.draw_text_indicator(12, 4, w - 24, 20, &title, [50, 50, 50, 255]);
        for (idx, line) in lines.iter().take(6).enumerate() {
            canvas.draw_text_indicator(
                16,
                40 + idx as i32 * 22,
                w - 32,
                20,
                line,
                [70, 70, 70, 255],
            );
        }
        for (idx, label) in buttons.iter().enumerate() {
            let x = w as i32 - 232 + idx as i32 * 112;
            canvas.draw_rect(x, h as i32 - 48, 100, 32, [232, 234, 238, 255]);
            canvas.draw_border(x, h as i32 - 48, 100, 32, [160, 164, 172, 255]);
            canvas.draw_text_indicator(x, h as i32 - 48, 100, 32, label, [40, 40, 40, 255]);
        }
        canvas.draw_border(0, 0, w, h, [160, 164, 172, 255]);
        Ok(CaptureImage::new(w, h, buffer))
    }

    fn mock_widget_dimensions(spec: &WidgetSpec) -> (u32, u32) {
        if let Some((w, h)) = spec.size {
            if w > 0 && h > 0 {
                return (w as u32, h as u32);
            }
        }
        match spec.kind {
            WidgetKind::Window => (800, 600),
            #[cfg(feature = "widgets-containers")]
            WidgetKind::AlertDialog => (420, 240),
            #[cfg(feature = "widgets-pickers")]
            WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
                (420, 240)
            }
            WidgetKind::Container => (320, 200),
            #[cfg(feature = "widgets-containers")]
            WidgetKind::GroupBox | WidgetKind::SplitPane | WidgetKind::Tabs => (320, 200),
            WidgetKind::Button => (100, 32),
            #[cfg(feature = "widgets-text")]
            WidgetKind::LinkLabel => (100, 32),
            #[cfg(feature = "widgets-text")]
            WidgetKind::TextInput => (160, 28),
            #[cfg(feature = "widgets-text")]
            WidgetKind::TextArea => (240, 120),
            #[cfg(feature = "widgets-choice")]
            WidgetKind::Checkbox | WidgetKind::RadioButton => (120, 24),
            #[cfg(feature = "widgets-range")]
            WidgetKind::Slider | WidgetKind::ProgressBar => (160, 24),
            #[cfg(feature = "widgets-range")]
            WidgetKind::SpinBox => (80, 24),
            #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
            WidgetKind::ComboBox | WidgetKind::DataList | WidgetKind::MultiSelect => (140, 28),
            #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
            WidgetKind::ComboBox | WidgetKind::MultiSelect => (140, 28),
            #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
            WidgetKind::DataList => (140, 28),
            WidgetKind::Label => (100, 20),
            #[cfg(feature = "widgets-data")]
            WidgetKind::ListView | WidgetKind::TreeView | WidgetKind::DataGrid => (220, 160),
            #[cfg(feature = "widgets-canvas")]
            WidgetKind::Canvas | WidgetKind::VulkanCanvas => (300, 200),
            _ => (100, 30),
        }
    }

    fn collect_visible_descendants(&self, root_id: WidgetId) -> GuiResult<Vec<WidgetSpec>> {
        let mut result = Vec::new();
        let all = self.ui.e2e_widget_specs();
        for spec in all {
            if spec.id == root_id || !self.ui.is_visible(spec.id) {
                continue;
            }
            let mut cursor = spec.parent;
            let mut visited = HashSet::new();
            while let Some(parent_id) = cursor {
                if parent_id == root_id {
                    result.push(spec.clone());
                    break;
                }
                if !visited.insert(parent_id) {
                    break;
                }
                cursor = self.ui.widget(parent_id).and_then(|p| p.parent);
            }
        }
        result.sort_by_key(|s| s.id.0);
        Ok(result)
    }

    fn relative_position(
        &self,
        widget_id: WidgetId,
        root_id: WidgetId,
    ) -> GuiResult<Option<(i32, i32)>> {
        let mut total_x = 0;
        let mut total_y = 0;
        let mut cursor = Some(widget_id);
        let mut visited = HashSet::new();
        let mut has_pos = false;

        while let Some(id) = cursor {
            if id == root_id {
                return Ok(if has_pos {
                    Some((total_x, total_y))
                } else {
                    None
                });
            }
            if !visited.insert(id) {
                return Ok(None);
            }
            if let Some(spec) = self.ui.widget(id) {
                if let Some((x, y)) = spec.position {
                    total_x += x;
                    total_y += y;
                    has_pos = true;
                }
                cursor = spec.parent;
            } else {
                return Ok(None);
            }
        }
        Ok(None)
    }

    fn bind(&mut self, widget_id: WidgetId, value: String, test_id: bool) -> GuiResult<()> {
        if value.is_empty() {
            return Err(GuiError::Backend(
                "E2E names and test ids must not be empty".to_owned(),
            ));
        }
        if self.ui.widget(widget_id).is_none() {
            return Err(GuiError::WidgetNotFound(widget_id.0));
        }
        let registry = if test_id {
            &mut self.test_ids
        } else {
            &mut self.names
        };
        registry.retain(|_, existing_id| self.ui.widget(*existing_id).is_some());
        if registry
            .get(&value)
            .is_some_and(|existing_id| *existing_id != widget_id)
        {
            return Err(GuiError::Backend(format!(
                "E2E binding {value:?} is already registered"
            )));
        }
        registry.insert(value, widget_id);
        Ok(())
    }

    fn element(&self, widget_id: WidgetId) -> Element {
        Element {
            widget_id,
            session: Rc::downgrade(&self.session),
            _thread_affine: PhantomData,
        }
    }

    fn validate_element(&self, element: &Element) -> GuiResult<&WidgetSpec> {
        if !Weak::ptr_eq(&element.session, &Rc::downgrade(&self.session)) {
            return Err(GuiError::Backend(
                "E2E element belongs to a different or expired driver session".to_owned(),
            ));
        }
        self.ui
            .widget(element.widget_id)
            .ok_or(GuiError::WidgetNotFound(element.widget_id.0))
    }

    fn matches_locator(&self, widget_id: WidgetId, locator: &Locator) -> GuiResult<bool> {
        let Some(spec) = self.ui.widget(widget_id) else {
            return Ok(false);
        };
        for selector in &locator.selectors {
            let matches = match selector {
                Selector::Id(id) => *id == widget_id,
                Selector::Name(name) => self.names.get(name) == Some(&widget_id),
                Selector::TestId(test_id) => self.test_ids.get(test_id) == Some(&widget_id),
                Selector::Role(role, label) => {
                    spec.accessibility.role == *role
                        && spec
                            .accessibility
                            .name
                            .as_deref()
                            .or(spec.text.as_deref())
                            .unwrap_or_default()
                            == label
                }
                Selector::Kind(kind) => spec.kind == *kind,
                Selector::Text(text) => spec.text.as_deref().unwrap_or_default() == text,
                Selector::Dialog => {
                    is_dialog(spec.kind)
                        || spec.accessibility.role == AccessibleRole::Dialog
                        || spec.accessibility.role == AccessibleRole::Alert
                }
                Selector::TopLevel => is_window_or_dialog(spec.kind),
            };
            if !matches {
                return Ok(false);
            }
        }

        for relation in &locator.relations {
            match relation {
                Relation::ChildOf(parent_locator) => {
                    let Some(parent_id) = spec.parent else {
                        return Ok(false);
                    };
                    self.require_live_parent(parent_id)?;
                    if !self.matches_locator(parent_id, parent_locator)? {
                        return Ok(false);
                    }
                }
                Relation::DescendantOf(ancestor_locator) => {
                    if !self.has_matching_ancestor(widget_id, ancestor_locator, false)? {
                        return Ok(false);
                    }
                }
                Relation::InWindow(window_locator) => {
                    if !self.has_matching_ancestor(widget_id, window_locator, true)? {
                        return Ok(false);
                    }
                }
            }
        }
        Ok(true)
    }

    fn has_matching_ancestor(
        &self,
        widget_id: WidgetId,
        locator: &Locator,
        include_self: bool,
    ) -> GuiResult<bool> {
        let mut cursor = if include_self {
            Some(widget_id)
        } else {
            self.ui.widget(widget_id).and_then(|spec| spec.parent)
        };
        let mut visited = HashSet::new();
        while let Some(ancestor_id) = cursor {
            if !visited.insert(ancestor_id) {
                return Err(GuiError::Backend(
                    "E2E widget graph contains a parent cycle".to_owned(),
                ));
            }
            let ancestor = self.require_live_parent(ancestor_id)?;
            if include_self && is_window_or_dialog(ancestor.kind) {
                if self.matches_locator(ancestor_id, locator)? {
                    return Ok(true);
                }
            } else if !include_self && self.matches_locator(ancestor_id, locator)? {
                return Ok(true);
            }
            cursor = ancestor.parent;
        }
        Ok(false)
    }

    fn require_live_parent(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
        self.ui.widget(widget_id).ok_or_else(|| {
            GuiError::Backend(format!(
                "E2E widget graph references missing parent {}",
                widget_id.0
            ))
        })
    }

    fn deadline(&self, options: WaitOptions) -> GuiResult<Instant> {
        if options.poll_interval.is_zero() {
            return Err(GuiError::Backend(
                "E2E poll interval must be greater than zero".to_owned(),
            ));
        }
        Instant::now()
            .checked_add(options.timeout)
            .ok_or_else(|| GuiError::Backend("E2E wait deadline overflow".to_owned()))
    }

    fn pause_until(&self, deadline: Instant, options: WaitOptions) -> GuiResult<()> {
        let remaining = deadline.saturating_duration_since(Instant::now());
        let slice = options
            .poll_interval
            .min(Duration::from_millis(25))
            .min(remaining);
        if !slice.is_zero() {
            std::thread::sleep(slice);
        }
        Ok(())
    }

    /// Delivers queued backend events to the handler without performing an
    /// action, returning how many were dispatched.
    ///
    /// Scenarios that feed recorded events into an app model call this after
    /// the app queues follow-up events of its own (for example `Ui::activate`).
    pub fn pump(&mut self) -> GuiResult<usize>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        self.ensure_running()?;
        let start = Instant::now();
        let mut dispatched = 0;
        while dispatched < 64 && start.elapsed() < Duration::from_millis(5) {
            let Some(flow) = self.ui.e2e_dispatch_one(&mut self.handler)? else {
                break;
            };
            dispatched += 1;
            if flow == LoopFlow::Exit {
                self.exited = true;
                break;
            }
        }
        Ok(dispatched)
    }

    fn is_enabled(&self, element: &Element) -> GuiResult<bool> {
        let mut cursor = Some(element.widget_id);
        let mut visited = HashSet::new();
        while let Some(id) = cursor {
            if !visited.insert(id) {
                return Err(GuiError::Backend(
                    "E2E widget graph contains a parent cycle".to_owned(),
                ));
            }
            let spec = self.ui.widget(id).ok_or(GuiError::WidgetNotFound(id.0))?;
            if spec.enabled == Some(false) {
                return Ok(false);
            }
            cursor = spec.parent;
        }
        Ok(true)
    }

    fn is_visible(&self, element: &Element) -> GuiResult<bool> {
        let mut cursor = Some(element.widget_id);
        let mut visited = HashSet::new();
        while let Some(id) = cursor {
            if !visited.insert(id) {
                return Err(GuiError::Backend(
                    "E2E widget graph contains a parent cycle".to_owned(),
                ));
            }
            if !self.ui.is_visible(id) {
                return Ok(false);
            }
            cursor = self.ui.widget(id).and_then(|spec| spec.parent);
        }
        Ok(true)
    }

    fn value(&self, element: &Element) -> GuiResult<i32> {
        let spec = self.validate_element(element)?;
        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_backend: &dyn std::any::Any = self.ui.backend();
            if let Some(mock) = any_backend.downcast_ref::<MockBackend>() {
                return mock.e2e_mock_value(element.widget_id);
            }
        }
        spec.value.ok_or_else(|| {
            GuiError::Backend(format!(
                "E2E widget {} has no numeric value",
                element.widget_id.0
            ))
        })
    }

    /// Returns every top-level window in the UI.
    pub fn windows(&self) -> GuiResult<Vec<Element>> {
        self.find_all(&Locator::kind(WidgetKind::Window))
    }

    /// Returns every dialog surface (alerts, file pickers, color/font dialogs, custom modal windows).
    pub fn dialogs(&self) -> GuiResult<Vec<DialogHandle>> {
        let mut result = Vec::new();
        for spec in self.ui.e2e_widget_specs() {
            if is_dialog(spec.kind)
                || (spec.kind == WidgetKind::Window
                    && (spec.accessibility.role == AccessibleRole::Dialog
                        || spec.accessibility.role == AccessibleRole::Alert
                        || self.active_modal == Some(spec.id)))
            {
                result.push(DialogHandle::new(spec.id, spec.kind));
            }
        }

        // Include any pending confirm dialog requests on MockBackend
        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_backend: &dyn std::any::Any = self.ui.backend();
            if let Some(mock) = any_backend.downcast_ref::<MockBackend>() {
                for (token, _title, _msg) in &mock.confirm_requests {
                    let fake_id = self.active_modal.unwrap_or(WidgetId(999_000 + *token));
                    result.push(DialogHandle::for_token(fake_id, *token));
                }
            }
        }

        Ok(result)
    }

    /// Finds a dialog matching the given locator.
    pub fn find_dialog(&self, locator: &Locator) -> GuiResult<Option<DialogHandle>> {
        let matching = self.find(locator)?;
        if let Some(elem) = matching {
            let spec = self
                .ui
                .widget(elem.id())
                .ok_or(GuiError::WidgetNotFound(elem.id().0))?;
            if is_window_or_dialog(spec.kind) {
                return Ok(Some(DialogHandle::new(elem.id(), spec.kind)));
            }
        }
        Ok(None)
    }

    /// Requires exactly one dialog matching `locator`.
    pub fn expect_dialog(&self, locator: &Locator) -> GuiResult<DialogHandle> {
        let elem = self.expect_one(locator)?;
        let spec = self
            .ui
            .widget(elem.id())
            .ok_or(GuiError::WidgetNotFound(elem.id().0))?;
        if is_window_or_dialog(spec.kind) {
            Ok(DialogHandle::new(elem.id(), spec.kind))
        } else {
            Err(GuiError::Backend(format!(
                "e2e.dialog: widget {} is not a window or dialog (kind {:?})",
                elem.id().0,
                spec.kind
            )))
        }
    }

    /// Finds an element scoped within a specific window or dialog surface.
    pub fn find_in_window(
        &self,
        window_id: WidgetId,
        locator: &Locator,
    ) -> GuiResult<Option<Element>> {
        self.find(&locator.clone().in_window(Locator::id(window_id)))
    }

    /// Finds all elements scoped within a specific window or dialog surface.
    pub fn find_all_in_window(
        &self,
        window_id: WidgetId,
        locator: &Locator,
    ) -> GuiResult<Vec<Element>> {
        self.find_all(&locator.clone().in_window(Locator::id(window_id)))
    }

    /// Requires exactly one element scoped within a specific window or dialog surface.
    pub fn expect_one_in_window(
        &self,
        window_id: WidgetId,
        locator: &Locator,
    ) -> GuiResult<Element> {
        self.expect_one(&locator.clone().in_window(Locator::id(window_id)))
    }

    /// Returns recorded confirm dialog requests `(token, title, message)` if running on MockBackend.
    pub fn pending_confirm_requests(&self) -> Vec<(u64, String, String)> {
        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_backend: &dyn std::any::Any = self.ui.backend();
            if let Some(mock) = any_backend.downcast_ref::<MockBackend>() {
                return mock.confirm_requests.clone();
            }
        }
        Vec::new()
    }

    /// Returns the stable backend identifier string used for per-backend baseline directory paths.
    pub fn backend_name(&self) -> &'static str {
        self.ui.backend().backend_name()
    }

    /// Compares a screenshot with an expected baseline image and options, without erroring on mismatch.
    pub fn compare_screenshot(
        &mut self,
        target: CaptureTarget,
        expected: &CaptureImage,
        options: &ImageDiffOptions,
    ) -> GuiResult<ImageDiffResult> {
        let actual = self.screenshot(target.clone())?;
        let mask_rects = self.resolve_mask_rects(&target, options)?;
        compare_images(&actual, expected, options, &mask_rects)
    }

    fn resolve_mask_rects(
        &self,
        target: &CaptureTarget,
        options: &ImageDiffOptions,
    ) -> GuiResult<Vec<Rect>> {
        let mut resolved = Vec::new();
        for mask in &options.masks {
            match mask {
                MaskRegion::Rect(rect) => resolved.push(*rect),
                MaskRegion::Element(locator) => {
                    if let Ok(Some(elem)) = self.find(locator) {
                        if let Some(spec) = self.ui.widget(elem.widget_id) {
                            let (cw, ch) = Self::mock_widget_dimensions(spec);
                            let pos = match target {
                                CaptureTarget::Window(win_id) => self
                                    .relative_position(elem.widget_id, *win_id)?
                                    .unwrap_or((0, 0)),
                                CaptureTarget::Element(_) => (0, 0),
                                CaptureTarget::Viewport => spec.position.unwrap_or((0, 0)),
                                CaptureTarget::Prompt(_) => continue,
                            };
                            let rx = pos.0.max(0) as u32;
                            let ry = pos.1.max(0) as u32;
                            resolved.push(Rect::new(rx, ry, cw, ch));
                        }
                    }
                }
            }
        }
        Ok(resolved)
    }
}

impl<B: E2eBackend, H> Driver<B, H>
where
    H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
{
    fn complete_action(&mut self, started: Instant) -> GuiResult<()> {
        let drain_timeout = self.action_timeout.max(Duration::from_secs(5));
        loop {
            if started.elapsed() >= drain_timeout {
                return Err(GuiError::Backend(
                    "e2e.timeout: action dispatch did not finish; input will not be replayed"
                        .into(),
                ));
            }
            if self.pump()? == 0 || self.exited {
                return Ok(());
            }
        }
    }

    fn check_readiness(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
        let mut cursor = Some(widget_id);
        let mut visited = HashSet::new();
        let mut target = None;
        while let Some(id) = cursor {
            if !visited.insert(id) {
                return Err(GuiError::Backend(
                    "E2E widget graph contains a parent cycle".to_owned(),
                ));
            }
            let spec = self.ui.widget(id).ok_or(GuiError::WidgetNotFound(id.0))?;
            if !self.ui.is_visible(id) || spec.enabled == Some(false) {
                return Err(GuiError::Backend(format!(
                    "E2E widget {} is hidden or disabled",
                    id.0
                )));
            }
            if id == widget_id {
                target = Some(spec);
            }
            cursor = spec.parent;
        }

        if !self.is_modal_eligible(widget_id)? {
            let modal_desc = self.active_modal.map(|m| m.0).unwrap_or(0);
            return Err(GuiError::Backend(format!(
                "e2e.readiness: widget {} is blocked by active modal {}",
                widget_id.0, modal_desc
            )));
        }

        target.ok_or(GuiError::WidgetNotFound(widget_id.0))
    }

    #[allow(dead_code)]
    fn ensure_actionable(&self, widget_id: WidgetId) -> GuiResult<&WidgetSpec> {
        self.check_readiness(widget_id)
    }

    fn wait_for_readiness(&mut self, widget_id: WidgetId, started: Instant) -> GuiResult<()> {
        let deadline = started + self.action_timeout;
        let poll_interval = Duration::from_millis(10);
        loop {
            match self.check_readiness(widget_id) {
                Ok(_) => return Ok(()),
                Err(err) => {
                    if matches!(err, GuiError::WidgetNotFound(_)) {
                        return Err(err);
                    }
                    if Instant::now() >= deadline {
                        return Err(GuiError::Backend(format!(
                            "e2e.timeout: readiness auto-wait timed out: {err}"
                        )));
                    }
                }
            }
            self.pump()?;
            self.ensure_running()?;
            let remaining = deadline.saturating_duration_since(Instant::now());
            let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
            if !slice.is_zero() {
                std::thread::sleep(slice);
            }
        }
    }

    fn click(&mut self, element: &Element) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Click)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let deadline = started + self.action_timeout;
        let poll_interval = Duration::from_millis(10);
        loop {
            match self.ui.backend_mut().e2e_click(element.widget_id) {
                Ok(()) => break,
                Err(GuiError::Backend(msg)) if msg.starts_with("e2e.readiness:") => {
                    if Instant::now() >= deadline {
                        return Err(GuiError::Backend(format!(
                            "e2e.timeout: readiness auto-wait timed out: {msg}"
                        )));
                    }
                    self.pump()?;
                    self.ensure_running()?;
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
                    if !slice.is_zero() {
                        std::thread::sleep(slice);
                    }
                }
                Err(err) => return Err(err),
            }
        }
        self.complete_action(started)
    }

    fn type_text(&mut self, element: &Element, text: &str) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::TypeText)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let deadline = started + self.action_timeout;
        let poll_interval = Duration::from_millis(10);
        loop {
            let res = self.ui.backend_mut().e2e_type_text(element.widget_id, text);
            match res {
                Ok(()) => break,
                Err(GuiError::Backend(msg)) if msg.starts_with("e2e.readiness:") => {
                    if Instant::now() >= deadline {
                        return Err(GuiError::Backend(format!(
                            "e2e.timeout: readiness auto-wait timed out: {msg}"
                        )));
                    }
                    self.pump()?;
                    self.ensure_running()?;
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
                    if !slice.is_zero() {
                        std::thread::sleep(slice);
                    }
                }
                Err(GuiError::UnsupportedWidget(_)) => {
                    let is_mock =
                        std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
                    if is_mock {
                        let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
                        if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                            mock.e2e_mock_type_text(element.widget_id, text)?;
                            break;
                        }
                    }
                    if self
                        .ui
                        .backend_mut()
                        .native_type_text(element.widget_id, text)?
                    {
                        break;
                    }
                    return Err(GuiError::UnsupportedWidget("e2e.type_text"));
                }
                Err(err) => return Err(err),
            }
        }
        self.complete_action(started)
    }

    fn check(&mut self, element: &Element, checked: bool) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Check)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let deadline = started + self.action_timeout;
        let poll_interval = Duration::from_millis(10);
        loop {
            let res = self.ui.backend_mut().e2e_check(element.widget_id, checked);
            match res {
                Ok(()) => break,
                Err(GuiError::Backend(msg)) if msg.starts_with("e2e.readiness:") => {
                    if Instant::now() >= deadline {
                        return Err(GuiError::Backend(format!(
                            "e2e.timeout: readiness auto-wait timed out: {msg}"
                        )));
                    }
                    self.pump()?;
                    self.ensure_running()?;
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    let slice = poll_interval.min(Duration::from_millis(25)).min(remaining);
                    if !slice.is_zero() {
                        std::thread::sleep(slice);
                    }
                }
                Err(GuiError::UnsupportedWidget(_)) => {
                    let is_mock =
                        std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
                    if is_mock {
                        let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
                        if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                            mock.e2e_mock_check(element.widget_id, checked)?;
                            break;
                        }
                    }
                    if self.ui.backend_mut().native_click(element.widget_id)? {
                        break;
                    }
                    return Err(GuiError::UnsupportedWidget("e2e.check"));
                }
                Err(err) => return Err(err),
            }
        }
        self.complete_action(started)
    }

    fn press(&mut self, element: &Element, chord: &str) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Press)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_press(element.widget_id, chord)?;
            }
        } else {
            return Err(GuiError::UnsupportedWidget("e2e.press"));
        }
        self.complete_action(started)
    }

    fn select(&mut self, element: &Element, index: usize) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Select)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_select(element.widget_id, index)?;
            }
        } else {
            return Err(GuiError::UnsupportedWidget("e2e.select"));
        }
        self.complete_action(started)
    }

    fn select_text(&mut self, element: &Element, start: usize, end: usize) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Select)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_select_text(element.widget_id, start, end)?;
            }
        } else {
            return Err(GuiError::UnsupportedWidget("e2e.select"));
        }
        self.complete_action(started)
    }

    fn set_value(&mut self, element: &Element, value: i32) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::SetValue)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_set_value(element.widget_id, value)?;
            }
        } else {
            return Err(GuiError::UnsupportedWidget("e2e.set_value"));
        }
        self.complete_action(started)
    }

    fn scroll(&mut self, element: &Element, delta_x: f64, delta_y: f64) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Scroll)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_scroll(element.widget_id, delta_x, delta_y)?;
            }
        } else {
            return Err(GuiError::UnsupportedWidget("e2e.scroll"));
        }
        self.complete_action(started)
    }

    fn drag_to(&mut self, source: &Element, target: &Element) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(source, Operation::DragTo)?;
        self.validate_element(target)?;
        self.wait_for_readiness(source.widget_id, started)?;
        self.wait_for_readiness(target.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_drag_to(source.widget_id, target.widget_id)?;
            }
        } else {
            return Err(GuiError::UnsupportedWidget("e2e.drag_to"));
        }
        self.complete_action(started)
    }

    fn close(&mut self, element: &Element) -> GuiResult<()> {
        let started = Instant::now();
        self.require_operation(element, Operation::Close)?;
        self.wait_for_readiness(element.widget_id, started)?;

        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.e2e_mock_close(element.widget_id)?;
            }
        } else {
            if self.ui.backend_mut().native_close(element.widget_id)? {
                // Closed via native WM_CLOSE
            } else {
                return Err(GuiError::UnsupportedWidget("e2e.close"));
            }
        }
        self.complete_action(started)
    }

    /// Waits until a dialog matching `locator` appears.
    pub fn wait_for_dialog(
        &mut self,
        locator: &Locator,
        options: WaitOptions,
    ) -> GuiResult<DialogHandle> {
        let elem = self.wait_for(locator, options)?;
        let spec = self
            .ui
            .widget(elem.id())
            .ok_or(GuiError::WidgetNotFound(elem.id().0))?;
        if is_window_or_dialog(spec.kind) {
            Ok(DialogHandle::new(elem.id(), spec.kind))
        } else {
            Err(GuiError::Backend(format!(
                "e2e.dialog: widget {} is not a window or dialog (kind {:?})",
                elem.id().0,
                spec.kind
            )))
        }
    }

    /// Waits for an element scoped within a specific window or dialog surface.
    pub fn wait_for_in_window(
        &mut self,
        window_id: WidgetId,
        locator: &Locator,
        options: WaitOptions,
    ) -> GuiResult<Element> {
        self.wait_for(&locator.clone().in_window(Locator::id(window_id)), options)
    }

    /// Responds to a modal confirm dialog by token and dispatches the response event.
    pub fn respond_confirm_dialog(&mut self, token: u64, confirmed: bool) -> GuiResult<()> {
        let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
        if is_mock {
            let any_mut: &mut dyn std::any::Any = self.ui.backend_mut();
            if let Some(mock) = any_mut.downcast_mut::<MockBackend>() {
                mock.events
                    .push_back(UiEvent::DialogResponse { token, confirmed });
            }
        }
        self.pump()?;
        Ok(())
    }

    /// Compares a captured screenshot against a golden baseline file on disk.
    ///
    /// The baseline is looked up in `tests/e2e-baselines/[backend]/[baseline_name].png`
    /// (or custom path from `NATIVE_GUI_E2E_BASELINES_DIR`).
    ///
    /// If `NATIVE_GUI_E2E_UPDATE_BASELINES=1` is set in the environment, the current screenshot
    /// will overwrite or initialize the baseline image and return a passing result.
    ///
    /// If the comparison fails (mismatch exceeds `max_mismatch_percent`), diff and actual
    /// PNG artifacts are automatically saved to `target/native-gui-e2e/diffs/[backend]/` and
    /// an error describing the percentage and diff bounds is returned.
    pub fn assert_screenshot_matches(
        &mut self,
        target: CaptureTarget,
        baseline_name: &str,
        options: &ImageDiffOptions,
    ) -> GuiResult<ImageDiffResult> {
        let actual = self.screenshot(target.clone())?;
        let backend_name = self.backend_name();

        let base_dir = std::env::var("NATIVE_GUI_E2E_BASELINES_DIR")
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|_| std::path::PathBuf::from("tests/e2e-baselines"));
        let backend_dir = base_dir.join(backend_name);
        let baseline_path = backend_dir.join(format!("{baseline_name}.png"));

        let update_env = std::env::var("NATIVE_GUI_E2E_UPDATE_BASELINES")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);

        if update_env {
            std::fs::create_dir_all(&backend_dir).map_err(|e| {
                GuiError::Backend(format!(
                    "e2e.visual: failed to create baseline directory '{}': {e}",
                    backend_dir.display()
                ))
            })?;
            actual.save_png(&baseline_path)?;
            let total = (actual.width as usize) * (actual.height as usize);
            return Ok(ImageDiffResult {
                passed: true,
                mismatch_percentage: 0.0,
                mismatched_pixels: 0,
                total_pixels: total,
                diff_bounds: None,
                diff_image: None,
            });
        }

        if !baseline_path.exists() {
            return Err(GuiError::Backend(format!(
                "e2e.visual: baseline image not found at '{}'. Run with NATIVE_GUI_E2E_UPDATE_BASELINES=1 to record it.",
                baseline_path.display()
            )));
        }

        let expected = CaptureImage::load_png(&baseline_path)?;
        let mask_rects = self.resolve_mask_rects(&target, options)?;
        let result = compare_images(&actual, &expected, options, &mask_rects)?;

        if !result.passed {
            let diff_dir = options.diff_output_dir.clone().unwrap_or_else(|| {
                std::path::PathBuf::from("target/native-gui-e2e/diffs").join(backend_name)
            });
            let _ = std::fs::create_dir_all(&diff_dir);
            let diff_file = diff_dir.join(format!("{baseline_name}_diff.png"));
            let actual_file = diff_dir.join(format!("{baseline_name}_actual.png"));
            if let Some(diff_img) = &result.diff_image {
                let _ = diff_img.save_png(&diff_file);
            }
            let _ = actual.save_png(&actual_file);

            return Err(GuiError::Backend(format!(
                "e2e.visual: screenshot '{}' differs from baseline ({:.2}% mismatch, {} differing pixels). Diff saved to '{}'",
                baseline_name,
                result.mismatch_percentage,
                result.mismatched_pixels,
                diff_file.display()
            )));
        }

        Ok(result)
    }

    /// Captures the full viewport and asserts it matches the baseline with default options.
    pub fn expect_screenshot(&mut self, baseline_name: &str) -> GuiResult<ImageDiffResult> {
        self.assert_screenshot_matches(
            CaptureTarget::Viewport,
            baseline_name,
            &ImageDiffOptions::default(),
        )
    }
}

/// A detached handle to one widget in a single driver session.
#[derive(Debug, Clone)]
pub struct Element {
    widget_id: WidgetId,
    session: Weak<()>,
    _thread_affine: PhantomData<Rc<()>>,
}

impl Element {
    /// Returns this element's shared widget identifier.
    pub fn id(&self) -> WidgetId {
        self.widget_id
    }

    /// Reads current backend text; unavailable readback is an explicit error.
    pub fn text<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<String> {
        driver.require_operation(self, Operation::Text)?;
        match driver.ui.backend().e2e_text(self.widget_id) {
            Ok(text) => Ok(text),
            Err(GuiError::UnsupportedWidget(_)) => {
                if let Some(text) = driver.ui.backend().native_read_text(self.widget_id)? {
                    return Ok(text);
                }
                let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
                if is_mock {
                    if let Some(spec) = driver.ui.widget(self.widget_id) {
                        return Ok(spec.text.clone().unwrap_or_default());
                    }
                }
                Err(GuiError::UnsupportedWidget("e2e.text"))
            }
            Err(err) => Err(err),
        }
    }

    /// Reads current backend checked state.
    pub fn is_checked<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
        driver.require_operation(self, Operation::Checked)?;
        match driver.ui.backend().e2e_checked(self.widget_id) {
            Ok(checked) => Ok(checked),
            Err(GuiError::UnsupportedWidget(_)) => {
                if let Some(checked) = driver.ui.backend().native_read_checked(self.widget_id)? {
                    return Ok(checked);
                }
                let is_mock = std::any::TypeId::of::<B>() == std::any::TypeId::of::<MockBackend>();
                if is_mock {
                    if let Some(spec) = driver.ui.widget(self.widget_id) {
                        return Ok(spec.checked.unwrap_or(false));
                    }
                }
                Err(GuiError::UnsupportedWidget("e2e.checked"))
            }
            Err(err) => Err(err),
        }
    }

    /// Returns whether this element and all its ancestors are enabled.
    pub fn is_enabled<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
        driver.is_enabled(self)
    }

    /// Returns whether this element and all its ancestors are visible.
    pub fn is_visible<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
        driver.is_visible(self)
    }

    /// Checks if this element is eligible to receive input given any active modal.
    pub fn is_modal_eligible<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<bool> {
        driver.validate_element(self)?;
        driver.is_modal_eligible(self.widget_id)
    }

    /// Reads numeric value from a value-capable widget.
    pub fn value<B: E2eBackend, H>(&self, driver: &Driver<B, H>) -> GuiResult<i32> {
        driver.value(self)
    }

    /// Activates a supported clickable widget.
    pub fn click<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.click(self)
    }

    /// Inserts committed Unicode text at the current selection or caret.
    pub fn type_text<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
        text: &str,
    ) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.type_text(self, text)
    }

    /// Sets checkbox state idempotently.
    pub fn check<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>, checked: bool) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.check(self, checked)
    }

    /// Dispatches a key chord stroke (e.g. "Ctrl+S", "Enter", "Tab").
    pub fn press<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>, chord: &str) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.press(self, chord)
    }

    /// Selects an item by index in a selection-capable control.
    pub fn select<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>, index: usize) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.select(self, index)
    }

    /// Selects a character range in an editable text control.
    pub fn select_text<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
        start: usize,
        end: usize,
    ) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.select_text(self, start, end)
    }

    /// Sets a numeric value on a value-capable control.
    pub fn set_value<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
        value: i32,
    ) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.set_value(self, value)
    }

    /// Scrolls a scrollable control by logical pixel deltas.
    pub fn scroll<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
        delta_x: f64,
        delta_y: f64,
    ) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.scroll(self, delta_x, delta_y)
    }

    /// Performs a drag-and-drop gesture from this element to a target element.
    pub fn drag_to<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
        target: &Element,
    ) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.drag_to(self, target)
    }

    /// Requests window or dialog closure.
    pub fn close<B: E2eBackend, H>(&self, driver: &mut Driver<B, H>) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.close(self)
    }

    /// Waits until live backend text equals `expected`.
    pub fn expect_text<B: E2eBackend, H>(
        &self,
        driver: &mut Driver<B, H>,
        expected: &str,
        options: WaitOptions,
    ) -> GuiResult<()>
    where
        H: for<'a> FnMut(&'a mut Ui<B>, UiEvent) -> GuiResult<LoopFlow>,
    {
        driver.wait_until(
            options,
            |driver| Ok(self.text(driver)?.as_str() == expected),
        )
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::rc::Rc;

    use super::*;

    type Handler = Box<dyn for<'a> FnMut(&'a mut Ui<MockBackend>, UiEvent) -> GuiResult<LoopFlow>>;

    fn driver() -> (Driver<MockBackend, Handler>, WidgetId, WidgetId) {
        let mut ui = Ui::new(MockBackend::default());
        let window = ui.create(WidgetKind::Window, Some("main")).expect("window");
        let button = ui.create(WidgetKind::Button, Some("Save")).expect("button");
        ui.attach(window, button).expect("attach button");
        ui.show(window).expect("show window");
        (
            Driver::new(ui, Box::new(|_ui, _event| Ok(LoopFlow::Continue))),
            window,
            button,
        )
    }

    #[test]
    fn screenshot_mock_and_capture_routing_b945() {
        let (mut driver, win, btn) = driver();
        // Mock driver routes through mock_screenshot producing valid RGBA buffers
        let win_shot = driver
            .screenshot(CaptureTarget::Window(win))
            .expect("window shot");
        assert!(win_shot.width() > 0);
        assert!(win_shot.height() > 0);
        assert_eq!(
            win_shot.data().len(),
            (win_shot.width() * win_shot.height() * 4) as usize
        );

        let elem_shot = driver
            .screenshot(CaptureTarget::Element(Locator::id(btn)))
            .expect("elem shot");
        assert!(elem_shot.width() > 0);
        assert!(elem_shot.height() > 0);
        assert_eq!(
            elem_shot.data().len(),
            (elem_shot.width() * elem_shot.height() * 4) as usize
        );

        let vp_shot = driver
            .screenshot(CaptureTarget::Viewport)
            .expect("viewport shot");
        assert!(vp_shot.width() >= win_shot.width());
        assert!(vp_shot.height() >= win_shot.height());
    }

    #[test]
    fn locators_cover_bindings_metadata_and_parent_scopes() {
        let (mut driver, window, button) = driver();
        driver.bind_name(button, "save").expect("bind name");
        driver
            .bind_test_id(button, "save-button")
            .expect("bind test id");

        assert_eq!(
            driver
                .expect_one(&Locator::name("save"))
                .expect("named button")
                .id(),
            button
        );
        assert_eq!(
            driver
                .expect_one(&Locator::test_id("save-button"))
                .expect("test id")
                .id(),
            button
        );
        assert_eq!(
            driver
                .expect_one(&Locator::role(AccessibleRole::Button, "Save"))
                .expect("role")
                .id(),
            button
        );
        assert_eq!(
            driver
                .find_all(&Locator::text("Save").in_window(Locator::id(window)))
                .expect("scoped query")
                .len(),
            1
        );
        assert_eq!(
            driver
                .find_all(&Locator::kind(WidgetKind::Button).child_of(Locator::id(window)))
                .expect("direct child query")
                .len(),
            1
        );
        assert_eq!(
            driver
                .find_all(&Locator::kind(WidgetKind::Button).descendant_of(Locator::id(window)))
                .expect("descendant query")
                .len(),
            1
        );
    }

    #[test]
    fn ambiguous_queries_error_and_find_all_is_sorted() {
        let (mut driver, window, first) = driver();
        let second = driver
            .ui_mut()
            .create(WidgetKind::Button, Some("Save"))
            .expect("second button");
        driver
            .ui_mut()
            .attach(window, second)
            .expect("attach second");
        assert!(driver.find(&Locator::text("Save")).is_err());
        assert_eq!(
            driver
                .find_all(&Locator::kind(WidgetKind::Button))
                .expect("buttons")
                .iter()
                .map(Element::id)
                .collect::<Vec<_>>(),
            vec![first, second]
        );
        driver.bind_name(first, "save").expect("bind first name");
        assert!(driver.bind_name(second, "save").is_err());
    }

    #[test]
    fn click_delivers_the_normal_application_event() {
        let clicked = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&clicked);
        let mut ui = Ui::new(MockBackend::default());
        let window = ui.create(WidgetKind::Window, Some("main")).expect("window");
        let button = ui.create(WidgetKind::Button, Some("Save")).expect("button");
        ui.attach(window, button).expect("attach button");
        ui.show(window).expect("show window");
        let mut driver = Driver::new(
            ui,
            Box::new(move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
                seen.borrow_mut().push(event);
                Ok(LoopFlow::Continue)
            }) as Handler,
        );
        driver
            .expect_one(&Locator::id(button))
            .expect("button")
            .click(&mut driver)
            .expect("click");
        assert_eq!(
            *clicked.borrow(),
            vec![UiEvent::Clicked { widget_id: button }]
        );
    }

    #[test]
    #[cfg(feature = "widgets-text")]
    fn typing_inserts_at_the_unicode_character_selection_and_dispatches_event() {
        let mut ui = Ui::new(MockBackend::default());
        let input = ui
            .create(WidgetKind::TextInput, Some("aéz"))
            .expect("input");
        ui.set_text_selection(input, 1, 2)
            .expect("select character");
        let seen = Rc::new(RefCell::new(Vec::new()));
        let captured = Rc::clone(&seen);
        let mut driver = Driver::new(
            ui,
            Box::new(move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
                captured.borrow_mut().push(event);
                Ok(LoopFlow::Continue)
            }) as Handler,
        );

        driver
            .expect_one(&Locator::id(input))
            .expect("input element")
            .type_text(&mut driver, "🙂")
            .expect("type text");
        assert_eq!(
            driver
                .expect_one(&Locator::id(input))
                .expect("input")
                .text(&driver),
            Ok("a🙂z".to_owned())
        );
        assert!(seen.borrow().iter().any(|event| {
            *event
                == UiEvent::TextChanged {
                    widget_id: input,
                    text: "a🙂z".to_owned(),
                }
        }));
    }

    #[test]
    #[cfg(feature = "widgets-choice")]
    fn checkbox_action_is_idempotent_and_observed_through_events() {
        let mut ui = Ui::new(MockBackend::default());
        let checkbox = ui
            .create(WidgetKind::Checkbox, Some("Enabled"))
            .expect("checkbox");
        ui.show(checkbox).expect("show checkbox");
        let events = Rc::new(RefCell::new(Vec::new()));
        let captured = Rc::clone(&events);
        let mut driver = Driver::new(
            ui,
            Box::new(move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
                captured.borrow_mut().push(event);
                Ok(LoopFlow::Continue)
            }) as Handler,
        );
        let element = driver.expect_one(&Locator::id(checkbox)).expect("element");

        element.check(&mut driver, true).expect("check");
        element.check(&mut driver, true).expect("repeat check");
        assert!(element.is_checked(&driver).expect("checked state"));
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::Toggled {
                widget_id: checkbox,
                checked: true,
            }]
        );
    }

    #[test]
    fn stale_foreign_and_timed_out_queries_fail_explicitly() {
        let (mut first, _window, button) = driver();
        let element = first.expect_one(&Locator::id(button)).expect("element");
        let (second, _, _) = driver();
        assert!(matches!(element.text(&second), Err(GuiError::Backend(_))));

        first.ui_mut().remove(button).expect("remove button");
        assert_eq!(
            element.text(&first),
            Err(GuiError::WidgetNotFound(button.0))
        );
        assert!(first.find(&Locator::kind(WidgetKind::Window)).is_ok());
        assert!(first
            .wait_for(
                &Locator::text("not present"),
                WaitOptions::new(Duration::from_millis(2)).poll_interval(Duration::from_millis(1)),
            )
            .is_err());
        assert!(first
            .wait_until(WaitOptions::new(Duration::ZERO), |_| Ok(false),)
            .is_err());
    }

    #[test]
    fn action_rejects_hidden_or_disabled_controls() {
        let (mut driver, _, button) = driver();
        driver.ui_mut().set_enabled(button, false).expect("disable");
        let element = driver.expect_one(&Locator::id(button)).expect("button");
        assert!(element.click(&mut driver).is_err());

        driver.ui_mut().set_enabled(button, true).expect("enable");
        driver.ui_mut().set_visible(button, false).expect("hide");
        assert!(element.click(&mut driver).is_err());
    }

    #[test]
    fn fidelity_refusal_has_no_side_effect_and_unknown_queries_error() {
        let (driver, _, button) = driver();
        let element = driver.expect_one(&Locator::id(button)).unwrap();
        let mut driver = driver.with_input_mode(InputMode::HardwareNative);
        assert_eq!(
            element.click(&mut driver),
            Err(GuiError::UnsupportedWidget("e2e.click"))
        );
        assert!(driver.ui().backend().events.is_empty());
        assert_eq!(
            driver
                .ui()
                .backend()
                .e2e_capability(WidgetId(u64::MAX), Operation::Click),
            Err(GuiError::WidgetNotFound(u64::MAX))
        );
        assert!(matches!(
            driver.capability(&element, Operation::Press).unwrap(),
            Capability::Unsupported { .. }
        ));
    }

    #[test]
    fn wait_pump_is_bounded_when_handler_continually_enqueues_work() {
        let mut ui = Ui::new(MockBackend::default());
        let button = ui.create(WidgetKind::Button, Some("again")).unwrap();
        ui.backend_mut()
            .push_event(UiEvent::Clicked { widget_id: button });
        let mut driver = Driver::new(ui, move |ui: &mut Ui<MockBackend>, _event| {
            ui.backend_mut()
                .push_event(UiEvent::Clicked { widget_id: button });
            Ok(LoopFlow::Continue)
        });
        let start = Instant::now();
        assert!(driver
            .wait_until(WaitOptions::new(Duration::from_millis(10)), |_| Ok(false))
            .is_err());
        assert!(start.elapsed() < Duration::from_secs(5));
        assert!(!driver.ui().backend().events.is_empty());
    }

    #[test]
    fn handler_exit_stops_future_input_and_observation() {
        let mut ui = Ui::new(MockBackend::default());
        let button = ui.create(WidgetKind::Button, Some("Exit")).unwrap();
        let mut driver = Driver::new(ui, |_ui: &mut Ui<MockBackend>, _event| Ok(LoopFlow::Exit));
        let element = driver.expect_one(&Locator::id(button)).unwrap();
        element.click(&mut driver).unwrap();
        assert!(matches!(
            element.click(&mut driver),
            Err(GuiError::Backend(_))
        ));
        assert!(matches!(element.text(&driver), Err(GuiError::Backend(_))));
    }

    #[test]
    fn action_drains_multiple_bounded_slices_in_fifo_order() {
        let mut ui = Ui::new(MockBackend::default());
        let button = ui.create(WidgetKind::Button, Some("Run")).unwrap();
        for index in 0..130 {
            ui.backend_mut().push_event(UiEvent::ValueChanged {
                widget_id: button,
                value: index,
            });
        }
        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui, event| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });
        let element = driver.expect_one(&Locator::id(button)).unwrap();
        element.click(&mut driver).unwrap();
        assert_eq!(events.borrow().len(), 131);
        assert_eq!(events.borrow()[130], UiEvent::Clicked { widget_id: button });
        for index in 0..130 {
            assert_eq!(
                events.borrow()[index],
                UiEvent::ValueChanged {
                    widget_id: button,
                    value: index as i32
                }
            );
        }
        assert!(driver.ui().backend().events.is_empty());
    }

    #[test]
    #[cfg(feature = "widgets-text")]
    fn press_dispatches_key_events_in_order() {
        let mut ui = Ui::new(MockBackend::default());
        let input = ui.create(WidgetKind::TextInput, Some("test")).unwrap();
        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });
        let element = driver.expect_one(&Locator::id(input)).unwrap();

        element.press(&mut driver, "Ctrl+S").expect("press chord");
        assert_eq!(
            *events.borrow(),
            vec![
                UiEvent::KeyDown {
                    widget_id: input,
                    key: "S".into(),
                    ctrl: true,
                    shift: false,
                    alt: false,
                },
                UiEvent::KeyUp {
                    widget_id: input,
                    key: "S".into(),
                    ctrl: true,
                    shift: false,
                    alt: false,
                },
            ]
        );

        events.borrow_mut().clear();
        element.press(&mut driver, "x").expect("press char");
        assert_eq!(
            *events.borrow(),
            vec![
                UiEvent::KeyDown {
                    widget_id: input,
                    key: "x".into(),
                    ctrl: false,
                    shift: false,
                    alt: false,
                },
                UiEvent::Char {
                    widget_id: input,
                    text: "x".into(),
                },
                UiEvent::KeyUp {
                    widget_id: input,
                    key: "x".into(),
                    ctrl: false,
                    shift: false,
                    alt: false,
                },
            ]
        );
    }

    #[test]
    #[cfg(all(feature = "widgets-text", feature = "widgets-data"))]
    fn select_and_select_text_update_model_and_dispatch_selection_event() {
        let mut ui = Ui::new(MockBackend::default());
        let combo = ui.create(WidgetKind::DataList, None).unwrap();
        ui.set_data_list_items(combo, &["first".into(), "second".into(), "third".into()])
            .unwrap();
        let input = ui
            .create(WidgetKind::TextInput, Some("hello world"))
            .unwrap();

        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });

        let combo_elem = driver.expect_one(&Locator::id(combo)).unwrap();
        combo_elem
            .select(&mut driver, 1)
            .expect("select combo item");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::SelectionChanged {
                widget_id: combo,
                selected: Some("second".into()),
                index: Some(1),
            }]
        );

        let input_elem = driver.expect_one(&Locator::id(input)).unwrap();
        input_elem
            .select_text(&mut driver, 0, 5)
            .expect("select text");
        assert_eq!(
            driver
                .ui()
                .backend()
                .created
                .get(&input)
                .unwrap()
                .text_selection,
            Some((0, 5))
        );
    }

    #[test]
    #[cfg(feature = "widgets-range")]
    fn numeric_value_validates_range_and_emits_value_changed() {
        let mut ui = Ui::new(MockBackend::default());
        let slider = ui.create(WidgetKind::Slider, None).unwrap();
        ui.set_range(slider, 0, 100).unwrap();
        ui.set_value(slider, 10).unwrap();

        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });
        let elem = driver.expect_one(&Locator::id(slider)).unwrap();

        assert_eq!(elem.value(&driver).unwrap(), 10);
        elem.set_value(&mut driver, 50).expect("set valid value");
        assert_eq!(elem.value(&driver).unwrap(), 50);
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::ValueChanged {
                widget_id: slider,
                value: 50,
            }]
        );

        assert!(elem.set_value(&mut driver, 150).is_err());
        assert!(elem.set_value(&mut driver, -10).is_err());
    }

    #[test]
    fn scroll_updates_scroll_target() {
        let mut ui = Ui::new(MockBackend::default());
        let container = ui.create(WidgetKind::Container, None).unwrap();
        let mut driver = Driver::new(ui, |_ui: &mut Ui<MockBackend>, _event| {
            Ok(LoopFlow::Continue)
        });
        let elem = driver.expect_one(&Locator::id(container)).unwrap();

        elem.scroll(&mut driver, 0.0, 20.0)
            .expect("scroll container");
        assert_eq!(
            driver.ui().backend().scroll_anchors.get(&container),
            Some(&20)
        );
    }

    #[test]
    #[cfg(feature = "widgets-data")]
    fn drag_to_emits_drag_and_drop_events() {
        let mut ui = Ui::new(MockBackend::default());
        let list1 = ui.create(WidgetKind::ListView, None).unwrap();
        let list2 = ui.create(WidgetKind::ListView, None).unwrap();

        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });

        let source = driver.expect_one(&Locator::id(list1)).unwrap();
        let target = driver.expect_one(&Locator::id(list2)).unwrap();
        source
            .drag_to(&mut driver, &target)
            .expect("drag to target");

        assert_eq!(
            *events.borrow(),
            vec![
                UiEvent::DragStarted {
                    widget_id: list1,
                    indices: vec![0],
                },
                UiEvent::Dropped {
                    widget_id: list2,
                    target_index: 0,
                    source_indices: vec![0],
                },
            ]
        );
    }

    #[test]
    fn close_respects_close_guard_and_window_lifecycle() {
        let mut ui = Ui::new(MockBackend::default());
        let window = ui.create(WidgetKind::Window, Some("guarded")).unwrap();
        ui.show(window).unwrap();
        ui.set_close_guard(window, true).unwrap();

        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui: &mut Ui<MockBackend>, event: UiEvent| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });

        let elem = driver.expect_one(&Locator::id(window)).unwrap();
        elem.close(&mut driver).expect("close guarded window");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::CloseRequested { widget_id: window }]
        );
        assert!(driver.ui().backend().shown.contains(&window));

        events.borrow_mut().clear();
        driver.ui_mut().set_close_guard(window, false).unwrap();
        elem.close(&mut driver).expect("close unguarded window");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::WindowClosed { widget_id: window }]
        );
        assert!(!driver.ui().backend().shown.contains(&window));
    }

    #[test]
    fn readiness_auto_wait_waits_for_disabled_control_to_become_enabled() {
        let mut ui = Ui::new(MockBackend::default());
        let window = ui.create(WidgetKind::Window, Some("main")).unwrap();
        let button = ui.create(WidgetKind::Button, Some("Submit")).unwrap();
        ui.attach(window, button).unwrap();
        ui.show(window).unwrap();
        ui.set_enabled(button, false).unwrap();

        let button_clone = button;
        let clicked = Rc::new(RefCell::new(false));
        let clicked_seen = Rc::clone(&clicked);
        ui.backend_mut().push_event(UiEvent::FocusChanged {
            widget_id: button,
            focused: true,
        });

        let mut driver = Driver::new(ui, move |ui: &mut Ui<MockBackend>, event: UiEvent| {
            if matches!(event, UiEvent::FocusChanged { .. }) {
                ui.set_enabled(button_clone, true).unwrap();
            } else if matches!(event, UiEvent::Clicked { widget_id } if widget_id == button_clone) {
                *clicked_seen.borrow_mut() = true;
            }
            Ok(LoopFlow::Continue)
        });
        driver = driver.with_action_timeout(Duration::from_secs(5));

        let element = driver.expect_one(&Locator::id(button)).unwrap();
        element
            .click(&mut driver)
            .expect("auto-wait succeeds when control becomes enabled");
        assert!(*clicked.borrow());
    }

    #[test]
    fn modal_eligibility_blocks_non_modal_widgets_and_auto_waits_until_modal_closes() {
        let mut ui = Ui::new(MockBackend::default());
        let main_win = ui.create(WidgetKind::Window, Some("main")).unwrap();
        let main_btn = ui.create(WidgetKind::Button, Some("MainBtn")).unwrap();
        ui.attach(main_win, main_btn).unwrap();
        ui.show(main_win).unwrap();

        let modal_win = ui.create(WidgetKind::Window, Some("modal")).unwrap();
        let modal_btn = ui.create(WidgetKind::Button, Some("ModalBtn")).unwrap();
        ui.attach(modal_win, modal_btn).unwrap();
        ui.show(modal_win).unwrap();

        let mut driver = Driver::new(ui, |_ui: &mut Ui<MockBackend>, _event| {
            Ok(LoopFlow::Continue)
        });
        driver.set_active_modal(Some(modal_win));

        let modal_elem = driver.expect_one(&Locator::id(modal_btn)).unwrap();
        let main_elem = driver.expect_one(&Locator::id(main_btn)).unwrap();

        assert!(modal_elem.is_modal_eligible(&driver).unwrap());
        assert!(!main_elem.is_modal_eligible(&driver).unwrap());

        modal_elem
            .click(&mut driver)
            .expect("modal element click succeeds");

        driver = driver.with_action_timeout(Duration::from_millis(50));
        assert!(main_elem.click(&mut driver).is_err());

        driver.set_active_modal(None);
        assert!(main_elem.is_modal_eligible(&driver).unwrap());
        main_elem
            .click(&mut driver)
            .expect("click succeeds after modal dismissed");
    }

    #[test]
    fn element_status_readbacks() {
        let (mut driver, _win, button) = driver();
        let elem = driver.expect_one(&Locator::id(button)).unwrap();

        assert!(elem.is_enabled(&driver).unwrap());
        assert!(elem.is_visible(&driver).unwrap());

        driver.ui_mut().set_enabled(button, false).unwrap();
        assert!(!elem.is_enabled(&driver).unwrap());

        driver.ui_mut().set_visible(button, false).unwrap();
        assert!(!elem.is_visible(&driver).unwrap());
    }

    #[test]
    fn screenshot_captures_window_element_and_viewport() {
        let (mut driver, win, button) = driver();
        let win_img = driver
            .screenshot(CaptureTarget::Window(win))
            .expect("window screenshot");
        assert!(win_img.width() > 0);
        assert!(win_img.height() > 0);
        assert_eq!(
            win_img.data().len(),
            (win_img.width() * win_img.height() * 4) as usize
        );

        let elem_img = driver
            .screenshot(CaptureTarget::Element(Locator::id(button)))
            .expect("element screenshot");
        assert!(elem_img.width() > 0);
        assert!(elem_img.height() > 0);

        let vp_img = driver
            .screenshot(CaptureTarget::Viewport)
            .expect("viewport screenshot");
        assert!(vp_img.width() > 0);
        assert!(vp_img.height() > 0);
        let png = vp_img.to_png().expect("to png");
        assert!(!png.is_empty());
    }

    #[test]
    fn visual_assertions_identical_images_match() {
        let pixels = [100u8, 150, 200, 255].repeat(16); // 4x4 image
        let img1 = CaptureImage::new(4, 4, pixels.clone());
        let img2 = CaptureImage::new(4, 4, pixels);

        let options = ImageDiffOptions::default();
        let result = img1.diff(&img2, &options).expect("diff");
        assert!(result.passed());
        assert_eq!(result.mismatched_pixels(), 0);
        assert_eq!(result.mismatch_percentage(), 0.0);
        assert_eq!(result.diff_bounds(), None);
    }

    #[test]
    fn visual_assertions_pixel_difference_and_diff_bounds_detected() {
        let mut pixels1 = [0u8, 0, 0, 255].repeat(100); // 10x10 image
        let pixels2 = pixels1.clone();

        // Change a 2x2 area from (3, 3) to (4, 4)
        for y in 3..=4 {
            for x in 3..=4 {
                let idx = ((y * 10 + x) * 4) as usize;
                pixels1[idx] = 255;
            }
        }

        let img1 = CaptureImage::new(10, 10, pixels1);
        let img2 = CaptureImage::new(10, 10, pixels2);

        let options = ImageDiffOptions::default();
        let result = img1.diff(&img2, &options).expect("diff");
        assert!(!result.passed());
        assert_eq!(result.mismatched_pixels(), 4);
        assert_eq!(result.mismatch_percentage(), 4.0); // 4 out of 100 pixels = 4%
        assert_eq!(result.diff_bounds(), Some(Rect::new(3, 3, 2, 2)));

        // Diff image highlights changed pixels in magenta
        let diff_img = result.diff_image().expect("diff image");
        let diff_px = diff_img.pixel(3, 3).expect("pixel");
        assert_eq!(diff_px, [255, 0, 128, 255]); // Mismatched highlight
        let same_px = diff_img.pixel(0, 0).expect("pixel");
        assert_ne!(same_px, [255, 0, 128, 255]); // Baseline faded
    }

    #[test]
    fn visual_assertions_tolerance_allows_small_variations() {
        let img1 = CaptureImage::new(2, 2, [100u8, 100, 100, 255].repeat(4));
        // Slight delta of +3 per channel
        let img2 = CaptureImage::new(2, 2, [103u8, 102, 101, 255].repeat(4));

        // Zero tolerance fails
        let strict = ImageDiffOptions::new().with_tolerance(0);
        let res_strict = img1.diff(&img2, &strict).expect("diff strict");
        assert!(!res_strict.passed());
        assert_eq!(res_strict.mismatched_pixels(), 4);

        // Tolerance of 5 allows the difference to pass
        let lenient = ImageDiffOptions::new().with_tolerance(5);
        let res_lenient = img1.diff(&img2, &lenient).expect("diff lenient");
        assert!(res_lenient.passed());
        assert_eq!(res_lenient.mismatched_pixels(), 0);
    }

    #[test]
    fn visual_assertions_masked_regions_are_ignored() {
        let mut pixels1 = [50u8, 50, 50, 255].repeat(100); // 10x10 image
        let pixels2 = pixels1.clone();

        // Change region (5, 5, 3, 3)
        for y in 5..8 {
            for x in 5..8 {
                let idx = ((y * 10 + x) * 4) as usize;
                pixels1[idx] = 220;
            }
        }

        let img1 = CaptureImage::new(10, 10, pixels1);
        let img2 = CaptureImage::new(10, 10, pixels2);

        // Without mask, it fails
        let no_mask = ImageDiffOptions::default();
        let res_no_mask = img1.diff(&img2, &no_mask).expect("no mask");
        assert!(!res_no_mask.passed());
        assert_eq!(res_no_mask.mismatched_pixels(), 9);

        // With mask covering the changed region, it passes!
        let masked = ImageDiffOptions::default().with_mask_rect(5, 5, 3, 3);
        let resolved = vec![Rect::new(5, 5, 3, 3)];
        let res_masked = compare_images(&img1, &img2, &masked, &resolved).expect("masked");
        assert!(res_masked.passed());
        assert_eq!(res_masked.mismatched_pixels(), 0);
        assert_eq!(res_masked.total_pixels, 91); // 100 - 9 masked pixels evaluated
    }

    #[test]
    fn png_encode_decode_round_trip() {
        let width = 8u32;
        let height = 6u32;
        let mut raw = Vec::with_capacity((width * height * 4) as usize);
        for y in 0..height {
            for x in 0..width {
                raw.push((x * 30) as u8);
                raw.push((y * 40) as u8);
                raw.push(180);
                raw.push(255);
            }
        }
        let original = CaptureImage::new(width, height, raw);
        let encoded_png = original.to_png().expect("encode png");
        assert!(encoded_png.len() > 8);

        let decoded = CaptureImage::from_png(&encoded_png).expect("decode png");
        assert_eq!(decoded.width(), original.width());
        assert_eq!(decoded.height(), original.height());
        assert_eq!(decoded.data(), original.data());
    }

    #[test]
    fn visual_golden_baseline_lifecycle_and_intentional_failure() {
        let scratch_dir =
            std::env::temp_dir().join(format!("native_gui_e2e_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&scratch_dir);
        let _ = std::fs::create_dir_all(&scratch_dir);

        let orig_baseline_env = std::env::var("NATIVE_GUI_E2E_BASELINES_DIR").ok();
        let orig_update_env = std::env::var("NATIVE_GUI_E2E_UPDATE_BASELINES").ok();

        std::env::set_var("NATIVE_GUI_E2E_BASELINES_DIR", &scratch_dir);

        let (mut driver, win, button) = driver();

        // 1. Missing baseline fails when update env is false
        std::env::remove_var("NATIVE_GUI_E2E_UPDATE_BASELINES");
        let miss_err = driver.assert_screenshot_matches(
            CaptureTarget::Window(win),
            "sample_win",
            &ImageDiffOptions::default(),
        );
        assert!(miss_err.is_err(), "missing baseline should fail");

        // 2. Setting NATIVE_GUI_E2E_UPDATE_BASELINES=1 writes the baseline and passes
        std::env::set_var("NATIVE_GUI_E2E_UPDATE_BASELINES", "1");
        let record_res = driver.assert_screenshot_matches(
            CaptureTarget::Window(win),
            "sample_win",
            &ImageDiffOptions::default(),
        );
        assert!(record_res.is_ok(), "recording baseline should succeed");
        std::env::remove_var("NATIVE_GUI_E2E_UPDATE_BASELINES");

        // Baseline file must now exist
        let baseline_file = scratch_dir.join("mock").join("sample_win.png");
        assert!(baseline_file.exists(), "baseline png must exist on disk");

        // 3. Unchanged UI matches the newly recorded baseline
        let match_res = driver.assert_screenshot_matches(
            CaptureTarget::Window(win),
            "sample_win",
            &ImageDiffOptions::default(),
        );
        assert!(match_res.is_ok(), "identical UI should match baseline");

        // 4. Intentional failure: modify UI state, assertion must fail and produce diff artifact
        driver.ui_mut().set_text(button, "MODIFIED_LABEL").unwrap();
        let diff_dir = scratch_dir.join("diffs");
        let fail_options = ImageDiffOptions::default().with_diff_output_dir(&diff_dir);
        let fail_res = driver.assert_screenshot_matches(
            CaptureTarget::Window(win),
            "sample_win",
            &fail_options,
        );
        assert!(fail_res.is_err(), "modified UI must fail visual assertion");

        let diff_file = diff_dir.join("sample_win_diff.png");
        let actual_file = diff_dir.join("sample_win_actual.png");
        assert!(diff_file.exists(), "diff artifact png must be created");
        assert!(actual_file.exists(), "actual artifact png must be created");

        // Clean up environment
        if let Some(val) = orig_baseline_env {
            std::env::set_var("NATIVE_GUI_E2E_BASELINES_DIR", val);
        } else {
            std::env::remove_var("NATIVE_GUI_E2E_BASELINES_DIR");
        }
        if let Some(val) = orig_update_env {
            std::env::set_var("NATIVE_GUI_E2E_UPDATE_BASELINES", val);
        } else {
            std::env::remove_var("NATIVE_GUI_E2E_UPDATE_BASELINES");
        }
        let _ = std::fs::remove_dir_all(&scratch_dir);
    }

    #[test]
    #[cfg(all(feature = "widgets-containers", feature = "widgets-pickers"))]
    fn dialog_and_secondary_window_automation_on_mock() {
        let mut ui = Ui::new(MockBackend::default());
        let main_win = ui.create(WidgetKind::Window, Some("Main Window")).unwrap();
        ui.show(main_win).unwrap();

        // Secondary window
        let sec_win = ui.create(WidgetKind::Window, Some("Settings")).unwrap();
        let sec_btn = ui.create(WidgetKind::Button, Some("Save")).unwrap();
        ui.attach(sec_win, sec_btn).unwrap();
        ui.show(sec_win).unwrap();

        // Alert dialog
        let alert = ui
            .create(WidgetKind::AlertDialog, Some("Confirm Exit"))
            .unwrap();
        let alert_ok = ui.create(WidgetKind::Button, Some("OK")).unwrap();
        ui.attach(alert, alert_ok).unwrap();
        ui.show(alert).unwrap();

        // File chooser dialog
        let chooser = ui
            .create(WidgetKind::FileChooserDialog, Some("Open File"))
            .unwrap();
        ui.show(chooser).unwrap();

        // Color dialog
        let color_dlg = ui
            .create(WidgetKind::ColorDialog, Some("Choose Color"))
            .unwrap();
        ui.set_color_dialog_data(
            color_dlg,
            native_gui_core::ColorDialogData::new(native_gui_core::Rgba::new(255, 0, 0, 255)),
        )
        .unwrap();
        ui.show(color_dlg).unwrap();

        // Font dialog
        let font_dlg = ui
            .create(WidgetKind::FontDialog, Some("Choose Font"))
            .unwrap();
        ui.set_font_dialog_data(
            font_dlg,
            native_gui_core::FontDialogData::new(native_gui_core::FontDescriptor::new(
                "Consolas", 14.0,
            )),
        )
        .unwrap();
        ui.show(font_dlg).unwrap();

        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui, event| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });

        // 1. Discover windows
        let windows = driver.windows().expect("driver.windows()");
        assert_eq!(windows.len(), 2);

        // 2. Discover dialogs
        let dialogs = driver.dialogs().expect("driver.dialogs()");
        assert_eq!(dialogs.len(), 4); // alert, chooser, color_dlg, font_dlg

        // 3. Scoped search inside secondary window
        let btn_in_sec = driver
            .find_in_window(sec_win, &Locator::text("Save"))
            .expect("find in window");
        assert!(btn_in_sec.is_some());
        assert_eq!(btn_in_sec.unwrap().id(), sec_btn);

        // 4. Find dialog by kind
        let mut alert_handle = driver
            .find_dialog(&Locator::kind(WidgetKind::AlertDialog))
            .expect("find alert")
            .expect("alert exists");
        assert_eq!(alert_handle.id(), alert);
        assert_eq!(alert_handle.title(&driver).unwrap(), "Confirm Exit");

        // 5. Screenshot dialog
        let alert_img = alert_handle
            .screenshot(&mut driver)
            .expect("dialog screenshot");
        assert!(alert_img.width() > 0 && alert_img.height() > 0);

        // 6. Accept alert dialog clicks OK button inside alert
        alert_handle.accept(&mut driver).expect("accept alert");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::Clicked {
                widget_id: alert_ok
            }]
        );
        events.borrow_mut().clear();

        // 7. Choose file on FileChooserDialog
        let mut chooser_handle = driver
            .expect_dialog(&Locator::kind(WidgetKind::FileChooserDialog))
            .expect("expect chooser");
        chooser_handle
            .choose_file(&mut driver, "C:/projects/sample-app/test.txt")
            .expect("choose file");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::TextChanged {
                widget_id: chooser,
                text: "C:/projects/sample-app/test.txt".into()
            }]
        );
        events.borrow_mut().clear();

        // 8. Color dialog accept and cancel
        let mut color_handle = driver
            .expect_dialog(&Locator::kind(WidgetKind::ColorDialog))
            .expect("expect color dlg");
        color_handle.accept(&mut driver).expect("accept color dlg");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::ColorSelected {
                widget_id: color_dlg,
                color: Some(native_gui_core::Rgba::new(255, 0, 0, 255))
            }]
        );
        events.borrow_mut().clear();

        color_handle.cancel(&mut driver).expect("cancel color dlg");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::ColorSelected {
                widget_id: color_dlg,
                color: None
            }]
        );
        events.borrow_mut().clear();

        // 9. Font dialog accept and cancel
        let mut font_handle = driver
            .expect_dialog(&Locator::kind(WidgetKind::FontDialog))
            .expect("expect font dlg");
        font_handle.accept(&mut driver).expect("accept font dlg");
        assert!(matches!(
            events.borrow().first(),
            Some(UiEvent::FontSelected { widget_id, selection: Some(_) }) if *widget_id == font_dlg
        ));
        events.borrow_mut().clear();

        font_handle.cancel(&mut driver).expect("cancel font dlg");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::FontSelected {
                widget_id: font_dlg,
                selection: None
            }]
        );
        events.borrow_mut().clear();
    }

    #[test]
    fn confirm_dialog_automation() {
        let mut ui = Ui::new(MockBackend::default());
        let main_win = ui.create(WidgetKind::Window, Some("Main")).unwrap();
        ui.show(main_win).unwrap();

        let token = ui
            .show_confirm_dialog("Delete file?", "Are you sure?")
            .expect("show confirm");

        let events = Rc::new(RefCell::new(Vec::new()));
        let seen = Rc::clone(&events);
        let mut driver = Driver::new(ui, move |_ui, event| {
            seen.borrow_mut().push(event);
            Ok(LoopFlow::Continue)
        });

        let requests = driver.pending_confirm_requests();
        assert_eq!(requests.len(), 1);
        assert_eq!(requests[0].0, token);
        assert_eq!(requests[0].1, "Delete file?");

        // Dialogs includes the pending confirm dialog
        let dialogs = driver.dialogs().expect("dialogs");
        assert_eq!(dialogs.len(), 1);
        assert_eq!(dialogs[0].token(), Some(token));

        // Responding confirms the dialog
        driver
            .respond_confirm_dialog(token, true)
            .expect("respond confirm");
        assert_eq!(
            *events.borrow(),
            vec![UiEvent::DialogResponse {
                token,
                confirmed: true
            }]
        );
    }

    #[test]
    fn harness_backend_type_selection() {
        assert_eq!(BackendType::Mock.as_str(), "mock");
        assert_eq!(BackendType::Gtk.as_str(), "gtk");
        assert_eq!(BackendType::Win32.as_str(), "win32");
        assert_eq!(BackendType::Cocoa.as_str(), "cocoa");
        assert!(BackendType::Mock.is_available());
        assert_eq!(BackendType::platform_default(), BackendType::Mock);
        assert!(!BackendType::Gtk.is_available());
        assert!(!BackendType::Win32.is_available());
        assert!(!BackendType::Cocoa.is_available());

        for (name, expected) in [
            ("mock", BackendType::Mock),
            ("win32", BackendType::Win32),
            (" WINDOWS ", BackendType::Win32),
            ("gtk", BackendType::Gtk),
            ("gtk4", BackendType::Gtk),
            ("cocoa", BackendType::Cocoa),
            ("macos", BackendType::Cocoa),
            ("appkit", BackendType::Cocoa),
        ] {
            assert_eq!(BackendType::from_name(name), Some(expected));
        }
        assert_eq!(BackendType::from_name("unknown"), None);
    }

    #[test]
    fn harness_refuses_native_requests_instead_of_running_mock() {
        for backend in [BackendType::Gtk, BackendType::Win32, BackendType::Cocoa] {
            let mut registry = ScenarioRegistry::new().with_config(HarnessConfig {
                backend,
                ..HarnessConfig::default()
            });
            registry.register_fn("native_request", |_| {
                panic!("a native request must not execute a Mock scenario")
            });

            let report = registry.run_all();
            assert_eq!(report.total(), 1);
            assert_eq!(report.passed(), 0);
            assert_eq!(report.failed(), 1);
            assert!(matches!(
                &report.results[0].status,
                ScenarioStatus::Failed(message)
                    if message.contains("e2e.unsupported_backend")
                        && message.contains(backend.as_str())
            ));
        }
    }

    #[test]
    fn harness_scenario_execution_and_artifacts() {
        let test_dir =
            std::env::temp_dir().join(format!("native-gui-e2e-test-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&test_dir);

        let config = HarnessConfig {
            backend: BackendType::Mock,
            default_timeout: Duration::from_secs(5),
            step_timeout: Duration::from_secs(2),
            artifacts_root: test_dir.clone(),
        };

        let mut registry = ScenarioRegistry::new().with_config(config);

        registry.register_fn("scenario_success", |ctx| {
            ctx.step("Create main window and button");
            let win = ctx
                .driver
                .ui_mut()
                .create(WidgetKind::Window, Some("App"))
                .unwrap();
            let btn = ctx
                .driver
                .ui_mut()
                .create(WidgetKind::Button, Some("Submit"))
                .unwrap();
            ctx.driver.ui_mut().attach(btn, win).unwrap();
            ctx.driver.ui_mut().show(win).unwrap();
            ctx.driver.ui_mut().show(btn).unwrap();

            ctx.step("Click submit button");
            let el = ctx
                .driver
                .expect_one(&Locator::role(AccessibleRole::Button, "Submit"))?;
            ctx.driver.click(&el)?;
            assert!(!ctx.events().is_empty());
            Ok(())
        });

        registry.register_fn("scenario_failure", |ctx| {
            ctx.step("Initialize window");
            let win = ctx
                .driver
                .ui_mut()
                .create(WidgetKind::Window, Some("Error Window"))
                .unwrap();
            let label = ctx
                .driver
                .ui_mut()
                .create(WidgetKind::Label, Some("Status Label"))
                .unwrap();
            ctx.driver.ui_mut().attach(label, win).unwrap();
            ctx.driver.ui_mut().show(win).unwrap();

            ctx.step("Simulate unexpected condition");
            Err(GuiError::Backend(
                "intentional test assertion failure".into(),
            ))
        });

        assert_eq!(registry.len(), 2);
        assert!(!registry.is_empty());

        let report = registry.run_all();
        assert_eq!(report.total(), 2);
        assert_eq!(report.passed(), 1);
        assert_eq!(report.failed(), 1);
        assert_eq!(report.skipped(), 0);

        // Verify successful scenario
        let pass_res = report
            .results
            .iter()
            .find(|r| r.name == "scenario_success")
            .unwrap();
        assert!(pass_res.is_pass());
        assert!(!pass_res.is_failure());
        assert_eq!(pass_res.steps.len(), 2);
        assert!(pass_res.artifacts_dir.is_none());

        // Verify failing scenario and generated artifacts
        let fail_res = report
            .results
            .iter()
            .find(|r| r.name == "scenario_failure")
            .unwrap();
        assert!(!fail_res.is_pass());
        assert!(fail_res.is_failure());
        assert_eq!(fail_res.steps.len(), 2);

        let artifacts_path = fail_res.artifacts_dir.as_ref().expect("artifacts dir");
        assert!(artifacts_path.exists());
        assert!(artifacts_path.join("screenshot.png").exists());
        assert!(artifacts_path.join("widget_tree.txt").exists());
        assert!(artifacts_path.join("events.log").exists());
        assert!(artifacts_path.join("error.txt").exists());

        // Inspect widget tree artifact
        let tree_content = std::fs::read_to_string(artifacts_path.join("widget_tree.txt")).unwrap();
        assert!(tree_content.contains("Window"));
        assert!(tree_content.contains("Error Window"));
        assert!(tree_content.contains("Label"));
        assert!(tree_content.contains("Status Label"));

        // Inspect error log artifact
        let err_content = std::fs::read_to_string(artifacts_path.join("error.txt")).unwrap();
        assert!(err_content.contains("intentional test assertion failure"));
        assert!(err_content.contains("1. Initialize window"));
        assert!(err_content.contains("2. Simulate unexpected condition"));

        // Verify JUnit XML serialization
        let junit = report.to_junit_xml();
        assert!(junit.contains("<testsuites tests=\"2\" failures=\"1\""));
        assert!(junit.contains("<testcase name=\"scenario_success\""));
        assert!(junit.contains("<testcase name=\"scenario_failure\""));
        assert!(junit.contains("intentional test assertion failure"));

        // Verify JSON serialization
        let json = report.to_json();
        assert!(json.contains("\"total\": 2"));
        assert!(json.contains("\"passed\": 1"));
        assert!(json.contains("\"failed\": 1"));
        assert!(json.contains("\"status\": \"passed\""));
        assert!(json.contains("\"status\": \"failed\""));

        let _ = std::fs::remove_dir_all(&test_dir);
    }

    #[test]
    fn harness_scenario_filtering() {
        let mut registry = ScenarioRegistry::new();
        registry.register_fn("auth_login", |_ctx| Ok(()));
        registry.register_fn("auth_logout", |_ctx| Ok(()));
        registry.register_fn("settings_update", |_ctx| Ok(()));

        let report_auth = registry.run_filtered("auth");
        assert_eq!(report_auth.total(), 2);
        assert_eq!(report_auth.passed(), 2);

        let report_settings = registry.run_filtered("settings");
        assert_eq!(report_settings.total(), 1);
        assert_eq!(report_settings.passed(), 1);

        let report_none = registry.run_filtered("nonexistent");
        assert_eq!(report_none.total(), 0);
    }

    #[test]
    #[cfg(feature = "widgets-text")]
    fn dump_widget_tree_formatting() {
        let mut ui = Ui::new(MockBackend::default());
        let win = ui.create(WidgetKind::Window, Some("Main Window")).unwrap();
        let cont = ui.create(WidgetKind::Container, None).unwrap();
        let btn = ui.create(WidgetKind::Button, Some("OK")).unwrap();
        let text = ui.create(WidgetKind::TextInput, Some("Hello")).unwrap();

        ui.attach(cont, win).unwrap();
        ui.attach(btn, cont).unwrap();
        ui.attach(text, cont).unwrap();
        ui.show(win).unwrap();

        let dump = dump_widget_tree(&ui);
        assert!(dump.contains("Window"));
        assert!(dump.contains("\"Main Window\""));
        assert!(dump.contains("Container"));
        assert!(dump.contains("Button"));
        assert!(dump.contains("\"OK\""));
        assert!(dump.contains("TextInput"));
        assert!(dump.contains("\"Hello\""));
    }
}