azul-layout 0.0.13

Layout solver + font and image loader the Azul GUI framework
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
//! Headless driver for E2E JSON scenarios.
//!
//! [`run_e2e_test`] runs an [`E2eTest`] end-to-end through the REAL server
//! op-dispatch (`super::full::process_debug_event` + the scenario runner
//! `resume_e2e_continuation`, pumped via `super::full::e2e_pump_continuation`) —
//! no HTTP, no timer, no DLL. It emulates the slice of the platform event loop
//! the E2E path needs, and it emulates it by PORTING the DLL, not by
//! approximating it:
//!
//! * [`Runner::apply_user_change`] is a port of `PlatformWindow::apply_user_change`
//!   (`dll/src/desktop/shell2/common/event.rs`) for the `CallbackChange`
//!   variants the E2E op set can produce — DOM mutation included.
//! * [`Runner::regenerate_layout`] / [`Runner::relayout_only`] port
//!   `regenerate_layout` / `incremental_relayout`
//!   (`dll/src/desktop/shell2/common/layout.rs`) plus the render + damage tail
//!   of the headless backend (`dll/src/desktop/shell2/headless/mod.rs`).
//! * [`super::cpu_backend::CpuBackend`] is the port of that backend's CPU
//!   renderer, which is what fills `LayoutWindow::frame_report` — without it
//!   every damage assertion reports "nothing was repainted (stale screen)".
//! * The font pipeline mirrors `AppInternal::create` + the font-snapshot block
//!   at the top of `regenerate_layout`, because font RESOLUTION differs between
//!   "one `FcFontCache::build()` for the whole process" and "an async registry
//!   snapshot re-installed on every DOM regeneration" — and the corpus contains
//!   a scenario (`mock_font_exact_metrics`) whose verdict depends on exactly
//!   that difference.
//!
//! The window/callback scaffolding mirrors the pattern in
//! `tests/contenteditable_e2e.rs` (LayoutWindow + `RendererResources::default()`
//! + `ExternalSystemCallbacks::rust_internal()` + `FullWindowState`).

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::Instant;

use azul_core::{
    dom::{DomId, DomNodeId, NodeId},
    events::ProcessEventResult,
    gl::OptionGlContextPtr,
    geom::{LogicalPosition, LogicalRect, LogicalSize},
    hit_test::ScrollPosition,
    refany::{OptionRefAny, RefAny},
    resources::RendererResources,
    styled_dom::{NodeHierarchyItemId, StyledDom},
    window::{MonitorVec, RawWindowHandle},
    xml::ComponentMap,
};
use azul_css::system::SystemStyle;
use rust_fontconfig::FcFontCache;

use azul_layout::{
    callbacks::{CallbackChange, CallbackInfo, CallbackInfoRefData, ExternalSystemCallbacks},
    window::{LayoutWindow, MAX_EVENT_RECURSION_DEPTH},
    window_state::FullWindowState,
};

use super::cpu_backend::CpuBackend;
use super::full::{
    process_debug_event, e2e_pump_continuation, DebugEvent, DebugRequest, DebugResponseData,
    E2eSession, E2eStepResult, E2eTest, E2eTestResult, ResponseData,
};

// ── Headless window scaffolding ──────────────────────────────────────────────

struct Runner {
    layout_window: LayoutWindow,
    renderer_resources: RendererResources,
    system_callbacks: ExternalSystemCallbacks,
    window_state: FullWindowState,
    /// The sync baseline the state-diff pass reads, i.e.
    /// `CommonWindowState::previous_window_state`. `determine_all_events`
    /// derives EVERY synthetic event (MouseDown/Up, KeyDown/Up, WindowFocusIn/
    /// Out, WindowMove/Resize) from `current` vs `previous`, so without this
    /// field the diff is always empty and no pointer or key event exists at
    /// all. Advanced by `ModifyWindowState` / `QueueWindowStateSequence`
    /// exactly where the DLL calls `set_previous_window_state`.
    previous_window_state: Option<FullWindowState>,
    /// Pointer→node resolution, i.e. `CommonWindowState::cpu_hit_tester`.
    ///
    /// The runner has no WebRender, so this is the same `CpuHitTester` the
    /// headless / CPU-mode desktop backends use, rebuilt from the layout
    /// results (see [`Runner::rebuild_hit_tester`]).
    cpu_hit_tester: azul_layout::headless::CpuHitTester,
    /// CPU renderer + retained damage state (port of the headless backend).
    cpu_backend: CpuBackend,
    /// The app-level font cache, i.e. `AppInternal::fc_cache`. Re-installed on
    /// the layout window's font manager at the top of every `regenerate_layout`,
    /// exactly like the DLL does.
    app_fc_cache: FcFontCache,
    /// The async font registry, i.e. `AppInternal::font_registry`.
    #[cfg(feature = "font_async_registry")]
    font_registry: Option<Arc<azul_layout::FcFontRegistry>>,
    /// Set by a `ModifyWindowState` whose size or DPI changed — the DLL answers
    /// that with `request_regeneration(RelayoutReason::Resize)`,
    /// which invalidates every cached rasterisation.
    resize_pending: bool,
    /// `CallbackChange`s this host could not apply faithfully (see
    /// [`Runner::unsupported`]). Non-empty ⇒ the scenario FAILS: it asked the
    /// engine to do something the headless runner cannot do, so whatever it
    /// asserted afterwards was asserted against a window where that something
    /// never happened.
    unsupported_changes: Vec<String>,
    /// The redraw a rendered frame asked for, i.e. the platform loop's
    /// `request_redraw()`.
    ///
    /// PORT of the tail of every DLL present path (x11 `mod.rs:4031`, wayland
    /// `mod.rs:4761`, windows `mod.rs:1062`/`1297`, macos `mod.rs:6334`):
    ///
    /// ```ignore
    /// // If any scrollbar is actively fading (0 < opacity < 1), schedule
    /// // another frame so the fade-out animation runs to completion.
    /// if lw.gpu_state_manager.scrollbar_fade_active { self.request_redraw(); }
    /// ```
    ///
    /// This host had no such re-arm, so the frame driven by `tick_ms` /
    /// `wait_frame` was the LAST one: a `wait` yields with a resume deadline,
    /// the pump sleeps, and `service()` then finds no pending change and
    /// renders nothing. Every state that settles on ELAPSED TIME — and the
    /// scrollbar fade, at `fade_delay` 500 ms + `fade_duration` 200 ms, is the
    /// one the corpus exercises — stayed frozen at whatever the last explicit
    /// frame left behind, so `scrollbar_fade_active` was still true when the
    /// scenario asked whether the window had settled.
    pending_redraw: bool,
}

impl Runner {
    fn new(width: f32, height: f32, dpi: u32) -> Self {
        let mut ws = FullWindowState::default();
        ws.size.dimensions = LogicalSize::new(width, height);
        ws.size.dpi = dpi;

        // Port of `AppInternal::create`'s font setup: the app starts with an
        // async registry and an EMPTY `FcFontCache` (or a disk-cache snapshot);
        // the cache is populated from the registry at the first layout. This is
        // NOT the same as handing the window one eagerly-built `FcFontCache`:
        // the registry snapshot replaces the window's cache handle, which is
        // what makes in-memory (`register_named_font`) families behave the way
        // they do in a real app.
        #[cfg(feature = "font_async_registry")]
        let (app_fc_cache, font_registry) = {
            // `FcFontRegistry::new()` already returns an `Arc<Self>`.
            let registry = azul_layout::FcFontRegistry::new();
            let had_cache = registry.load_from_disk_cache();
            registry.spawn_scout_and_builders();
            // DETERMINISM: block until the scout has published the font set
            // (no-op when a disk cache was loaded; 5 s cap inside).
            //
            // Without this the fonts a DOM resolves depend on HOW FAR the
            // background builders happened to get before that particular
            // layout ran — so the same scenario resolves a 1-font fallback
            // chain when a step services a mount immediately and a 7-font one
            // when a `wait` delays it, and any assertion over font resources
            // silently measures thread scheduling. A verdict that moves with
            // background-thread progress is exactly the flake class this suite
            // exists to eliminate.
            registry.wait_for_scout();
            let cache = if had_cache.is_some() {
                registry.shared_cache()
            } else {
                FcFontCache::default()
            };
            (cache, Some(registry))
        };
        #[cfg(not(feature = "font_async_registry"))]
        let app_fc_cache = FcFontCache::build();

        Self {
            layout_window: LayoutWindow::new(app_fc_cache.clone()).expect("LayoutWindow::new"),
            renderer_resources: RendererResources::default(),
            system_callbacks: ExternalSystemCallbacks::rust_internal(),
            window_state: ws,
            previous_window_state: None,
            cpu_hit_tester: azul_layout::headless::CpuHitTester::new(),
            cpu_backend: CpuBackend::new(),
            app_fc_cache,
            #[cfg(feature = "font_async_registry")]
            font_registry,
            resize_pending: false,
            unsupported_changes: Vec::new(),
            pending_redraw: false,
        }
    }

    fn now(&self) -> azul_core::task::Instant {
        (self.system_callbacks.get_system_time_fn.cb)()
    }

    /// Build a `CallbackInfo` over the current window/state and run `f` with it.
    /// `ref_data` and the transient locals it borrows are dropped when `f`
    /// returns, releasing the borrow so the caller can relayout.
    fn with_callback_info<R>(
        &mut self,
        changes: &Arc<Mutex<Vec<CallbackChange>>>,
        f: impl FnOnce(&mut CallbackInfo) -> R,
    ) -> R {
        let previous_window_state: Option<FullWindowState> = None;
        let gl_context = OptionGlContextPtr::None;
        let scroll_states: BTreeMap<DomId, BTreeMap<NodeHierarchyItemId, ScrollPosition>> =
            BTreeMap::new();
        let window_handle = RawWindowHandle::Unsupported;

        let ref_data = CallbackInfoRefData {
            layout_window: &self.layout_window,
            renderer_resources: &self.renderer_resources,
            previous_window_state: &previous_window_state,
            current_window_state: &self.window_state,
            gl_context: &gl_context,
            current_scroll_manager: &scroll_states,
            current_window_handle: &window_handle,
            system_callbacks: &self.system_callbacks,
            system_style: Arc::new(SystemStyle::default()),
            monitors: Arc::new(Mutex::new(MonitorVec::from_const_slice(&[]))),
            #[cfg(feature = "icu")]
            icu_localizer: crate::icu::IcuLocalizerHandle::default(),
            ctx: OptionRefAny::None,
        };

        let mut callback_info = CallbackInfo::new(
            &ref_data,
            changes,
            DomNodeId { dom: DomId::ROOT_ID, node: NodeHierarchyItemId::NONE },
            azul_core::geom::OptionLogicalPosition::None,
            azul_core::geom::OptionLogicalPosition::None,
        );
        f(&mut callback_info)
    }

    /// Run the full layout pipeline for `styled_dom` and re-register scroll nodes.
    fn layout(&mut self, styled_dom: StyledDom) {
        let mut dbg = Some(Vec::new());
        self.layout_window
            .layout_and_generate_display_list(
                styled_dom,
                &self.window_state,
                &self.renderer_resources,
                &self.system_callbacks,
                &mut dbg,
            )
            .expect("layout_and_generate_display_list");
        self.register_scroll_nodes();
        self.rebuild_hit_tester();
    }

    /// Rebuild [`Runner::cpu_hit_tester`] from the current layout results.
    ///
    /// Port of the headless backend's post-`regenerate_layout` rebuild
    /// (`dll/.../shell2/headless/mod.rs`), which carries this comment: *without
    /// this rebuild that tester stays empty, so every click hit-tests to
    /// nothing and widget callbacks never fire*.
    ///
    /// Called from exactly two places, and both are load-bearing:
    ///
    /// * [`Runner::layout`] — the single funnel every layout pass goes through
    ///   (`regenerate_layout` for mount / remount / resize / DPI, and
    ///   `relayout_only` for an in-place DOM or style mutation). Rebuilding
    ///   here is what keeps a `click` after a `set_node_text` from testing the
    ///   pre-mutation geometry.
    /// * the tail of [`Runner::service`] — the paths that produce a new frame
    ///   WITHOUT running layout (`ShouldReRenderCurrentWindow`,
    ///   `ShouldUpdateDisplayListCurrentWindow`,
    ///   `UpdateHitTesterAndProcessAgain` — the last one names it outright) all
    ///   land there, and a display-list rebuild can move the `VirtualView`
    ///   placements this tester translates child DOMs by. It also guarantees
    ///   the invariant that actually matters: at the START of every op the
    ///   tester agrees with the frame on screen. A stale tester does not fail
    ///   loudly — it silently answers with the WRONG node, which is worse than
    ///   the `unsupported` refusal this replaced.
    fn rebuild_hit_tester(&mut self) {
        self.cpu_hit_tester
            .rebuild_from_layout(&self.layout_window.layout_results);
    }

    /// Port of `PlatformWindow::update_hit_test_at`
    /// (`dll/src/desktop/shell2/common/event.rs`): resolve the pointer position
    /// to nodes and publish the result on the hover manager, which is where
    /// `determine_all_events` reads the mouse target from and where
    /// `CallbackInfo::get_hit_node` / text selection look it up.
    ///
    /// The CPU→`FullHitTest` conversion is the SAME function the desktop
    /// shells' `perform_hit_test` uses
    /// ([`azul_layout::headless::convert_cpu_hit_test_to_full`]) — not a
    /// re-derivation.
    fn update_hit_test_at(&mut self, position: LogicalPosition) {
        use azul_layout::managers::hover::InputPointId;

        let focused_node = self.layout_window.focus_manager.get_focused_node().copied();
        let hits = self.cpu_hit_tester.hit_test(position);
        let hit_test = azul_layout::headless::convert_cpu_hit_test_to_full(
            &hits,
            focused_node,
            &self.layout_window.layout_results,
            position,
        );
        self.layout_window
            .hover_manager
            .push_hit_test(InputPointId::Mouse, hit_test);
    }

    /// Publish one hit test per live touch point and drive the gesture
    /// manager's per-finger sessions.
    ///
    /// This is the port of the X11 XI2 touch handler
    /// (`dll/src/desktop/shell2/linux/x11/mod.rs`), which does exactly these
    /// two things next to writing `touch_state`: it feeds
    /// `gesture_drag_manager.touch_down/touch_move/touch_up` (what
    /// `detect_pinch` / `detect_rotation` / `detect_swipe_direction` consume)
    /// and lets the state-diff pass derive the touch events.
    ///
    /// DELIBERATE DEVIATION: the shells pass the pointer's SCREEN position as
    /// the second coordinate; a headless window has no screen, so the window
    /// position is reused. Only multi-window gesture bookkeeping reads it.
    fn sync_touch_points(&mut self, old_points: &[azul_core::window::TouchPoint]) {
        use azul_layout::managers::hover::InputPointId;

        let now = self.now();
        let window_position = self.window_state.position;
        let focused_node = self.layout_window.focus_manager.get_focused_node().copied();
        let new_points: Vec<azul_core::window::TouchPoint> =
            self.window_state.touch_state.touch_points.as_ref().to_vec();

        for point in &new_points {
            let hits = self.cpu_hit_tester.hit_test(point.position);
            let hit_test = azul_layout::headless::convert_cpu_hit_test_to_full(
                &hits,
                focused_node,
                &self.layout_window.layout_results,
                point.position,
            );
            self.layout_window
                .hover_manager
                .push_hit_test(InputPointId::Touch(point.id), hit_test);

            match old_points.iter().find(|q| q.id == point.id) {
                None => self.layout_window.gesture_drag_manager.touch_down(
                    point.id,
                    point.position,
                    now.clone(),
                    window_position,
                    point.position,
                ),
                Some(before) if before.position != point.position => {
                    let _ = self.layout_window.gesture_drag_manager.touch_move(
                        point.id,
                        point.position,
                        now.clone(),
                        point.position,
                    );
                }
                Some(_) => {}
            }
        }
        for point in old_points {
            if !new_points.iter().any(|p| p.id == point.id) {
                self.layout_window.gesture_drag_manager.touch_up(
                    point.id,
                    point.position,
                    now.clone(),
                    point.position,
                );
            }
        }
    }

    /// Drop the hover history of every touch point that is no longer down.
    ///
    /// Runs at the END of [`Runner::service`], not inside
    /// [`Runner::sync_touch_points`]: `determine_all_events` resolves the
    /// TARGET of a `TouchEnd` through that history, so purging before the pass
    /// would send every touch-up to the mouse target instead of to the node the
    /// finger was actually on. Purging afterwards keeps
    /// `HoverManager::hover_histories` from growing one entry per touch id
    /// forever, which is exactly the kind of per-interaction growth the
    /// `[idle/growth]` family exists to catch.
    fn purge_ended_touch_points(&mut self) {
        use azul_layout::managers::hover::InputPointId;

        let live: Vec<u64> = self
            .window_state
            .touch_state
            .touch_points
            .as_ref()
            .iter()
            .map(|p| p.id)
            .collect();
        let stale: Vec<InputPointId> = self
            .layout_window
            .hover_manager
            .get_active_input_points()
            .into_iter()
            .filter(|id| matches!(id, InputPointId::Touch(t) if !live.contains(t)))
            .collect();
        for id in stale {
            self.layout_window.hover_manager.remove_input_point(&id);
        }
    }

    /// Apply the `CallbackChange`s the runner pushed this pump, then finish the
    /// frame the way the platform event loop does.
    ///
    /// `needs_update` is the debug-op `needs_update` flag: the DLL's debug timer
    /// returns `Update::RefreshDom` for it, which the event loop turns into a
    /// full `regenerate_layout()`.
    fn service(&mut self, changes: &Arc<Mutex<Vec<CallbackChange>>>, needs_update: bool) {
        let drained = changes
            .lock()
            .map(|mut c| std::mem::take(&mut *c))
            .unwrap_or_default();

        // Each change is applied IN ORDER, as it is drained — NOT collapsed into
        // "the last one wins". The real shell runs `apply_user_change` once per
        // change and takes the MAX of the results; collapsing loses transient
        // states (a `key_down`+`key_up` pair that lands in a single continuation
        // slice would leave only the key-RELEASED state, and Tab-to-focus-next
        // would silently do nothing).
        // The redraw the PREVIOUS frame asked for (see `pending_redraw`). The
        // platform loops service `request_redraw()` on the next turn of the
        // loop, which is exactly here — and it is the only thing that lets a
        // time-driven animation advance across a step that pushes no change of
        // its own (`wait`).
        let mut result = if core::mem::take(&mut self.pending_redraw) {
            ProcessEventResult::ShouldReRenderCurrentWindow
        } else {
            ProcessEventResult::DoNothing
        };
        for ch in drained {
            result = result.max(self.apply_user_change(&ch));
        }
        // Timers, AFTER this pass's changes: an op that ARMS a timer (focusing a
        // contenteditable arms the caret blink) has to have armed it before the
        // pump looks, or the timer would always be one op late.
        result = result.max(self.pump_timers());
        if needs_update {
            result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
        }
        // A pending mount/unmount always needs the DOM rebuilt, even if the op
        // that produced it somehow did not set `needs_update`. (`RemountDom`
        // already returns `ShouldRegenerateDomCurrentWindow` from
        // `apply_user_change`; this covers a mount left dirty by an earlier
        // pass that never got to regenerate.)
        if self.layout_window.e2e_mount.is_dirty() {
            result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
        }
        // A size/DPI change invalidates every rasterised pixel — same thing
        // WM_DPICHANGED / the X11 DPI path do (`request_regeneration`).
        if self.resize_pending {
            result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
        }

        self.layout_window.sync_frame_report();
        self.layout_window.frame_report.terminal_result = result as u8;

        match result {
            ProcessEventResult::DoNothing => {}
            ProcessEventResult::ShouldRegenerateDomCurrentWindow
            | ProcessEventResult::ShouldRegenerateDomAllWindows => self.regenerate_layout(),
            ProcessEventResult::ShouldIncrementalRelayout => self.relayout_only(),
            // The name IS the contract. A paint-only restyle (`:hover` /
            // `:focus` changing a colour) mutates the styled DOM's property
            // cache and asks for exactly this — but the DISPLAY LIST still
            // carries the old paint, so rendering without rebuilding it shows
            // the pre-restyle pixels and reports zero damage.
            //
            // This was invisible while every pointer op set `needs_update`: the
            // forced `regenerate_layout()` rebuilt the display list as a side
            // effect, so `:hover` appeared to work for the wrong reason. With
            // the op no longer fabricating that rebuild, the arm has to do the
            // work its own name promises.
            //
            // `UpdateHitTesterAndProcessAgain` is grouped here because it ranks
            // ABOVE `ShouldUpdateDisplayListCurrentWindow` in
            // `ProcessEventResult`'s order — it may never do less work than the
            // result it dominates. (The real shells map it to a full
            // regeneration; a display-list rebuild is the floor, not the cap.)
            ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            | ProcessEventResult::UpdateHitTesterAndProcessAgain => {
                self.layout_window.regenerate_display_list_for_dom(DomId::ROOT_ID);
                self.render_and_record();
            }
            ProcessEventResult::ShouldReRenderCurrentWindow => self.render_and_record(),
        }

        // Keep servicing the redraws the frames themselves ask for, until the
        // window stops changing. The platform loops do this across turns of the
        // event loop; here it has to happen INSIDE one `service()`, because the
        // next thing the pump runs is the scenario's next step — and if that
        // step is an idleness assertion, it reads whatever this call left
        // behind. The scrollbar fade is 700 ms of WALL CLOCK (`fade_delay` 500 +
        // `fade_duration` 200) and each headless frame costs about a
        // millisecond, so this is a real-time-paced loop, exactly like a shell
        // redrawing at the display's rate — not a spin that fabricates time.
        self.pump_pending_redraws();

        // The frame is now final for this op. Re-derive the pointer→node map
        // from it so the NEXT op's hit test cannot read geometry that a
        // display-list-only path (the render-only arms above) just moved. See
        // [`Runner::rebuild_hit_tester`].
        self.rebuild_hit_tester();
        self.purge_ended_touch_points();
    }

    /// Run every timer that is due, i.e. the timer half of the DLL's
    /// `PlatformWindow::process_timers_and_threads` +
    /// `PlatformWindow::invoke_expired_timers`
    /// (`dll/src/desktop/shell2/common/event.rs`).
    ///
    /// WHY IT EXISTS: `AddTimer` / `RemoveTimer` / `StartCursorBlinkTimer` /
    /// `StopCursorBlinkTimer` were all declared `unsupported("no timer driver")`
    /// — every one of `LayoutWindow`'s pieces (`tick_timers`, `run_single_timer`,
    /// `time_until_next_timer_ms`) existed, but nothing in this host ever drove
    /// them. Caret blink was therefore untestable and any behaviour that only
    /// happens on a timer expiry could not be expressed as a scenario.
    ///
    /// TIME. `Instant::now()` honours the thread-scoped test clock that the
    /// `tick_ms` op advances (`azul_core::task::advance_test_clock_ms`), so a
    /// scenario drives timers by *asserting* time rather than by sleeping
    /// through it: `tick_ms 600` expires a 530 ms blink, deterministically, in
    /// microseconds.
    ///
    /// READINESS is decided by `Timer::invoke`, not here — `tick_timers`
    /// deliberately returns every registered timer and `invoke` returns
    /// `DoNothing`/`Continue` for one whose delay or interval has not elapsed.
    /// That is why pumping on every `service()` is cheap and correct rather
    /// than a spin.
    ///
    /// The `Update` a timer callback returns is NOT the only way a rebuild gets
    /// requested (465060f5b): `apply_user_change` runs a whole event pass for
    /// `ModifyWindowState` / `CreateTextInput`, and a user callback dispatched
    /// inside it can itself return `Update::RefreshDom`, which surfaces as a
    /// `ShouldRegenerateDom*` RESULT. Folding both into one `max` is what keeps
    /// a requested DOM rebuild from being downgraded to a relayout of the DOM it
    /// was supposed to replace — the bug just fixed on the DLL side.
    fn pump_timers(&mut self) -> ProcessEventResult {
        use azul_core::callbacks::Update;
        use azul_core::task::TimerId;

        if self.layout_window.timers.is_empty() {
            return ProcessEventResult::DoNothing;
        }

        let frame_start = self.now();
        let due: Vec<TimerId> = self.layout_window.tick_timers(frame_start.clone());

        let window_handle = RawWindowHandle::Unsupported;
        let gl_context = OptionGlContextPtr::None;

        let mut result = ProcessEventResult::DoNothing;
        let mut needs_dom_regeneration = false;

        for timer_id in due {
            let (changes, update) = {
                let Self {
                    layout_window,
                    window_state,
                    previous_window_state,
                    renderer_resources,
                    system_callbacks,
                    ..
                } = self;
                layout_window.run_single_timer(
                    timer_id.id,
                    frame_start.clone(),
                    &window_handle,
                    &gl_context,
                    Arc::new(SystemStyle::default()),
                    system_callbacks,
                    previous_window_state,
                    window_state,
                    renderer_resources,
                )
            };

            // Applied IMMEDIATELY, before the next timer runs, so inter-timer
            // visibility works: a timer that removes another timer must actually
            // have removed it by the time that one is reached. (A `Timer` that
            // asked to terminate arrives here as a `RemoveTimer` change appended
            // by `run_single_timer` itself.)
            for change in &changes {
                result = result.max(self.apply_user_change(change));
            }
            if matches!(update, Update::RefreshDom | Update::RefreshDomAllWindows) {
                needs_dom_regeneration = true;
            }
        }

        if needs_dom_regeneration {
            result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
        }
        result
    }

    /// Service the redraws a rendered frame asked for (`pending_redraw`), until
    /// the window stops changing.
    ///
    /// The cap is a SAFETY NET for a flag that never clears, not the expected
    /// exit: the scrollbar fade is driven by a monotonic clock, so it always
    /// terminates on its own. Hitting the cap deliberately leaves the state
    /// machine visibly un-settled rather than hanging the run — which is the
    /// outcome `assert_state_machines_idle` exists to report.
    fn pump_pending_redraws(&mut self) {
        const MAX_REDRAW_FRAMES: usize = 4096;
        let mut frames = 0usize;
        while self.pending_redraw && frames < MAX_REDRAW_FRAMES {
            self.render_and_record();
            frames += 1;
        }
    }

    /// Port of `PlatformWindow::process_window_events`
    /// (`dll/src/desktop/shell2/common/event.rs`) — the state-diff pass, and the
    /// thing `FrameReport::relayout_iterations` counts.
    ///
    /// The DLL records `max(depth + 1)` in an observability wrapper around this
    /// function and sets `hit_depth_cap` when the recursion is broken off at
    /// `MAX_EVENT_RECURSION_DEPTH`. Both are ported here VERBATIM, because the
    /// number an assertion reads has to mean the same thing in both hosts:
    ///
    /// * `0` — no event pass ran at all. That is what an idle frame looks like:
    ///   a clock tick with no state delta produces a repaint and nothing else.
    /// * `1` — one pass, converged.
    /// * `>1` — the pass had to be re-entered (a callback changed state that
    ///   raised new events); this is the invalidation-loop signal.
    ///
    /// Before this existed the runner hard-coded `1` inside the
    /// `ModifyWindowState` arm, so an idle frame reported the same number as a
    /// converged event pass and `assert_work_bounded` could not tell "no work"
    /// from "one pass of work".
    ///
    /// The pass itself mirrors the DLL's ordering: determine events → `:hover`
    /// restyle → user callbacks → click-to-focus → keyboard default action →
    /// focus events → re-entry. It used to run ONLY the keyboard branch, which
    /// is why no pointer op could focus a node headlessly.
    fn process_window_events(&mut self, depth: usize) -> ProcessEventResult {
        #[allow(clippy::cast_possible_truncation)]
        let depth_u32 = depth as u32;
        self.layout_window.sync_frame_report();
        let r = &mut self.layout_window.frame_report;
        r.relayout_iterations = r.relayout_iterations.max(depth_u32 + 1);

        if depth >= MAX_EVENT_RECURSION_DEPTH {
            // The DLL log_warn's here and returns; the flag is what turns that
            // silent cap into a red assertion.
            self.layout_window.frame_report.hit_depth_cap = true;
            return ProcessEventResult::DoNothing;
        }

        // ── 1. EVENT DETERMINATION ───────────────────────────────────────
        //
        // `determine_all_events` is the ONLY thing that turns a window-state
        // delta into events. It reads the pointer target off the hover
        // manager, which the callers of this pass (`ModifyWindowState`,
        // `QueueWindowStateSequence`, `RequestHitTestUpdate`) fill in via
        // `update_hit_test_at` — exactly as the DLL's platform layer does
        // before calling `process_window_events`.
        let previous_state = self
            .previous_window_state
            .clone()
            .unwrap_or_else(|| self.window_state.clone());
        let timestamp = self.now();
        let wheel_delta = self.layout_window.scroll_manager.pending_wheel_event;
        let synthetic_events = {
            let lw = &self.layout_window;
            let providers: Vec<&dyn azul_core::events::EventProvider> = vec![
                &lw.text_input_manager,
                &lw.sensor_manager,
                &lw.gamepad_manager,
                &lw.geolocation_manager,
                &lw.permission_manager,
                &lw.biometric_manager,
                &lw.keyring_manager,
            ];
            azul_layout::event_determination::determine_all_events(
                &self.window_state,
                &previous_state,
                &lw.hover_manager,
                &lw.focus_manager,
                &lw.file_drop_manager,
                Some(&lw.gesture_drag_manager),
                &providers,
                wheel_delta,
                timestamp,
            )
        };

        // Clear the one-shot pending-event flags now that this pass has
        // collected them — one event per change, not one per frame (the DLL
        // does this at the same point, right after determination).
        {
            let lw = &mut self.layout_window;
            lw.sensor_manager.clear_pending_event();
            lw.gamepad_manager.clear_pending_event();
            lw.geolocation_manager.clear_pending_event();
            lw.permission_manager.clear_pending_changed();
            lw.biometric_manager.clear_pending_event();
            lw.keyring_manager.clear_pending_event();
            lw.gesture_drag_manager.clear_pen_event_pending();
            lw.gesture_drag_manager.clear_native_gesture();
        }

        if synthetic_events.is_empty() {
            return ProcessEventResult::DoNothing;
        }

        let mut result = ProcessEventResult::DoNothing;

        // ── 2. INCREMENTAL `:hover` RESTYLE ──────────────────────────────
        // Enter/leave targets of THIS pass, restyled now so pure-CSS `:hover`
        // rules take effect without a DOM regeneration.
        {
            let mut per_dom: BTreeMap<DomId, azul_core::styled_dom::HoverChange> = BTreeMap::new();
            for ev in &synthetic_events {
                let is_enter = ev.event_type == azul_core::events::EventType::MouseEnter;
                let is_leave = ev.event_type == azul_core::events::EventType::MouseLeave;
                if !is_enter && !is_leave {
                    continue;
                }
                let Some(node) = ev.target.node.into_crate_internal() else {
                    continue;
                };
                let entry = per_dom.entry(ev.target.dom).or_insert_with(|| {
                    azul_core::styled_dom::HoverChange {
                        left_nodes: Vec::new(),
                        entered_nodes: Vec::new(),
                    }
                });
                if is_enter {
                    entry.entered_nodes.push(node);
                } else {
                    entry.left_nodes.push(node);
                }
            }
            if !per_dom.is_empty() {
                result = result.max(apply_hover_restyle(&mut self.layout_window, per_dom));
            }
        }

        // The hit test the callbacks (and the click-to-focus pass below) see.
        let hit_test_for_dispatch = self
            .layout_window
            .hover_manager
            .get_current(&azul_layout::managers::hover::InputPointId::Mouse)
            .cloned();

        // ── 3. USER CALLBACK DISPATCH (W3C capture → target → bubble) ────
        let old_focus = self.layout_window.focus_manager.get_focused_node().copied();
        let (changes_result, callback_update, prevent_default) =
            self.dispatch_events_propagated(&synthetic_events);
        result = result.max(changes_result);

        // The wheel delta has now been delivered; clear it so no later pass
        // re-fires a stale Scroll event.
        self.layout_window.scroll_manager.pending_wheel_event = None;

        let mut should_recurse = false;
        if matches!(
            callback_update,
            azul_core::callbacks::Update::RefreshDom
                | azul_core::callbacks::Update::RefreshDomAllWindows
        ) {
            result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
            should_recurse = true;
        }

        // ── 4. MOUSE CLICK-TO-FOCUS (W3C default action) ─────────────────
        // The deepest focusable ancestor of the deepest hit node takes focus
        // on MouseDown. This is the default action that makes `click` able to
        // focus anything at all — before the hit tester was wired, the ONLY
        // way to move focus headlessly was Tab.
        let mut mouse_click_focus_changed = false;
        if !prevent_default
            && synthetic_events
                .iter()
                .any(|e| e.event_type == azul_core::events::EventType::MouseDown)
        {
            let clicked_focusable_node = hit_test_for_dispatch.as_ref().and_then(|hit_test| {
                let mut found: Option<DomNodeId> = None;
                for (dom_id, hit_test_data) in &hit_test.hovered_nodes {
                    let deepest = hit_test_data
                        .regular_hit_test_nodes
                        .iter()
                        .max_by_key(|(_, hit_item)| core::cmp::Reverse(hit_item.hit_depth));
                    let Some((node_id, _)) = deepest else { continue };
                    let Some(layout_result) = self.layout_window.layout_results.get(dom_id) else {
                        continue;
                    };
                    let node_data = layout_result.styled_dom.node_data.as_container();
                    let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
                    let mut current = Some(*node_id);
                    while let Some(nid) = current {
                        if node_data.get(nid).is_some_and(azul_core::dom::NodeData::is_focusable) {
                            found = Some(DomNodeId {
                                dom: *dom_id,
                                node: NodeHierarchyItemId::from_crate_internal(Some(nid)),
                            });
                            break;
                        }
                        current = node_hierarchy.get(nid).and_then(|h| h.parent_id());
                    }
                }
                found
            });

            if let Some(new_focus_target) = clicked_focusable_node {
                if old_focus.and_then(|f| f.node.into_crate_internal())
                    != new_focus_target.node.into_crate_internal()
                {
                    result = result.max(self.set_focus(Some(new_focus_target), old_focus));
                    mouse_click_focus_changed = true;
                }
            }
        }

        // ── 5. KEYBOARD DEFAULT ACTIONS (Tab / Shift+Tab / Escape) ───────
        // Gated on a KeyDown in THIS pass, like the DLL. Before that gate
        // existed the runner re-ran the action on every recursion level, so a
        // single Tab walked the focus ring MAX_EVENT_RECURSION_DEPTH times and
        // set `hit_depth_cap` on every key press (it only produced the right
        // answer because 7 steps over 3 focusables is a net +1).
        let mut default_action_focus_changed = false;
        if !prevent_default
            && synthetic_events
                .iter()
                .any(|e| e.event_type == azul_core::events::EventType::KeyDown)
        {
            let (r, changed) = self.run_keyboard_default_action();
            result = result.max(r);
            default_action_focus_changed = changed;
        }

        // ── 6. FOCUS EVENTS + RE-ENTRY ───────────────────────────────────
        if (default_action_focus_changed || mouse_click_focus_changed)
            && depth + 1 < MAX_EVENT_RECURSION_DEPTH
        {
            let new_focus = self.layout_window.focus_manager.get_focused_node().copied();

            // Collapse any selection: standard UI behaviour on focus change.
            if let Some(mc) = self.layout_window.text_edit_manager.multi_cursor.as_mut() {
                if let Some(cursor) = mc.get_primary_cursor() {
                    mc.set_single_cursor(cursor);
                }
            }

            let now = self.now();
            let mut focus_events = Vec::new();
            if let Some(old_node) = old_focus {
                focus_events.push(azul_core::events::SyntheticEvent::new(
                    azul_core::events::EventType::Blur,
                    azul_core::events::EventSource::User,
                    old_node,
                    now.clone(),
                    azul_core::events::EventData::None,
                ));
            }
            if let Some(new_node) = new_focus {
                focus_events.push(azul_core::events::SyntheticEvent::new(
                    azul_core::events::EventType::Focus,
                    azul_core::events::EventSource::User,
                    new_node,
                    now,
                    azul_core::events::EventData::None,
                ));
            }
            if !focus_events.is_empty() {
                let (focus_result, focus_update, _) =
                    self.dispatch_events_propagated(&focus_events);
                result = result.max(focus_result);
                if matches!(
                    focus_update,
                    azul_core::callbacks::Update::RefreshDom
                        | azul_core::callbacks::Update::RefreshDomAllWindows
                ) {
                    result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
                }
            }

            // CRITICAL (verbatim from the DLL): advance the sync baseline
            // BEFORE recursing, or the SAME MouseDown / Tab is re-detected at
            // depth+1 and its default action fires again on every level.
            self.previous_window_state = Some(self.window_state.clone());
            result = result.max(self.process_window_events(depth + 1));
        } else if should_recurse && depth + 1 < MAX_EVENT_RECURSION_DEPTH {
            self.previous_window_state = Some(self.window_state.clone());
            result = result.max(self.process_window_events(depth + 1));
        }

        // Finalize pending focus changes (caret init for contenteditable) —
        // the DLL's end-of-pass `SystemChange::FinalizePendingFocusChanges`.
        self.layout_window.finalize_pending_focus_changes();

        // DELIBERATE DEVIATION, floored not faithful: the DLL returns `result`
        // as-is, so a pass whose events changed nothing observable returns
        // DoNothing and the shell skips the frame. This host's damage
        // machinery is fed by `render_and_record` (see `Runner::service`), and
        // an event pass that produced no frame at all leaves the frame report
        // describing the PREVIOUS op. Flooring at "repaint" costs an extra
        // no-damage render and never hides one.
        result.max(ProcessEventResult::ShouldReRenderCurrentWindow)
    }

    /// Port of the DLL's `apply_system_change(SystemChange::SetFocus { .. })`:
    /// move focus, scroll the new node into view, and apply the `:focus`
    /// restyle so focus styling lands on THIS frame instead of the next resize.
    fn set_focus(
        &mut self,
        new_focus: Option<DomNodeId>,
        old_focus: Option<DomNodeId>,
    ) -> ProcessEventResult {
        use azul_layout::managers::scroll_into_view::ScrollIntoViewOptions;

        let old_focus_node_id = old_focus.and_then(|f| f.node.into_crate_internal());
        let new_focus_node_id = new_focus.and_then(|f| f.node.into_crate_internal());

        let now = self.now();
        let window_state = self.window_state.clone();
        let lw = &mut self.layout_window;
        lw.focus_manager.set_focused_node(new_focus);
        if let Some(focus_node) = new_focus {
            lw.scroll_node_into_view(focus_node, ScrollIntoViewOptions::nearest(), now);
        }
        arm_caret_for_focus(lw, new_focus, &window_state);

        let mut result = ProcessEventResult::ShouldReRenderCurrentWindow;
        if old_focus_node_id != new_focus_node_id {
            result = result.max(apply_focus_restyle(lw, old_focus_node_id, new_focus_node_id));
        }
        result
    }

    /// Port of `PlatformWindow::dispatch_events_propagated`
    /// (`dll/src/desktop/shell2/common/event.rs`): plan the callback
    /// invocations for a batch of `SyntheticEvent`s using the W3C
    /// capture→target→bubble model, invoke them, then apply every
    /// `CallbackChange` they produced through [`Runner::apply_user_change`].
    ///
    /// Returns `(max ProcessEventResult, merged Update, any preventDefault)`.
    /// `preventDefault` is what suppresses the click-to-focus and keyboard
    /// default actions above, so this cannot be short-circuited to "no
    /// callbacks exist in an XML mount" — a scenario that mounts a component
    /// carrying callbacks would then silently take the default action anyway.
    #[allow(clippy::too_many_lines)]
    fn dispatch_events_propagated(
        &mut self,
        events: &[azul_core::events::SyntheticEvent],
    ) -> (ProcessEventResult, azul_core::callbacks::Update, bool) {
        use azul_core::{
            callbacks::{CoreCallbackData, Update},
            events::EventFilter,
            id::NodeId as CoreNodeId,
        };

        struct PlannedInvocation {
            dom_id: DomId,
            node_id: NodeId,
            callback_data: CoreCallbackData,
        }

        // Phase 1 — build the dispatch plan (read-only over the layout window).
        let planned_callbacks: Vec<PlannedInvocation> = {
            let lw = &self.layout_window;
            let focused_node = lw.focus_manager.get_focused_node().copied();
            let mut planned = Vec::new();

            for event in events {
                let event_filters =
                    azul_core::events::event_type_to_filters(event.event_type, &event.data);

                for filter in &event_filters {
                    match filter {
                        EventFilter::Hover(_) => {
                            let dom_id = event.target.dom;
                            let Some(layout_result) = lw.layout_results.get(&dom_id) else {
                                continue;
                            };

                            let node_hierarchy = {
                                let items = layout_result.styled_dom.node_hierarchy.as_container();
                                let nodes: Vec<azul_core::id::Node> = (0..items.len())
                                    .map(|i| {
                                        let item = &items.internal[i];
                                        azul_core::id::Node {
                                            parent: CoreNodeId::from_usize(item.parent),
                                            previous_sibling: CoreNodeId::from_usize(
                                                item.previous_sibling,
                                            ),
                                            next_sibling: CoreNodeId::from_usize(item.next_sibling),
                                            last_child: CoreNodeId::from_usize(item.last_child),
                                        }
                                    })
                                    .collect();
                                azul_core::id::NodeHierarchy::new(nodes)
                            };

                            let node_data_container =
                                layout_result.styled_dom.node_data.as_container();
                            let mut callback_map: BTreeMap<CoreNodeId, Vec<EventFilter>> =
                                BTreeMap::new();
                            for node_idx in 0..node_data_container.len() {
                                let node_id = CoreNodeId::new(node_idx);
                                if let Some(nd) = node_data_container.get(node_id) {
                                    let matching: Vec<EventFilter> = nd
                                        .get_callbacks()
                                        .as_ref()
                                        .iter()
                                        .filter(|cb| cb.event == *filter)
                                        .map(|cb| cb.event)
                                        .collect();
                                    if !matching.is_empty() {
                                        callback_map.insert(node_id, matching);
                                    }
                                }
                            }
                            if callback_map.is_empty() {
                                continue;
                            }

                            let mut event_clone = event.clone();
                            let prop_result = azul_core::events::propagate_event(
                                &mut event_clone,
                                &node_hierarchy,
                                &callback_map,
                            );

                            for (node_id, matched_filter) in &prop_result.callbacks_to_invoke {
                                let Some(nd) = node_data_container.get(*node_id) else {
                                    continue;
                                };
                                for cb in nd.get_callbacks().as_ref() {
                                    if cb.event == *matched_filter {
                                        planned.push(PlannedInvocation {
                                            dom_id,
                                            node_id: *node_id,
                                            callback_data: cb.clone(),
                                        });
                                    }
                                }
                            }
                        }
                        EventFilter::Focus(_) => {
                            // Focus events fire on the focused node only.
                            let Some(focused) = focused_node else { continue };
                            let Some(node_id) = focused.node.into_crate_internal() else {
                                continue;
                            };
                            let Some(lr) = lw.layout_results.get(&focused.dom) else {
                                continue;
                            };
                            let ndc = lr.styled_dom.node_data.as_container();
                            let Some(nd) = ndc.get(node_id) else { continue };
                            for cb in nd.get_callbacks().as_ref() {
                                if cb.event == *filter {
                                    planned.push(PlannedInvocation {
                                        dom_id: focused.dom,
                                        node_id,
                                        callback_data: cb.clone(),
                                    });
                                }
                            }
                        }
                        EventFilter::Window(_) | EventFilter::Application(_) => {
                            // Window / Application events fire on EVERY node
                            // carrying a matching callback.
                            for (dom_id, lr) in &lw.layout_results {
                                let ndc = lr.styled_dom.node_data.as_container();
                                for node_idx in 0..ndc.len() {
                                    let node_id = CoreNodeId::new(node_idx);
                                    let Some(nd) = ndc.get(node_id) else { continue };
                                    for cb in nd.get_callbacks().as_ref() {
                                        if cb.event == *filter {
                                            planned.push(PlannedInvocation {
                                                dom_id: *dom_id,
                                                node_id,
                                                callback_data: cb.clone(),
                                            });
                                        }
                                    }
                                }
                            }
                        }
                        EventFilter::Component(_) => {
                            // Lifecycle events carry their target node; no
                            // propagation.
                            let dom_id = event.target.dom;
                            let Some(node_id) = event.target.node.into_crate_internal() else {
                                continue;
                            };
                            let Some(lr) = lw.layout_results.get(&dom_id) else {
                                continue;
                            };
                            let ndc = lr.styled_dom.node_data.as_container();
                            let Some(nd) = ndc.get(node_id) else { continue };
                            for cb in nd.get_callbacks().as_ref() {
                                if cb.event == *filter {
                                    planned.push(PlannedInvocation {
                                        dom_id,
                                        node_id,
                                        callback_data: cb.clone(),
                                    });
                                }
                            }
                        }
                    }
                }
            }
            planned
        };

        if planned_callbacks.is_empty() {
            return (ProcessEventResult::DoNothing, Update::DoNothing, false);
        }

        // Phase 2 — invoke.
        let previous_window_state = self.previous_window_state.clone();
        let gl_context = OptionGlContextPtr::None;
        let window_handle = RawWindowHandle::Unsupported;
        let system_style = Arc::new(SystemStyle::default());

        let mut all_updates: Vec<Update> = Vec::new();
        let mut all_changes: Vec<CallbackChange> = Vec::new();
        let mut any_prevent_default = false;
        let mut propagation_stopped = false;
        let mut propagation_stopped_node: Option<(DomId, NodeId)> = None;

        for planned in planned_callbacks {
            // W3C stopPropagation: remaining handlers on the SAME node still
            // run; the first handler on a different node ends the dispatch.
            if propagation_stopped
                && propagation_stopped_node
                    .is_none_or(|(dom, nid)| dom != planned.dom_id || nid != planned.node_id)
            {
                break;
            }

            let mut callback =
                azul_layout::callbacks::Callback::from_core(planned.callback_data.callback);
            let hit_node = DomNodeId {
                dom: planned.dom_id,
                node: NodeHierarchyItemId::from_crate_internal(Some(planned.node_id)),
            };

            let (changes, update) = {
                let lw = &mut self.layout_window;
                lw.invoke_single_callback_at(
                    hit_node,
                    &mut callback,
                    &mut planned.callback_data.refany.clone(),
                    &window_handle,
                    &gl_context,
                    system_style.clone(),
                    &ExternalSystemCallbacks::rust_internal(),
                    &previous_window_state,
                    &self.window_state,
                    &self.renderer_resources,
                )
            };

            all_updates.push(update);

            let mut should_stop_immediate = false;
            let mut should_stop_propagation = false;
            for change in &changes {
                match change {
                    CallbackChange::PreventDefault => any_prevent_default = true,
                    CallbackChange::StopImmediatePropagation => should_stop_immediate = true,
                    CallbackChange::StopPropagation => should_stop_propagation = true,
                    _ => {}
                }
            }
            all_changes.extend(changes);

            if should_stop_propagation && !propagation_stopped {
                propagation_stopped = true;
                propagation_stopped_node = Some((planned.dom_id, planned.node_id));
            }
            if should_stop_immediate {
                break;
            }
        }

        let mut changes_result = ProcessEventResult::DoNothing;
        for change in &all_changes {
            changes_result = changes_result.max(self.apply_user_change(change));
        }

        let merged_update = all_updates
            .iter()
            .copied()
            .fold(Update::DoNothing, Update::max);

        (changes_result, merged_update, any_prevent_default)
    }

    /// Port of `PlatformWindow::apply_user_change`
    /// (`dll/src/desktop/shell2/common/event.rs`) for the `CallbackChange`
    /// variants the E2E op set can produce. Each arm mirrors the DLL's arm —
    /// including its relayout / display-list bookkeeping, which is what makes
    /// the damage the assertions observe the SAME damage the real host produces.
    #[allow(clippy::too_many_lines)]
    fn apply_user_change(&mut self, change: &CallbackChange) -> ProcessEventResult {
        match change {
            // === Window State ===
            CallbackChange::ModifyWindowState { state } => {
                let old = std::mem::replace(&mut self.window_state, state.clone());
                let size_changed = self.window_state.size.dimensions != old.size.dimensions;
                let dpi_changed = self.window_state.size.dpi != old.size.dpi;
                let mouse_state_changed = self.window_state.mouse_state != old.mouse_state;
                if size_changed || dpi_changed {
                    self.resize_pending = true;
                }
                if state.flags.close_requested {
                    return ProcessEventResult::DoNothing;
                }

                // Port of the DLL's `anything_changed` gate: the state-diff pass
                // runs ONCE per ModifyWindowState **that actually changed
                // something**, and NOT AT ALL for a state re-push. That gate is
                // what makes `relayout_iterations` mean what it says — a
                // repaint request (`tick_ms` / `wait_frame`, which re-push the
                // current state) is not an event pass and must not be counted
                // as one.
                // `touch_state` was MISSING from this list, and the string
                // `touch_state` appeared nowhere in this file. A touch op
                // mutated the state, the gate answered "nothing changed", the
                // pass never ran and no touch event was ever determined — with
                // no `unsupported`, no `send_err` and a green `ok`. 48 corpus
                // lines executed nothing and passed.
                let touch_state_changed = self.window_state.touch_state != old.touch_state;
                // Captured BEFORE `old` is moved into `previous_window_state`
                // below; `sync_touch_points` needs the previous point set to
                // tell a new finger from a moved one.
                let old_touch_points: Vec<azul_core::window::TouchPoint> = if touch_state_changed {
                    old.touch_state.touch_points.as_ref().to_vec()
                } else {
                    Vec::new()
                };
                let anything_changed = size_changed
                    || dpi_changed
                    || touch_state_changed
                    || self.window_state.mouse_state != old.mouse_state
                    || self.window_state.keyboard_state != old.keyboard_state
                    || self.window_state.window_focused != old.window_focused
                    || self.window_state.flags.has_focus != old.flags.has_focus
                    || self.window_state.position != old.position;

                let mut result = ProcessEventResult::ShouldReRenderCurrentWindow;
                if anything_changed {
                    // Advance the sync baseline BEFORE the pass — it is what
                    // `determine_all_events` diffs `current` against, so
                    // forgetting it makes every event pass see a zero delta
                    // and produce nothing.
                    self.previous_window_state = Some(old);
                }
                // Mouse state changed → re-resolve the pointer target before
                // the pass, exactly where the DLL calls `update_hit_test_at`.
                if mouse_state_changed {
                    if let Some(pos) = self.window_state.mouse_state.cursor_position.get_position()
                    {
                        self.update_hit_test_at(pos);
                    }
                }
                // Same idea for touch, one hit test PER FINGER — see
                // [`Runner::sync_touch_points`].
                if touch_state_changed {
                    self.sync_touch_points(&old_touch_points);
                }
                if anything_changed {
                    result = result.max(self.process_window_events(0));
                }
                result
            }

            // === Focus ===
            CallbackChange::SetFocusTarget { target } => {
                use azul_layout::managers::focus_cursor::resolve_focus_target;
                use azul_layout::managers::scroll_into_view::ScrollIntoViewOptions;

                let now = self.now();
                let window_state = self.window_state.clone();
                let lw = &mut self.layout_window;
                let current_focus = lw.focus_manager.get_focused_node().copied();
                match resolve_focus_target(target, &lw.layout_results, current_focus) {
                    Ok(Some(new_focus)) => {
                        lw.focus_manager.set_focused_node(Some(new_focus));
                        lw.scroll_node_into_view(new_focus, ScrollIntoViewOptions::nearest(), now);
                        arm_caret_for_focus(lw, Some(new_focus), &window_state);
                        lw.finalize_pending_focus_changes();
                        ProcessEventResult::ShouldReRenderCurrentWindow
                    }
                    Ok(None) => {
                        lw.focus_manager.set_focused_node(None);
                        arm_caret_for_focus(lw, None, &window_state);
                        lw.finalize_pending_focus_changes();
                        ProcessEventResult::ShouldReRenderCurrentWindow
                    }
                    Err(_) => ProcessEventResult::DoNothing,
                }
            }

            // === Content Modifications ===
            CallbackChange::ChangeNodeText { node_id, text } => {
                let dom_id = node_id.dom;
                let Some(internal_node_id) = node_id.node.into_crate_internal() else {
                    return ProcessEventResult::DoNothing;
                };
                let lw = &mut self.layout_window;

                // NO-OP SHORT CIRCUIT. Setting the text to the byte-identical
                // string used to throw away the ENTIRE incremental shaped-text
                // cache and re-shape every run in the DOM, then relayout the
                // whole root — the maximum work in the engine, for a write that
                // changed nothing. It also went green: the re-shape reproduces
                // identical glyphs, so the display list is identical, so the
                // damage is `none` and `assert_damage {"kind":"none"}` passed
                // while the engine did everything. That IS over-invalidation,
                // and it was invisible to every assertion the harness had.
                let unchanged = lw
                    .layout_results
                    .get(&dom_id)
                    .is_some_and(|lr| {
                        let nodes = lr.styled_dom.node_data.as_container();
                        nodes.get(internal_node_id).is_some_and(|node| {
                            matches!(
                                node.get_node_type(),
                                azul_core::dom::NodeType::Text(existing)
                                    if existing.as_str() == text.as_str()
                            )
                        })
                    });
                if unchanged {
                    return ProcessEventResult::DoNothing;
                }

                if let Some(layout_result) = lw.layout_results.get_mut(&dom_id) {
                    let idx = internal_node_id.index();
                    if idx < layout_result.styled_dom.node_data.as_ref().len() {
                        layout_result.styled_dom.node_data.as_container_mut()[internal_node_id]
                            .set_node_type(azul_core::dom::NodeType::Text(
                                azul_css::css::BoxOrStatic::heap(text.clone()),
                            ));
                    }
                }
                // The incremental layout cache keys its shaped-text runs on the
                // DOM pointer, which a text mutation does not change — so the
                // next relayout happily reused the OLD glyph runs and the screen
                // kept showing the previous text (damage was reported, yet not
                // one pixel differed). Drop the incremental cache so the text is
                // re-shaped…
                lw.layout_cache.reset_incremental();
                // …and rebuild the display list, which otherwise still carries
                // the old glyph run.
                lw.regenerate_display_list_for_dom(dom_id);
                ProcessEventResult::ShouldIncrementalRelayout
            }

            CallbackChange::ChangeNodeImage { dom_id, node_id, image, update_type: _ } => {
                let lw = &mut self.layout_window;
                if let Some(layout_result) = lw.layout_results.get_mut(dom_id) {
                    let idx = node_id.index();
                    if idx < layout_result.styled_dom.node_data.as_ref().len() {
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_node_type(azul_core::dom::NodeType::Image(
                                azul_css::css::BoxOrStatic::heap(image.clone()),
                            ));
                    }
                }
                lw.regenerate_display_list_for_dom(*dom_id);
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }

            CallbackChange::ChangeNodeImageMask { dom_id, node_id, mask } => {
                let lw = &mut self.layout_window;
                if let Some(layout_result) = lw.layout_results.get_mut(dom_id) {
                    let idx = node_id.index();
                    if idx < layout_result.styled_dom.node_data.as_ref().len() {
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_clip_mask(mask.clone());
                    }
                }
                lw.regenerate_display_list_for_dom(*dom_id);
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }

            CallbackChange::ChangeNodeCssProperties { dom_id, node_id, properties } => {
                let lw = &mut self.layout_window;
                if let Some(layout_result) = lw.layout_results.get_mut(dom_id) {
                    let idx = node_id.index();
                    if idx < layout_result.styled_dom.node_data.as_ref().len() {
                        use azul_css::dynamic_selector::CssPropertyWithConditions;
                        let new_props: Vec<CssPropertyWithConditions> = properties
                            .as_ref()
                            .iter()
                            .map(|p| CssPropertyWithConditions::simple(p.clone()))
                            .collect();
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_css_props(new_props.into());

                        // STALE-SCREEN FIX: `set_css_props` only writes the
                        // node's INLINE property vec. Layout and the display
                        // list read the CSS PROPERTY CACHE, which still holds the
                        // cascaded value — so the node kept its old paint, the
                        // display list came out identical, the diff reported no
                        // damage and the screen went stale. Push the same
                        // properties through the user-override channel (the one
                        // the resolver consults FIRST).
                        let props_slice: Vec<azul_css::props::property::CssProperty> =
                            properties.as_ref().iter().cloned().collect();
                        drop(
                            layout_result
                                .styled_dom
                                .restyle_user_property(node_id, &props_slice),
                        );
                    }
                }
                lw.regenerate_display_list_for_dom(*dom_id);
                // A paint-only property (colour, background, opacity,
                // transform, shadow, …) cannot move geometry, so it must not
                // charge the window a layout pass. See
                // `crate::callbacks::css_properties_need_relayout`.
                if crate::callbacks::css_properties_need_relayout(properties) {
                    ProcessEventResult::ShouldIncrementalRelayout
                } else {
                    ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
                }
            }

            CallbackChange::OverrideNodeCssProperties { dom_id, node_id, properties } => {
                // Fast-path override channel: writes land in
                // `CssPropertyCache::user_overridden_properties`, which the
                // property resolver consults first.
                let lw = &mut self.layout_window;
                if let Some(layout_result) = lw.layout_results.get_mut(dom_id) {
                    let idx = node_id.index();
                    if idx < layout_result.styled_dom.node_data.as_ref().len() {
                        let props_slice: Vec<azul_css::props::property::CssProperty> =
                            properties.as_ref().iter().cloned().collect();
                        drop(
                            layout_result
                                .styled_dom
                                .restyle_user_property(node_id, &props_slice),
                        );
                    }
                }
                // Same rule as `ChangeNodeCssProperties`: the override channel
                // exists precisely so an animation can push a handful of
                // properties per frame cheaply — charging it a layout pass for
                // a colour defeats the point.
                if crate::callbacks::css_properties_need_relayout(properties) {
                    ProcessEventResult::ShouldIncrementalRelayout
                } else {
                    ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
                }
            }

            CallbackChange::UpdateVirtualView { dom_id, node_id } => {
                let mut updates = BTreeMap::new();
                let mut set = azul_core::FastBTreeSet::new();
                set.insert(*node_id);
                updates.insert(*dom_id, set);
                self.layout_window.queue_virtual_view_updates(updates);
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }

            CallbackChange::UpdateAllVirtualViews => {
                self.layout_window.queue_all_virtual_view_reinvoke();
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }

            CallbackChange::UpdateImageCallback { .. }
            | CallbackChange::UpdateAllImageCallbacks => {
                ProcessEventResult::ShouldReRenderCurrentWindow
            }

            // === DOM structure ===
            CallbackChange::InsertChildNode {
                dom_id, parent_node_id, node_type_str, position, classes, id,
            } => {
                let lw = &mut self.layout_window;
                if let Some(layout_result) = lw.layout_results.get_mut(dom_id) {
                    let parent_idx = parent_node_id.index();
                    if parent_idx < layout_result.styled_dom.node_data.as_ref().len() {
                        let node_type = parse_node_type_from_str(node_type_str.as_str());
                        let mut dom = azul_core::dom::Dom::create_node(node_type);
                        if let Some(id_str) = id.as_ref() {
                            dom = dom.with_id(id_str.clone());
                        }
                        for class in classes.iter() {
                            dom = dom.with_class(class.clone());
                        }
                        // Style it (empty CSS — the author rules are unavailable
                        // here; they are re-applied by `restyle_retained` below).
                        let css = azul_css::css::Css::empty();
                        let styled = StyledDom::create(&mut dom, css);

                        // `append_child` always attaches to the DOM's ROOT — the
                        // requested `parent_node_id` was accepted, validated and
                        // then IGNORED, so every inserted node landed as a last
                        // child of <html>. Append first, then RE-PARENT.
                        let sd = &mut layout_result.styled_dom;
                        let new_id = NodeId::new(sd.node_data.as_ref().len());
                        let root_id = sd.root.into_crate_internal().unwrap_or(NodeId::ZERO);
                        let root_last_before =
                            sd.node_hierarchy.as_container()[root_id].last_child_id();
                        sd.append_child(styled);

                        if *parent_node_id != root_id {
                            // The hierarchy is a FLAT DFS array whose
                            // `first_child_id(n)` is DERIVED as `n + 1`. A node
                            // appended at the end can therefore only ever be a
                            // LAST child, and only of a parent that already has
                            // children. Anything else needs a full re-index of
                            // the DOM (and every node-keyed manager), so it is
                            // rejected instead of silently corrupting the tree.
                            let parent_last =
                                sd.node_hierarchy.as_container()[*parent_node_id].last_child_id();
                            if let Some(parent_last) = parent_last {
                                // 1. unlink the new node from the root chain
                                {
                                    let h = &mut sd.node_hierarchy;
                                    h.as_container_mut()[root_id].last_child =
                                        NodeId::into_raw(&root_last_before);
                                    if let Some(rl) = root_last_before {
                                        h.as_container_mut()[rl].next_sibling =
                                            NodeId::into_raw(&None);
                                    }
                                    // 2. link it as the parent's new last child
                                    h.as_container_mut()[parent_last].next_sibling =
                                        NodeId::into_raw(&Some(new_id));
                                    h.as_container_mut()[new_id].previous_sibling =
                                        NodeId::into_raw(&Some(parent_last));
                                    h.as_container_mut()[new_id].next_sibling =
                                        NodeId::into_raw(&None);
                                    h.as_container_mut()[new_id].parent =
                                        NodeId::into_raw(&Some(*parent_node_id));
                                    h.as_container_mut()[*parent_node_id].last_child =
                                        NodeId::into_raw(&Some(new_id));
                                }
                                // 3. keep the cascade bookkeeping consistent
                                let sibling_index = {
                                    let h = sd.node_hierarchy.as_container();
                                    parent_node_id.az_children(&h).count().saturating_sub(1)
                                };
                                let ci = sd.cascade_info.as_mut();
                                ci[parent_last.index()].is_last_child = false;
                                ci[new_id.index()].index_in_parent =
                                    u32::try_from(sibling_index).unwrap_or(u32::MAX);
                                ci[new_id.index()].is_last_child = true;
                                sd.finalize_non_leaf_nodes();
                            }
                        }
                        let _ = position; // only append-as-last-child is representable

                        // Re-run the author cascade from the retained stylesheet:
                        // the node was styled with an EMPTY css above, so without
                        // this it would never match rules like `.hot { width: 80px }`
                        // — the "inserted node never gets the author cascade" bug.
                        sd.extend_author_scopes_for_appended(new_id, *parent_node_id);
                        sd.restyle_retained();
                        // `append_child` composes the trees but does NOT re-run
                        // inheritance or rebuild the compact cache: the appended
                        // node would keep its isolated cascade (no inherited
                        // font-size/color, no UA defaults, no compact-cache entry)
                        // and measure 0×0.
                        sd.recompute_inheritance_and_compact_cache();
                    }
                }
                // The tree changed shape: the incremental layout cache (keyed on
                // the DOM pointer) would otherwise reuse the old tree, and the
                // stored display list still describes the OLD tree.
                lw.layout_cache.reset_incremental();
                lw.regenerate_display_list_for_dom(*dom_id);
                ProcessEventResult::ShouldIncrementalRelayout
            }

            CallbackChange::DeleteNode { dom_id, node_id } => {
                let lw = &mut self.layout_window;
                if let Some(layout_result) = lw.layout_results.get_mut(dom_id) {
                    let idx = node_id.index();
                    let node_count = layout_result.styled_dom.node_data.as_ref().len();
                    if idx < node_count && idx != 0 {
                        // Tombstone: set node to empty Div and unlink it.
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_node_type(azul_core::dom::NodeType::Div);
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_ids_and_classes(Vec::new().into());
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_callbacks(Vec::new().into());

                        let hierarchy = &mut layout_result.styled_dom.node_hierarchy;
                        let prev_sib = hierarchy.as_container()[*node_id].previous_sibling_id();
                        let next_sib = hierarchy.as_container()[*node_id].next_sibling_id();
                        let parent = hierarchy.as_container()[*node_id].parent_id();

                        if let Some(prev) = prev_sib {
                            hierarchy.as_container_mut()[prev].next_sibling =
                                NodeId::into_raw(&next_sib);
                        }
                        if let Some(next) = next_sib {
                            hierarchy.as_container_mut()[next].previous_sibling =
                                NodeId::into_raw(&prev_sib);
                        } else if let Some(p) = parent {
                            hierarchy.as_container_mut()[p].last_child =
                                NodeId::into_raw(&prev_sib);
                        }

                        hierarchy.as_container_mut()[*node_id].parent = 0;
                        hierarchy.as_container_mut()[*node_id].previous_sibling = 0;
                        hierarchy.as_container_mut()[*node_id].next_sibling = 0;
                        hierarchy.as_container_mut()[*node_id].last_child = 0;
                    }
                }
                ProcessEventResult::ShouldIncrementalRelayout
            }

            CallbackChange::SetNodeIdsAndClasses { dom_id, node_id, ids_and_classes } => {
                if let Some(layout_result) = self.layout_window.layout_results.get_mut(dom_id) {
                    let idx = node_id.index();
                    if idx < layout_result.styled_dom.node_data.as_ref().len() {
                        layout_result.styled_dom.node_data.as_container_mut()[*node_id]
                            .set_ids_and_classes(ids_and_classes.clone());
                    }
                }
                ProcessEventResult::ShouldIncrementalRelayout
            }

            CallbackChange::RemountDom { xml } => {
                // The E2E `mount` / `unmount` document is per-window state, not
                // a process-global sink: store it on the window and let
                // `regenerate_layout` read it back on the next pass.
                self.layout_window
                    .e2e_mount
                    .set(xml.as_ref().map(|s| s.as_str().to_string()));
                ProcessEventResult::ShouldRegenerateDomCurrentWindow
            }

            // === Scroll ===
            CallbackChange::ScrollTo { dom_id, node_id, position, unclamped } => {
                let now = self.now();
                if let Some(internal_node_id) = node_id.into_crate_internal() {
                    let lw = &mut self.layout_window;
                    if *unclamped {
                        lw.scroll_manager.set_scroll_position_unclamped(
                            *dom_id, internal_node_id, *position, now,
                        );
                    } else {
                        lw.scroll_manager.scroll_to(
                            *dom_id,
                            internal_node_id,
                            *position,
                            std::time::Duration::from_millis(0).into(),
                            azul_core::events::EasingFunction::Linear,
                            now,
                        );
                    }
                    // Recalculate scrollbar geometry so CPU-side hit testing has
                    // up-to-date thumb positions.
                    lw.scroll_manager.calculate_scrollbar_states();
                }
                ProcessEventResult::ShouldReRenderCurrentWindow
            }

            CallbackChange::ScrollIntoView { node_id, options } => {
                let now = self.now();
                let lw = &mut self.layout_window;
                azul_layout::managers::scroll_into_view::scroll_node_into_view(
                    *node_id,
                    &lw.layout_results,
                    &mut lw.scroll_manager,
                    *options,
                    now,
                );
                ProcessEventResult::ShouldReRenderCurrentWindow
            }

            // === Font cache ===
            CallbackChange::ReloadSystemFonts => {
                self.layout_window
                    .font_manager
                    .replace_fc_cache(FcFontCache::build());
                ProcessEventResult::DoNothing
            }

            // === Propagation control (consumed by the dispatch loop) ===
            CallbackChange::StopPropagation
            | CallbackChange::StopImmediatePropagation
            | CallbackChange::PreventDefault => ProcessEventResult::DoNothing,

            // === Window lifetime ===
            CallbackChange::CloseWindow => {
                self.window_state.flags.close_requested = true;
                ProcessEventResult::DoNothing
            }

            // === Text editing ===
            CallbackChange::InsertText { dom_id, node_id, text } => {
                use azul_layout::managers::text_input::TextInputSource;
                let lw = &mut self.layout_window;
                let dom_node_id = DomNodeId {
                    dom: *dom_id,
                    node: NodeHierarchyItemId::from_crate_internal(Some(*node_id)),
                };
                let old_inline_content = lw.get_text_before_textinput(*dom_id, *node_id);
                let old_text = lw.extract_text_from_inline_content(&old_inline_content);
                lw.text_input_manager.record_input(
                    dom_node_id,
                    text.to_string(),
                    old_text,
                    TextInputSource::Programmatic,
                );
                ProcessEventResult::ShouldReRenderCurrentWindow
            }
            CallbackChange::DeleteBackward { dom_id, node_id } => {
                let lw = &mut self.layout_window;
                if let Some(cursor) = lw.text_edit_manager.get_primary_cursor() {
                    let content = lw.get_text_before_textinput(*dom_id, *node_id);
                    let (updated_content, new_cursor) =
                        azul_layout::text3::edit::delete_backward(&content, &cursor);
                    if let Some(mc) = lw.text_edit_manager.multi_cursor.as_mut() {
                        mc.set_single_cursor(new_cursor);
                    }
                    lw.update_text_cache_after_edit(*dom_id, *node_id, updated_content);
                }
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::DeleteForward { dom_id, node_id } => {
                let lw = &mut self.layout_window;
                if let Some(cursor) = lw.text_edit_manager.get_primary_cursor() {
                    let content = lw.get_text_before_textinput(*dom_id, *node_id);
                    let (updated_content, new_cursor) =
                        azul_layout::text3::edit::delete_forward(&content, &cursor);
                    if let Some(mc) = lw.text_edit_manager.multi_cursor.as_mut() {
                        mc.set_single_cursor(new_cursor);
                    }
                    lw.update_text_cache_after_edit(*dom_id, *node_id, updated_content);
                }
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::MoveCursor { dom_id: _, node_id: _, cursor } => {
                if let Some(mc) = self.layout_window.text_edit_manager.multi_cursor.as_mut() {
                    mc.set_single_cursor(*cursor);
                }
                ProcessEventResult::ShouldReRenderCurrentWindow
            }
            CallbackChange::SetSelection { dom_id: _, node_id: _, selection } => {
                use azul_core::selection::Selection;
                if let Some(mc) = self.layout_window.text_edit_manager.multi_cursor.as_mut() {
                    match selection {
                        Selection::Cursor(cursor) => mc.set_single_cursor(*cursor),
                        Selection::Range(range) => mc.set_single_range(*range),
                    }
                }
                ProcessEventResult::ShouldReRenderCurrentWindow
            }
            CallbackChange::SetTextChangeset { changeset } => {
                self.layout_window.text_input_manager.pending_changeset = Some(changeset.clone());
                ProcessEventResult::DoNothing
            }

            // === Cursor movement ===
            CallbackChange::MoveCursorLeft { dom_id, node_id, extend_selection } => {
                self.move_cursor(*dom_id, *node_id, *extend_selection, |layout, cursor| {
                    layout.move_cursor_left(*cursor, &mut None)
                })
            }
            CallbackChange::MoveCursorRight { dom_id, node_id, extend_selection } => {
                self.move_cursor(*dom_id, *node_id, *extend_selection, |layout, cursor| {
                    layout.move_cursor_right(*cursor, &mut None)
                })
            }
            CallbackChange::MoveCursorUp { dom_id, node_id, extend_selection } => {
                self.move_cursor(*dom_id, *node_id, *extend_selection, |layout, cursor| {
                    layout.move_cursor_up(*cursor, &mut None, &mut None)
                })
            }
            CallbackChange::MoveCursorDown { dom_id, node_id, extend_selection } => {
                self.move_cursor(*dom_id, *node_id, *extend_selection, |layout, cursor| {
                    layout.move_cursor_down(*cursor, &mut None, &mut None)
                })
            }
            CallbackChange::MoveCursorToLineStart { dom_id, node_id, extend_selection } => {
                self.move_cursor(*dom_id, *node_id, *extend_selection, |layout, cursor| {
                    layout.move_cursor_to_line_start(*cursor, &mut None)
                })
            }
            CallbackChange::MoveCursorToLineEnd { dom_id, node_id, extend_selection } => {
                self.move_cursor(*dom_id, *node_id, *extend_selection, |layout, cursor| {
                    layout.move_cursor_to_line_end(*cursor, &mut None)
                })
            }
            // Document start/end are NOT a `move_cursor_in_node` movement in the
            // DLL either — they read the first/last cluster straight off the
            // inline layout.
            CallbackChange::MoveCursorToDocumentStart { dom_id, node_id, extend_selection } => {
                use azul_core::selection::{CursorAffinity, TextCursor};
                let lw = &mut self.layout_window;
                let first = lw
                    .get_inline_layout_for_node(*dom_id, *node_id)
                    .and_then(|layout| layout.items.first().and_then(|i| i.item.as_cluster()))
                    .map(|c| TextCursor {
                        cluster_id: c.source_cluster_id,
                        affinity: CursorAffinity::Leading,
                    });
                if let Some(doc_start) = first {
                    lw.handle_cursor_movement(*dom_id, *node_id, doc_start, *extend_selection);
                }
                ProcessEventResult::ShouldReRenderCurrentWindow
            }
            CallbackChange::MoveCursorToDocumentEnd { dom_id, node_id, extend_selection } => {
                use azul_core::selection::{CursorAffinity, TextCursor};
                let lw = &mut self.layout_window;
                let last = lw
                    .get_inline_layout_for_node(*dom_id, *node_id)
                    .and_then(|layout| layout.items.last().and_then(|i| i.item.as_cluster()))
                    .map(|c| TextCursor {
                        cluster_id: c.source_cluster_id,
                        affinity: CursorAffinity::Trailing,
                    });
                if let Some(doc_end) = last {
                    lw.handle_cursor_movement(*dom_id, *node_id, doc_end, *extend_selection);
                }
                ProcessEventResult::ShouldReRenderCurrentWindow
            }

            // === Multi-cursor / selection ===
            CallbackChange::AddCursor { dom_id, node_id, cursor } => {
                use azul_core::selection::MultiCursorState;
                let lw = &mut self.layout_window;
                if let Some(mc) = lw.text_edit_manager.multi_cursor.as_mut() {
                    let _ = mc.add_cursor(*cursor);
                } else {
                    let dom_node_id = DomNodeId {
                        dom: *dom_id,
                        node: NodeHierarchyItemId::from_crate_internal(Some(*node_id)),
                    };
                    lw.text_edit_manager.multi_cursor =
                        Some(MultiCursorState::new_with_cursor(*cursor, dom_node_id, 0));
                }
                lw.text_edit_manager.mark_dirty();
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::AddSelectionRange { dom_id, node_id, range } => {
                use azul_core::selection::MultiCursorState;
                let lw = &mut self.layout_window;
                if let Some(mc) = lw.text_edit_manager.multi_cursor.as_mut() {
                    let _ = mc.add_selection(*range);
                } else {
                    let dom_node_id = DomNodeId {
                        dom: *dom_id,
                        node: NodeHierarchyItemId::from_crate_internal(Some(*node_id)),
                    };
                    let mut mc = MultiCursorState::new_with_cursor(range.start, dom_node_id, 0);
                    mc.set_single_range(*range);
                    lw.text_edit_manager.multi_cursor = Some(mc);
                }
                lw.text_edit_manager.mark_dirty();
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::RemoveSelectionById { selection_id } => {
                let lw = &mut self.layout_window;
                if let Some(mc) = lw.text_edit_manager.multi_cursor.as_mut() {
                    let _ = mc.remove_selection(*selection_id);
                    lw.text_edit_manager.mark_dirty();
                }
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::SetSelectAllRange { target: _, range } => {
                if let Some(mc) = self.layout_window.text_edit_manager.multi_cursor.as_mut() {
                    mc.set_single_range(*range);
                }
                ProcessEventResult::DoNothing
            }
            CallbackChange::ProcessTextSelectionClick { position, time_ms } => {
                self.layout_window
                    .process_mouse_click_for_selection(*position, *time_ms);
                ProcessEventResult::ShouldReRenderCurrentWindow
            }
            CallbackChange::ScrollActiveCursorIntoView => {
                self.layout_window.scroll_selection_into_view(
                    azul_layout::window::SelectionScrollType::Cursor,
                    azul_layout::window::ScrollMode::Instant,
                );
                ProcessEventResult::ShouldReRenderCurrentWindow
            }

            // === Cursor blink STATE (the blink TIMER is a separate story, below) ===
            CallbackChange::SetCursorVisibility { visible } => {
                let lw = &mut self.layout_window;
                lw.text_edit_manager.blink.set_visibility(*visible);
                if let Some(dom_id) = lw.text_edit_manager.get_editing_dom_id() {
                    lw.regenerate_display_list_for_dom(dom_id);
                }
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::ToggleCursorVisibility => {
                let now = self.now();
                let lw = &mut self.layout_window;
                if lw.text_edit_manager.blink.should_blink(&now) {
                    lw.text_edit_manager.blink.toggle_visibility();
                } else {
                    lw.text_edit_manager.blink.set_visibility(true);
                }
                if let Some(dom_id) = lw.text_edit_manager.get_editing_dom_id() {
                    lw.regenerate_display_list_for_dom(dom_id);
                }
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            }
            CallbackChange::ResetCursorBlink => {
                let now = self.now();
                self.layout_window
                    .text_edit_manager
                    .blink
                    .reset_blink_on_input(now);
                ProcessEventResult::DoNothing
            }

            // === Drag & drop payload (the GESTURE that starts a drag is input) ===
            CallbackChange::SetDragData { mime_type, data } => {
                if let Some(ctx) = self
                    .layout_window
                    .gesture_drag_manager
                    .get_drag_context_mut()
                {
                    if let Some(node_drag) = ctx.as_node_drag_mut() {
                        node_drag.drag_data.set_data(mime_type.clone(), data.clone());
                    }
                }
                ProcessEventResult::DoNothing
            }
            CallbackChange::AcceptDrop => {
                if let Some(ctx) = self
                    .layout_window
                    .gesture_drag_manager
                    .get_drag_context_mut()
                {
                    if let Some(node_drag) = ctx.as_node_drag_mut() {
                        node_drag.drop_accepted = true;
                    }
                }
                ProcessEventResult::DoNothing
            }
            CallbackChange::SetDropEffect { effect } => {
                if let Some(ctx) = self
                    .layout_window
                    .gesture_drag_manager
                    .get_drag_context_mut()
                {
                    if let Some(node_drag) = ctx.as_node_drag_mut() {
                        node_drag.drop_effect = *effect;
                    }
                }
                ProcessEventResult::DoNothing
            }

            // ── NOT SUPPORTED HEADLESSLY ────────────────────────────────────
            //
            // Everything below needs a facility this host does not have. Each
            // one FAILS THE SCENARIO by name (see `Runner::unsupported`) instead
            // of being dropped on the floor: a change that is silently ignored
            // produces a test that executes nothing and PASSES, which in a
            // generated corpus is indistinguishable from a real pass and would
            // certify thousands of scenarios that never ran.
            //
            // The variants are listed EXPLICITLY, with no `_` arm, so that a new
            // `CallbackChange` in `layout/src/callbacks.rs` is a COMPILE ERROR
            // here and forces a decision: port it (preferred — the reference is
            // `dll/src/desktop/shell2/common/event.rs::apply_user_change`) or
            // declare it unsupported.

            // Synthetic pointer input. `click` / `double_click` / `drag` all
            // land here: a SEQUENCE of window states that has to be applied ONE
            // AT A TIME, each with its own hit test and its own state-diff pass
            // — collapsing them to "the last one wins" would leave only the
            // button-RELEASED state and no MouseDown would ever exist (the same
            // transient-input bug documented in `Runner::service`).
            CallbackChange::QueueWindowStateSequence { states } => {
                let mut result = ProcessEventResult::DoNothing;
                for queued_state in states {
                    let old = self.window_state.clone();
                    self.previous_window_state = Some(old.clone());

                    // The DLL copies exactly these fields (not the whole
                    // state): the queued states are built from a clone of the
                    // current state, so anything else would be a no-op copy.
                    {
                        let current = &mut self.window_state;
                        current.mouse_state = queued_state.mouse_state;
                        current.keyboard_state = queued_state.keyboard_state.clone();
                        current.title = queued_state.title.clone();
                        current.size = queued_state.size;
                        current.position = queued_state.position;
                        current.flags = queued_state.flags;
                    }
                    // Not in the DLL's arm, which has no equivalent bookkeeping:
                    // this host caches rasterisations per size/DPI, so a queued
                    // size change has to invalidate them or the frame keeps the
                    // old scale (`ModifyWindowState` does the same).
                    if self.window_state.size.dimensions != old.size.dimensions
                        || self.window_state.size.dpi != old.size.dpi
                    {
                        self.resize_pending = true;
                    }

                    if let Some(pos) = queued_state.mouse_state.cursor_position.get_position() {
                        self.update_hit_test_at(pos);
                    }

                    result = result.max(self.process_window_events(0));
                }
                result
            }
            CallbackChange::RequestHitTestUpdate { position } => {
                self.update_hit_test_at(*position);
                ProcessEventResult::DoNothing
            }
            CallbackChange::InjectNativeGesture { .. } => {
                self.unsupported("InjectNativeGesture", "no platform gesture source")
            }

            // Accessibility action, i.e. what a screen reader asks for.
            //
            // PORT of the DLL's arm, which routes through
            // `PlatformWindow::dispatch_accessibility_actions`: apply the action
            // to the managers, THEN dispatch the synthetic events it mapped to.
            // Doing only the first half is the exact bug the DLL shipped once —
            // AT-SPI `do_action` was accepted, decoded to the right node, and
            // then invoked no callback at all — so this host does both halves or
            // the port is worthless.
            //
            // Not `unsupported`: nothing here needs a platform. The whole action
            // path lives in `LayoutWindow`, which this host owns.
            CallbackChange::PerformAccessibilityAction {
                dom_id,
                node_id,
                action,
            } => {
                use azul_core::events::{
                    EventData, EventFilter, EventSource, EventType, FocusEventFilter,
                    HoverEventFilter, KeyModifiers, MouseButton, MouseEventData, SyntheticEvent,
                };

                let affected = self.layout_window.process_accessibility_action(
                    *dom_id,
                    *node_id,
                    action.clone(),
                    azul_core::task::Instant::now(),
                );

                // NOT gated on `affected.is_empty()`. Focus / Blur / the
                // Scroll* family / SetTextSelection all mutate manager state and
                // map to NO callback, so their affected map is empty while the
                // screen is genuinely stale — which is why every platform
                // backend calls `request_redraw()` unconditionally after a
                // batch. `ShouldReRenderCurrentWindow` is this host's equivalent.
                {
                    let timestamp = self.now();
                    let mut events = Vec::new();
                    for (node, (filters, _needs_relayout)) in &affected {
                        // Synthetic pointer events carry the node's centre so a
                        // callback reading the cursor position sees an in-bounds
                        // point (same choice the DLL makes).
                        let centre = self
                            .layout_window
                            .get_node_layout_rect(*node)
                            .map_or(LogicalPosition { x: 0.0, y: 0.0 }, |r| LogicalPosition {
                                x: r.origin.x + r.size.width / 2.0,
                                y: r.origin.y + r.size.height / 2.0,
                            });
                        let mouse_data = || {
                            EventData::Mouse(MouseEventData {
                                position: centre,
                                button: MouseButton::Left,
                                buttons: 0,
                                modifiers: KeyModifiers::default(),
                            })
                        };
                        for f in filters {
                            let (event_type, data) = match f {
                                EventFilter::Hover(HoverEventFilter::MouseUp)
                                | EventFilter::Focus(FocusEventFilter::MouseUp) => {
                                    (EventType::MouseUp, mouse_data())
                                }
                                EventFilter::Hover(HoverEventFilter::MouseDown)
                                | EventFilter::Focus(FocusEventFilter::MouseDown) => {
                                    (EventType::MouseDown, mouse_data())
                                }
                                _ => continue,
                            };
                            events.push(SyntheticEvent::new(
                                event_type,
                                EventSource::Synthetic,
                                *node,
                                timestamp.clone(),
                                data,
                            ));
                        }
                    }

                    // The action already moved focus / scroll / cursor state, so
                    // the frame is stale even when it mapped to no callback.
                    let mut result = ProcessEventResult::ShouldReRenderCurrentWindow;
                    if !events.is_empty() {
                        let (r, _update, _) = self.dispatch_events_propagated(&events);
                        result = result.max(r);
                    }
                    result
                }
            }

            // === Timers ===
            //
            // Port of the DLL's four arms. There, `lw.timers.insert(..)` records
            // the timer and the platform trait's `start_timer` arms the OS
            // wakeup that will get the loop back to `process_timers_and_threads`.
            // This host has no OS: `LayoutWindow::timers` IS the registry and
            // [`Runner::pump_timers`] IS the loop, so the insert alone is the
            // whole job. Time comes from `Instant::now()`, which honours the
            // thread-scoped test clock the `tick_ms` op advances, so a timer
            // fires when the SCENARIO says it does — no sleeping, no race.
            //
            // HOW THE FIRST TWO ARE REACHED FROM A SCENARIO. `AddTimer` /
            // `RemoveTimer` are produced by `CallbackInfo::add_timer` /
            // `remove_timer`, an APP-callback API — and a scenario is HTML + CSS
            // + ops, so it cannot install the Rust `TimerCallback` fn pointer an
            // `AddTimer` carries. The `add_timer` / `remove_timer` DEBUG OPS
            // (`DebugEvent::AddTimer` / `RemoveTimer` in `full.rs`) close that
            // gap: they build a timer around a callback the e2e module itself
            // owns and push it through the same two `CallbackInfo` methods a
            // real app calls, so these arms run for real.
            // `e2e/op-add-remove-timer.json` is the guard.
            CallbackChange::AddTimer { timer_id, timer } => {
                self.layout_window.add_timer(*timer_id, timer.clone());
                ProcessEventResult::DoNothing
            }
            CallbackChange::RemoveTimer { timer_id } => {
                self.layout_window.remove_timer(timer_id);
                ProcessEventResult::DoNothing
            }
            CallbackChange::StartCursorBlinkTimer => {
                use azul_core::task::CURSOR_BLINK_TIMER_ID;
                // Idempotent, like the DLL's arm: re-arming an already-running
                // blink would reset `last_run` and stall the caret forever under
                // a stream of input events.
                if !self.layout_window.text_edit_manager.blink.is_blink_timer_active() {
                    self.layout_window
                        .text_edit_manager
                        .blink
                        .set_blink_timer_active(true);
                    let window_state = self.window_state.clone();
                    let timer = self.layout_window.create_cursor_blink_timer(&window_state);
                    self.layout_window.add_timer(CURSOR_BLINK_TIMER_ID, timer);
                }
                ProcessEventResult::DoNothing
            }
            CallbackChange::StopCursorBlinkTimer => {
                use azul_core::task::CURSOR_BLINK_TIMER_ID;
                if self.layout_window.text_edit_manager.blink.is_blink_timer_active() {
                    self.layout_window
                        .text_edit_manager
                        .blink
                        .set_blink_timer_active(false);
                }
                self.layout_window.remove_timer(&CURSOR_BLINK_TIMER_ID);
                ProcessEventResult::DoNothing
            }

            // No thread pump: nothing polls thread writebacks.
            CallbackChange::AddThread { .. } => {
                self.unsupported("AddThread", "no thread pump — the writeback would never run")
            }
            CallbackChange::RemoveThread { .. } => {
                self.unsupported("RemoveThread", "no thread pump")
            }

            // No OS integration.
            CallbackChange::SetCopyContent { .. } => {
                self.unsupported("SetCopyContent", "no OS clipboard")
            }
            CallbackChange::SetCutContent { .. } => {
                self.unsupported("SetCutContent", "no OS clipboard")
            }
            CallbackChange::CreateNewWindow { .. } => {
                self.unsupported("CreateNewWindow", "single-window host")
            }
            CallbackChange::BeginInteractiveMove => {
                self.unsupported("BeginInteractiveMove", "no window manager")
            }
            CallbackChange::OpenMenu { .. } => {
                self.unsupported("OpenMenu", "no native menu host")
            }
            CallbackChange::ShowTooltip { .. } => {
                self.unsupported("ShowTooltip", "tooltips are a second platform window")
            }
            CallbackChange::HideTooltip => {
                self.unsupported("HideTooltip", "tooltips are a second platform window")
            }

            // No app-level image cache: the runner lays out against
            // `RendererResources` alone, so an image registered here would be
            // invisible to the layout that is supposed to display it.
            CallbackChange::AddImageToCache { .. } => {
                self.unsupported("AddImageToCache", "no app-level ImageCache")
            }
            CallbackChange::RemoveImageFromCache { .. } => {
                self.unsupported("RemoveImageFromCache", "no app-level ImageCache")
            }

            // No app data / undo manager: the runner's `RefAny` app data is `()`,
            // so a snapshot or an undo would restore nothing.
            CallbackChange::CommitUndoSnapshot => {
                self.unsupported("CommitUndoSnapshot", "no app-data undo manager")
            }
            CallbackChange::UndoAppState => {
                self.unsupported("UndoAppState", "no app-data undo manager")
            }
            CallbackChange::RedoAppState => {
                self.unsupported("RedoAppState", "no app-data undo manager")
            }

            // Text input. `process_text_input` records the changeset and
            // reports the affected nodes; the host then dispatches one `Input`
            // event per node and only THEN applies the changeset, so an
            // `On::Input` callback observes the pre-edit text exactly as it
            // does in the DLL. Applying only the first half would edit the text
            // while no callback ever fired.
            CallbackChange::CreateTextInput { text } => {
                let affected_nodes = self.layout_window.process_text_input(text.as_str());
                if affected_nodes.is_empty() {
                    return ProcessEventResult::DoNothing;
                }

                let now = self.now();
                let text_events: Vec<_> = affected_nodes
                    .keys()
                    .map(|dom_node_id| {
                        azul_core::events::SyntheticEvent::new(
                            azul_core::events::EventType::Input,
                            azul_core::events::EventSource::User,
                            *dom_node_id,
                            now.clone(),
                            azul_core::events::EventData::None,
                        )
                    })
                    .collect();

                let mut result = ProcessEventResult::DoNothing;
                let (text_changes_result, text_update, _) =
                    self.dispatch_events_propagated(&text_events);
                result = result.max(text_changes_result);
                if matches!(
                    text_update,
                    azul_core::callbacks::Update::RefreshDom
                        | azul_core::callbacks::Update::RefreshDomAllWindows
                ) {
                    result = result.max(ProcessEventResult::ShouldRegenerateDomCurrentWindow);
                }

                let changeset_result = self.layout_window.apply_text_changeset();
                if !changeset_result.dirty_nodes.is_empty() {
                    result = result.max(if changeset_result.needs_relayout {
                        ProcessEventResult::ShouldIncrementalRelayout
                    } else {
                        ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
                    });
                    self.layout_window.scroll_selection_into_view(
                        azul_layout::window::SelectionScrollType::Cursor,
                        azul_layout::window::ScrollMode::Instant,
                    );
                }
                result
            }

            // The runner mounts XML documents; it never invokes a layout
            // callback, which is the only thing a route switch changes.
            CallbackChange::SwitchRoute { .. } => {
                self.unsupported("SwitchRoute", "no layout callback — the runner mounts XML")
            }
        }
    }

    /// Shared body of the eight `MoveCursor*` arms (port of the DLL's, which are
    /// the same call with a different closure).
    fn move_cursor(
        &mut self,
        dom_id: DomId,
        node_id: NodeId,
        extend_selection: bool,
        f: impl FnOnce(
            &azul_layout::text3::cache::UnifiedLayout,
            &azul_core::selection::TextCursor,
        ) -> azul_core::selection::TextCursor,
    ) -> ProcessEventResult {
        let lw = &mut self.layout_window;
        if let Some(new_cursor) = lw.move_cursor_in_node(dom_id, node_id, f) {
            lw.handle_cursor_movement(dom_id, node_id, new_cursor, extend_selection);
        }
        ProcessEventResult::ShouldReRenderCurrentWindow
    }

    /// Record a `CallbackChange` this host cannot apply faithfully, and FAIL the
    /// scenario for it (`run_e2e_test` turns a non-empty list into a red test).
    ///
    /// This is deliberately not a `log_warn` and not a `DoNothing`: an ignored
    /// change makes a scenario that exercises nothing report the same "pass" as
    /// one that exercised everything.
    fn unsupported(&mut self, variant: &str, why: &str) -> ProcessEventResult {
        self.unsupported_changes.push(format!(
            "e2e runner: CallbackChange::{variant} is not supported by the headless runner \
             ({why}) — this scenario cannot be executed faithfully (port the arm from \
             dll/src/desktop/shell2/common/event.rs::apply_user_change)"
        ));
        ProcessEventResult::DoNothing
    }

    /// Port of `common::layout::regenerate_layout` + the headless backend's
    /// render/damage tail: refresh the font snapshot, install the pending mount
    /// document (or keep the already-mounted, possibly-mutated DOM), re-run
    /// layout and render a frame.
    fn regenerate_layout(&mut self) {
        self.refresh_font_snapshot();

        self.layout_window.sync_frame_report();
        self.layout_window.frame_report.dom_regenerations =
            self.layout_window.frame_report.dom_regenerations.saturating_add(1);

        // E2E `mount` override: replace the DOM wholesale with the test's inline
        // XML+CSS document, but ONLY when the mount is dirty — otherwise keep the
        // already-mounted DOM (with any debug DOM mutations applied to it).
        let mount_change = self
            .layout_window
            .e2e_mount
            .take_dirty()
            .then(|| self.layout_window.e2e_mount.xml().map(str::to_string));
        let styled_dom = match mount_change {
            Some(Some(xml)) => match azul_layout::xml::parse_xml_to_styled_dom(&xml) {
                Ok(sd) => Some(sd),
                Err(_) => None,
            },
            Some(None) => {
                // `unmount`: drop the mounted document entirely.
                self.layout_window.layout_results.clear();
                self.cpu_backend.previous_display_list = None;
                self.resize_pending = false;
                return;
            }
            None => self
                .layout_window
                .layout_results
                .remove(&DomId::ROOT_ID)
                .map(|lr| lr.styled_dom),
        };

        let Some(mut styled_dom) = styled_dom else {
            self.resize_pending = false;
            return;
        };

        // A DPI or size change invalidates every cached rasterisation and every
        // shaped run measured at the old scale.
        if self.resize_pending {
            self.layout_window.clear_caches();
            self.resize_pending = false;
        }

        // Step 3.4 of `regenerate_layout`: re-run inheritance + rebuild the
        // compact cache on the composed tree.
        styled_dom.recompute_inheritance_and_compact_cache();

        self.layout(styled_dom);
        self.render_and_record();
    }

    /// Port of `common::layout::incremental_relayout` + the headless backend's
    /// render/damage tail: re-run layout on the EXISTING (already mutated)
    /// `StyledDom`, then render.
    ///
    /// This is NOT the same as `regenerate_layout()` for an in-place DOM
    /// mutation: `regenerate_layout` short-circuits on
    /// `is_layout_equivalent(old, new)`, and after an in-place mutation "old"
    /// and "new" are the same DOM — so layout would be skipped and the frame
    /// would keep the pre-mutation shaped text and geometry forever.
    fn relayout_only(&mut self) {
        if let Some(layout_result) = self.layout_window.layout_results.remove(&DomId::ROOT_ID) {
            self.layout(layout_result.styled_dom);
        }
        self.render_and_record();
    }

    /// CPU-render the current frame and publish its damage onto the
    /// `LayoutWindow`, where `CallbackInfo::get_layout_window()` — and therefore
    /// an E2E assertion — can see it.
    fn render_and_record(&mut self) {
        // The scrollbar thumb transform and fade opacity live in the GPU value
        // cache, which the WebRender builders refresh every frame and the CPU
        // path has to refresh by hand. `LayoutWindow::refresh_scrollbar_gpu_cache_for_cpu_frame`
        // says so in its own doc comment ("before `CpuBackend::render_frame`"),
        // and ALL SEVEN DLL platform loops call it — this host did not. So the
        // cache was only ever advanced by a full relayout: `scrollbar_fade_active`
        // never became true, `has_gpu_damage` never became true from a fade, and
        // NO SCROLLBAR FADE WAS OBSERVABLE IN E2E AT ALL. The `full.rs:5285`
        // leak check for "an idle scrollbar'd window re-presenting forever"
        // could not fire either.
        let gpu_cache_moved = self.layout_window.refresh_scrollbar_gpu_cache_for_cpu_frame();

        let width = self.window_state.size.dimensions.width;
        let height = self.window_state.size.dimensions.height;
        #[allow(clippy::cast_precision_loss)]
        let dpi = self.window_state.size.dpi as f32 / 96.0;
        self.cpu_backend.render_frame(
            &self.layout_window,
            &self.renderer_resources,
            width,
            height,
            dpi,
        );
        let paint = self.cpu_backend.last_frame_damage.clone();
        let present = self.cpu_backend.last_present_damage.clone();
        self.layout_window.record_frame(paint, present);

        // "If any scrollbar is actively fading (0 < opacity < 1), schedule
        // another frame so the fade-out animation runs to completion." — the
        // tail of every DLL present path, ported. See `Runner::pending_redraw`.
        //
        // `gpu_cache_moved` is the extra term the DLL does not need and this
        // host does: the frame that lands the fade on opacity 0.0 clears
        // `scrollbar_fade_active` and still repaints the strip the scrollbar
        // vacated, so stopping on the flag alone leaves the LAST frame carrying
        // damage. A shell does not care (nothing asks it whether it settled);
        // an idleness assertion reads exactly that frame. One more frame after
        // the last change is what makes "settled" observable.
        self.pending_redraw =
            self.layout_window.gpu_state_manager.scrollbar_fade_active || gpu_cache_moved;

        // Publish the DAMAGE-DRIVEN framebuffer so `assert_damage_sound`'s
        // `pixel_identity` check can compare it against an independent full
        // repaint (`CallbackInfo::take_screenshot`). Only this host can: the DLL
        // presents from the GPU, which is why the op FAILS there rather than
        // silently skipping the check.
        #[cfg(feature = "cpurender")]
        if let Some(frame) = self.cpu_backend.last_frame.as_ref() {
            super::full::e2e_set_presented_frame(&self.layout_window, frame);
        }
    }

    /// Port of the font-snapshot block at the top of `regenerate_layout`: the
    /// window's font cache is re-installed from the async registry (or from the
    /// app-level cache when there is none) before every DOM regeneration.
    fn refresh_font_snapshot(&mut self) {
        #[cfg(feature = "font_async_registry")]
        if let Some(registry) = self.font_registry.as_ref() {
            // Avoid replacing a complete font cache with an incomplete snapshot
            // while the background builder threads are still parsing fonts.
            let current_cache_empty = self.layout_window.font_manager.fc_cache.is_empty();
            let build_complete = registry.is_build_complete();
            if current_cache_empty || build_complete {
                let font_stacks = rust_fontconfig::config::tokenize_common_families(
                    rust_fontconfig::OperatingSystem::current(),
                );
                registry.request_fonts(&font_stacks);
                self.layout_window
                    .font_manager
                    .replace_fc_cache(registry.shared_cache());
            }
            return;
        }
        // Fallback: use the app-level cache directly.
        self.layout_window
            .font_manager
            .replace_fc_cache(self.app_fc_cache.clone());
    }

    /// Port of the DLL event loop's keyboard-default-action pass: Tab →
    /// FocusNext/Previous, Escape → ClearFocus. Runs once per pass that saw a
    /// `KeyDown`, which is the DLL's `has_key_event` gate.
    ///
    /// Returns `(result, focus_changed)`; the caller uses `focus_changed` to
    /// decide whether to dispatch Blur/Focus and re-enter the pass.
    fn run_keyboard_default_action(&mut self) -> (ProcessEventResult, bool) {
        use azul_core::events::DefaultAction;
        use azul_layout::default_actions::{
            default_action_to_focus_target, determine_keyboard_default_action,
        };
        use azul_layout::managers::focus_cursor::resolve_focus_target;

        let ks = self.window_state.keyboard_state.clone();
        let focused = self.layout_window.focus_manager.get_focused_node().copied();
        let action = determine_keyboard_default_action(
            &ks,
            focused,
            &self.layout_window.layout_results,
            false,
        );
        if !action.has_action() {
            return (ProcessEventResult::DoNothing, false);
        }

        match &action.action {
            DefaultAction::FocusNext
            | DefaultAction::FocusPrevious
            | DefaultAction::FocusFirst
            | DefaultAction::FocusLast => {
                let Some(target) = default_action_to_focus_target(&action.action) else {
                    return (ProcessEventResult::DoNothing, false);
                };
                let Ok(resolved) =
                    resolve_focus_target(&target, &self.layout_window.layout_results, focused)
                else {
                    return (ProcessEventResult::DoNothing, false);
                };
                if resolved == focused {
                    return (ProcessEventResult::DoNothing, false);
                }
                (self.set_focus(resolved, focused), true)
            }
            DefaultAction::ClearFocus => {
                if focused.is_none() {
                    return (ProcessEventResult::DoNothing, false);
                }
                (self.set_focus(None, focused), true)
            }
            _ => (ProcessEventResult::DoNothing, false),
        }
    }

    /// Port of the DLL's `register_scroll_nodes` (dll/.../common/layout.rs):
    /// after layout, push each scrollable container's bounds into the
    /// ScrollManager so scroll ops + reads work.
    fn register_scroll_nodes(&mut self) {
        let now = self.now();
        let lw = &mut self.layout_window;
        let mut regs: Vec<(DomId, NodeId, LogicalRect, LogicalSize, f32, f32, bool, bool)> =
            Vec::new();
        for (dom_id, layout_result) in &lw.layout_results {
            for (node_idx, node) in layout_result.layout_tree.nodes.iter().enumerate() {
                let Some(sb) = layout_result
                    .layout_tree
                    .warm(node_idx)
                    .and_then(|w| w.scrollbar_info.as_ref())
                else {
                    continue;
                };
                if !(sb.needs_vertical || sb.needs_horizontal) {
                    continue;
                }
                let Some(dom_node_id) = node.dom_node_id else {
                    continue;
                };
                let border_box_size = node.used_size.unwrap_or_default();
                let resolved = node.box_props.unpack();
                let border = &resolved.border;
                let container_size = LogicalSize {
                    width: (border_box_size.width - border.left - border.right).max(0.0),
                    height: (border_box_size.height - border.top - border.bottom).max(0.0),
                };
                let container_origin = layout_result
                    .calculated_positions
                    .get(node_idx)
                    .copied()
                    .unwrap_or_else(LogicalPosition::zero);
                let container_rect = LogicalRect { origin: container_origin, size: container_size };
                let content_size = layout_result.layout_tree.get_content_size(node_idx);
                let thickness = sb.scrollbar_width.max(sb.scrollbar_height);
                regs.push((
                    *dom_id,
                    dom_node_id,
                    container_rect,
                    content_size,
                    thickness,
                    sb.visual_width_px,
                    sb.needs_horizontal,
                    sb.needs_vertical,
                ));
            }
        }
        for (dom_id, node_id, container_rect, content_size, thickness, vis, h, v) in regs {
            lw.scroll_manager.register_or_update_scroll_node(
                dom_id, node_id, container_rect, content_size, now.clone(), thickness, vis, h, v,
            );
        }
        lw.scroll_manager.calculate_scrollbar_states();
    }
}

/// Port of the DLL's `apply_focus_restyle` (`.../common/event.rs`): apply the
/// `:focus` / `:focus-within` state change to the styled DOM and classify how
/// much work the resulting property deltas need.
///
/// Without this a click (or a Tab) moved focus but left the node painted
/// unfocused until the next full DOM regeneration.
fn apply_focus_restyle(
    layout_window: &mut LayoutWindow,
    old_focus: Option<NodeId>,
    new_focus: Option<NodeId>,
) -> ProcessEventResult {
    use azul_core::{diff::ChangeAccumulator, styled_dom::FocusChange};

    let Some((_, layout_result)) = layout_window.layout_results.iter_mut().next() else {
        return ProcessEventResult::ShouldReRenderCurrentWindow;
    };

    let restyle_result = layout_result.styled_dom.restyle_on_state_change(
        Some(FocusChange {
            lost_focus: old_focus,
            gained_focus: new_focus,
        }),
        None, // hover
        None, // active
    );

    if restyle_result.changed_nodes.is_empty() || restyle_result.gpu_only_changes {
        return ProcessEventResult::ShouldReRenderCurrentWindow;
    }

    let mut accumulator = ChangeAccumulator::new();
    accumulator.merge_restyle_result(&restyle_result);
    if accumulator.needs_layout() {
        ProcessEventResult::ShouldIncrementalRelayout
    } else if accumulator.needs_paint_only() {
        ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
    } else {
        ProcessEventResult::ShouldReRenderCurrentWindow
    }
}

/// Port of the caret half of the DLL's `SystemChange::SetFocus` /
/// `CallbackChange::SetFocusTarget` handling.
///
/// `handle_focus_change_for_cursor_blink` is what FLAGS a contenteditable focus
/// for caret initialisation; `finalize_pending_focus_changes` (already called at
/// the end of every pass) is what turns that flag into a real cursor. The runner
/// called only the second one, so the flag was never set, no cursor was ever
/// created, and `text_input` went through `record_text_input` (which only needs a
/// focused node) into `apply_text_changeset` (which needs a CURSOR) and produced
/// zero dirty nodes — a silent no-op with focus in place.
///
/// The returned `CursorBlinkTimerAction` is HONOURED: this host now has a timer
/// driver ([`Runner::pump_timers`]), so focusing a contenteditable really
/// registers `CURSOR_BLINK_TIMER_ID` and leaving one really removes it. The
/// action used to be dropped on the floor with "no timer driver, the caret is
/// drawn steady instead of blinking", which made caret blink untestable.
///
/// The DLL splits this over two seams — the platform trait's
/// `start_timer` / `stop_timer` arm the OS wakeup, and
/// `CallbackChange::StartCursorBlinkTimer` is what inserts the `Timer` into
/// `LayoutWindow::timers`. Here the two are the same thing: `timers` IS the
/// driver, so `Start` inserts and `Stop` removes, exactly as the DLL's
/// `StartCursorBlinkTimer` / `StopCursorBlinkTimer` arms do.
fn arm_caret_for_focus(
    layout_window: &mut LayoutWindow,
    new_focus: Option<DomNodeId>,
    window_state: &FullWindowState,
) {
    use azul_core::task::CURSOR_BLINK_TIMER_ID;
    use azul_layout::CursorBlinkTimerAction;

    match layout_window.handle_focus_change_for_cursor_blink(new_focus, window_state) {
        CursorBlinkTimerAction::Start(timer) => {
            layout_window.add_timer(CURSOR_BLINK_TIMER_ID, timer);
        }
        CursorBlinkTimerAction::Stop => {
            layout_window.remove_timer(&CURSOR_BLINK_TIMER_ID);
        }
        CursorBlinkTimerAction::NoChange => {}
    }
}

/// Port of the DLL's `apply_hover_restyle` (`.../common/event.rs`): apply this
/// pass's MouseEnter / MouseLeave targets to the styled DOM so pure-CSS
/// `:hover` rules take effect without a DOM regeneration.
fn apply_hover_restyle(
    layout_window: &mut LayoutWindow,
    changes_per_dom: BTreeMap<DomId, azul_core::styled_dom::HoverChange>,
) -> ProcessEventResult {
    use azul_core::diff::ChangeAccumulator;

    let mut result = ProcessEventResult::DoNothing;
    for (dom_id, hover_change) in changes_per_dom {
        let Some(layout_result) = layout_window.layout_results.get_mut(&dom_id) else {
            continue;
        };
        let restyle_result =
            layout_result
                .styled_dom
                .restyle_on_state_change(None, Some(hover_change), None);
        if restyle_result.changed_nodes.is_empty() {
            continue;
        }
        let r = if restyle_result.gpu_only_changes {
            ProcessEventResult::ShouldReRenderCurrentWindow
        } else {
            let mut accumulator = ChangeAccumulator::new();
            accumulator.merge_restyle_result(&restyle_result);
            if accumulator.needs_layout() {
                ProcessEventResult::ShouldIncrementalRelayout
            } else if accumulator.needs_paint_only() {
                ProcessEventResult::ShouldUpdateDisplayListCurrentWindow
            } else {
                ProcessEventResult::ShouldReRenderCurrentWindow
            }
        };
        result = result.max(r);
    }
    result
}

/// Port of `parse_node_type_from_str` (dll/.../common/event.rs) — the `insert_node`
/// op's `node_type` string (`"div"`, `"p"`, `"text:HELLO"`, …) → `NodeType`.
fn parse_node_type_from_str(s: &str) -> azul_core::dom::NodeType {
    use azul_core::dom::NodeType;
    if let Some(text) = s.strip_prefix("text:") {
        return NodeType::Text(azul_css::css::BoxOrStatic::heap(text.to_string().into()));
    }
    match s.to_lowercase().as_str() {
        "html" => NodeType::Html,
        "head" => NodeType::Head,
        "body" => NodeType::Body,
        "p" => NodeType::P,
        "article" => NodeType::Article,
        "section" => NodeType::Section,
        "nav" => NodeType::Nav,
        "aside" => NodeType::Aside,
        "header" => NodeType::Header,
        "footer" => NodeType::Footer,
        "main" => NodeType::Main,
        "h1" => NodeType::H1,
        "h2" => NodeType::H2,
        "h3" => NodeType::H3,
        "h4" => NodeType::H4,
        "h5" => NodeType::H5,
        "h6" => NodeType::H6,
        "br" => NodeType::Br,
        "hr" => NodeType::Hr,
        "pre" => NodeType::Pre,
        "blockquote" => NodeType::BlockQuote,
        "ul" => NodeType::Ul,
        "ol" => NodeType::Ol,
        "li" => NodeType::Li,
        "table" => NodeType::Table,
        "thead" => NodeType::THead,
        "tbody" => NodeType::TBody,
        "tr" => NodeType::Tr,
        "th" => NodeType::Th,
        "td" => NodeType::Td,
        "form" => NodeType::Form,
        "label" => NodeType::Label,
        "input" => NodeType::Input,
        "button" => NodeType::Button,
        _ => NodeType::Div,
    }
}

fn fail_result(test: &E2eTest, reason: &str) -> E2eTestResult {
    E2eTestResult {
        name: test.name.clone(),
        status: "fail".into(),
        duration_ms: 0,
        step_count: test.steps.len(),
        steps_passed: 0,
        steps_failed: test.steps.len(),
        steps: Vec::new(),
        final_screenshot: Some(format!("[runner] {reason}")),
    }
}

/// Run a single E2E JSON test end-to-end through the REAL server op-dispatch,
/// headlessly. Returns the server's own [`E2eTestResult`] (pass/fail + per-step
/// results) — the same value the HTTP `run_e2e_tests` command produces.
#[must_use]
pub fn run_e2e_test(test: &E2eTest) -> E2eTestResult {
    // Start this scenario on a clean clock. The `tick_ms` / `wait` ops advance a
    // clock scoped to the calling thread, and worker threads are reused across
    // scenarios — without this reset the next scenario scheduled onto this
    // thread would start with the previous one's accumulated offset.
    azul_core::task::reset_test_clock();
    // ...and then STOP real time for this thread, so engine time is a pure
    // function of the ops this scenario runs. Otherwise elapsed time is
    // (what the scenario asked for) + (what this build, under this load, spent
    // computing), and the suite runs scenarios 8-wide: that second term is large
    // and varies run to run, which is enough to flip an assertion on a blinking
    // caret's phase while the same scenario passes 10/10 in isolation.
    //
    // Only the ENGINE clock stops. The harness keeps measuring itself with
    // `wall_clock_now()`, so reported step durations stay real.
    azul_core::task::freeze_test_clock();

    // This scenario's own scheduler slot. It is a LOCAL, not a `Runner` field,
    // only because `Runner::with_callback_info` takes `&mut self` and the
    // dispatcher needs `&mut` on the session at the same time — borrowck, not
    // ambient state. It has exactly the lifetime of this run.
    let mut session = E2eSession::new();

    let (w, h, dpi) = match &test.setup {
        Some(s) => (s.window_width as f32, s.window_height as f32, s.dpi),
        None => (800.0, 600.0, 96),
    };
    let mut runner = Runner::new(w, h, dpi);

    let (tx, rx) = std::sync::mpsc::channel();
    let request = DebugRequest {
        request_id: 1,
        event: DebugEvent::RunE2eTests { tests: vec![test.clone()], snapshots: None },
        window_id: None,
        wait_for_render: false,
        response_tx: tx,
    };
    let mut app_data = RefAny::new(());
    let component_map = Arc::new(Mutex::new(ComponentMap::default()));
    let callback_changes: Arc<Mutex<Vec<CallbackChange>>> = Arc::new(Mutex::new(Vec::new()));

    // First dispatch: RunE2eTests sets up the continuation and runs it until the
    // first yield (or completion).
    let needs_update = runner.with_callback_info(&callback_changes, |ci| {
        process_debug_event(&request, ci, &mut app_data, &component_map, &mut session)
    });
    runner.service(&callback_changes, needs_update);

    // Pump the continuation until it terminates (the result is sent on the final
    // resume). A generous cap guards against a non-terminating scenario.
    let mut iterations = 0usize;
    loop {
        let (needs_update, still_pending, resume_not_before) = runner
            .with_callback_info(&callback_changes, |ci| {
                e2e_pump_continuation(ci, &mut session)
            });

        // `resume_not_before` is never set to `Some` anywhere in the tree: a
        // `wait` yields with no deadline and advances the injectable clock
        // instead, so scenario time is a pure function of the ops a scenario ran
        // rather than of how fast the build is.
        //
        // This used to `std::thread::sleep` to the deadline. That is now
        // unreachable, and leaving it would be a landmine: the moment anything
        // repopulated the field the whole suite would silently go back to being
        // pinned to realtime — the exact regression that made
        // `bug_font_never_removed` red only on unoptimized builds. It would also
        // reintroduce a `std::time::Instant::now()` here, which panics on
        // wasm32.
        //
        // So it fails loudly instead. If you are here because this fired, the
        // fix is to advance the test clock (`advance_test_clock_ms`), not to
        // sleep.
        assert!(
            resume_not_before.is_none(),
            "e2e runner: scenario '{}' asked to resume at a wall-clock deadline. Scenario time \
             is virtual — advance the injectable clock instead of sleeping, or the suite is \
             pinned to realtime again.",
            test.name,
        );
        runner.service(&callback_changes, needs_update);

        if !still_pending {
            break;
        }
        iterations += 1;
        assert!(
            iterations < 100_000,
            "e2e runner: continuation for '{}' did not terminate",
            test.name
        );
    }

    let result = match rx.try_recv() {
        Ok(DebugResponseData::Ok { data: Some(ResponseData::E2eResults(r)), .. }) => r
            .results
            .into_iter()
            .next()
            .unwrap_or_else(|| fail_result(test, "RunE2eTests returned no results")),
        Ok(DebugResponseData::Ok { .. }) => {
            fail_result(test, "RunE2eTests returned a non-E2eResults response")
        }
        Ok(DebugResponseData::Err(e)) => fail_result(test, &e),
        Err(_) => fail_result(test, "RunE2eTests produced no response"),
    };

    // A scenario that asked the engine for something this host cannot do is
    // RED, no matter what its assertions said: they were evaluated against a
    // window where that something never happened. Reported per unsupported
    // change, by name — see `Runner::unsupported`.
    unsupported_to_failure(result, &runner.unsupported_changes)
}

/// Fold the runner's unsupported-change log into the scenario result, turning a
/// pass that skipped work into a named failure.
fn unsupported_to_failure(mut result: E2eTestResult, unsupported: &[String]) -> E2eTestResult {
    if unsupported.is_empty() {
        return result;
    }
    // Deduplicate: one line per distinct facility, not one per applied change.
    let mut seen: Vec<&String> = Vec::new();
    for u in unsupported {
        if !seen.contains(&u) {
            seen.push(u);
        }
    }
    let next_index = result.steps.len();
    for (i, message) in seen.iter().enumerate() {
        result.steps.push(E2eStepResult {
            step_index: next_index + i,
            op: "unsupported_callback_change".to_string(),
            status: "fail".to_string(),
            duration_ms: 0,
            logs: Vec::new(),
            screenshot: None,
            error: Some((*message).clone()),
            response: None,
        });
    }
    result.status = "fail".to_string();
    result.steps_failed += seen.len();
    result.step_count = result.steps.len();
    result
}