teksilo-core 0.9.0

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

use super::*;

use crate::gesture::{GestureEvent, RawPointerEvent, TapEvent};

/// Fire an `EventResponse`-returning handler from BOTH the external
/// and own slots (in that order). Returns `Handled` if either did,
/// `Ignored` otherwise. `None` slots are skipped.
fn fire_event_handler_both(
    external: &mut Option<Box<dyn FnMut(&WidgetEvent, &mut EventContext) -> EventResponse>>,
    own: &mut Option<Box<dyn FnMut(&WidgetEvent, &mut EventContext) -> EventResponse>>,
    event: &WidgetEvent,
    ctx: &mut EventContext,
) -> EventResponse {
    let r1 = external
        .as_mut()
        .map(|h| h(event, ctx))
        .unwrap_or(EventResponse::Ignored);
    let r2 = own
        .as_mut()
        .map(|h| h(event, ctx))
        .unwrap_or(EventResponse::Ignored);
    if r1 == EventResponse::Handled || r2 == EventResponse::Handled {
        EventResponse::Handled
    } else {
        EventResponse::Ignored
    }
}

impl WidgetTree {
    /// Hops from `focus` up to `scope_id` (0 when equal), or `None` when
    /// `scope_id` is not an ancestor-or-self of `focus`. Fewer hops means
    /// the scope sits closer to focus — i.e. a more specific binding.
    fn scope_distance_from_focus(&self, focus: WidgetId, scope_id: WidgetId) -> Option<usize> {
        let mut hops = 0usize;
        let mut current = Some(focus);
        while let Some(c) = current {
            if c == scope_id {
                return Some(hops);
            }
            current = self.arena.parent(c);
            hops += 1;
        }
        None
    }

    /// From every same-chord shortcut candidate, choose the one whose
    /// scope applies to the current focus, preferring the most specific
    /// scope: a `Scoped` binding whose subtree contains focus beats a
    /// `Global` one, and among nested applicable scopes the one closest
    /// to focus (fewest hops) wins. Equal-specificity ties keep the
    /// deterministic `(category, id)` order `candidates` arrives in (the
    /// first such candidate wins). Returns `None` when no candidate
    /// applies — every match is a scoped binding outside the focused
    /// subtree — so the caller falls through to normal KeyDown dispatch.
    fn select_shortcut_for_focus(
        &self,
        candidates: &[(&'static str, crate::shortcut::ShortcutScope, bool)],
    ) -> Option<(&'static str, crate::shortcut::ShortcutScope, bool)> {
        use crate::shortcut::ShortcutScope;
        let mut best: Option<(usize, (&'static str, ShortcutScope, bool))> = None;
        for &(id, scope, propagate) in candidates {
            // Specificity score, higher = more specific. Global is the
            // least-specific fallback (0); any applicable scoped binding
            // outranks it (`usize::MAX - hops`, so fewer hops = deeper
            // scope = higher score). Tree depth is tiny, so no overflow.
            let score = match scope {
                ShortcutScope::Global => Some(0usize),
                ShortcutScope::Scoped(scope_id) => self
                    .focused
                    .and_then(|f| self.scope_distance_from_focus(f, scope_id))
                    .map(|hops| usize::MAX - hops),
            };
            let Some(score) = score else { continue };
            // Strictly-greater keeps the first candidate on a tie, so the
            // existing `(category, id)` precedence holds within a scope.
            if best.as_ref().is_none_or(|(b, _)| score > *b) {
                best = Some((score, (id, scope, propagate)));
            }
        }
        best.map(|(_, c)| c)
    }

    /// Dispatch an event into the widget tree.
    ///
    /// Routing rules:
    /// - Pointer events -> hit testing against layout tree
    /// - Keyboard/IME events -> focused widget
    /// - AccessKit actions -> target widget directly
    /// - Scroll events -> hit testing (scroll target under pointer)
    ///
    /// Dispatch an event with the caller-supplied app-level
    /// [`WindowOps`](crate::window::WindowOps) sink. `teksilo-app` calls
    /// this variant; handlers can reach the multi-window API
    /// synchronously (`open_window` creates the winit window inside
    /// the same call before returning).
    pub fn dispatch_event_with_ops(
        &mut self,
        event: WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        self.dispatch_event_impl(event, ops)
    }

    /// Dispatch an event on a standalone tree (tests, headless
    /// scenarios). Handler code that calls `ctx.open_window(...)`
    /// from within this dispatch will panic — by design. See
    /// [`dispatch_event_with_ops`](Self::dispatch_event_with_ops)
    /// for the app-facing variant.
    pub fn dispatch_event(&mut self, event: WidgetEvent) {
        let mut noop = crate::window::NoopWindowOps;
        self.dispatch_event_impl(event, &mut noop);
    }

    fn dispatch_event_impl(&mut self, event: WidgetEvent, ops: &mut dyn crate::window::WindowOps) {
        // Track input modality for `:focus-visible`: keyboard input reveals
        // focus rings, pointer input hides them. Updated at the dispatch root so
        // every handler (and the next paint) observes the current modality.
        match &event {
            WidgetEvent::KeyDown { .. } if !self.focus_visible.get() => {
                self.focus_visible.set(true);
            }
            WidgetEvent::PointerDown { .. } if self.focus_visible.get() => {
                self.focus_visible.set(false);
            }
            _ => {}
        }

        // The "back toward the parent overlay" key closes the top nested
        // overlay (e.g. an open submenu over its parent menu). It is the
        // inline-start arrow: ArrowLeft under LTR, ArrowRight under RTL.
        // Without the RTL flip, ArrowLeft would navigate *into* a submenu
        // in RTL menus yet still dismiss it here.
        let overlay_back_key = match self.layout_direction {
            crate::environment::LayoutDirection::RightToLeft => Key::ArrowRight,
            crate::environment::LayoutDirection::LeftToRight => Key::ArrowLeft,
        };
        if let WidgetEvent::KeyDown { key, .. } = &event
            && *key == overlay_back_key
        {
            // Count menu-level (non-host) overlays. A revealed collapsible
            // `MenuBar` is itself a *host* overlay (Role::MenuBar), so a
            // single open top-level menu sitting over it must NOT be treated
            // as a nested submenu — otherwise the back key would close the
            // menu instead of letting the menubar navigate to the previous
            // one. Only when ≥2 non-host overlays are stacked (a submenu over
            // its parent menu) does the back key dismiss the top overlay.
            let nested_menu_overlays = {
                let ids: Vec<_> = self.overlay_manager.stack.iter().map(|o| o.id).collect();
                ids.into_iter()
                    .filter(|&id| !self.overlay_is_host_surface(id))
                    .count()
            };
            // The back key only navigates *menu* cascades; it must never close a
            // dialog / alert / modal that happens to sit on top. Each modal is a
            // scrim+panel overlay pair and the (non-host) scrims inflate the count
            // above, so also require the *topmost* overlay to be back-navigable —
            // i.e. a non-host (menu) surface — before dismissing it.
            let top_id = self.overlay_manager.stack.last().map(|o| o.id);
            let top_is_back_navigable = top_id.is_some_and(|id| !self.overlay_is_host_surface(id));
            if nested_menu_overlays > 1 && top_is_back_navigable {
                if let Some((_id, content_ids, focus_restore)) = self.overlay_manager.dismiss_top()
                {
                    self.dormant_dismissed_content(&content_ids, &mut *ops);
                    if let Some(restore_id) = focus_restore
                        && self.arena.is_active(restore_id)
                    {
                        self.focus_ops(restore_id, &mut *ops);
                    }
                }
                return;
            }
        }

        // Escape retires any shown tooltip first, and does **not** stop there —
        // see `tooltip_escape_pressed`. Ordered before the stack walk below so
        // that walk can no longer pick a tooltip as the thing to dismiss, which
        // is what used to spend the key on a tip nobody was reading while the
        // editor / menu / dialog the user meant stayed open.
        if let WidgetEvent::KeyDown {
            key: Key::Escape, ..
        } = &event
        {
            self.tooltip_escape_pressed();
        }

        if let WidgetEvent::KeyDown {
            key: Key::Escape, ..
        } = &event
            && !self.overlay_manager.is_empty()
            && let Some((_id, content_ids, focus_restore)) =
                self.overlay_manager.try_dismiss_top_on_escape()
        {
            self.dormant_dismissed_content(&content_ids, &mut *ops);
            if let Some(restore_id) = focus_restore
                && self.arena.is_active(restore_id)
            {
                self.focus_ops(restore_id, &mut *ops);
            }
            return;
        }

        if let WidgetEvent::PointerDown {
            position, button, ..
        } = &event
        {
            let (dismissed, focus_restore, toggle_anchors) =
                self.overlay_manager.handle_click_outside(*position);
            if !dismissed.is_empty() {
                self.dormant_dismissed_content(&dismissed, &mut *ops);
                if let Some(restore_id) = focus_restore
                    && self.arena.is_active(restore_id)
                {
                    self.focus_ops(restore_id, &mut *ops);
                }
                // The press dismissed one or more overlays. By default it
                // now ALSO falls through to the widget under the cursor,
                // so a single click both closes the menu/popover and
                // activates the control beneath — the behaviour a
                // secondary press already had. The one case still
                // swallowed: a primary press on the anchor of a
                // click-opened overlay, because the anchor's own tap
                // handler would otherwise reopen the overlay this very
                // press just dismissed (click-the-trigger-to-close).
                let on_toggle_anchor = *button == PointerButton::Primary
                    && toggle_anchors.iter().any(|&anchor| {
                        self.arena.is_active(anchor)
                            && self.arena.bounds(anchor).contains(*position)
                    });
                if on_toggle_anchor {
                    return;
                }
            }
        }

        // Key-capture mode: if a callback is armed (via
        // `WidgetTree::begin_key_capture`), the next KeyDown bypasses
        // shortcut resolution entirely and runs the callback with
        // mutable access to the registry AND an `EventContext` so
        // rebind handlers can also emit commands, send intents,
        // dismiss overlays, etc. The capture is one-shot; its slot
        // is emptied before the callback runs so a re-entrant
        // `begin_key_capture` call from inside the callback arms a
        // fresh session (rather than competing with the in-flight
        // one).
        if let WidgetEvent::KeyDown { key, modifiers, .. } = &event
            && let Some(callback) = self.take_key_capture()
        {
            let keystroke = crate::shortcut::KeyStroke::new(*key, *modifiers);
            let mut cap_ctx = self.make_event_context(&mut *ops);
            callback(keystroke, self.shortcut_registry_mut(), &mut cap_ctx);
            // Route side effects of the callback through the
            // focused widget (or an arbitrary root if no focus).
            let anchor = self.focused.or_else(|| self.arena.roots().first().copied());
            if let Some(anchor_id) = anchor {
                self.collect_from_ctx(cap_ctx, anchor_id);
                self.drain_pending_intents(&mut *ops);
            }
            return;
        }

        // Keyboard-capture surfaces (a terminal, a game viewport) opt out
        // of shortcut resolution entirely while focused: they want every
        // keystroke delivered raw so a host-app `Ctrl+C` shortcut can't
        // steal the SIGINT the child process needs. The Escape / overlay
        // back-navigation handled above still runs first, so an open
        // overlay is still dismissable. Only a KeyDown is affected; KeyUp
        // and IME already bypass the shortcut path.
        let focus_captures_keys = matches!(&event, WidgetEvent::KeyDown { .. })
            && self.focused.is_some_and(|f| self.is_keyboard_capture(f));

        // Shortcut → intent → action dispatch. A KeyDown whose chord
        // matches a registered enabled `Shortcut` whose scope contains
        // the focused widget is consumed here: the shortcut's
        // `on_activate` runs (producing an `Intent`), its ctx side
        // effects are collected, and the intent walks source-widget →
        // root firing any matching `Action`. Otherwise the focused
        // widget sees the raw KeyDown below.
        //
        // Two-phase: the registry is inspected first (immutable read)
        // to resolve `id / scope / propagate_when_disabled`. Only if
        // scope matches the current focus do we take a mutable borrow
        // to invoke `on_activate` — this way a scope mismatch cannot
        // drop side effects the closure put into its ctx, because
        // the closure never runs.
        if !focus_captures_keys && let WidgetEvent::KeyDown { key, modifiers, .. } = &event {
            let keystroke = crate::shortcut::KeyStroke::new(*key, *modifiers);
            // Gather every same-chord candidate (owned fields) before any
            // mutable borrow of the registry, then pick the one whose scope
            // actually applies to the current focus. `find_by_keystroke`
            // alone yields only the first by `(category, id)` order, which
            // can be a `Scoped` binding outside focus shadowing an
            // applicable `Global` one — or a `Global` binding that should
            // yield to an in-focus `Scoped` one. Selection needs focus +
            // the tree, so it happens here, not in the registry.
            let candidates: Vec<(&'static str, crate::shortcut::ShortcutScope, bool)> = self
                .shortcut_registry
                .matches_by_keystroke(keystroke)
                .map(|eff| {
                    (
                        eff.shortcut.id,
                        eff.shortcut.scope,
                        eff.shortcut.propagate_when_disabled,
                    )
                })
                .collect();
            let lookup = self.select_shortcut_for_focus(&candidates);
            if let Some((id, scope, propagate_when_disabled)) = lookup {
                let anchor = match scope {
                    // Global shortcuts fire regardless of focus. If no
                    // widget is currently focused, anchor the intent
                    // walk at an arbitrary root so actions registered
                    // at the top of the tree still see the intent.
                    crate::shortcut::ShortcutScope::Global => {
                        self.focused.or_else(|| self.arena.roots().first().copied())
                    }
                    crate::shortcut::ShortcutScope::Scoped(scope_id) => {
                        self.focused.filter(|f| self.is_descendant_of(*f, scope_id))
                    }
                };
                if let Some(anchor_id) = anchor {
                    let mut act_ctx = self.make_event_context(&mut *ops);
                    if let Some(intent) =
                        self.shortcut_registry
                            .invoke_on_activate(id, keystroke, &mut act_ctx)
                    {
                        self.collect_from_ctx(act_ctx, anchor_id);
                        // Tag shortcut origin so analytics can
                        // distinguish keyboard-driven activations from
                        // button / menu / programmatic ones.
                        let intent = intent.with_source(crate::telemetry::IntentSource::Shortcut);
                        self.enqueue_intent(anchor_id, intent, propagate_when_disabled);
                        self.drain_pending_intents(&mut *ops);
                        return;
                    }
                }
                // Chosen candidate had no anchor after all (e.g. a Global
                // match while nothing is focused and the tree has no
                // roots) — fall through to normal KeyDown dispatch.
                // `on_activate` was never called, so nothing to clean up.
            }
            // `lookup` is `None` when every same-chord candidate was a
            // scoped binding outside the focused subtree — fall through.
        }

        // Escape during an OS drag we escalated. There is no `active_drag`
        // any more — `try_escalate_to_os_drag` took it when the platform
        // accepted the hand-off — so this cannot live in the block below, but
        // it is the same user gesture and belongs on the same path rather than
        // being special-cased in the event loop of whichever backend needs it.
        if self.outbound_drag_source.is_some()
            && let WidgetEvent::KeyDown {
                key: Key::Escape, ..
            } = &event
        {
            ops.cancel_os_drag();
            // Deliberately no `return`: the backend answers asynchronously with
            // a terminal `DragEnded`, which is what actually tears the session
            // down via `handle_os_drag_ended`. Swallowing the key here would
            // also stop Escape from closing whatever else is open.
        }

        // --- Active drag session handling ---
        if self.active_drag.is_some() {
            match &event {
                WidgetEvent::PointerMove { position } => {
                    self.handle_drag_move(*position, &mut *ops);
                    return;
                }
                WidgetEvent::PointerUp { position, .. } => {
                    self.handle_drag_drop(*position, &mut *ops);
                    return;
                }
                WidgetEvent::KeyDown {
                    key: Key::Escape, ..
                } => {
                    self.cancel_active_drag(&mut *ops);
                    return;
                }
                WidgetEvent::Scroll { .. } => {
                    // Route the wheel to the current drop target so users
                    // can scroll the list/tree beneath the drag. Then
                    // synthesise a hover at the stationary pointer so
                    // feedback, drop-index math and the preview overlay
                    // all reflect the new scroll offset.
                    let target_and_pos = self
                        .active_drag
                        .as_ref()
                        .and_then(|d| d.current_target.map(|t| (t, d.current_position)));
                    if let Some((target, _pos)) = target_and_pos {
                        self.dispatch_to_widget(target, &event, &mut *ops);
                    }
                    if let Some((_, pos)) = target_and_pos
                        && self.active_drag.is_some()
                    {
                        self.handle_drag_move(pos, &mut *ops);
                    }
                    return;
                }
                _ => {}
            }
        }

        match &event {
            WidgetEvent::PointerMove { position } => {
                if let Some(captured) = self.pointer_captured_by {
                    self.dispatch_to_widget(
                        captured,
                        &WidgetEvent::PointerMove {
                            position: *position,
                        },
                        &mut *ops,
                    );
                    // Let armed ancestor drag recognizers observe the move so
                    // an ancestor drag can start while a descendant tap holds
                    // the capture. Once a drag latches, `active_drag` takes
                    // over and the capture branch above is bypassed.
                    if self.active_drag.is_none() {
                        self.advance_drag_observers(
                            &WidgetEvent::PointerMove {
                                position: *position,
                            },
                            &mut *ops,
                        );
                    }
                } else {
                    self.handle_pointer_move(*position, &mut *ops);
                }
                self.update_pointer_leave_overlays(*position, &mut *ops);
            }
            WidgetEvent::PointerDown {
                position, button, ..
            } => {
                // The user has acted — a tooltip that has not yet appeared is
                // now answering a question nobody is asking any more, and one
                // already up is covering the thing being clicked. Cancel the
                // pending dwell and retire any shown non-sticky tip, the way
                // Windows and GTK both do. Runs before hit-testing so it fires
                // even for a press that lands on nothing.
                self.tooltip_pointer_press(Some(*position));
                if let Some(target) = self.hit_test(*position) {
                    if *button == PointerButton::Secondary
                        && self.show_context_menu_for(target, *position, &mut *ops)
                    {
                        return;
                    }
                    if let Some(focusable) = self.find_focusable_at_or_above(target) {
                        self.focus_with_origin_ops(
                            focusable,
                            crate::focus::FocusOrigin::Pointer,
                            &mut *ops,
                        );
                    }
                    self.dispatch_to_widget(target, &event, &mut *ops);
                    // If a descendant captured the pointer for a tap (no drag
                    // started), arm ancestor drag recognizers so an ancestor
                    // drag can still begin on move (tap-vs-drag across the
                    // hit-path).
                    if self.active_drag.is_none()
                        && let Some(captured) = self.pointer_captured_by
                    {
                        self.arm_drag_observers(captured, &event, &mut *ops);
                    }
                }
            }
            WidgetEvent::PointerUp { position, .. } => {
                // The pointer sequence ends here — feed the `Up` to any armed
                // ancestor drag observers so their recognizer clears the press
                // origin it recorded on the press. Without this, a press that
                // an interactive descendant captured (a card's editor, a row's
                // button) leaves the ancestor's DragRecognizer armed, and the
                // next hover move starts a phantom drag. Also discards the list.
                self.release_drag_observers(&event, &mut *ops);
                if let Some(captured) = self.pointer_captured_by {
                    self.dispatch_to_widget(captured, &event, &mut *ops);
                    self.pointer_captured_by = None;
                } else if let Some(target) = self.hit_test(*position) {
                    self.dispatch_to_widget(target, &event, &mut *ops);
                }
            }
            WidgetEvent::Scroll { .. } => {
                if let Some(target) = self.hovered.or(self.focused) {
                    self.dispatch_to_widget(target, &event, &mut *ops);
                }
            }
            WidgetEvent::KeyDown { key, modifiers, .. } => {
                if *key == Key::Tab {
                    // Ctrl+Tab / Ctrl+Shift+Tab always leave a keyboard-capture
                    // surface (WCAG 2.1.2). A capture node exists precisely to
                    // swallow every keystroke — a terminal encodes Tab as `\t`
                    // and Shift+Tab as CSI Z — so the ordinary "dispatch first,
                    // cycle only when unhandled" rule below can never move focus
                    // out of one. Reserving this one chord at the dispatcher, not
                    // in each capture widget, is what makes the escape a property
                    // of `keyboard_capture` itself rather than a promise every
                    // future capture-surface author has to remember to keep.
                    //
                    // Literal `ctrl()`, not `command()`: Ctrl+Tab is Ctrl+Tab on
                    // macOS too — ⌘⇥ is the application switcher and never
                    // reaches an app at all. Same reading as `TableView`'s
                    // cell-grid escape and `RichTextEditor`'s `tab_escape`.
                    let captured_focus = self
                        .focused
                        .is_some_and(|focused| self.is_keyboard_capture(focused));
                    if captured_focus && modifiers.ctrl() {
                        self.cycle_focus(modifiers.shift(), &mut *ops);
                        return;
                    }
                    // Dispatch Tab to the focused widget first so
                    // ancestors (e.g. an open overlay that wants to
                    // close instead of moving focus out through its
                    // content) get a chance to intercept. Fall back to
                    // built-in focus cycling only when no handler
                    // returns `EventResponse::Handled`.
                    let handled = self
                        .focused
                        .map(|focused| {
                            self.dispatch_to_widget_returning_handled(focused, &event, &mut *ops)
                        })
                        .unwrap_or(false);
                    if !handled {
                        self.cycle_focus(modifiers.shift(), &mut *ops);
                    }
                } else if let Some(focused) = self.focused {
                    self.dispatch_to_widget(focused, &event, &mut *ops);
                }
            }
            WidgetEvent::KeyUp { .. }
            | WidgetEvent::ImeComposition { .. }
            | WidgetEvent::ImeCommit { .. } => {
                if let Some(focused) = self.focused {
                    self.dispatch_to_widget(focused, &event, &mut *ops);
                }
            }
            WidgetEvent::AccessAction { target, action, .. } => {
                // An AT action (e.g. VoiceOver's VO+Space → `Action::Click`)
                // always names the node it targets — the element under the
                // assistive-technology cursor. It must be delivered to THAT
                // node, never to whatever happens to hold keyboard focus.
                // Falling back to `self.focused` would make VO+Space fire the
                // focused control instead of the cursored one, and would mask
                // a stale/inactive target by silently activating something
                // else. If the target is missing or no longer active, drop the
                // action rather than redirecting it.
                if let Some(id) = target.filter(|id| self.arena.is_active(*id)) {
                    if *action == accesskit::Action::Focus {
                        self.focus_with_origin_ops(
                            id,
                            crate::focus::FocusOrigin::Programmatic,
                            &mut *ops,
                        );
                        // Focus is serviced here rather than by the widget, so
                        // "handled" means the focus actually landed.
                        self.access_action_handled = self.focused == Some(id);
                    } else if *action == accesskit::Action::ShowContextMenu {
                        // A "show context menu" AT action — a screen reader's
                        // menu key, or an automation `right_click` /
                        // `invoke_action(node, "show_context_menu")` — first
                        // offers itself to the node's own `on_access_action`
                        // handlers. If none consume it, fall through to the very
                        // same machinery a Secondary `PointerDown` drives, so a
                        // widget's `.context_menu(..)` factory opens without the
                        // caller having to synthesise a right-click. The AT
                        // action carries no point, so anchor the menu at the
                        // node's centre. Without this, the AT action was a silent
                        // no-op for every widget that wires its menu through the
                        // factory (i.e. all of them) — see `show_context_menu_for`.
                        // Handled = the widget consumed it, or the factory
                        // fallback actually opened a menu. A node with neither
                        // reports unhandled rather than a silent success.
                        self.access_action_handled =
                            if self.dispatch_to_widget_returning_handled(id, &event, &mut *ops) {
                                true
                            } else {
                                let position = self.arena.bounds(id).center();
                                self.show_context_menu_for(id, position, &mut *ops)
                            };
                    } else {
                        self.access_action_handled =
                            self.dispatch_to_widget_returning_handled(id, &event, &mut *ops);
                    }
                }
            }
            WidgetEvent::Gesture { .. } => {
                if let Some(target) = self.hovered.or(self.focused) {
                    self.dispatch_to_widget(target, &event, &mut *ops);
                }
            }
            WidgetEvent::ScrollIntoView { .. }
            | WidgetEvent::PointerEnter
            | WidgetEvent::PointerLeave
            | WidgetEvent::FocusGained { .. }
            | WidgetEvent::FocusLost => {}
        }
        // Any intents queued by handlers via `ctx.send_intent(...)`
        // are dispatched after the raw event has been handled but
        // before commands are flushed, so commands emitted from
        // action handlers land on the same tick.
        self.drain_pending_intents(&mut *ops);
    }

    fn show_context_menu_for(
        &mut self,
        target: WidgetId,
        position: Point,
        ops: &mut dyn crate::window::WindowOps,
    ) -> bool {
        // Walks up the parent chain calling each factory in turn. A
        // factory returning `Some(menu)` claims the click and mounts;
        // a factory returning `None` declines and the walk continues.
        // No factory anywhere on the chain → fall through to whatever
        // the caller does with the unconsumed PointerDown.
        let mut ctx = self.make_event_context(&mut *ops);
        let mut walker = Some(target);
        let menu_decision: Option<(WidgetId, Box<dyn Widget>)> = loop {
            // Walk to the next ancestor (including `walker` itself)
            // that owns a factory.
            let owner_id = {
                let mut probe = walker;
                loop {
                    match probe {
                        None => break None,
                        Some(id) => {
                            if self
                                .arena
                                .get(id)
                                .is_some_and(|node| node.context_menu_factory.is_some())
                            {
                                break Some(id);
                            }
                            probe = self.arena.get(id).and_then(|node| node.parent);
                        }
                    }
                }
            };
            let Some(owner_id) = owner_id else {
                break None;
            };
            // Invoke the factory with the click position and a real
            // EventContext. The factory is `Fn` (not FnMut), so we
            // can call it through an immutable borrow on the node.
            // `ctx` is a local — its `&mut WindowOps` lifetime is
            // disjoint from `self.arena`, so the immutable arena
            // borrow doesn't conflict with the mutable ctx borrow.
            let outcome: Option<Box<dyn Widget>> = {
                let node = self
                    .arena
                    .get(owner_id)
                    .expect("owner_id from active arena walk");
                let factory = node
                    .context_menu_factory
                    .as_ref()
                    .expect("owner_id only set when factory present");
                factory(position, &mut ctx)
            };
            match outcome {
                Some(menu) => break Some((owner_id, menu)),
                None => {
                    // Decline → keep walking up from the parent.
                    walker = self.arena.get(owner_id).and_then(|n| n.parent);
                }
            }
        };

        // Drain ctx side effects regardless of whether a menu showed —
        // a factory that returns `None` may still have queued intents,
        // updated signals, or requested a frame.
        let drain_anchor = menu_decision
            .as_ref()
            .map(|(id, _)| *id)
            .or_else(|| self.arena.roots().first().copied())
            .unwrap_or(target);
        self.collect_from_ctx(ctx, drain_anchor);

        let Some((owner_id, menu_widget)) = menu_decision else {
            return false;
        };

        // Clear stale transient overlays (other menus / popovers) before mounting
        // the new menu, but KEEP any overlay that *contains* the right-clicked
        // widget — otherwise a right-click inside a modal editor would tear down
        // the modal it lives in (dismiss_all did exactly that). The context menu
        // then mounts on top of its host overlay.
        let keep: std::collections::HashSet<WidgetId> = self
            .overlay_manager
            .stack
            .iter()
            .map(|o| o.content_id)
            .filter(|&content_id| self.is_descendant_of(owner_id, content_id))
            .collect();
        let dismissed = self.overlay_manager.dismiss_except(&keep);
        self.dormant_dismissed_content(&dismissed, &mut *ops);

        let content_id = self.add_boxed(menu_widget);
        let prev_focus = self.focused;
        self.overlay_manager.show(crate::overlay::OverlayRequest {
            content_id,
            anchor: owner_id,
            placement: crate::overlay::OverlayPlacement::AtPointer(position),
            dismiss: crate::overlay::DismissBehavior::EscapeOrClickOutside,
            layer: crate::overlay::OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        if let Some(focus_id) = prev_focus {
            self.overlay_manager.set_top_focus_restore(focus_id);
        }
        self.focus_ops(content_id, &mut *ops);
        // Flush intents the factory queued so they take effect on the
        // same dispatch tick as the menu mount. The caller's
        // PointerDown handler returns after we return `true`, skipping
        // its own drain — fire ours here.
        self.drain_pending_intents(&mut *ops);
        true
    }

    fn handle_pointer_move(&mut self, position: Point, ops: &mut dyn crate::window::WindowOps) {
        self.last_pointer_position = Some(position);
        let target = self.hit_test(position);

        if target != self.hovered {
            let previously_hovered = self.hovered;
            if let Some(old) = self.hovered {
                self.dispatch_to_widget(old, &WidgetEvent::PointerLeave, &mut *ops);
                self.tooltip_pointer_leave(old, &mut *ops);
            }
            if let Some(new) = target {
                self.dispatch_to_widget(new, &WidgetEvent::PointerEnter, &mut *ops);
                self.tooltip_pointer_enter(new);
            }
            self.set_hovered(target);
            self.update_hover_within_signals(previously_hovered, target);
        } else if let Some(target) = target {
            // Same hover target — restart pending tooltip timers if the
            // pointer is still moving beyond the stationary slop.
            self.tooltip_pointer_moved(target, position);
        }

        if let Some(target) = target {
            self.dispatch_to_widget(target, &WidgetEvent::PointerMove { position }, &mut *ops);
        }
    }

    pub(super) fn dispatch_to_widget(
        &mut self,
        target: WidgetId,
        event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        self.dispatch_to_widget_returning_handled(target, event, ops);
    }

    /// Whether `id` carries a drag or swipe handler (hence gets a drag/swipe
    /// recognizer once its arena is built).
    fn widget_has_drag(&self, id: WidgetId) -> bool {
        self.arena
            .get(id)
            .map(|n| n.any_handler(|h| h.on_drag.is_some() || h.on_swipe.is_some()))
            .unwrap_or(false)
    }

    /// Whether `id` is a gesture dead-zone boundary — a press inside its
    /// subtree must not arm a drag/swipe on any ancestor above it. See
    /// [`WidgetNode::gesture_dead_zone`](crate::arena::WidgetNode::gesture_dead_zone).
    fn is_gesture_dead_zone(&self, id: WidgetId) -> bool {
        self.arena
            .get(id)
            .map(|n| n.gesture_dead_zone)
            .unwrap_or(false)
    }

    /// Whether `id` is a keyboard-capture surface — while focused it
    /// receives every `KeyDown` raw, bypassing shortcut resolution. See
    /// [`WidgetNode::keyboard_capture`](crate::arena::WidgetNode::keyboard_capture).
    fn is_keyboard_capture(&self, id: WidgetId) -> bool {
        self.arena
            .get(id)
            .map(|n| n.keyboard_capture)
            .unwrap_or(false)
    }

    /// On `PointerDown`, when a descendant has captured the pointer for a
    /// non-drag gesture (a tap / long-press), arm every strict ancestor that
    /// carries a drag/swipe recognizer so an ancestor drag can still begin
    /// once the pointer moves past threshold — the tap-vs-drag disambiguation
    /// across the hit-path. Without this a descendant `on_tap` permanently
    /// shadows an ancestor `on_drag` (the bubble stops + capture routes every
    /// move to the descendant alone).
    ///
    /// Skipped when the captured widget can itself drag: the innermost drag
    /// owns the gesture, so no ancestor observation.
    pub(super) fn arm_drag_observers(
        &mut self,
        captured: WidgetId,
        down_event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        self.drag_observers.clear();
        if self.widget_has_drag(captured) {
            return;
        }
        // The press is inside a gesture dead zone (the captured control *is* the
        // dead zone) → arm no ancestor drag at all.
        if self.is_gesture_dead_zone(captured) {
            return;
        }
        let mut observers = Vec::new();
        let mut current = self.arena.parent(captured);
        while let Some(id) = current {
            // A dead-zone boundary stops the walk: ancestors AT or ABOVE it are
            // never armed, so a control inside the dead zone can never start the
            // ancestor's drag (the robust fix for "clicking a header button +
            // a few px of jitter drags the whole panel").
            if self.is_gesture_dead_zone(id) {
                break;
            }
            if self.widget_has_drag(id) {
                // Build the arena (the bubble never reached this ancestor) and
                // feed it the press so its DragRecognizer records the origin.
                {
                    let WidgetTree {
                        arena,
                        gesture_owners,
                        ..
                    } = self;
                    if let Some(node) = arena.get_mut(id) {
                        Self::ensure_gesture_arena(node, id, gesture_owners);
                    }
                }
                self.observe_drag_on_ancestor(id, down_event, ops);
                observers.push(id);
            }
            current = self.arena.parent(id);
        }
        self.drag_observers = observers;
    }

    /// The pointer sequence ended (a tap / plain release) WITHOUT the armed
    /// ancestor drag latching. Feed the terminating `Up` to each armed ancestor
    /// so its `DragRecognizer` clears the press origin it recorded when it was
    /// armed on `PointerDown` — otherwise a later *hover* move would cross the
    /// drag threshold and start a phantom drag. This matters because the press
    /// was captured by an interactive descendant (e.g. a card's read-only
    /// `RichTextEditor`), so the ancestor's own arena never saw this `Up` on
    /// its own and its recognizer would stay armed indefinitely. Also discards
    /// the observer list.
    pub(super) fn release_drag_observers(
        &mut self,
        up_event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        if self.drag_observers.is_empty() {
            return;
        }
        let observers = std::mem::take(&mut self.drag_observers);
        for id in &observers {
            // An `Up` while the recognizer is not mid-drag resolves it to
            // `Failed` and clears `down_position` — no gesture is produced, so
            // this only tidies recognizer state.
            self.observe_drag_on_ancestor(*id, up_event, ops);
        }
    }

    /// On a captured `PointerMove`, feed the move to each armed ancestor drag
    /// observer (innermost first). If one latches a drag, it has already called
    /// `start_drag` (so `active_drag` now owns the pointer) — stop observing.
    pub(super) fn advance_drag_observers(
        &mut self,
        move_event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        if self.drag_observers.is_empty() {
            return;
        }
        let observers = std::mem::take(&mut self.drag_observers);
        for id in &observers {
            let recognized = self.observe_drag_on_ancestor(*id, move_event, ops);
            if recognized || self.active_drag.is_some() {
                // A drag latched on this ancestor — it now owns the pointer.
                return;
            }
        }
        // No drag yet — keep observing on the next move.
        self.drag_observers = observers;
    }

    /// Feed one raw pointer event to `id`'s gesture arena WITHOUT firing its
    /// `on_pointer_event` or taking the implicit capture (the descendant
    /// already holds it). Returns `true` if the arena recognized a gesture
    /// (a drag/swipe latched), in which case it is dispatched so the
    /// `on_drag` handler's `start_drag` runs and `active_drag` takes over.
    fn observe_drag_on_ancestor(
        &mut self,
        id: WidgetId,
        event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) -> bool {
        let localized = self.localize_event(id, event);
        let event = localized.as_ref().unwrap_or(event);
        let raw = match event {
            WidgetEvent::PointerDown {
                position,
                button,
                modifiers,
            } => crate::gesture::RawPointerEvent::Down {
                position: *position,
                button: *button,
                modifiers: *modifiers,
            },
            WidgetEvent::PointerMove { position } => crate::gesture::RawPointerEvent::Move {
                position: *position,
            },
            WidgetEvent::PointerUp {
                position,
                button,
                modifiers,
            } => crate::gesture::RawPointerEvent::Up {
                position: *position,
                button: *button,
                modifiers: *modifiers,
            },
            _ => return false,
        };
        let mut ctx = self.make_event_context(&mut *ops);
        let WidgetTree { arena, .. } = self;
        let recognized = if let Some(node) = arena.get_mut(id) {
            if let Some(arena_ref) = node.handlers.gesture_arena.as_mut() {
                if let Some(gesture) = arena_ref.process(&raw) {
                    Self::dispatch_recognized_gesture(node, gesture, &mut ctx);
                    true
                } else {
                    false
                }
            } else {
                false
            }
        } else {
            false
        };
        self.collect_from_ctx(ctx, id);
        recognized
    }

    /// Rebuild `event` with any pointer position converted into `id`'s
    /// **widget-local** space. Returns `None` for events that carry no
    /// position, so the caller keeps the original event.
    ///
    /// This is the single point where the framework localizes pointer
    /// coordinates. It runs once per node in both the preview and bubble
    /// passes, and because both `on_pointer_event` and the gesture arena
    /// read the position out of `event`, localizing it here makes
    /// `on_tap` / `on_double_tap` / `on_long_press` / `on_drag` and
    /// `on_pointer_event` all receive widget-local coordinates uniformly.
    /// See [`WidgetArena::local_pointer_position`].
    fn localize_event(&self, id: WidgetId, event: &WidgetEvent) -> Option<WidgetEvent> {
        match event {
            WidgetEvent::PointerDown {
                position,
                button,
                modifiers,
            } => Some(WidgetEvent::PointerDown {
                position: self.arena.local_pointer_position(id, *position),
                button: *button,
                modifiers: *modifiers,
            }),
            WidgetEvent::PointerUp {
                position,
                button,
                modifiers,
            } => Some(WidgetEvent::PointerUp {
                position: self.arena.local_pointer_position(id, *position),
                button: *button,
                modifiers: *modifiers,
            }),
            WidgetEvent::PointerMove { position } => Some(WidgetEvent::PointerMove {
                position: self.arena.local_pointer_position(id, *position),
            }),
            WidgetEvent::Gesture { gesture } => Some(WidgetEvent::Gesture {
                gesture: self.localize_gesture(id, gesture),
            }),
            _ => None,
        }
    }

    /// Convert every position / center field of a pre-recognized
    /// [`GestureEvent`] into `id`'s widget-local space (`DragMoved.delta`
    /// is relative and left untouched). Used for the platform gesture
    /// path; arena-recognized gestures are already local because the
    /// `RawPointerEvent` feeding the arena was localized by
    /// [`Self::localize_event`].
    fn localize_gesture(&self, id: WidgetId, gesture: &GestureEvent) -> GestureEvent {
        let loc = |p: teksilo_canvas::Point| self.arena.local_pointer_position(id, p);
        let tap = |t: &TapEvent| TapEvent::new(loc(t.position), t.button, t.modifiers);
        match gesture {
            GestureEvent::Tap(t) => GestureEvent::Tap(tap(t)),
            GestureEvent::DoubleTap(t) => GestureEvent::DoubleTap(tap(t)),
            GestureEvent::TripleTap(t) => GestureEvent::TripleTap(tap(t)),
            GestureEvent::LongPress(t) => GestureEvent::LongPress(tap(t)),
            GestureEvent::DragStarted { position, button } => GestureEvent::DragStarted {
                position: loc(*position),
                button: *button,
            },
            GestureEvent::DragMoved { position, delta } => GestureEvent::DragMoved {
                position: loc(*position),
                delta: *delta,
            },
            GestureEvent::DragEnded { position } => GestureEvent::DragEnded {
                position: loc(*position),
            },
            GestureEvent::PinchStarted { center } => GestureEvent::PinchStarted {
                center: loc(*center),
            },
            GestureEvent::PinchChanged {
                center,
                scale,
                rotation,
            } => GestureEvent::PinchChanged {
                center: loc(*center),
                scale: *scale,
                rotation: *rotation,
            },
            GestureEvent::PinchEnded => GestureEvent::PinchEnded,
            GestureEvent::Swipe {
                direction,
                velocity,
            } => GestureEvent::Swipe {
                direction: *direction,
                velocity: *velocity,
            },
        }
    }

    /// Same as `dispatch_to_widget` but returns `true` when any
    /// preview or bubble handler consumed the event. Used for keyboard
    /// events the framework wants to consume by default (Tab focus
    /// navigation): callers can dispatch first, then fall back to
    /// built-in behavior only when no widget claimed it.
    pub(super) fn dispatch_to_widget_returning_handled(
        &mut self,
        target: WidgetId,
        event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) -> bool {
        if !self.arena.is_enabled(target) {
            return false;
        }

        let mut ancestors = Vec::new();
        let mut current = self.arena.parent(target);
        while let Some(id) = current {
            ancestors.push(id);
            current = self.arena.parent(id);
        }
        ancestors.reverse();

        // For a pointer press, find the innermost tap-owning node at-or-above
        // the hit target (a chevron / checkbox / inline button). A row or
        // container that selects on press consults
        // `ctx.press_claimed_by_interactive_child()` to skip selecting when this
        // owner is a strict descendant of it — the press belongs to the inner
        // control, not the row. Tap-like handlers only; drag/swipe are excluded
        // so a draggable row still selects itself on press.
        //
        // **`on_tap` / `on_long_press` only — never `on_double_tap` alone.**
        // The question this answers is "does a descendant own *this press*",
        // and a widget that wired only a multi-tap handler does not: the first
        // click of a double-click is not its business. Counting it meant a
        // table cell could not carry double-click-to-edit without also
        // silently stopping its row from selecting on a plain click — while
        // every file manager selects a row on the first click of the
        // double-click that opens it. A node that wants the press still has
        // `on_tap` (a real `Button`, a checkbox), and those are unaffected.
        let tap_owner: Option<WidgetId> = if matches!(
            event,
            WidgetEvent::PointerDown { .. } | WidgetEvent::PointerUp { .. }
        ) {
            let mut owner = None;
            let mut cur = Some(target);
            while let Some(id) = cur {
                if self.arena.get(id).is_some_and(|n| {
                    n.any_handler(|h| h.on_tap.is_some() || h.on_long_press.is_some())
                }) {
                    owner = Some(id);
                    break;
                }
                cur = self.arena.parent(id);
            }
            owner
        } else {
            None
        };

        for &id in &ancestors {
            let mut ctx = self.make_event_context(&mut *ops);
            ctx.press_claimed_by_interactive_child =
                tap_owner.is_some_and(|owner| owner != id && self.is_descendant_of(owner, id));
            // Convert any pointer position into this node's widget-local
            // space before its handlers see it (see `localize_event`).
            let localized = self.localize_event(id, event);
            let event = localized.as_ref().unwrap_or(event);
            let response = if let Some(node) = self.arena.get_mut(id) {
                Self::try_handler_preview(node, event, &mut ctx).unwrap_or(EventResponse::Ignored)
            } else {
                EventResponse::Ignored
            };
            self.collect_from_ctx(ctx, id);
            if response == EventResponse::Handled {
                self.arena.mark_needs_paint(id);
                return true;
            }
        }

        let needs_layout_on_handle = matches!(
            event,
            WidgetEvent::Scroll { .. } | WidgetEvent::ScrollIntoView { .. }
        );
        let mut current = Some(target);
        let mut is_target = true;
        while let Some(id) = current {
            let mut ctx = self.make_event_context(&mut *ops);
            ctx.press_claimed_by_interactive_child =
                tap_owner.is_some_and(|owner| owner != id && self.is_descendant_of(owner, id));
            // Convert any pointer position into this node's widget-local
            // space before its handlers (and its gesture arena) see it.
            let localized = self.localize_event(id, event);
            let WidgetTree {
                arena,
                gesture_owners,
                ..
            } = self;
            let event = localized.as_ref().unwrap_or(event);
            let response = if let Some(node) = arena.get_mut(id) {
                Self::try_handler_bubble(node, event, &mut ctx, is_target, id, gesture_owners)
                    .unwrap_or(EventResponse::Ignored)
            } else {
                EventResponse::Ignored
            };
            self.collect_from_ctx(ctx, id);
            if response == EventResponse::Handled {
                if needs_layout_on_handle {
                    self.arena.mark_needs_layout(id);
                } else {
                    self.arena.mark_needs_paint(id);
                }
                // **Hover transitions are notifications, and every ancestor is
                // entitled to one.** Stopping the bubble here left a container
                // stuck hovered whenever the pointer left it *through* an
                // interactive child: the child's own `on_hover` handled the
                // `PointerLeave`, the bubble stopped, and the row went on believing
                // the pointer was still over it. A search result whose controls
                // appear on hover then kept them after the pointer had gone.
                //
                // The preview pass already refuses to let an ancestor swallow a
                // descendant's Enter/Leave; this is that rule in the other
                // direction, and it is what makes a container's hover mean "the
                // pointer is somewhere inside me" rather than "the pointer is on my
                // own background". Every other event still stops at its handler,
                // which is what makes handling one mean anything.
                if !matches!(event, WidgetEvent::PointerEnter | WidgetEvent::PointerLeave) {
                    return true;
                }
            }
            is_target = false;
            current = self.arena.parent(id);
        }
        false
    }

    pub(super) fn dispatch_to_widget_direct(
        &mut self,
        target: WidgetId,
        event: &WidgetEvent,
        ops: &mut dyn crate::window::WindowOps,
    ) {
        if !self.arena.is_enabled(target) {
            return;
        }

        let mut ctx = self.make_event_context(&mut *ops);
        let WidgetTree {
            arena,
            gesture_owners,
            ..
        } = self;
        let response = if let Some(node) = arena.get_mut(target) {
            Self::try_handler_bubble(node, event, &mut ctx, true, target, gesture_owners)
                .unwrap_or(EventResponse::Ignored)
        } else {
            EventResponse::Ignored
        };
        self.collect_from_ctx(ctx, target);

        if response == EventResponse::Handled {
            self.arena.mark_needs_paint(target);
        }
    }

    fn try_handler_preview(
        node: &mut crate::arena::WidgetNode,
        event: &WidgetEvent,
        ctx: &mut EventContext,
    ) -> Option<EventResponse> {
        match event {
            // Key + IME events fire `on_key_preview` on each strict
            // ancestor of the focused widget (root → parent-of-target).
            // Mirrors how `on_pointer_event` previews on the pointer
            // side; the focused widget itself does NOT see its own
            // `on_key_preview` (the dispatch loop builds an ancestors
            // list that excludes the target, so this is enforced by
            // the caller, not here).
            WidgetEvent::KeyDown { .. }
            | WidgetEvent::KeyUp { .. }
            | WidgetEvent::ImeComposition { .. }
            | WidgetEvent::ImeCommit { .. } => {
                let has = node.external_handlers.on_key_preview.is_some()
                    || node.handlers.on_key_preview.is_some();
                if !has {
                    return None;
                }
                Some(fire_event_handler_both(
                    &mut node.external_handlers.on_key_preview,
                    &mut node.handlers.on_key_preview,
                    event,
                    ctx,
                ))
            }
            // `PointerEnter` / `PointerLeave` are per-node hover transitions
            // synthesized by `handle_pointer_move`, not part of the raw pointer
            // stream. Running them through the ancestor preview pass would let
            // a drag-detecting ancestor whose `on_pointer_event` returns
            // `Handled` silently swallow a descendant's hover (its cursor and
            // `on_hover` would never fire). They are delivered to their target
            // directly via the bubble pass (where Enter/Leave fire `on_hover`),
            // so they have no business in preview. `PointerMove`/`Down`/`Up`
            // and `Scroll` still preview through the catch-all below — the
            // tab-bar wheel-remap (`tab_widget/bar.rs`) and the split-view /
            // rich-text drag guards depend on that.
            WidgetEvent::PointerEnter | WidgetEvent::PointerLeave => None,
            _ => {
                let has = node.external_handlers.on_pointer_event.is_some()
                    || node.handlers.on_pointer_event.is_some();
                if !has {
                    return None;
                }
                Some(fire_event_handler_both(
                    &mut node.external_handlers.on_pointer_event,
                    &mut node.handlers.on_pointer_event,
                    event,
                    ctx,
                ))
            }
        }
    }

    /// `fire_on_pointer_event` gates the pre-gesture `on_pointer_event`
    /// intercept. Set it to `true` for the bubble target (the widget the
    /// event was dispatched at) and `false` for every ancestor, because
    /// ancestors already fired their `on_pointer_event` during the
    /// preview pass — firing it again in bubble was the source of
    /// double-toggle / double-select bugs when a wrapper widget (e.g.
    /// `ListItemWrapper`) held the handler and a child leaf was the hit
    /// target.
    fn try_handler_bubble(
        node: &mut crate::arena::WidgetNode,
        event: &WidgetEvent,
        ctx: &mut EventContext,
        fire_on_pointer_event: bool,
        node_id: WidgetId,
        gesture_owners: &mut std::collections::HashSet<WidgetId>,
    ) -> Option<EventResponse> {
        match event {
            WidgetEvent::PointerEnter => {
                if let Some(cursor) = node.node_cursor {
                    ctx.set_cursor(cursor);
                }
                let mut fired = false;
                if let Some(h) = node.external_handlers.on_hover.as_mut() {
                    h(true, ctx);
                    fired = true;
                }
                if let Some(h) = node.handlers.on_hover.as_mut() {
                    h(true, ctx);
                    fired = true;
                }
                if fired {
                    Some(EventResponse::Handled)
                } else {
                    node.node_cursor.map(|_| EventResponse::Handled)
                }
            }
            WidgetEvent::PointerLeave => {
                if node.node_cursor.is_some() {
                    ctx.set_cursor(crate::widget::CursorIcon::Default);
                }
                let mut fired = false;
                if let Some(h) = node.external_handlers.on_hover.as_mut() {
                    h(false, ctx);
                    fired = true;
                }
                if let Some(h) = node.handlers.on_hover.as_mut() {
                    h(false, ctx);
                    fired = true;
                }
                if fired {
                    Some(EventResponse::Handled)
                } else {
                    node.node_cursor.map(|_| EventResponse::Handled)
                }
            }
            WidgetEvent::FocusGained { .. } => {
                let mut fired = false;
                if let Some(h) = node.external_handlers.on_focus.as_mut() {
                    h(true, ctx);
                    fired = true;
                }
                if let Some(h) = node.handlers.on_focus.as_mut() {
                    h(true, ctx);
                    fired = true;
                }
                fired.then_some(EventResponse::Handled)
            }
            WidgetEvent::FocusLost => {
                let mut fired = false;
                if let Some(h) = node.external_handlers.on_focus.as_mut() {
                    h(false, ctx);
                    fired = true;
                }
                if let Some(h) = node.handlers.on_focus.as_mut() {
                    h(false, ctx);
                    fired = true;
                }
                fired.then_some(EventResponse::Handled)
            }
            WidgetEvent::KeyDown { .. }
            | WidgetEvent::KeyUp { .. }
            | WidgetEvent::ImeComposition { .. }
            | WidgetEvent::ImeCommit { .. } => {
                if node.external_handlers.on_key.is_some() || node.handlers.on_key.is_some() {
                    Some(fire_event_handler_both(
                        &mut node.external_handlers.on_key,
                        &mut node.handlers.on_key,
                        event,
                        ctx,
                    ))
                } else {
                    None
                }
            }
            WidgetEvent::Scroll { .. } | WidgetEvent::ScrollIntoView { .. } => {
                if node.external_handlers.on_scroll.is_some() || node.handlers.on_scroll.is_some() {
                    Some(fire_event_handler_both(
                        &mut node.external_handlers.on_scroll,
                        &mut node.handlers.on_scroll,
                        event,
                        ctx,
                    ))
                } else {
                    None
                }
            }
            WidgetEvent::AccessAction {
                action,
                target_node,
                data,
                ..
            } => {
                // Prefer the full-payload handler when the widget has
                // opted in; it's the one that receives `target_node` and
                // `data`. Within each payload variant, fire BOTH external
                // and own handlers — Button (own) and Dialog (external)
                // layered together rely on both firing for a single
                // accesskit click.
                // Assistive-tech action paths run under
                // the `Accessibility` source label. Restored after
                // the inner if/else.
                let saved_a11y_source = ctx
                    .current_source
                    .replace(crate::telemetry::IntentSource::Accessibility);
                let request_is_set = node.handlers.on_access_action_request.is_some()
                    || node.external_handlers.on_access_action_request.is_some();
                let user_handled = if request_is_set {
                    let r1 = node
                        .external_handlers
                        .on_access_action_request
                        .as_mut()
                        .map(|h| h(*action, *target_node, data.clone(), ctx))
                        .unwrap_or(EventResponse::Ignored);
                    let r2 = node
                        .handlers
                        .on_access_action_request
                        .as_mut()
                        .map(|h| h(*action, *target_node, data.clone(), ctx))
                        .unwrap_or(EventResponse::Ignored);
                    Some(
                        if r1 == EventResponse::Handled || r2 == EventResponse::Handled {
                            EventResponse::Handled
                        } else {
                            EventResponse::Ignored
                        },
                    )
                } else if node.handlers.on_access_action.is_some()
                    || node.external_handlers.on_access_action.is_some()
                {
                    let r1 = node
                        .external_handlers
                        .on_access_action
                        .as_mut()
                        .map(|h| h(*action, ctx))
                        .unwrap_or(EventResponse::Ignored);
                    let r2 = node
                        .handlers
                        .on_access_action
                        .as_mut()
                        .map(|h| h(*action, ctx))
                        .unwrap_or(EventResponse::Ignored);
                    Some(
                        if r1 == EventResponse::Handled || r2 == EventResponse::Handled {
                            EventResponse::Handled
                        } else {
                            EventResponse::Ignored
                        },
                    )
                } else {
                    None
                };

                // Builder-level access_action / access_custom_action
                // callbacks. These layer on top of any user-installed
                // on_access_action / on_access_action_request — both
                // fire for the same dispatched event. Drives the
                // SwiftUI `.accessibilityAction(...)` parity.
                let mut override_handled = false;
                if let Some(ov) = node.access_overrides.as_deref_mut() {
                    if matches!(action, accesskit::Action::CustomAction) {
                        if let Some(accesskit::ActionData::CustomAction(idx)) = data
                            && let Some((_, cb)) = ov.custom_actions.get_mut(*idx as usize)
                        {
                            cb(ctx);
                            override_handled = true;
                        }
                    } else {
                        for (a, cb) in ov.actions.iter_mut() {
                            if *a == *action {
                                cb(ctx);
                                override_handled = true;
                            }
                        }
                    }
                }

                ctx.current_source = saved_a11y_source;
                match (user_handled, override_handled) {
                    (Some(EventResponse::Handled), _) | (_, true) => Some(EventResponse::Handled),
                    (Some(EventResponse::Ignored), false) => Some(EventResponse::Ignored),
                    (None, false) => None,
                }
            }
            WidgetEvent::Gesture { gesture } => {
                // Pre-recognized gestures from the platform (OS trackpad
                // pinch/rotation, double-tap, …) bypass the gesture arena
                // and go straight to the matching handler. See §10.
                let matched = matches!(
                    gesture,
                    GestureEvent::PinchStarted { .. }
                        | GestureEvent::PinchChanged { .. }
                        | GestureEvent::PinchEnded
                        | GestureEvent::Swipe { .. }
                        | GestureEvent::DoubleTap { .. }
                        | GestureEvent::TripleTap { .. }
                ) && {
                    let has_handler = match gesture {
                        GestureEvent::PinchStarted { .. }
                        | GestureEvent::PinchChanged { .. }
                        | GestureEvent::PinchEnded => node.any_handler(|h| h.on_pinch.is_some()),
                        GestureEvent::Swipe { .. } => node.any_handler(|h| h.on_swipe.is_some()),
                        GestureEvent::DoubleTap { .. } => {
                            node.any_handler(|h| h.on_double_tap.is_some())
                        }
                        GestureEvent::TripleTap { .. } => {
                            node.any_handler(|h| h.on_triple_tap.is_some())
                        }
                        _ => false,
                    };
                    if has_handler {
                        Self::dispatch_recognized_gesture(node, *gesture, ctx);
                    }
                    has_handler
                };
                if matched {
                    Some(EventResponse::Handled)
                } else {
                    None
                }
            }
            WidgetEvent::PointerDown {
                position,
                button,
                modifiers,
            } => {
                // Raw pointer handler runs first so widgets can intercept
                // events that the gesture recognizers won't catch (e.g.
                // right-click → context menu). If it returns Handled the
                // gesture arena is skipped; otherwise we fall through.
                // Only fire for the target — ancestors already fired
                // on_pointer_event during the preview pass.
                if fire_on_pointer_event {
                    let r = fire_event_handler_both(
                        &mut node.external_handlers.on_pointer_event,
                        &mut node.handlers.on_pointer_event,
                        event,
                        ctx,
                    );
                    if r == EventResponse::Handled {
                        return Some(EventResponse::Handled);
                    }
                }
                Self::ensure_gesture_arena(node, node_id, gesture_owners);
                if let Some(arena) = node.handlers.gesture_arena.as_mut() {
                    // Implicit capture for the Down..Up sequence so that
                    // moves leaving the widget bounds still reach the
                    // arena. Without this, a drag that starts inside the
                    // widget but crosses its edge before the recognizer
                    // latches would be hit-tested to another widget and
                    // the press-origin arena would never see a `Move`.
                    // Released unconditionally by the `PointerUp` branch
                    // in `dispatch_event`.
                    ctx.capture_pointer();
                    let result = arena.process(&RawPointerEvent::Down {
                        position: *position,
                        button: *button,
                        modifiers: *modifiers,
                    });
                    if let Some(gesture) = result {
                        Self::dispatch_recognized_gesture(node, gesture, ctx);
                    }
                    return Some(EventResponse::Handled);
                }
                None
            }
            WidgetEvent::PointerUp {
                position,
                button,
                modifiers,
            } => {
                if fire_on_pointer_event {
                    let r = fire_event_handler_both(
                        &mut node.external_handlers.on_pointer_event,
                        &mut node.handlers.on_pointer_event,
                        event,
                        ctx,
                    );
                    if r == EventResponse::Handled {
                        return Some(EventResponse::Handled);
                    }
                }
                if let Some(arena) = node.handlers.gesture_arena.as_mut() {
                    let result = arena.process(&RawPointerEvent::Up {
                        position: *position,
                        button: *button,
                        modifiers: *modifiers,
                    });
                    if let Some(gesture) = result {
                        Self::dispatch_recognized_gesture(node, gesture, ctx);
                    }
                    return Some(EventResponse::Handled);
                }
                None
            }
            WidgetEvent::PointerMove { position } => {
                if fire_on_pointer_event {
                    let r = fire_event_handler_both(
                        &mut node.external_handlers.on_pointer_event,
                        &mut node.handlers.on_pointer_event,
                        event,
                        ctx,
                    );
                    if r == EventResponse::Handled {
                        return Some(EventResponse::Handled);
                    }
                }
                if let Some(arena) = node.handlers.gesture_arena.as_mut() {
                    let result = arena.process(&RawPointerEvent::Move {
                        position: *position,
                    });
                    if let Some(gesture) = result {
                        Self::dispatch_recognized_gesture(node, gesture, ctx);
                        // A recognized gesture (DragStarted / DragMoved / …)
                        // almost always changes visible state — return
                        // `Handled` so the bubble loop marks this widget
                        // `needs_paint`, which in turn makes
                        // `WidgetTree::needs_redraw()` return true and
                        // triggers a `request_redraw` for the next frame.
                        // Without this, state updates via bound signals are
                        // only observed on the *next* layout/render pass,
                        // which in turn is never scheduled because
                        // `teksilo-app::update_control_flow` only wakes up when
                        // `needs_redraw()` is true.
                        return Some(EventResponse::Handled);
                    }
                    return Some(EventResponse::Ignored);
                }
                None
            }
        }
    }

    pub(super) fn collect_from_ctx<'ops>(
        &mut self,
        mut ctx: EventContext<'ops>,
        source_widget: WidgetId,
    ) {
        // Take the ops handle out of ctx up front so we can freely
        // reborrow it inside the method without fighting the 'ops
        // lifetime propagation when other fields of `ctx` are moved.
        // When no ops is set (standalone trees / tests), fall back to
        // a stack NoopWindowOps.
        let local_ops = ctx.window_ops.take();
        let mut noop = crate::window::NoopWindowOps;
        let ops: &mut dyn crate::window::WindowOps = match local_ops {
            Some(o) => o,
            None => &mut noop,
        };
        if ctx.frame_requested {
            self.request_frame();
        }
        if let Some(cursor) = ctx.cursor_request {
            self.current_cursor = cursor;
        }
        // Intents queued through `ctx.send_intent` are anchored at
        // the originating widget. Programmatic sends default to
        // `propagate_when_disabled = true` — there is no shortcut to
        // consult, and propagation is the safe, least-surprising
        // default.
        for intent in ctx.pending_intents {
            self.enqueue_intent(source_widget, intent, true);
        }
        // Key capture: process cancel before arm, matching the
        // handler's call order (the handler sets `cancel_key_capture`
        // when it calls `ctx.cancel_key_capture()`, and separately
        // stores `pending_key_capture` when it calls
        // `ctx.begin_key_capture(...)`). If the handler did both,
        // arm wins (whichever was called last on the ctx has
        // already overwritten the other field's effect via the
        // setter logic).
        if ctx.cancel_key_capture {
            self.cancel_key_capture();
        }
        if let Some(slot) = ctx.pending_key_capture {
            self.key_capture = Some(slot);
        }
        // Registry mutations queued by settings-UI buttons.
        for mutation in ctx.pending_shortcut_mutations {
            match mutation {
                crate::widget::ShortcutMutation::RebindPrimary { id, keystroke } => {
                    self.shortcut_registry.rebind_primary(id, keystroke);
                }
                crate::widget::ShortcutMutation::RebindSecondary { id, keystroke } => {
                    self.shortcut_registry.rebind_secondary(id, keystroke);
                }
                crate::widget::ShortcutMutation::ClearOverride { id } => {
                    self.shortcut_registry.clear_override(&id);
                }
            }
        }
        if ctx.close_window_requested {
            self.close_window_requested = true;
        }
        if ctx.force_close_requested {
            self.force_close_requested = true;
        }
        self.pending_modal_requests
            .extend(ctx.modal_requests.into_iter().map(|request| {
                crate::modal::QueuedModalRequest {
                    source_widget,
                    request,
                }
            }));
        if ctx.dismiss_modal && !self.dismiss_modal_for_source(source_widget, &mut *ops) {
            self.pending_modal_dismissal = true;
        }
        for callback in ctx.idle_callbacks {
            self.idle_queue.push_boxed(callback);
        }
        match ctx.dismiss_scope {
            Some(crate::widget::DismissScope::All) => {
                let dismissed = self.overlay_manager.dismiss_all();
                self.dormant_dismissed_content(&dismissed, &mut *ops);
            }
            Some(crate::widget::DismissScope::AllExceptHosts) => {
                self.dismiss_all_overlays_except_hosts(&mut *ops);
            }
            Some(crate::widget::DismissScope::SelfChain) => {
                self.dismiss_self_overlay_chain_for_source(source_widget, &mut *ops);
            }
            Some(crate::widget::DismissScope::Top) => {
                if let Some((_id, content_ids, focus_restore)) = self.overlay_manager.dismiss_top()
                {
                    self.dormant_dismissed_content(&content_ids, &mut *ops);
                    if let Some(restore_id) = focus_restore
                        && self.arena.is_active(restore_id)
                    {
                        self.focus_ops(restore_id, &mut *ops);
                    }
                }
            }
            None => {
                for id in ctx.overlay_dismissals {
                    let dismissed = self.overlay_manager.dismiss(id);
                    self.dormant_dismissed_content(&dismissed, &mut *ops);
                }
            }
        }
        // Content-keyed dismissals (`dismiss_overlay_by_content`). Drained
        // unconditionally — independent of `dismiss_scope` and of the
        // pending delayed-overlay list — so a handler can retract a shown
        // reusable overlay it identifies only by content. Resolving the
        // id here (not at call time) is what lets the caller skip
        // tracking the `OverlayId`.
        for content_id in ctx.overlay_content_dismissals {
            if let Some(overlay_id) = self.overlay_manager.find_by_content(content_id) {
                let dismissed = self.overlay_manager.dismiss(overlay_id);
                self.dormant_dismissed_content(&dismissed, &mut *ops);
            }
        }
        // Apply pause/resume queue (ToastHost hover-pause). Drained
        // here so the handler-side `ctx.pause_overlay_auto_dismiss(id)`
        // is order-independent with `dismiss_overlay(id)` and the
        // scope-based dismissals: pause/resume on an overlay that
        // was concurrently dismissed is silently dropped (the find
        // inside the OverlayManager methods misses on the gone id).
        for (id, pause) in ctx.overlay_pause_requests {
            if pause {
                self.overlay_manager.pause_auto_dismiss(id);
            } else {
                self.overlay_manager.resume_auto_dismiss(id);
            }
        }
        for preserve_content in ctx.dismiss_descendant_overlays {
            self.dismiss_child_overlays_for_source(source_widget, preserve_content, &mut *ops);
        }
        self.apply_tree_mutations(std::mem::take(&mut ctx.tree_mutations));
        if ctx.request_a11y_update {
            self.a11y_dirty = true;
        }
        for mut req in ctx.overlay_requests {
            if req.parent_overlay.is_none() {
                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
            }
            if self
                .overlay_manager
                .find_by_content(req.content_id)
                .is_some()
            {
                continue;
            }
            let current_focus = self.focused;
            self.overlay_manager.show(req);
            // Overlay show changes the AT tree shape — mirror the
            // `WidgetTree::show_overlay` path. The dismissal sibling
            // (`dismiss_overlay_with_ops`) already flips this.
            self.a11y_dirty = true;
            if let Some(focus_id) = current_focus {
                self.overlay_manager.set_top_focus_restore(focus_id);
            }
        }
        for (mut req, duration) in ctx.timed_overlay_requests {
            if req.parent_overlay.is_none() {
                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
            }
            if self
                .overlay_manager
                .find_by_content(req.content_id)
                .is_some()
            {
                continue;
            }
            let current_focus = self.focused;
            let overlay_id = self.overlay_manager.show_for(req, duration);
            self.overlay_manager
                .set_shown_at_sim(overlay_id, self.sim_clock);
            self.a11y_dirty = true;
            if let Some(focus_id) = current_focus {
                self.overlay_manager.set_top_focus_restore(focus_id);
            }
        }
        for (mut req, progress, duration) in ctx.reveal_overlay_requests {
            if req.parent_overlay.is_none() {
                req.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
            }
            if self
                .overlay_manager
                .find_by_content(req.content_id)
                .is_some()
            {
                continue;
            }
            let content_id = req.content_id;
            let current_focus = self.focused;
            let overlay_id = self.overlay_manager.show(req);
            self.overlay_manager
                .set_shown_at_sim(overlay_id, self.sim_clock);
            self.a11y_dirty = true;
            if let Some(focus_id) = current_focus {
                self.overlay_manager.set_top_focus_restore(focus_id);
            }
            // Drive the caller's progress signal 0 → 1, and register it
            // as the overlay's fade-state signal so every dismiss path
            // tweens it 1 → 0 and defers removal until it completes — the
            // same deferral machinery as `with_fade`, minus `set_opacity`
            // (the caller owns how `progress` paints).
            self.register_animated_signal(&progress, content_id);
            let _ = progress.try_animate_with_options(crate::animation::AnimationRequest {
                target: 1.0,
                duration,
                easing: teksilo_tokens::Easing::EaseOut,
                frame_interval: None,
                looping: false,
                epsilon: 0.0,
                max_duration: None,
            });
            self.overlay_manager
                .attach_fade(overlay_id, progress, duration);
        }
        if let Some(capture) = ctx.pointer_capture {
            if capture {
                self.pointer_captured_by = Some(source_widget);
            } else {
                self.pointer_captured_by = None;
            }
        }
        for (mut request, delay, focus_target) in ctx.delayed_overlay_requests {
            if request.parent_overlay.is_none() {
                request.parent_overlay = self.overlay_ancestor_for_widget(source_widget);
            }
            if self
                .overlay_manager
                .find_by_content(request.content_id)
                .is_some()
            {
                continue;
            }
            let content_id = request.content_id;
            self.pending_delayed_overlays
                .retain(|pending| pending.request.content_id != content_id);
            self.pending_delayed_overlays.push(PendingDelayedOverlay {
                request,
                delay,
                focus_target,
                real_requested_at: std::time::Instant::now(),
                sim_requested_at: self.sim_clock,
            });
            self.arena.mark_needs_paint(source_widget);
        }
        for content_id in ctx.cancel_delayed_overlays {
            self.pending_delayed_overlays
                .retain(|pending| pending.request.content_id != content_id);
        }
        for id in ctx.repaint_requests {
            self.arena.mark_needs_paint(id);
        }
        for id in ctx.synthetic_clicks {
            // Over the caller's ops, never a standalone dispatch: the
            // tapped widget's own handler runs inside this nested
            // dispatch, so a standalone one would deny it the
            // multi-window API this dispatch already has in hand.
            self.synthesise_tap_with_ops(id, &mut *ops);
        }
        if let Some(&id) = ctx.focus_requests.last() {
            // If the requested widget is itself not focusable (e.g. a
            // composite like `TextInput` whose focus-handling lives on
            // an inner leaf), walk into the subtree and land on the
            // first focusable descendant in document order. This makes
            // `ctx.request_focus(some_composite)` Do The Right Thing
            // without every caller having to reach into private inner
            // ids. `first_focusable_descendant` returns the node itself
            // when it's focusable, so the usual leaf-target case is
            // still a no-op lookup.
            let target = self.first_focusable_descendant(id).unwrap_or(id);
            self.focus_ops(target, &mut *ops);
        }
        if let Some(&id) = ctx.focus_into_requests.last() {
            // "Focus into" semantics: land on the first focusable descendant
            // and — unlike `focus_requests` above — do NOT fall back to the
            // container itself. A region with no focusable content (and not
            // focusable in its own right) leaves focus untouched rather than
            // trapping it on a non-interactive node. Drives Enter-on-a-tab →
            // into the tab panel.
            if let Some(target) = self.first_focusable_descendant(id) {
                self.focus_ops(target, &mut *ops);
            }
        }

        // Rect-based "scroll this into view" requests (`ctx.ensure_visible`).
        // Walk outward from the widget whose handler queued the request and
        // reveal the rect inside every enclosing scroll container. Run after
        // focus so that if the same handler also moved focus, both follows
        // settle against the same (pre-relayout) bounds; each dispatch is
        // gated on the container not already showing the rect, so ordering is
        // harmless. The source widget itself is excluded from the walk — it
        // owns revealing an interior rect inside its own viewport.
        for req in ctx.scroll_into_view_requests {
            self.scroll_rect_into_view(
                // Whoever the rect belongs to — the source widget unless the caller
                // named another. See `EventContext::ensure_visible_from`.
                req.from.unwrap_or(source_widget),
                req.rect,
                req.margin,
                req.align,
                req.motion,
                &mut *ops,
            );
        }
        // Id-based `ctx.ensure_widget_visible`: resolve to the target's current
        // absolute bounds and walk *its* ancestors (skip if it was destroyed
        // before the drain). Walking from the target — not `source_widget` —
        // means the request reveals that widget wherever it sits, even when the
        // handler runs on a different node (a group's roving-key handler
        // revealing the child tile it just selected).
        for (id, margin) in ctx.scroll_widget_into_view_requests {
            if self.arena.get(id).is_some() {
                let bounds = self.arena.bounds(id);
                self.scroll_rect_into_view(
                    id,
                    bounds,
                    margin,
                    crate::event::ScrollAlign::Minimal,
                    crate::event::ScrollMotion::Instant,
                    &mut *ops,
                );
            }
        }

        // Keyboard-highlight tooltip: surface the highlighted (menu) item's
        // tooltip immediately and dismiss the previously-highlighted one. Keyed
        // on the item id, NOT real focus (which stays on the menu panel for key
        // handling). Only the last request per handler is honoured.
        if let Some(&id) = ctx.highlight_tooltip_requests.last() {
            self.show_highlight_tooltip(id, &mut *ops);
        }

        // --- Drag and drop ---
        if let Some((source_widget, payload, preview_widget)) = ctx.drag_start_request {
            let (preview_content_id, preview_overlay_id) = if let Some(preview) = preview_widget {
                // `add_boxed` — NOT `arena.insert` — runs the widget's
                // `build()` so composite previews (our `DragPreview`
                // wrapper in teksilo-widgets, or anything a user supplies)
                // actually instantiate their child subtree. Plain
                // `arena.insert` stops at the root node, leaves build
                // un-fired, and the overlay renders an empty widget.
                let content_id = self.add_boxed(preview);
                let overlay_id = self.overlay_manager.show(crate::overlay::OverlayRequest {
                    content_id,
                    anchor: source_widget,
                    placement: crate::overlay::OverlayPlacement::AtPointer(
                        teksilo_canvas::Point::ZERO,
                    ),
                    dismiss: crate::overlay::DismissBehavior::Manual,
                    layer: crate::overlay::OverlayLayer::InTree,
                    parent_overlay: None,
                    on_dismiss: None,
                    fade_duration: None,
                });
                // Force the next layout pass to run `position_overlays`
                // and `set_content_bounds` — otherwise the preview sits
                // at its initial (0, 0) placement forever.
                self.arena.mark_needs_layout(content_id);
                (Some(content_id), Some(overlay_id))
            } else {
                (None, None)
            };
            self.active_drag = Some(crate::drag_state::DragSession {
                payload,
                source_widget: Some(source_widget),
                is_external: false,
                current_position: teksilo_canvas::Point::ZERO,
                current_target: None,
                feedback: crate::drag_state::DropFeedback::NoFeedback,
                preview_content_id,
                preview_overlay_id,
            });
            self.pointer_captured_by = Some(source_widget);
            // Grabbing-hand cursor while the drag is in flight. Reset on
            // drop / cancel / source-destroyed below.
            self.current_cursor = crate::widget::CursorIcon::Grabbing;
        }
        if ctx.cancel_drag {
            self.cancel_active_drag(&mut *ops);
        }

        // --- Environment changes (architecture §9.5) ---
        if let Some(theme) = ctx.theme_request {
            // Stored, not applied: the app layer routes this through
            // `WindowManager::set_theme` so every window re-themes, matching
            // the app-wide `set_locale` path below. Applying
            // `WidgetTree::set_theme` inline would re-theme only the
            // originating window.
            self.pending_theme_request = Some(theme);
        }
        if ctx.follow_system_request {
            // Stored, not applied: the app layer switches to
            // `ThemeMode::Native` and recomputes the theme from the current
            // OS colours, fanning it to every window.
            self.pending_follow_system_request = true;
        }
        if let Some(locale) = ctx.locale_request {
            // Stored, not applied: the app layer must route this through
            // `WindowManager::set_locale` so the `I18nManager`'s active
            // locale and direction stay in sync. Applying via
            // `WidgetTree::set_locale` alone would leave `tr!` bindings
            // reading the old translations.
            self.pending_locale_request = Some(locale);
        }
        if let Some(scale) = ctx.text_scale_request {
            // Stored, not applied: the app layer routes this through
            // `WindowManager::set_text_scale` so every window re-scales its
            // text. Applying `WidgetTree::set_user_text_scale` inline would
            // grow only the originating window.
            self.pending_text_scale_request = Some(scale);
        }
    }

    fn apply_tree_mutations(&mut self, mutations: Vec<crate::widget::TreeMutation>) {
        use crate::binding::BindingLevel;
        use crate::widget::TreeMutation;

        for mutation in mutations {
            match mutation {
                TreeMutation::SetDormant(id) => self.arena.set_dormant(id),
                TreeMutation::Activate(id) => self.arena.activate(id),
                TreeMutation::Destroy(id) => {
                    // Route through `destroy_subtree`, NOT the bare
                    // `arena.destroy`: the latter only unlinks nodes from
                    // the slotmap and leaks everything the widget owned —
                    // animation-scheduler entries (which hold strong
                    // `Signal<f32>` clones, so the widget keeps animating
                    // after it's gone), animated-quad slots, event-source
                    // subscriptions, registered shortcuts, bindings, and
                    // gesture ownership — and leaves `focused`/`hovered`
                    // dangling at a removed id. This mirrors the build-time
                    // `BuildContext::destroy_subtree`, including dismissing
                    // any overlay that still references the subtree so the
                    // manager doesn't retain a stale content reference.
                    if let Some(overlay_id) = self.overlay_manager().find_by_content(id) {
                        self.dismiss_overlay(overlay_id);
                    }
                    self.destroy_subtree(id);
                }
                // Build now, not next frame: the same handler is about to show
                // an overlay over this node and move focus into it, and both
                // read the subtree. See `EventContext::materialize_now`.
                TreeMutation::MaterializeNow(id) => {
                    if self.arena.get(id).is_some() {
                        self.rebuild_single_widget(id);
                    }
                }
                TreeMutation::WithWidgetMut { id, dirty, apply } => {
                    // Run the typed mutation while `&mut arena` is live, then
                    // drop the borrow before dirty-marking (the `mark_*` calls
                    // re-borrow the arena). Only dirty-mark a live node so we
                    // never call `mark_ancestors_need_layout` on a destroyed id.
                    let existed = if let Some(any) =
                        self.arena.get_mut(id).and_then(|n| n.widget.as_any_mut())
                    {
                        apply(any);
                        true
                    } else {
                        false
                    };
                    if existed {
                        match dirty {
                            BindingLevel::RepaintOnly => self.arena.mark_needs_paint(id),
                            BindingLevel::SubtreeRepaint => self.arena.mark_subtree_needs_paint(id),
                            BindingLevel::Relayout => {
                                self.arena.mark_needs_layout(id);
                                self.arena.mark_ancestors_need_layout(id);
                            }
                            BindingLevel::Rebuild => {
                                self.arena.mark_needs_rebuild(id);
                                self.arena.mark_ancestors_need_layout(id);
                            }
                            BindingLevel::AccessibilityOnly => self.a11y_dirty = true,
                        }
                    }
                }
            }
        }
    }

    pub fn hit_test(&self, point: Point) -> Option<WidgetId> {
        self.hit_test_excluding_overlay_and_widget(point, None, None)
    }

    /// Hit-test at a point, excluding a specific overlay and widget from consideration.
    /// Used during drag-and-drop to exclude the preview overlay and its content widget,
    /// so they don't block hit-testing of the actual drop targets underneath.
    pub fn hit_test_excluding_overlay_and_widget(
        &self,
        point: Point,
        exclude_overlay: Option<crate::overlay::OverlayId>,
        exclude_widget: Option<WidgetId>,
    ) -> Option<WidgetId> {
        if let Some(overlay_id) = self.overlay_manager.hit_test(point) {
            if Some(overlay_id) == exclude_overlay {
                // Skip this excluded overlay, fall through to widget tree
            } else if let Some(overlay) = self.overlay_manager.overlay(overlay_id) {
                return self.arena.hit_test_in_subtree_excluding(
                    overlay.content_id,
                    point,
                    exclude_widget,
                );
            }
        }

        if self.overlay_manager.topmost_centered().is_some() {
            return None;
        }

        // Delegates to WidgetArena::hit_test_at, which honors
        // event_pass_through and clips_children correctly.
        self.arena.hit_test_at(point, exclude_widget)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_widgets::FillWidget;
    use crate::widget::CursorIcon;
    use crate::widget_builder::WidgetBuilder;

    #[test]
    fn pointer_enter_leave_synthesized() {
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new());
        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.pointer_move(Point::new(50.0, 25.0));
        assert_eq!(tree.hovered, Some(widget));
        tree.pointer_move(Point::new(200.0, 200.0));
        assert_eq!(tree.hovered, None);
    }

    #[test]
    fn pointer_hover_updates_current_cursor() {
        let mut tree = WidgetTree::new();
        tree.add(FillWidget::new().cursor(CursorIcon::ColResize));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.pointer_move(Point::new(50.0, 25.0));
        assert_eq!(tree.current_cursor(), CursorIcon::ColResize);

        tree.pointer_move(Point::new(200.0, 200.0));
        assert_eq!(tree.current_cursor(), CursorIcon::Default);
    }

    // A leaf that opts into typed introspection, so `with_widget_mut` /
    // `widget_as_any(_mut)` can reach it (the default `as_any_mut` is `None`).
    #[derive(Debug)]
    struct Bumpable {
        value: i32,
    }

    impl crate::widget::Widget for Bumpable {
        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(10.0, 10.0).into()
        }
        fn as_any(&self) -> Option<&dyn std::any::Any> {
            Some(self)
        }
        fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
            Some(self)
        }
    }

    #[test]
    fn with_widget_mut_applies_and_dirty_marks() {
        let mut tree = WidgetTree::new();
        let id = tree.add(Bumpable { value: 0 });
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let mut ctx = EventContext::new();
        ctx.with_widget_mut::<Bumpable>(id, crate::binding::BindingLevel::Relayout, |b| {
            b.value = 42;
        });
        tree.collect_from_ctx(ctx, id);

        let value = tree
            .widget_as_any(id)
            .and_then(|a| a.downcast_ref::<Bumpable>())
            .map(|b| b.value);
        assert_eq!(
            value,
            Some(42),
            "the deferred closure must mutate the live widget"
        );
        assert!(
            tree.needs_layout(),
            "Relayout dirty level must mark the tree for relayout"
        );
    }

    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "not the requested type")]
    fn with_widget_mut_wrong_type_panics_in_debug() {
        struct Other;
        let mut tree = WidgetTree::new();
        let id = tree.add(Bumpable { value: 0 });
        let mut ctx = EventContext::new();
        ctx.with_widget_mut::<Other>(
            id,
            crate::binding::BindingLevel::RepaintOnly,
            |_o: &mut Other| {},
        );
        // Bumpable opts into as_any_mut, so the closure runs and the
        // wrong-type downcast trips the debug_assert.
        tree.collect_from_ctx(ctx, id);
    }

    #[test]
    fn with_widget_mut_closure_may_fire_observed_signals() {
        // Reentrancy guard. The closure runs inside `apply_tree_mutations`
        // while the target arena node is mutably borrowed. If it fires a
        // `Signal` whose observer sets *another* signal — the exact
        // `SceneView` shape (`item_change_signal` → bump `reconcile_dirty`) —
        // nothing may double-borrow the arena. The arena borrow is scoped to
        // the closure call and dropped before dirty-marking; signal/observer
        // work touches the binding registry, not the arena.
        use crate::signal::Signal;
        let mut tree = WidgetTree::new();
        let id = tree.add(Bumpable { value: 0 });
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let trigger = Signal::new(0_u64);
        let echo = Signal::new(0_u64);
        let echo_for_obs = echo.clone();
        let _obs = trigger.observe(move |v| echo_for_obs.set(*v));

        let trigger_in = trigger.clone();
        let mut ctx = EventContext::new();
        ctx.with_widget_mut::<Bumpable>(id, crate::binding::BindingLevel::RepaintOnly, move |b| {
            b.value = 7;
            // Fires `_obs` synchronously, mid-deferred-apply.
            trigger_in.set(99);
        });
        tree.collect_from_ctx(ctx, id); // must not panic / double-borrow

        assert_eq!(
            echo.get(),
            99,
            "the observer ran during the deferred mutation"
        );
        let value = tree
            .widget_as_any(id)
            .and_then(|a| a.downcast_ref::<Bumpable>())
            .map(|b| b.value);
        assert_eq!(value, Some(7));
    }

    #[test]
    fn request_accessibility_update_forces_rewalk() {
        let mut tree = WidgetTree::new();
        let id = tree.add(Bumpable { value: 0 });
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let _ = tree.sync_accessibility(); // populate cache, clears a11y_dirty
        assert!(
            !tree.a11y_dirty,
            "sync_accessibility should clear the dirty flag"
        );

        let mut ctx = EventContext::new();
        ctx.request_accessibility_update();
        tree.collect_from_ctx(ctx, id);
        assert!(
            tree.a11y_dirty,
            "request_accessibility_update must force an AT re-walk"
        );
    }

    #[test]
    fn rebuild_dirties_accessibility_tree() {
        // Regression for audit Blocker G1: every `BindingLevel::Rebuild`
        // consumer (ListView / TreeView / TableView / ComboBox / Calendar /
        // DockingLayout / ...) tears down and re-creates its subtree on an
        // ordinary model change, allocating fresh WidgetIds and changing the
        // AccessKit tree shape. That pass must dirty the cached AT snapshot,
        // or screen readers keep reading the pre-mutation tree indefinitely.
        let mut tree = WidgetTree::new();
        let id = tree.add(Bumpable { value: 0 });
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let _ = tree.sync_accessibility(); // populate cache, clears a11y_dirty
        assert!(
            !tree.a11y_dirty,
            "sync_accessibility should clear the dirty flag"
        );

        // Marking for rebuild is exactly what a Rebuild-level binding does;
        // the following layout pass drains pending rebuilds.
        tree.arena_mark_needs_rebuild_for_testing(id);
        tree.layout(SizeProposal::exact(100.0, 100.0));
        assert!(
            tree.a11y_dirty,
            "a rebuild must dirty the AT tree so the next sync re-walks"
        );
    }

    #[test]
    fn bound_access_label_change_dirties_accessibility_tree() {
        use crate::signal::Signal;
        use crate::test_widgets::FillWidget;
        use crate::widget_builder::WidgetBuilder;

        // Regression for audit G15: a reactive `.access_label(signal)` (and
        // likewise description / value) must register at AccessibilityOnly so
        // changing the signal re-walks the AT tree and re-resolves the
        // announced name. Previously only `access_hidden` was registered, so
        // label / description / value updates were invisible to screen readers.
        let label = Signal::new("first".to_string());
        let mut tree = WidgetTree::new();
        let _id = tree.add(FillWidget::new().access_label(label.clone()));
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let _ = tree.sync_accessibility(); // populate cache, clears a11y_dirty
        assert!(!tree.a11y_dirty, "sync_accessibility should clear the flag");

        label.set("second".to_string());
        tree.layout(SizeProposal::exact(100.0, 100.0));
        assert!(
            tree.a11y_dirty,
            "changing a bound access_label must dirty the AT tree"
        );
    }

    #[test]
    fn disabled_ancestor_blocks_event_to_descendant() {
        use crate::signal::Signal;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let tapped = Rc::new(Cell::new(false));
        let flag = tapped.clone();
        let enabled = Signal::new(true);

        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_tap(move |_pos, _ctx| {
            flag.set(true);
        }));
        let parent = tree.add(StackWidget::new().add_child(child));
        tree.enabled_when(parent, enabled.clone());
        tree.layout(SizeProposal::exact(100.0, 50.0));

        enabled.set(false);
        tree.click(child);
        assert!(
            !tapped.get(),
            "disabled ancestor should block descendant tap"
        );

        enabled.set(true);
        tree.click(child);
        assert!(tapped.get(), "re-enabling should restore dispatch");
    }

    #[test]
    fn pointer_positions_are_widget_local_at_nonzero_origin() {
        use crate::event::{Modifiers, PointerButton};
        use crate::test_widgets::InsetWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        // A 20px inset places the child at window origin (20, 20).
        let tap_pos: Rc<Cell<Option<Point>>> = Rc::new(Cell::new(None));
        let down_pos: Rc<Cell<Option<Point>>> = Rc::new(Cell::new(None));
        let drag_pos: Rc<Cell<Option<Point>>> = Rc::new(Cell::new(None));
        let (tp, dp, gp) = (tap_pos.clone(), down_pos.clone(), drag_pos.clone());

        let mut tree = WidgetTree::new();
        let child = tree.add(
            FillWidget::new()
                .on_tap(move |ev, _ctx| tp.set(Some(ev.position)))
                .on_pointer_event(move |ev, _ctx| {
                    if let WidgetEvent::PointerDown { position, .. } = ev {
                        dp.set(Some(*position));
                    }
                    crate::event::EventResponse::Ignored
                })
                .on_drag(move |phase, _ctx| {
                    use crate::gesture::DragPhase;
                    match phase {
                        DragPhase::Started { position, .. }
                        | DragPhase::Moved { position, .. }
                        | DragPhase::Ended { position } => gp.set(Some(position)),
                    }
                }),
        );
        let inset = tree.add(InsetWidget::new(20.0).set_child(child));
        let _ = inset;
        tree.layout(SizeProposal::exact(200.0, 200.0));
        assert_eq!(tree.bounds(child).origin(), Point::new(20.0, 20.0));

        // A tap at window (50, 40) must reach the handler as local (30, 20).
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(50.0, 40.0),
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        assert_eq!(
            down_pos.get(),
            Some(Point::new(30.0, 20.0)),
            "on_pointer_event PointerDown must be widget-local"
        );
        tree.dispatch_event(WidgetEvent::PointerUp {
            position: Point::new(50.0, 40.0),
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        assert_eq!(
            tap_pos.get(),
            Some(Point::new(30.0, 20.0)),
            "on_tap position must be widget-local"
        );

        // A drag (down then a move past the recognizer threshold) must
        // also deliver widget-local coordinates.
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(50.0, 40.0),
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        // First move crosses the recognizer threshold (DragStarted);
        // the second reports a known DragMoved position.
        tree.dispatch_event(WidgetEvent::PointerMove {
            position: Point::new(65.0, 55.0),
        });
        tree.dispatch_event(WidgetEvent::PointerMove {
            position: Point::new(90.0, 70.0),
        });
        assert_eq!(
            drag_pos.get(),
            Some(Point::new(70.0, 50.0)),
            "on_drag position must be widget-local"
        );
    }

    #[test]
    fn dormant_widget_not_hit_tested() {
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new());
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.pointer_move(Point::new(50.0, 25.0));
        assert_eq!(tree.hovered, Some(widget));

        tree.set_dormant(widget);
        tree.pointer_move(Point::new(200.0, 200.0));
        tree.pointer_move(Point::new(50.0, 25.0));
        assert_eq!(tree.hovered, None);
    }

    #[test]
    fn ancestor_pointer_handler_does_not_suppress_descendant_hover() {
        use crate::event::EventResponse;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        // The child reports its own hover transitions via `on_hover`.
        let hovered = Rc::new(Cell::new(false));
        let h = hovered.clone();

        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_hover(move |entered, _ctx| h.set(entered)));
        // An ancestor whose `on_pointer_event` greedily claims everything it
        // previews — exactly the "drag-detecting ancestor" footgun. Before the
        // fix it consumed the descendant's `PointerEnter`/`Leave` in the
        // preview pass and the child's hover never fired.
        tree.add(
            StackWidget::new()
                .add_child(child)
                .on_pointer_event(|_event, _ctx| EventResponse::Handled),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.pointer_move(Point::new(50.0, 25.0));
        assert!(
            hovered.get(),
            "a greedy ancestor on_pointer_event must NOT swallow the child's PointerEnter"
        );

        tree.pointer_move(Point::new(500.0, 500.0));
        assert!(
            !hovered.get(),
            "PointerLeave must likewise reach the child despite the ancestor"
        );
    }

    /// **The other direction: a child must not swallow its ancestor's hover.**
    ///
    /// A row that reveals controls on hover puts interactive children inside
    /// itself, and the pointer leaves the row *through* one of them. The child's
    /// own `on_hover` used to handle the `PointerLeave` and stop the bubble there,
    /// so the row went on believing the pointer was still over it and kept its
    /// controls showing after the pointer had gone.
    #[test]
    fn a_child_hover_handler_does_not_swallow_its_ancestors() {
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let (row, button) = (Rc::new(Cell::new(false)), Rc::new(Cell::new(false)));
        let (r, b) = (row.clone(), button.clone());

        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_hover(move |entered, _ctx| b.set(entered)));
        tree.add(
            StackWidget::new()
                .add_child(child)
                .on_hover(move |entered, _ctx| r.set(entered)),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));

        tree.pointer_move(Point::new(50.0, 25.0));
        assert!(button.get(), "the child is hovered");
        assert!(row.get(), "and so is the row it is inside");

        tree.pointer_move(Point::new(500.0, 500.0));
        assert!(!button.get(), "the child heard the leave");
        assert!(
            !row.get(),
            "and so did the row — a container is not still hovered because the \
             pointer left it through a button"
        );
    }

    #[test]
    fn destroy_subtree_clears_dangling_pointer_capture() {
        use crate::event::{EventResponse, Modifiers, PointerButton};
        use crate::test_widgets::StackWidget;

        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new().on_pointer_event(|event, ctx| {
            if matches!(event, WidgetEvent::PointerDown { .. }) {
                ctx.capture_pointer();
            }
            EventResponse::Ignored
        }));
        let parent = tree.add(StackWidget::new().add_child(child));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // A press inside the child captures the pointer to it.
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(50.0, 25.0),
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        assert_eq!(
            tree.pointer_captured_by,
            Some(child),
            "PointerDown handler should have captured the pointer"
        );

        // Tearing down the capturing subtree (e.g. mid-gesture rebuild) must
        // release the capture eagerly rather than leaving a dangling id that
        // swallows every later Move/Up until the next layout pass heals it.
        tree.destroy_subtree(parent);
        assert_eq!(
            tree.pointer_captured_by, None,
            "destroy_subtree must clear a capture anchored at a destroyed widget"
        );
    }

    // NOTE: legacy `shortcut_intercepts_before_widget` test removed with
    // the ShortcutMap dispatch path. The new shortcut→intent interception
    // is built on top of `ShortcutRegistry` + `Action`.

    // ── on_key_preview ──────────────────────────────────────────

    #[test]
    fn key_preview_consumes_before_focused_on_key() {
        // root → mid → leaf (focused). Root consumes Enter via
        // on_key_preview; the leaf's on_key must NOT fire.
        use crate::event::EventResponse;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let leaf_fired = Rc::new(Cell::new(false));
        let leaf_flag = leaf_fired.clone();
        let preview_fired = Rc::new(Cell::new(false));
        let preview_flag = preview_fired.clone();

        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new().focusable().on_key(move |event, _c| {
            // Only count KeyDown so the trailing KeyUp from
            // press_key doesn't trigger us spuriously.
            if matches!(event, WidgetEvent::KeyDown { .. }) {
                leaf_flag.set(true);
            }
            EventResponse::Handled
        }));
        let mid = tree.add(StackWidget::new().add_child(leaf));
        let _root =
            tree.add(StackWidget::new().add_child(mid).on_key_preview(
                move |event, _c| match event {
                    WidgetEvent::KeyDown {
                        key: Key::Enter, ..
                    } => {
                        preview_flag.set(true);
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                },
            ));

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(leaf);
        tree.press_key(Key::Enter, Modifiers::NONE);

        assert!(
            preview_fired.get(),
            "ancestor on_key_preview must fire for KeyDown on a focused descendant"
        );
        assert!(
            !leaf_fired.get(),
            "consuming the event in preview must prevent the focused widget's on_key from running"
        );
    }

    #[test]
    fn key_preview_falls_through_when_returning_ignored() {
        // Same shape; this time the preview returns Ignored, so
        // the leaf's on_key must still fire.
        use crate::event::EventResponse;
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        let leaf_fired = Rc::new(Cell::new(false));
        let leaf_flag = leaf_fired.clone();
        let preview_fired = Rc::new(Cell::new(false));
        let preview_flag = preview_fired.clone();

        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new().focusable().on_key(move |_e, _c| {
            leaf_flag.set(true);
            EventResponse::Handled
        }));
        let mid = tree.add(StackWidget::new().add_child(leaf));
        let _root = tree.add(StackWidget::new().add_child(mid).on_key_preview(
            move |_event, _c| {
                preview_flag.set(true);
                EventResponse::Ignored
            },
        ));

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(leaf);
        tree.press_key(Key::Enter, Modifiers::NONE);

        assert!(preview_fired.get(), "preview must always be invoked");
        assert!(
            leaf_fired.get(),
            "preview returning Ignored must not block the focused widget's on_key"
        );
    }

    #[test]
    fn key_preview_excludes_focused_target_itself() {
        // Strict-ancestors-only: the focused widget's own
        // on_key_preview must NOT fire — the preview pass walks
        // strict ancestors only.
        use crate::event::EventResponse;
        use std::cell::Cell;
        use std::rc::Rc;

        let preview_on_target = Rc::new(Cell::new(false));
        let pf = preview_on_target.clone();

        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new().focusable().on_key_preview(move |_e, _c| {
            pf.set(true);
            EventResponse::Handled
        }));
        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(leaf);
        tree.press_key(Key::Enter, Modifiers::NONE);

        assert!(
            !preview_on_target.get(),
            "the focused widget itself must not see its own on_key_preview"
        );
    }

    #[test]
    fn key_preview_root_to_target_order() {
        // Two ancestors with on_key_preview attached. The outer
        // (root-side) one must fire first; the closer one (still
        // ancestor of the focused leaf) fires second.
        use crate::event::EventResponse;
        use crate::test_widgets::StackWidget;
        use std::cell::RefCell;
        use std::rc::Rc;

        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
        let outer_log = order.clone();
        let inner_log = order.clone();

        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new().focusable());
        let inner = tree.add(StackWidget::new().add_child(leaf).on_key_preview(
            move |event, _c| {
                if matches!(event, WidgetEvent::KeyDown { .. }) {
                    inner_log.borrow_mut().push("inner");
                }
                EventResponse::Ignored
            },
        ));
        let _outer = tree.add(StackWidget::new().add_child(inner).on_key_preview(
            move |event, _c| {
                if matches!(event, WidgetEvent::KeyDown { .. }) {
                    outer_log.borrow_mut().push("outer");
                }
                EventResponse::Ignored
            },
        ));

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(leaf);
        tree.dispatch_event(WidgetEvent::KeyDown {
            key: Key::Enter,
            modifiers: Modifiers::NONE,
            text: None,
        });

        assert_eq!(
            *order.borrow(),
            vec!["outer", "inner"],
            "preview must walk root → parent-of-target"
        );
    }

    #[test]
    fn access_action_routes_to_cursored_target_not_focus() {
        // VoiceOver's VO+Space targets the node under the AT cursor (`b`),
        // even when keyboard focus is on a different control (`a`). The action
        // must fire on `b`, never get redirected to the focused `a`.
        use crate::signal::Signal;
        let a_fired = Signal::new(false);
        let b_fired = Signal::new(false);
        let a_cb = a_fired.clone();
        let b_cb = b_fired.clone();

        let mut tree = WidgetTree::new();
        let a = tree.add(
            FillWidget::new().access_action(accesskit::Action::Click, move |_ctx| a_cb.set(true)),
        );
        let b = tree.add(
            FillWidget::new().access_action(accesskit::Action::Click, move |_ctx| b_cb.set(true)),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        tree.focus(a);
        tree.dispatch_event(WidgetEvent::AccessAction {
            action: accesskit::Action::Click,
            target: Some(b),
            target_node: crate::accessibility::widget_id_to_node_id(b),
            data: None,
        });

        assert!(b_fired.get(), "the cursored target must receive the action");
        assert!(
            !a_fired.get(),
            "the keyboard-focused widget must NOT receive an action targeting another node"
        );
    }

    #[test]
    fn access_action_without_target_is_dropped_not_redirected_to_focus() {
        // An action with no (or an inactive) target must be dropped — never
        // silently re-routed to whatever holds keyboard focus.
        use crate::signal::Signal;
        let fired = Signal::new(false);
        let cb = fired.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(
            FillWidget::new().access_action(accesskit::Action::Click, move |_ctx| cb.set(true)),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        tree.focus(widget);
        tree.dispatch_event(WidgetEvent::AccessAction {
            action: accesskit::Action::Click,
            target: None,
            target_node: crate::accessibility::root_node_id(),
            data: None,
        });

        assert!(
            !fired.get(),
            "a target-less action must not be redirected to the focused widget"
        );
    }

    // NOTE: legacy `scoped_shortcut_fires_when_focused_in_subtree` test
    // removed along with the ShortcutMap dispatch path. Scope-aware
    // dispatch is handled by the new ShortcutRegistry.

    // --- Intent / Action dispatch ------------------------------

    #[test]
    fn shortcut_fires_matching_action_on_source_widget() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        let fired = Rc::new(Cell::new(false));
        let fired_flag = fired.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable());
        tree.push_action(
            widget,
            Action::new("app.save").on_invoke(move |_intent, _ctx| {
                fired_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(fired.get(), "matching action must fire on KeyDown");
    }

    #[test]
    fn global_shortcut_fires_without_focused_widget() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        // Regression: a global shortcut must fire even when no widget
        // is focused. A root-registered action should still receive
        // the intent (anchored at the root as a fallback).
        let fired = Rc::new(Cell::new(false));
        let fired_flag = fired.clone();

        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        tree.push_action(
            root,
            Action::new("app.save").on_invoke(move |_intent, _ctx| {
                fired_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        // Deliberately no focus() call.

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(
            fired.get(),
            "global shortcut must fire without a focused widget"
        );
    }

    #[test]
    fn global_shortcut_fires_after_focused_widget_destroyed() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        // Regression: if the focused widget is destroyed (e.g. during a
        // rebuild after a settings-panel rebind), focus must be cleared
        // so the next global shortcut falls through to the root-anchor
        // path instead of dispatching from a stale, destroyed id.
        let fired = Rc::new(Cell::new(false));
        let fired_flag = fired.clone();

        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        let focusable = tree.add_child(root, FillWidget::new().focusable());
        tree.push_action(
            root,
            Action::new("app.save").on_invoke(move |_intent, _ctx| {
                fired_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(focusable);
        assert_eq!(tree.focused(), Some(focusable));

        // Destroy the focused subtree (simulates a rebuild that drops
        // the currently-focused Rebind button).
        tree.destroy_subtree(focusable);
        assert_eq!(tree.focused(), None, "focus must clear when destroyed");

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(
            fired.get(),
            "global shortcut must still fire after the focused widget is destroyed"
        );
    }

    #[test]
    fn scoped_shortcut_matches_only_when_focus_in_scope() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
        use std::cell::Cell;
        use std::rc::Rc;

        let fired = Rc::new(Cell::new(0));
        let fired_flag = fired.clone();

        let mut tree = WidgetTree::new();
        let scope_root = tree.add(FillWidget::new().focusable());
        let inside = tree.add_child(scope_root, FillWidget::new().focusable());
        let outside = tree.add(FillWidget::new().focusable());

        tree.push_action(
            scope_root,
            Action::new("editor.find").on_invoke(move |_i, _c| {
                fired_flag.set(fired_flag.get() + 1);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("editor.find")
                .primary(KeyStroke::command(Key::F))
                .scope(ShortcutScope::Scoped(scope_root))
                .build(),
        );

        tree.layout(SizeProposal::exact(200.0, 100.0));

        // Focus outside the scope: the shortcut does NOT activate.
        tree.focus(outside);
        tree.press_key(Key::F, Modifiers::COMMAND);
        assert_eq!(
            fired.get(),
            0,
            "scoped shortcut must not fire outside scope"
        );

        // Focus inside the scope: it fires.
        tree.focus(inside);
        tree.press_key(Key::F, Modifiers::COMMAND);
        assert_eq!(
            fired.get(),
            1,
            "scoped shortcut must fire when focus in scope"
        );
    }

    #[test]
    fn same_chord_scoped_first_falls_back_to_global_when_focus_outside() {
        // Defect 1: a Scoped binding that sorts first by id must NOT
        // shadow the slot when focus is outside its subtree — the
        // applicable Global binding fires instead. (`editor.saveBlock`
        // < `zzz.global.save`, so the scoped one wins the id-order race
        // that `find_by_keystroke` used to settle on.)
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
        use std::cell::Cell;
        use std::rc::Rc;

        let scoped_fired = Rc::new(Cell::new(0));
        let global_fired = Rc::new(Cell::new(0));
        let sf = scoped_fired.clone();
        let gf = global_fired.clone();

        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        let editor = tree.add_child(root, FillWidget::new().focusable());
        let _editor_inner = tree.add_child(editor, FillWidget::new().focusable());
        let sidebar = tree.add_child(root, FillWidget::new().focusable());

        tree.push_action(
            editor,
            Action::new("editor.saveBlock").on_invoke(move |_i, _c| sf.set(sf.get() + 1)),
        );
        tree.push_action(
            root,
            Action::new("zzz.global.save").on_invoke(move |_i, _c| gf.set(gf.get() + 1)),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("editor.saveBlock")
                .primary(KeyStroke::command(Key::S))
                .scope(ShortcutScope::Scoped(editor))
                .build(),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("zzz.global.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(200.0, 100.0));
        tree.focus(sidebar);
        tree.press_key(Key::S, Modifiers::COMMAND);

        assert_eq!(global_fired.get(), 1, "applicable global must fire");
        assert_eq!(
            scoped_fired.get(),
            0,
            "inapplicable scoped binding must not eat the chord"
        );
    }

    #[test]
    fn same_chord_global_first_yields_to_scoped_when_focus_inside() {
        // Defect 2: a Global binding that sorts first by id must yield to
        // an in-focus Scoped binding (most-specific-scope wins), then
        // reclaim the chord once focus leaves the scope. (`app.save` <
        // `editor.saveBlock`, so the global one wins id order.)
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
        use std::cell::Cell;
        use std::rc::Rc;

        let scoped_fired = Rc::new(Cell::new(0));
        let global_fired = Rc::new(Cell::new(0));
        let sf = scoped_fired.clone();
        let gf = global_fired.clone();

        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        let editor = tree.add_child(root, FillWidget::new().focusable());
        let editor_inner = tree.add_child(editor, FillWidget::new().focusable());
        let sidebar = tree.add_child(root, FillWidget::new().focusable());

        tree.push_action(
            editor,
            Action::new("editor.saveBlock").on_invoke(move |_i, _c| sf.set(sf.get() + 1)),
        );
        tree.push_action(
            root,
            Action::new("app.save").on_invoke(move |_i, _c| gf.set(gf.get() + 1)),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("editor.saveBlock")
                .primary(KeyStroke::command(Key::S))
                .scope(ShortcutScope::Scoped(editor))
                .build(),
        );

        tree.layout(SizeProposal::exact(200.0, 100.0));

        // Focus inside the editor: the scoped binding wins over global.
        tree.focus(editor_inner);
        tree.press_key(Key::S, Modifiers::COMMAND);
        assert_eq!(
            scoped_fired.get(),
            1,
            "in-focus scoped must win over global"
        );
        assert_eq!(
            global_fired.get(),
            0,
            "global must yield to the scoped binding"
        );

        // Focus outside the editor: global reclaims the chord.
        tree.focus(sidebar);
        tree.press_key(Key::S, Modifiers::COMMAND);
        assert_eq!(scoped_fired.get(), 1, "scoped stays put outside its scope");
        assert_eq!(
            global_fired.get(),
            1,
            "global fires when focus leaves the scope"
        );
    }

    #[test]
    fn propagated_action_lets_ancestor_handle() {
        use crate::action::Action;
        use crate::intent::IntentResponse;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        let inner_seen = Rc::new(Cell::new(false));
        let outer_seen = Rc::new(Cell::new(false));
        let inner_flag = inner_seen.clone();
        let outer_flag = outer_seen.clone();

        let mut tree = WidgetTree::new();
        let outer = tree.add(FillWidget::new().focusable());
        let inner = tree.add_child(outer, FillWidget::new().focusable());

        // Inner observes then propagates; outer consumes.
        tree.push_action(
            inner,
            Action::new("app.save").on_invoke_with_response(move |_i, _c| {
                inner_flag.set(true);
                IntentResponse::Propagated
            }),
        );
        tree.push_action(
            outer,
            Action::new("app.save").on_invoke(move |_i, _c| {
                outer_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(inner);

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(inner_seen.get(), "inner action observed the intent");
        assert!(outer_seen.get(), "outer action reached after Propagated");
    }

    #[test]
    fn handled_action_stops_propagation() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        let inner_seen = Rc::new(Cell::new(false));
        let outer_seen = Rc::new(Cell::new(false));
        let inner_flag = inner_seen.clone();
        let outer_flag = outer_seen.clone();

        let mut tree = WidgetTree::new();
        let outer = tree.add(FillWidget::new().focusable());
        let inner = tree.add_child(outer, FillWidget::new().focusable());

        tree.push_action(
            inner,
            Action::new("app.save").on_invoke(move |_i, _c| {
                inner_flag.set(true);
            }),
        );
        tree.push_action(
            outer,
            Action::new("app.save").on_invoke(move |_i, _c| {
                outer_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(inner);

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(inner_seen.get());
        assert!(!outer_seen.get(), "Handled at inner must stop propagation");
    }

    #[test]
    fn disabled_action_propagates_by_default() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use crate::signal::Signal;
        use std::cell::Cell;
        use std::rc::Rc;

        let inner_seen = Rc::new(Cell::new(false));
        let outer_seen = Rc::new(Cell::new(false));
        let inner_flag = inner_seen.clone();
        let outer_flag = outer_seen.clone();

        let mut tree = WidgetTree::new();
        let outer = tree.add(FillWidget::new().focusable());
        let inner = tree.add_child(outer, FillWidget::new().focusable());

        let enabled = Signal::new(false);
        tree.push_action(
            inner,
            Action::new("app.save")
                .enabled_when(enabled.clone())
                .on_invoke(move |_i, _c| {
                    inner_flag.set(true);
                }),
        );
        tree.push_action(
            outer,
            Action::new("app.save").on_invoke(move |_i, _c| {
                outer_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(inner);

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(!inner_seen.get(), "disabled inner must not run");
        assert!(
            outer_seen.get(),
            "intent must propagate past disabled inner"
        );
    }

    #[test]
    fn disabled_action_with_non_propagating_shortcut_consumes() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use crate::signal::Signal;
        use std::cell::Cell;
        use std::rc::Rc;

        let inner_seen = Rc::new(Cell::new(false));
        let outer_seen = Rc::new(Cell::new(false));
        let inner_flag = inner_seen.clone();
        let outer_flag = outer_seen.clone();

        let mut tree = WidgetTree::new();
        let outer = tree.add(FillWidget::new().focusable());
        let inner = tree.add_child(outer, FillWidget::new().focusable());

        let enabled = Signal::new(false);
        tree.push_action(
            inner,
            Action::new("app.save")
                .enabled_when(enabled.clone())
                .on_invoke(move |_i, _c| {
                    inner_flag.set(true);
                }),
        );
        tree.push_action(
            outer,
            Action::new("app.save").on_invoke(move |_i, _c| {
                outer_flag.set(true);
            }),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .propagate_when_disabled(false)
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(inner);

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(!inner_seen.get(), "disabled inner still does not run");
        assert!(
            !outer_seen.get(),
            "intent must NOT propagate when shortcut disallows it"
        );
    }

    #[test]
    fn send_intent_from_handler_reaches_ancestor_action() {
        use crate::action::Action;
        use crate::intent::Intent;
        use std::cell::Cell;
        use std::rc::Rc;

        let save_seen = Rc::new(Cell::new(false));
        let save_flag = save_seen.clone();

        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        let button = tree.add_child(
            root,
            FillWidget::new().on_tap(|_pos, ctx| {
                ctx.send_intent(Intent::new("app.save"));
            }),
        );
        tree.push_action(
            root,
            Action::new("app.save").on_invoke(move |_i, _c| {
                save_flag.set(true);
            }),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.click(button);
        assert!(
            save_seen.get(),
            "ctx.send_intent must reach ancestor action"
        );
    }

    #[test]
    fn widget_type_histogram_counts_distinct_types() {
        // The histogram surfaces concrete widget types
        // by std::any::type_name_of_val. Widgets become active
        // after the first layout pass, so we run that before
        // checking the histogram.
        let mut tree = WidgetTree::new();
        let _ = tree.add(FillWidget::new());
        let _ = tree.add(FillWidget::new());
        let _ = tree.add(FillWidget::new());
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let histogram = tree.widget_type_histogram();
        let total: u32 = histogram.values().sum();
        assert!(
            total >= 3,
            "expected at least 3 active widgets, got {total}: {histogram:?}"
        );
        let fillwidget_entries: u32 = histogram
            .iter()
            .filter(|(k, _)| k.contains("FillWidget"))
            .map(|(_, v)| *v)
            .sum();
        assert!(
            fillwidget_entries >= 3,
            "expected ≥3 FillWidget instances; histogram = {histogram:?}"
        );
        assert_eq!(tree.active_widget_count() as u32, total);
    }

    #[test]
    fn intent_source_tagged_handler_for_tap_activation() {
        // A tap-driven `ctx.send_intent` must surface as
        // `IntentSource::Handler` to ancestor actions, not the
        // `Programmatic` default of `Intent::new`.
        use crate::action::Action;
        use crate::intent::Intent;
        use crate::telemetry::IntentSource;
        use std::cell::Cell;
        use std::rc::Rc;
        let captured = Rc::new(Cell::new(IntentSource::Unknown));
        let captured_for_action = captured.clone();

        let mut tree = WidgetTree::new();
        let root = tree.add(FillWidget::new());
        let button = tree.add_child(
            root,
            FillWidget::new().on_tap(|_pos, ctx| {
                ctx.send_intent(Intent::new("app.save"));
            }),
        );
        tree.push_action(
            root,
            Action::new("app.save").on_invoke(move |intent, _c| {
                captured_for_action.set(intent.source);
            }),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.click(button);
        assert_eq!(
            captured.get(),
            IntentSource::Handler,
            "tap-driven intent must tag IntentSource::Handler"
        );
    }

    #[test]
    fn intent_source_programmatic_when_no_handler_active() {
        use crate::intent::Intent;
        use crate::telemetry::IntentSource;
        let intent = Intent::new("app.demo");
        assert_eq!(intent.source, IntentSource::Programmatic);

        // ctx.send_intent without a handler scope keeps it Programmatic.
        let mut ctx = EventContext::new();
        ctx.send_intent(Intent::new("app.demo"));
        let queued = ctx.pending_intents.first().expect("intent queued");
        assert_eq!(queued.source, IntentSource::Programmatic);
    }

    #[test]
    fn with_intent_source_overrides_for_managed_widgets() {
        use crate::intent::Intent;
        use crate::telemetry::IntentSource;
        let mut ctx = EventContext::new();
        ctx.with_intent_source(IntentSource::Menu, |ctx| {
            ctx.send_intent(Intent::new("app.demo"));
        });
        let queued = ctx.pending_intents.first().expect("intent queued");
        assert_eq!(
            queued.source,
            IntentSource::Menu,
            "with_intent_source(Menu) must tag the dispatched intent"
        );

        // After the closure returns, current_source is restored —
        // a follow-up send_intent without a wrapping closure goes
        // back to the default (no override).
        ctx.send_intent(Intent::new("app.next"));
        let next = ctx.pending_intents.last().expect("second intent");
        assert_eq!(next.source, IntentSource::Programmatic);
    }

    #[test]
    fn disabled_shortcut_falls_through_to_focused_widget() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use crate::signal::Signal;
        use std::cell::Cell;
        use std::rc::Rc;

        let action_fired = Rc::new(Cell::new(false));
        let on_key_fired = Rc::new(Cell::new(false));
        let af = action_fired.clone();
        let kf = on_key_fired.clone();

        let enabled = Signal::new(false);

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable().on_key(move |event, _ctx| {
            if matches!(
                event,
                WidgetEvent::KeyDown {
                    key: Key::S,
                    modifiers,
                    ..
                } if modifiers.ctrl()
            ) {
                kf.set(true);
                return EventResponse::Handled;
            }
            EventResponse::Ignored
        }));
        tree.push_action(
            widget,
            Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .enabled_when(enabled.clone())
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        // Disabled: keystroke falls through to on_key.
        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(
            !action_fired.get(),
            "disabled shortcut must not invoke its action"
        );
        assert!(
            on_key_fired.get(),
            "disabled shortcut must let KeyDown reach the focused widget"
        );

        // Re-enable → action fires, on_key does not.
        on_key_fired.set(false);
        enabled.set(true);
        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(action_fired.get(), "re-enabled shortcut must dispatch");
        assert!(
            !on_key_fired.get(),
            "enabled shortcut must consume the KeyDown"
        );
    }

    #[test]
    fn keyboard_capture_bypasses_shortcut() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        // A focused keyboard-capture surface (e.g. a terminal) must receive
        // Ctrl+S itself, even though an ENABLED global shortcut binds it — the
        // whole point of GAP 1. A non-capturing widget must yield to the
        // shortcut (the control case).
        fn run(capture: bool) -> (bool, bool) {
            let action_fired = Rc::new(Cell::new(false));
            let on_key_fired = Rc::new(Cell::new(false));
            let af = action_fired.clone();
            let kf = on_key_fired.clone();

            let mut tree = WidgetTree::new();
            let widget = tree.add(
                FillWidget::new()
                    .focusable()
                    .keyboard_capture(capture)
                    .on_key(move |event, _ctx| {
                        if matches!(
                            event,
                            WidgetEvent::KeyDown { key: Key::S, modifiers, .. } if modifiers.ctrl()
                        ) {
                            kf.set(true);
                            return EventResponse::Handled;
                        }
                        EventResponse::Ignored
                    }),
            );
            tree.push_action(
                widget,
                Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
            );
            tree.shortcut_registry_mut().register(
                Shortcut::new("app.save")
                    .primary(KeyStroke::command(Key::S))
                    .build(),
            );

            tree.layout(SizeProposal::exact(100.0, 50.0));
            tree.focus(widget);
            tree.press_key(Key::S, Modifiers::COMMAND);
            (action_fired.get(), on_key_fired.get())
        }

        // Capture on: the shortcut is bypassed, the widget sees the key.
        let (action, on_key) = run(true);
        assert!(
            !action,
            "keyboard_capture must suppress the shortcut action"
        );
        assert!(on_key, "keyboard_capture must deliver the raw KeyDown");

        // Capture off (control): the shortcut consumes the key.
        let (action, on_key) = run(false);
        assert!(action, "without capture the shortcut must fire");
        assert!(!on_key, "without capture the widget must not see the key");
    }

    #[test]
    fn ctrl_tab_always_escapes_a_keyboard_capture_surface() {
        use std::cell::Cell;
        use std::rc::Rc;

        // WCAG 2.1.2. A capture surface answers `Handled` to every key —
        // that is what it is for — so the "cycle focus only when the focused
        // widget did not handle Tab" rule can never get focus out of one.
        // Ctrl+Tab / Ctrl+Shift+Tab are therefore reserved by the dispatcher
        // and never reach the widget at all.
        let saw_key = Rc::new(Cell::new(false));
        let sk = saw_key.clone();

        let mut tree = WidgetTree::new();
        let capture = tree.add(
            FillWidget::new()
                .focusable()
                .keyboard_capture(true)
                // The greediest possible handler: everything is consumed.
                .on_key(move |_event, _ctx| {
                    sk.set(true);
                    EventResponse::Handled
                }),
        );
        let neighbour = tree.add(FillWidget::new().focusable());
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // Plain Tab stays inside: the widget consumed it (a terminal writes
        // it to the child as `\t`).
        tree.focus(capture);
        tree.press_key(Key::Tab, Modifiers::NONE);
        assert!(saw_key.get(), "plain Tab must reach the capture surface");
        assert_eq!(
            tree.focused(),
            Some(capture),
            "plain Tab must not move focus off a capture surface"
        );

        // Ctrl+Tab escapes forward, without the widget ever seeing it.
        saw_key.set(false);
        tree.press_key(Key::Tab, Modifiers::CTRL);
        assert!(
            !saw_key.get(),
            "Ctrl+Tab is reserved and must not reach the capture surface"
        );
        assert_eq!(
            tree.focused(),
            Some(neighbour),
            "Ctrl+Tab must move focus out of a capture surface"
        );

        // And backwards.
        tree.focus(capture);
        tree.press_key(Key::Tab, Modifiers::CTRL | Modifiers::SHIFT);
        assert_eq!(
            tree.focused(),
            Some(neighbour),
            "Ctrl+Shift+Tab must move focus out of a capture surface"
        );
    }

    #[test]
    fn scope_mismatch_does_not_invoke_on_activate() {
        use crate::intent::Intent;
        use crate::shortcut::{KeyStroke, Shortcut, ShortcutScope};
        use std::cell::Cell;
        use std::rc::Rc;

        // Regression: before the find/invoke split, `on_activate` ran
        // even when the focused widget was outside the shortcut's
        // scope, and any side effects on its ctx were silently
        // dropped. The closure must now only run when the scope
        // check has already passed.
        let activated = Rc::new(Cell::new(false));
        let activated_flag = activated.clone();

        let mut tree = WidgetTree::new();
        let scope_root = tree.add(FillWidget::new().focusable());
        let outside = tree.add(FillWidget::new().focusable());

        tree.shortcut_registry_mut().register(
            Shortcut::new("editor.find")
                .primary(KeyStroke::command(Key::F))
                .scope(ShortcutScope::Scoped(scope_root))
                .on_activate(move |_ks, _ctx| {
                    activated_flag.set(true);
                    Intent::new("editor.find")
                })
                .build(),
        );

        tree.layout(SizeProposal::exact(200.0, 100.0));
        tree.focus(outside);

        tree.press_key(Key::F, Modifiers::COMMAND);
        assert!(
            !activated.get(),
            "on_activate must not run when focus is outside the shortcut's scope"
        );
    }

    #[test]
    fn key_capture_runs_callback_and_bypasses_registry() {
        use crate::action::Action;
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        let action_fired = Rc::new(Cell::new(false));
        let af = action_fired.clone();
        let captured = Rc::new(Cell::new(None));
        let cf = captured.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable());
        tree.push_action(
            widget,
            Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        let handle = tree.begin_key_capture(move |ks, _reg, _ctx| cf.set(Some(ks)));
        assert!(tree.is_capturing_keys());

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert_eq!(
            captured.get(),
            Some(KeyStroke::command(Key::S)),
            "capture callback must receive the chord"
        );
        assert!(
            !action_fired.get(),
            "shortcut action must not fire while capture is armed"
        );
        assert!(
            !tree.is_capturing_keys(),
            "capture is one-shot; next KeyDown flows normally"
        );
        drop(handle);
    }

    #[test]
    fn key_capture_can_rebind_through_registry() {
        use crate::shortcut::{KeyStroke, Shortcut};

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable());
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );

        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        // Arm capture: whatever chord comes next, rebind app.save to it.
        let _h = tree.begin_key_capture(|ks, reg, _ctx| {
            reg.rebind_primary("app.save", Some(ks));
        });

        tree.press_key(Key::B, Modifiers::COMMAND | Modifiers::SHIFT);
        assert_eq!(
            tree.shortcut_registry()
                .effective("app.save")
                .unwrap()
                .primary,
            Some(KeyStroke::command_shift(Key::B))
        );
    }

    #[test]
    fn dropping_capture_handle_cancels_capture() {
        use crate::shortcut::{KeyStroke, Shortcut};
        use std::cell::Cell;
        use std::rc::Rc;

        let action_fired = Rc::new(Cell::new(false));
        let af = action_fired.clone();
        let capture_fired = Rc::new(Cell::new(false));
        let cf = capture_fired.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable());
        tree.push_action(
            widget,
            crate::action::Action::new("app.save").on_invoke(move |_i, _c| af.set(true)),
        );
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        // Arm capture in a scope, then drop the handle before any key
        // is pressed. The next KeyDown must fall through to the normal
        // shortcut path, firing the action — not the cancelled capture.
        {
            let _h = tree.begin_key_capture(move |_ks, _reg, _ctx| cf.set(true));
            assert!(tree.is_capturing_keys());
            // `_h` drops here → cancel.
        }
        assert!(
            !tree.is_capturing_keys(),
            "dropping the handle must cancel the capture"
        );

        tree.press_key(Key::S, Modifiers::COMMAND);
        assert!(!capture_fired.get(), "cancelled capture must not fire");
        assert!(
            action_fired.get(),
            "shortcut action runs after capture was cancelled"
        );
    }

    #[test]
    fn second_begin_key_capture_does_not_racecancel_first() {
        use std::cell::Cell;
        use std::rc::Rc;

        let first = Rc::new(Cell::new(false));
        let second = Rc::new(Cell::new(false));
        let f = first.clone();
        let s = second.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable());
        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        // Arm #1 then replace with #2. #1's handle is later dropped,
        // which would have cancelled the active capture under the old
        // `Option<Box<FnOnce>>` design — CaptureHandle now ties each
        // session to its own slot, so the drop only clears #1's
        // (orphaned) slot, not #2.
        let h1 = tree.begin_key_capture(move |_ks, _reg, _ctx| f.set(true));
        let _h2 = tree.begin_key_capture(move |_ks, _reg, _ctx| s.set(true));
        drop(h1);

        assert!(
            tree.is_capturing_keys(),
            "dropping the older handle must not cancel the active capture"
        );
        tree.press_key(Key::K, Modifiers::COMMAND);
        assert!(!first.get());
        assert!(second.get(), "newest capture wins");
    }

    #[test]
    fn capture_callback_can_send_intent() {
        use crate::action::Action;
        use crate::intent::Intent;

        use std::cell::Cell;
        use std::rc::Rc;

        let ran = Rc::new(Cell::new(false));
        let flag = ran.clone();

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().focusable());
        tree.push_action(
            widget,
            Action::new("app.save").on_invoke(move |_i, _c| flag.set(true)),
        );
        tree.layout(SizeProposal::exact(100.0, 50.0));
        tree.focus(widget);

        let _h = tree.begin_key_capture(|_ks, _reg, ctx| {
            ctx.send_intent(Intent::new("app.save"));
        });
        tree.press_key(Key::X, Modifiers::COMMAND);
        assert!(
            ran.get(),
            "intent queued from capture callback must dispatch"
        );
    }

    #[test]
    fn binding_registry_does_not_accumulate_across_rebuilds() {
        use crate::binding::BindingLevel;
        use crate::signal::Signal;

        #[derive(Debug)]
        struct BoundLeaf {
            tick: Signal<u64>,
        }
        impl crate::widget::Widget for BoundLeaf {
            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
                self.tick.bind_to(
                    ctx.self_id(),
                    ctx.binding_registry(),
                    BindingLevel::Relayout,
                );
                Vec::new()
            }
            fn layout_response(
                &self,
                proposal: SizeProposal,
                _ctx: &crate::widget::LayoutContext,
            ) -> crate::widget::LayoutResponse {
                proposal.resolve(10.0, 10.0).into()
            }
        }

        let mut tree = WidgetTree::new();
        let tick = Signal::new(0_u64);
        let widget = tree.add(BoundLeaf { tick: tick.clone() });
        tree.layout(SizeProposal::exact(200.0, 200.0));
        let after_first_build = tree.binding_registry().len();
        assert!(after_first_build >= 1);

        // Force rebuild a handful of times and verify the binding
        // count does not keep growing. Pre-fix: each rebuild pushed
        // a new entry for the same (widget, signal) pair.
        for _ in 0..5 {
            tree.arena.mark_needs_rebuild(widget);
            tree.layout(SizeProposal::exact(200.0, 200.0));
        }
        assert_eq!(
            tree.binding_registry().len(),
            after_first_build,
            "bindings must be cleared on rebuild"
        );

        tree.destroy_subtree(widget);
        assert_eq!(
            tree.binding_registry().len(),
            0,
            "bindings must be cleared on destroy"
        );
        // Silence unused-variable warning for the signal.
        let _ = tick;
    }

    #[test]
    fn ctx_destroy_cancels_animations_and_bindings_via_deferred_path() {
        // Regression: `EventContext::destroy` queues
        // `TreeMutation::Destroy`, which used to be applied with the
        // bare `arena.destroy` — unlinking the node but leaking the
        // animation-scheduler entry (it holds a strong `Signal<f32>`
        // clone, so the widget kept animating after destruction) and
        // the widget's bindings. It must route through
        // `destroy_subtree` like every other destroy path does.
        use crate::binding::BindingLevel;
        use crate::signal::Signal;
        use std::time::{Duration, Instant};
        use teksilo_tokens::Easing;

        #[derive(Debug)]
        struct BoundLeaf {
            tick: Signal<u64>,
        }
        impl crate::widget::Widget for BoundLeaf {
            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
                self.tick.bind_to(
                    ctx.self_id(),
                    ctx.binding_registry(),
                    BindingLevel::Relayout,
                );
                Vec::new()
            }
            fn layout_response(
                &self,
                proposal: SizeProposal,
                _ctx: &crate::widget::LayoutContext,
            ) -> crate::widget::LayoutResponse {
                proposal.resolve(10.0, 10.0).into()
            }
        }

        let mut tree = WidgetTree::new();
        let widget = tree.add(BoundLeaf {
            tick: Signal::new(0_u64),
        });
        tree.layout(SizeProposal::exact(200.0, 200.0));
        assert!(tree.binding_registry().len() >= 1);

        // Seed an animation owned by the widget — exactly the strong
        // `Signal<f32>` clone the scheduler outlives the widget with.
        let anim = Signal::<f32>::new_animated(0.0);
        tree.animation_scheduler.animate(
            &anim,
            widget,
            1.0,
            Duration::from_secs(10),
            Easing::Linear,
            Instant::now(),
        );
        assert_eq!(tree.animation_scheduler.active_count(), 1);

        // Destroy via the deferred handler-time path.
        let mut noop = crate::window::NoopWindowOps;
        tree.run_with_event_context(&mut noop, |ctx| ctx.destroy(widget));

        assert_eq!(
            tree.animation_scheduler.active_count(),
            0,
            "ctx.destroy must cancel animations owned by the destroyed widget"
        );
        assert_eq!(
            tree.binding_registry().len(),
            0,
            "ctx.destroy must unregister the destroyed widget's bindings"
        );
        assert!(
            tree.arena.get(widget).is_none(),
            "node must be removed from the arena"
        );
    }

    #[test]
    fn clear_shortcut_override_via_event_context_restores_default() {
        use crate::shortcut::{KeyStroke, Shortcut};

        let mut tree = WidgetTree::new();
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );
        tree.shortcut_registry_mut()
            .rebind_primary("app.save", Some(KeyStroke::alt(Key::S)));

        let source = tree.add(FillWidget::new());
        let mut ctx = EventContext::new();
        ctx.clear_shortcut_override("app.save");
        tree.collect_from_ctx(ctx, source);

        assert_eq!(
            tree.shortcut_registry()
                .effective("app.save")
                .unwrap()
                .primary,
            Some(KeyStroke::command(Key::S))
        );
    }

    #[test]
    fn rebind_shortcut_primary_via_event_context() {
        use crate::shortcut::{KeyStroke, Shortcut};

        let mut tree = WidgetTree::new();
        tree.shortcut_registry_mut().register(
            Shortcut::new("app.save")
                .primary(KeyStroke::command(Key::S))
                .build(),
        );
        let source = tree.add(FillWidget::new());

        let mut ctx = EventContext::new();
        ctx.rebind_shortcut_primary("app.save", Some(KeyStroke::alt(Key::S)));
        tree.collect_from_ctx(ctx, source);

        assert_eq!(
            tree.shortcut_registry()
                .effective("app.save")
                .unwrap()
                .primary,
            Some(KeyStroke::alt(Key::S))
        );
    }

    #[test]
    fn unregister_all_for_owner_called_on_destroy() {
        use crate::shortcut::{KeyStroke, Shortcut};

        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new());
        let widget_owner = widget;
        tree.shortcut_registry_mut().register_owned(
            Shortcut::new("scoped.thing")
                .primary(KeyStroke::command(Key::K))
                .build(),
            widget_owner,
        );
        assert!(
            tree.shortcut_registry()
                .get_default("scoped.thing")
                .is_some()
        );

        tree.destroy_subtree(widget);
        assert!(
            tree.shortcut_registry()
                .get_default("scoped.thing")
                .is_none(),
            "destroying the owner must unregister its shortcut"
        );
    }

    /// A global action fires for an intent dispatched from a widget in a
    /// completely unrelated subtree — proving it is a position-independent
    /// fallback (the menu-bar-vs-content case).
    #[test]
    fn global_action_reached_from_unrelated_source() {
        use crate::action::Action;
        use crate::intent::Intent;
        use std::cell::Cell;
        use std::rc::Rc;

        #[derive(Debug)]
        struct Registrar(Rc<Cell<bool>>);
        impl crate::widget::Widget for Registrar {
            fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
                let flag = self.0.clone();
                ctx.register_action_global(
                    Action::new("test.global").on_invoke(move |_i, _c| flag.set(true)),
                );
                vec![]
            }
            fn layout_response(
                &self,
                _p: teksilo_canvas::SizeProposal,
                _c: &crate::widget::LayoutContext,
            ) -> crate::widget::LayoutResponse {
                teksilo_canvas::Size::new(0.0, 0.0).into()
            }
        }

        let mut tree = WidgetTree::new();
        let fired = Rc::new(Cell::new(false));
        let registrar = tree.add(Registrar(fired.clone()));
        let source = tree.add(FillWidget::new()); // unrelated sibling root
        let mut ops = crate::window::NoopWindowOps;

        tree.dispatch_intent(source, Intent::new("test.global"), true, &mut ops);
        assert!(
            fired.get(),
            "global action must fire from an unrelated source"
        );

        // And it is torn down with its owner.
        fired.set(false);
        tree.destroy_subtree(registrar);
        tree.dispatch_intent(source, Intent::new("test.global"), true, &mut ops);
        assert!(
            !fired.get(),
            "destroying the owner must remove its global action"
        );
    }

    // --- Transform-aware hit-testing -------------------------------------
    //
    // `set_transform` scopes are paint-only: the renderer pushes the
    // transform around the subtree, so the visually-displayed area is
    // shifted relative to `arena.bounds(id)`. Hit-testing must inverse-
    // transform the screen-space input point as it descends through each
    // transform scope so that a click on the visually-rendered area lands
    // on the correct widget. Pre-fix, screen-space `bounds.contains(point)`
    // returned the *pre-transform* widget for in-bounds-pre-transform
    // points and missed the visually-shifted hit area entirely.

    #[test]
    fn hit_test_through_translate_scope() {
        use crate::test_widgets::StackWidget;
        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new());
        let parent = tree.add(StackWidget::new().add_child(child));
        // Visually shift the entire subtree right by 100px.
        tree.set_transform(parent, teksilo_canvas::Transform2D::translate(100.0, 0.0));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // (50, 25) is inside the *pre-transform* bounds but the widget is
        // visually painted at x=100..200; a click at (50, 25) lands on
        // empty space.
        assert_eq!(
            tree.hit_test(Point::new(50.0, 25.0)),
            None,
            "pre-transform area is not visually populated and must not hit"
        );
        // (150, 25) is inside the visually-rendered area (post-translate).
        assert_eq!(
            tree.hit_test(Point::new(150.0, 25.0)),
            Some(child),
            "visually-rendered area must hit the child"
        );
        // Off everything.
        assert_eq!(tree.hit_test(Point::new(250.0, 25.0)), None);
    }

    #[test]
    fn hit_test_through_scale_scope() {
        use crate::test_widgets::StackWidget;
        let mut tree = WidgetTree::new();
        let child = tree.add(FillWidget::new());
        let parent = tree.add(StackWidget::new().add_child(child));
        // Halve the visual size: pre-transform bounds (0,0,100,50) →
        // visually (0,0,50,25).
        tree.set_transform(parent, teksilo_canvas::Transform2D::scale(0.5, 0.5));
        tree.layout(SizeProposal::exact(100.0, 50.0));

        // Inside the visual area.
        assert_eq!(tree.hit_test(Point::new(25.0, 12.0)), Some(child));
        // Outside the visual area but inside the pre-transform bounds.
        // Without the fix this would (incorrectly) hit the child.
        assert_eq!(
            tree.hit_test(Point::new(75.0, 25.0)),
            None,
            "scaled-out region must not hit"
        );
    }

    #[test]
    fn hit_test_through_nested_transforms_compose() {
        use crate::test_widgets::StackWidget;
        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new());
        let inner = tree.add(StackWidget::new().add_child(leaf));
        let outer = tree.add(StackWidget::new().add_child(inner));
        // Outer translates by (100, 0); inner additionally scales by 2.
        // Effective at leaf = scale(2,2).then(translate(100,0)) — the
        // renderer composes deepest-first (see `effective_transform`).
        tree.set_transform(outer, teksilo_canvas::Transform2D::translate(100.0, 0.0));
        tree.set_transform(inner, teksilo_canvas::Transform2D::scale(2.0, 2.0));
        tree.layout(SizeProposal::exact(50.0, 25.0));

        // Leaf-local (0, 0) → scale → (0, 0) → translate → (100, 0).
        // Leaf-local (50, 25) → scale → (100, 50) → translate → (200, 50).
        // So the visual hit area is x in [100, 200], y in [0, 50].
        assert_eq!(tree.hit_test(Point::new(150.0, 25.0)), Some(leaf));
        assert_eq!(tree.hit_test(Point::new(50.0, 25.0)), None);
        assert_eq!(tree.hit_test(Point::new(250.0, 25.0)), None);
    }

    #[test]
    fn hit_test_identity_transform_unchanged() {
        // Sanity: an identity transform must not perturb the existing
        // hit-test behavior. Guards against accidental over-application
        // of inversion on the hot path.
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new());
        tree.set_transform(widget, teksilo_canvas::Transform2D::IDENTITY);
        tree.layout(SizeProposal::exact(100.0, 50.0));
        assert_eq!(tree.hit_test(Point::new(50.0, 25.0)), Some(widget));
    }

    #[test]
    fn arena_effective_transform_composes_ancestors() {
        // `arena.effective_transform(id)` must equal the renderer's
        // transform-stack top by the time it begins painting `id` —
        // i.e. mapping `id`'s pre-transform local point to screen space.
        // The renderer's `PushTransform` handler composes as
        // `device_t.then(prev_top)` (see `teksilo-render/src/renderer.rs`),
        // so the *innermost* transform applies first to a local point.
        // For ancestors [outer, inner] both with transforms, this means
        // effective = inner.then(outer), NOT outer.then(inner).
        // teksilo-scene relies on this to project scene-coord bounds to
        // screen space when emitting AT nodes for view-transformed items.
        use crate::test_widgets::StackWidget;
        let mut tree = WidgetTree::new();
        let leaf = tree.add(FillWidget::new());
        let inner = tree.add(StackWidget::new().add_child(leaf));
        let outer = tree.add(StackWidget::new().add_child(inner));
        tree.set_transform(outer, teksilo_canvas::Transform2D::translate(100.0, 0.0));
        tree.set_transform(inner, teksilo_canvas::Transform2D::scale(2.0, 2.0));
        tree.layout(SizeProposal::exact(50.0, 25.0));

        let eff = tree.arena.effective_transform(leaf);
        let expected = teksilo_canvas::Transform2D::scale(2.0, 2.0)
            .then(&teksilo_canvas::Transform2D::translate(100.0, 0.0));
        for (a, b) in eff.m.iter().zip(expected.m.iter()) {
            assert!(
                (a - b).abs() < 1e-5,
                "effective_transform mismatch: got {:?}, want {:?}",
                eff.m,
                expected.m
            );
        }

        // Concrete-point check that pins the composition order without
        // relying on matrix equality alone: a leaf-local point at the
        // bounds origin (0, 0) should land at screen (100, 0) — scale
        // first (still (0,0)), then translate by 100 in x. With the
        // wrong composition order it would land at (200, 0).
        let screen_origin = eff.apply_point(Point::new(0.0, 0.0));
        assert!((screen_origin.x - 100.0).abs() < 1e-5);
        assert!((screen_origin.y - 0.0).abs() < 1e-5);
        // Far corner: leaf-local (50, 25) → scale → (100, 50) → translate
        // by 100 in x → (200, 50).
        let screen_corner = eff.apply_point(Point::new(50.0, 25.0));
        assert!((screen_corner.x - 200.0).abs() < 1e-5);
        assert!((screen_corner.y - 50.0).abs() < 1e-5);
    }

    // ─── Context-menu factory: position, ctx, None fall-through ─────────

    /// A throwaway content widget the factory mounts. We never paint
    /// it — the test only checks that it lands in the overlay manager.
    #[derive(Debug)]
    struct StubMenu;
    impl crate::widget::Widget for StubMenu {
        fn layout_response(
            &self,
            _proposal: SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            teksilo_canvas::Size::new(100.0, 40.0).into()
        }
    }

    #[test]
    fn context_menu_factory_receives_click_position() {
        use crate::event::{Modifiers, PointerButton};
        use std::cell::Cell;
        use std::rc::Rc;

        let captured_position = Rc::new(Cell::new(None::<Point>));
        let cap = captured_position.clone();
        let mut tree = WidgetTree::new();
        let widget = tree.add(FillWidget::new().context_menu(move |pos, _ctx| {
            cap.set(Some(pos));
            Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
        }));
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let click = Point::new(73.0, 42.0);
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: click,
            button: PointerButton::Secondary,
            modifiers: Modifiers::NONE,
        });

        let got = captured_position.get();
        assert_eq!(
            got,
            Some(click),
            "factory must receive the click position; got {:?}",
            got
        );
        let _ = widget;
    }

    #[test]
    fn context_menu_factory_returning_none_falls_through_to_parent() {
        use crate::event::{Modifiers, PointerButton};
        use crate::test_widgets::StackWidget;
        use std::cell::Cell;
        use std::rc::Rc;

        // Outer factory always returns Some(StubMenu); inner factory
        // returns None. Right-click should walk past the inner and
        // mount the outer's menu.
        let outer_called = Rc::new(Cell::new(0_u32));
        let outer_flag = outer_called.clone();
        let mut tree = WidgetTree::new();
        let inner = tree.add(FillWidget::new().context_menu(|_pos, _ctx| None));
        let _outer = tree.add(StackWidget::new().add_child(inner).context_menu(
            move |_pos, _ctx| {
                outer_flag.set(outer_flag.get() + 1);
                Some(Box::new(StubMenu) as Box<dyn crate::widget::Widget>)
            },
        ));
        tree.layout(SizeProposal::exact(200.0, 100.0));

        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(50.0, 25.0),
            button: PointerButton::Secondary,
            modifiers: Modifiers::NONE,
        });

        assert_eq!(
            outer_called.get(),
            1,
            "inner returning None must fall through to the outer factory"
        );
    }

    #[test]
    fn context_menu_factory_none_throughout_chain_does_not_show_overlay() {
        use crate::event::{Modifiers, PointerButton};

        // Single factory returning None → no overlay shown, no panic.
        let mut tree = WidgetTree::new();
        tree.add(FillWidget::new().context_menu(|_pos, _ctx| None));
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let overlay_count_before = tree.overlay_manager.len();
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(50.0, 25.0),
            button: PointerButton::Secondary,
            modifiers: Modifiers::NONE,
        });
        let overlay_count_after = tree.overlay_manager.len();
        assert_eq!(
            overlay_count_before, overlay_count_after,
            "a factory returning None must not mount any overlay"
        );
    }

    // ---- Reconcile-on-rebuild (`preserves_children_on_rebuild`) ----------
    //
    // These pin the contract that the preserve path RECONCILES: it keeps the
    // children a rebuild re-attaches (and any subtree re-parented into the new
    // tree) while reaping the ones it drops — so memoizing widgets are both
    // stateful and leak-free. Regression guard for the orphan-leak the old
    // "preserve = destroy nothing" behaviour caused.

    /// `build()` mints a fresh child every time and returns only it, abandoning
    /// the previous one. Used to prove dropped children are reaped, not leaked.
    #[derive(Debug)]
    struct FreshChildHost {
        preserve: bool,
    }
    impl Widget for FreshChildHost {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            vec![ctx.add(FillWidget::new())]
        }
        fn layout_response(
            &self,
            p: SizeProposal,
            _c: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            p.resolve(10.0, 10.0).into()
        }
        fn preserves_children_on_rebuild(&self) -> bool {
            self.preserve
        }
    }

    #[test]
    fn reconcile_reaps_dropped_children_no_leak() {
        // preserve=false (destroy-all) and preserve=true (reconcile) must BOTH
        // keep the arena bounded when a rebuild drops its old child. Before the
        // reconcile fix, preserve=true grew the arena (and the active set) by
        // one stranded orphan per rebuild.
        for preserve in [false, true] {
            let mut tree = WidgetTree::new();
            let host = tree.add(FreshChildHost { preserve });
            tree.layout(SizeProposal::exact(100.0, 100.0));
            let total0 = tree.arena.len();
            let active0 = tree.active_widget_count();
            for _ in 0..5 {
                tree.arena_mark_needs_rebuild_for_testing(host);
                tree.layout(SizeProposal::exact(100.0, 100.0));
            }
            assert_eq!(
                tree.arena.len(),
                total0,
                "preserve={preserve}: dropped children must be reaped, not leaked"
            );
            assert_eq!(
                tree.active_widget_count(),
                active0,
                "preserve={preserve}: no stranded still-active orphans"
            );
        }
    }

    /// `build()` mints one **detached** node every time — the shape of every
    /// pre-built popup in the widget crate (a dropdown, a calendar, a
    /// tooltip's cascade children): parked dormant, shown later through an
    /// overlay, and deliberately not a child, since activation and paint both
    /// descend through `children`.
    #[derive(Debug)]
    struct DetachedContentHost {
        preserve: bool,
    }
    impl Widget for DetachedContentHost {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            let popup = ctx.add_detached(FillWidget::new());
            ctx.set_dormant(popup);
            vec![ctx.add(FillWidget::new())]
        }
        fn layout_response(
            &self,
            p: SizeProposal,
            _c: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            p.resolve(10.0, 10.0).into()
        }
        fn preserves_children_on_rebuild(&self) -> bool {
            self.preserve
        }
    }

    #[test]
    fn rebuilding_reaps_detached_content_no_leak() {
        // A parentless node is reachable from no walk at all — not the child
        // teardown, not the accessibility tree, not `active_widget_count`. Held
        // by a bare `ctx.add` it simply accumulated: one stranded popup per
        // rebuild, for the lifetime of the process. `add_detached` records the
        // ownership edge that makes it reapable.
        for preserve in [false, true] {
            let mut tree = WidgetTree::new();
            let host = tree.add(DetachedContentHost { preserve });
            tree.layout(SizeProposal::exact(100.0, 100.0));
            let total0 = tree.arena.len();
            for _ in 0..5 {
                tree.arena_mark_needs_rebuild_for_testing(host);
                tree.layout(SizeProposal::exact(100.0, 100.0));
            }
            assert_eq!(
                tree.arena.len(),
                total0,
                "preserve={preserve}: the previous build's detached content must be reaped"
            );
        }
    }

    #[test]
    fn destroying_a_host_reaps_its_detached_content() {
        let mut tree = WidgetTree::new();
        let outer = tree.add(FillWidget::new());
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let empty = tree.arena.len();

        let host = tree.add_child(outer, DetachedContentHost { preserve: false });
        tree.layout(SizeProposal::exact(100.0, 100.0));
        assert!(tree.arena.len() > empty);

        tree.destroy_subtree(host);
        assert_eq!(
            tree.arena.len(),
            empty,
            "the popup must die with the widget that built it"
        );
    }

    /// Memoizes one child and re-attaches the same id every build.
    #[derive(Debug)]
    struct StableChildHost {
        child: Option<WidgetId>,
        probe: std::rc::Rc<std::cell::Cell<Option<WidgetId>>>,
    }
    impl Widget for StableChildHost {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            let id = match self.child {
                Some(id) => id,
                None => {
                    let id = ctx.add(FillWidget::new());
                    self.child = Some(id);
                    self.probe.set(Some(id));
                    id
                }
            };
            vec![id]
        }
        fn layout_response(
            &self,
            p: SizeProposal,
            _c: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            p.resolve(10.0, 10.0).into()
        }
        fn preserves_children_on_rebuild(&self) -> bool {
            true
        }
    }

    #[test]
    fn reconcile_preserves_reattached_child() {
        let probe = std::rc::Rc::new(std::cell::Cell::new(None));
        let mut tree = WidgetTree::new();
        let host = tree.add(StableChildHost {
            child: None,
            probe: probe.clone(),
        });
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let child = probe.get().expect("child mounted");
        let total0 = tree.arena.len();
        for _ in 0..5 {
            tree.arena_mark_needs_rebuild_for_testing(host);
            tree.layout(SizeProposal::exact(100.0, 100.0));
        }
        assert!(
            tree.arena.is_active(child),
            "the re-attached child must survive every rebuild"
        );
        assert_eq!(tree.arena.len(), total0, "no growth — same child reused");
    }

    /// Re-homes a node returned from its `build()` under itself.
    #[derive(Debug)]
    struct Wrapper {
        child: WidgetId,
    }
    impl Widget for Wrapper {
        fn build(&mut self, _ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            vec![self.child]
        }
        fn layout_response(
            &self,
            p: SizeProposal,
            _c: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            p.resolve(10.0, 10.0).into()
        }
    }

    /// Memoizes a body, then wraps it in a FRESH `Wrapper` each build —
    /// re-parenting the body out of the previous (now dropped) wrapper. This is
    /// the TabWidget / CompositeTooltip pattern in miniature.
    #[derive(Debug)]
    struct ReparentHost {
        body: Option<WidgetId>,
        probe: std::rc::Rc<std::cell::Cell<Option<WidgetId>>>,
    }
    impl Widget for ReparentHost {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            let body = match self.body {
                Some(id) => id,
                None => {
                    let id = ctx.add(FillWidget::new());
                    self.body = Some(id);
                    self.probe.set(Some(id));
                    id
                }
            };
            vec![ctx.add(Wrapper { child: body })]
        }
        fn layout_response(
            &self,
            p: SizeProposal,
            _c: &LayoutContext,
        ) -> crate::widget::LayoutResponse {
            p.resolve(10.0, 10.0).into()
        }
        fn preserves_children_on_rebuild(&self) -> bool {
            true
        }
    }

    #[test]
    fn reconcile_spares_reparented_survivor() {
        // The memoized body is re-parented into a fresh wrapper each rebuild;
        // the old wrapper is dropped. The body must survive (it is re-homed),
        // and the old wrappers must be reaped (no leak). This is the exact
        // failure that destroyed TabWidget's static panel before the fix: the
        // parent-authoritative recursion + single-node arena removal spare the
        // re-homed body while still reaping the dropped wrapper subtree.
        let probe = std::rc::Rc::new(std::cell::Cell::new(None));
        let mut tree = WidgetTree::new();
        let host = tree.add(ReparentHost {
            body: None,
            probe: probe.clone(),
        });
        tree.layout(SizeProposal::exact(100.0, 100.0));
        let body = probe.get().expect("body mounted");
        let total0 = tree.arena.len();
        for _ in 0..5 {
            tree.arena_mark_needs_rebuild_for_testing(host);
            tree.layout(SizeProposal::exact(100.0, 100.0));
        }
        assert!(
            tree.arena.is_active(body),
            "the re-parented body must survive — it was moved into the new tree, \
             not swept with the dropped wrapper"
        );
        assert_eq!(
            tree.arena.len(),
            total0,
            "dropped wrappers reaped — no per-rebuild leak"
        );
    }

    // -----------------------------------------------------------------
    // EventContext::ensure_visible / ensure_widget_visible — the
    // rect/id-based outer-scroll chase drained in `collect_from_ctx`.
    // -----------------------------------------------------------------

    /// A `clips_children` container that places its single child at a fixed
    /// vertical offset — used to give a child arena bounds *outside* the
    /// container's viewport so the id-based `ensure_widget_visible` walk has a
    /// reason to dispatch `ScrollIntoView`.
    #[derive(Debug)]
    struct BelowContainer {
        child: Option<WidgetId>,
        offset: f32,
    }

    impl crate::widget::Widget for BelowContainer {
        fn layout_response(
            &self,
            proposal: SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(0.0, 0.0).into()
        }
        fn place_children(
            &self,
            bounds: Rect,
            _proposal: SizeProposal,
            children: &mut [crate::widget::WidgetPlacement],
            _ctx: &crate::widget::LayoutContext,
        ) {
            for c in children.iter_mut() {
                c.origin = Point::new(bounds.x, bounds.y + self.offset);
                c.size = bounds.size();
            }
        }
        fn children(&self) -> Vec<WidgetId> {
            self.child.into_iter().collect()
        }
    }

    /// A `clips_children` container that records the `ScrollIntoView` it
    /// receives, so a test can assert what the framework dispatched to it.
    fn recording_scroll_container(
        tree: &mut WidgetTree,
        child: WidgetId,
        recorded: std::rc::Rc<std::cell::Cell<Option<Rect>>>,
    ) -> WidgetId {
        use crate::test_widgets::StackWidget;
        tree.add(
            StackWidget::new()
                .add_child(child)
                .on_scroll(move |ev, _ctx| match ev {
                    WidgetEvent::ScrollIntoView { target_bounds, .. } => {
                        recorded.set(Some(*target_bounds));
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                })
                .clips_children(true),
        )
    }

    #[test]
    fn ensure_visible_dispatches_scroll_into_view_to_clipping_ancestor() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        // A rect well below the 100px viewport — the container must be asked to
        // reveal it.
        let target = Rect::new(10.0, 500.0, 20.0, 15.0);
        let mut ctx = EventContext::new();
        ctx.ensure_visible(target);
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get(),
            Some(target),
            "ensure_visible(rect) must dispatch ScrollIntoView with the exact rect \
             to the clips_children ancestor"
        );
    }

    #[test]
    fn ensure_visible_is_noop_when_rect_already_visible() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        // Fully inside the viewport → the ancestor already shows it, so no
        // ScrollIntoView is dispatched.
        let mut ctx = EventContext::new();
        ctx.ensure_visible(Rect::new(10.0, 10.0, 20.0, 15.0));
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get(),
            None,
            "a rect already inside the viewport must not trigger a scroll"
        );
    }

    #[test]
    fn ensure_visible_margin_forces_scroll_near_edge() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        // Rect at y=95..99 is visible at margin 0, but with a 10px margin its
        // padded bottom (109) spills past the 100px viewport → scroll.
        let rect = Rect::new(10.0, 95.0, 20.0, 4.0);
        let mut ctx = EventContext::new();
        ctx.ensure_visible_with_margin(rect, 10.0);
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get(),
            Some(rect),
            "the margin must widen the visibility test so a near-edge rect scrolls"
        );
    }

    /// A `clips_children` container that records the alignment and motion of the
    /// `ScrollIntoView` it receives.
    fn recording_align_container(
        tree: &mut WidgetTree,
        child: WidgetId,
        recorded: std::rc::Rc<
            std::cell::Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>,
        >,
    ) -> WidgetId {
        use crate::test_widgets::StackWidget;
        tree.add(
            StackWidget::new()
                .add_child(child)
                .on_scroll(move |ev, _ctx| match ev {
                    WidgetEvent::ScrollIntoView { align, motion, .. } => {
                        recorded.set(Some((*align, *motion)));
                        EventResponse::Handled
                    }
                    _ => EventResponse::Ignored,
                })
                .clips_children(true),
        )
    }

    #[test]
    fn ensure_visible_aligned_scrolls_even_when_already_visible() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        // Comfortably inside the viewport — a *minimal* reveal would decline
        // (see `ensure_visible_is_noop_when_rect_already_visible`). A pin must
        // still fire: re-asserting unconditionally is the whole difference
        // between "keep it on screen" and "hold it at this height".
        let target = Rect::new(10.0, 10.0, 20.0, 15.0);
        let mut ctx = EventContext::new();
        ctx.ensure_visible_aligned(target, 0.5, crate::event::ScrollMotion::Instant);
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get(),
            Some(target),
            "an aligned reveal must dispatch even when the rect is already visible"
        );
    }

    #[test]
    fn ensure_visible_aligned_forwards_fraction_and_motion() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
            Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_align_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let mut ctx = EventContext::new();
        ctx.ensure_visible_aligned(
            Rect::new(10.0, 10.0, 20.0, 15.0),
            0.25,
            crate::event::ScrollMotion::Smooth,
        );
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get(),
            Some((
                crate::event::ScrollAlign::Fraction(0.25),
                crate::event::ScrollMotion::Smooth
            )),
            "the container must receive the requested fraction and motion verbatim"
        );
    }

    #[test]
    fn ensure_visible_aligned_clamps_the_fraction() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
            Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_align_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let mut ctx = EventContext::new();
        ctx.ensure_visible_aligned(
            Rect::new(10.0, 10.0, 20.0, 15.0),
            4.2,
            crate::event::ScrollMotion::Instant,
        );
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get().map(|(a, _)| a),
            Some(crate::event::ScrollAlign::Fraction(1.0)),
            "an out-of-range fraction must clamp rather than aim the pin off-screen"
        );
    }

    #[test]
    fn plain_ensure_visible_requests_minimal_alignment() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
            Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_align_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let mut ctx = EventContext::new();
        ctx.ensure_visible(Rect::new(10.0, 500.0, 20.0, 15.0));
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            recorded.get(),
            Some((
                crate::event::ScrollAlign::Minimal,
                crate::event::ScrollMotion::Instant
            )),
            "the pre-existing reveal API must keep its exact semantics"
        );
    }

    #[test]
    fn only_the_innermost_container_aligns() {
        use std::cell::Cell;
        use std::rc::Rc;
        let inner_rec: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
            Rc::new(Cell::new(None));
        let outer_rec: Rc<Cell<Option<(crate::event::ScrollAlign, crate::event::ScrollMotion)>>> =
            Rc::new(Cell::new(None));

        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let inner = recording_align_container(&mut tree, actor, inner_rec.clone());
        let _outer = recording_align_container(&mut tree, inner, outer_rec.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        // Off-screen, so the outer container is asked too (a `Minimal` request
        // is gated on visibility).
        let mut ctx = EventContext::new();
        ctx.ensure_visible_aligned(
            Rect::new(10.0, 500.0, 20.0, 15.0),
            0.5,
            crate::event::ScrollMotion::Instant,
        );
        tree.collect_from_ctx(ctx, actor);

        assert_eq!(
            inner_rec.get().map(|(a, _)| a),
            Some(crate::event::ScrollAlign::Fraction(0.5)),
            "the innermost clipping ancestor owns the pin"
        );
        assert_eq!(
            outer_rec.get().map(|(a, _)| a),
            Some(crate::event::ScrollAlign::Minimal),
            "an outer container must only bring the inner viewport into view — a \
             fraction names a height in one viewport, not in every ancestor's"
        );
    }

    #[test]
    fn ensure_widget_visible_uses_target_arena_bounds() {
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        // Target lives 500px below the container's top — off the viewport.
        let target = tree.add(FillWidget::new());
        let rec = recorded.clone();
        let container = tree.add(
            BelowContainer {
                child: Some(target),
                offset: 500.0,
            }
            .on_scroll(move |ev, _ctx| match ev {
                WidgetEvent::ScrollIntoView { target_bounds, .. } => {
                    rec.set(Some(*target_bounds));
                    EventResponse::Handled
                }
                _ => EventResponse::Ignored,
            })
            .clips_children(true),
        );
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let expected = tree.bounds(target);
        assert!(
            expected.y > 100.0,
            "fixture sanity: the target must sit below the viewport (y={})",
            expected.y
        );

        // The source widget is irrelevant for the id-based walk — it starts
        // from the *target's* parent — so pass the container itself.
        let mut ctx = EventContext::new();
        ctx.ensure_widget_visible(target);
        tree.collect_from_ctx(ctx, container);

        assert_eq!(
            recorded.get(),
            Some(expected),
            "ensure_widget_visible(id) must dispatch ScrollIntoView with the \
             target's current arena bounds"
        );
    }

    #[test]
    fn ensure_widget_visible_ignores_missing_widget() {
        // A never-mounted id must neither panic nor dispatch a spurious scroll.
        use std::cell::Cell;
        use std::rc::Rc;
        let recorded: Rc<Cell<Option<Rect>>> = Rc::new(Cell::new(None));
        let mut tree = WidgetTree::new();
        let actor = tree.add(FillWidget::new());
        let _container = recording_scroll_container(&mut tree, actor, recorded.clone());
        tree.layout(SizeProposal::exact(100.0, 100.0));

        let mut ctx = EventContext::new();
        ctx.ensure_widget_visible(WidgetId::default());
        tree.collect_from_ctx(ctx, actor); // must not panic

        assert_eq!(
            recorded.get(),
            None,
            "an unmounted id must not trigger a scroll"
        );
    }

    #[test]
    fn context_menu_inside_a_modal_keeps_the_modal() {
        // Regression: right-clicking a widget that lives inside an open modal must
        // open its context menu WITHOUT tearing down the modal. `show_context_menu_for`
        // used to `dismiss_all()`, which closed the very overlay hosting the editor.
        use crate::event::{Modifiers, PointerButton, WidgetEvent};
        use crate::overlay::{DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest};
        use crate::test_widgets::{FillWidget, StackWidget};

        let mut tree = WidgetTree::new();
        // A container standing in for the modal's content subtree, with the editor
        // (a right-clickable widget) inside it.
        let modal_content = tree.add(StackWidget::new());
        let _editor = tree.add_child(
            modal_content,
            FillWidget::new()
                .context_menu(|_pos, _ctx| Some(Box::new(FillWidget::new()) as Box<dyn Widget>)),
        );
        tree.layout(SizeProposal::exact(200.0, 100.0));

        let modal = tree.overlay_manager.show(OverlayRequest {
            content_id: modal_content,
            anchor: modal_content,
            placement: OverlayPlacement::Centered,
            dismiss: DismissBehavior::EscapeKey,
            layer: OverlayLayer::InTree,
            parent_overlay: None,
            on_dismiss: None,
            fade_duration: None,
        });
        // Give the overlay real bounds so the right-click hit-tests inside it.
        tree.overlay_manager
            .stack
            .iter_mut()
            .find(|o| o.id == modal)
            .unwrap()
            .bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
        assert_eq!(tree.overlay_manager.len(), 1);

        // Right-click the editor inside the modal.
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(50.0, 25.0),
            button: PointerButton::Secondary,
            modifiers: Modifiers::NONE,
        });

        assert!(
            tree.overlay_manager.active_ids().contains(&modal),
            "the modal must survive opening a context menu inside it"
        );
        assert_eq!(
            tree.overlay_manager.len(),
            2,
            "the context menu should now be open on top of the surviving modal"
        );
    }
}