rust_widgets 2.8.4

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Registry for library-painted widgets mounted into windows.
//!
//! # Why this exists
//!
//! `widget::WidgetFactory` can build a `Box<dyn Widget>` for any kind —
//! `CodeEditor`, `ColorPicker`, `GanttWidget`, … — but until this module existed
//! there was no path from such a box to pixels inside a real window. The platform
//! layer only knew how to create OS controls (an OS button, a text field, a
//! toolkit widget); a library-painted widget had to be handed to
//! `render_to_svg()` or it went nowhere. Mounting one into a window produced an
//! empty surface.
//!
//! This registry closes that loop. The host keeps ownership of the widget here,
//! keyed by [`ObjectId`]; a backend supplies the surface it paints widgets into
//! and, when a repaint is wanted, calls [`with_widget_mut`] and paints a
//! frame. **Which surface that is is a backend detail** — see
//! [`crate::platform::Platform::mount_surface`].
//!
//! # Threading
//!
//! Widgets are `!Send` (they own `Rc`/`RefCell` state), and the desktop backends
//! require UI work on the platform main thread anyway. The registry is therefore
//! **thread-local**, and [`register`] returns `None` when called from a thread
//! that has no registry rather than smuggling a non-`Send` value across threads.
//!
//! [`with_widget_mut`]: crate::widget::runtime::with_widget_mut

// `Point` is used by the hit-test API below, which is a core capability of the
// registry rather than a `full_widgets` extra: every profile that can mount a widget
// must be able to answer "which widget is under this point?".
use crate::compat::Rc;
use crate::core::{ObjectId, Point, Rect, Size};
use crate::event::{Event, FocusReason};
use crate::render::{PaintBackend, RenderContext, SoftwarePaintBackend};

/// Why a widget could not be mounted onto a host surface.
///
/// Lives here, beside the registry, because that is the layer that knows about
/// widget registration and ownership. `app` re-exports it, so callers that drive
/// mounting through a `WindowHandle` keep the same path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SurfaceMountError {
    /// The calling thread has no widget registry — mounting must happen on the
    /// thread that drives the UI.
    NoRegistryOnThread,
    /// This backend has no surface to offer
    /// (`Platform::supports_surfaces` returned `false`). Carries the
    /// backend name for the message.
    UnsupportedByBackend(&'static str),
    /// The backend claims support but refused this particular mount (unknown
    /// parent, wrong parent kind, allocation failure). Carries the backend name.
    RejectedByBackend(&'static str),
    /// A lookup by widget name did not match anything in the widget factory.
    UnknownWidgetName,
}

impl core::fmt::Display for SurfaceMountError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::NoRegistryOnThread => {
                write!(f, "widgets must be mounted on the UI thread (no registry on this thread)")
            }
            Self::UnsupportedByBackend(backend) => {
                write!(f, "backend '{backend}' has no surface to mount widgets onto")
            }
            Self::RejectedByBackend(backend) => {
                write!(f, "backend '{backend}' refused the mount (see logs for the reason)")
            }
            Self::UnknownWidgetName => {
                write!(f, "the widget factory has no widget registered under that name")
            }
        }
    }
}

impl std::error::Error for SurfaceMountError {}
use crate::widget::Widget;
use std::cell::RefCell;
use std::collections::HashMap;

/// One widget handed to the registry for display by the host surface.
struct Mounted {
    widget: Box<dyn Widget>,
}

// Per-thread widget registry.
//
// `clippy::missing_const_for_thread_local` fires on this block for the
// OpenHarmony target only: `std::collections::HashMap::new()` is not a `const
// fn` on any target, but the lint can resolve `HashMap` on the host and not on
// OpenHarmony's std, so there it suggests a `const` initializer that would not
// compile. The allow is per-cell rather than crate-wide.
thread_local! {
    /// Widgets mounted for display, keyed by their `ObjectId`.
    #[allow(clippy::missing_const_for_thread_local)]
    static MOUNTED: RefCell<HashMap<ObjectId, Mounted>> = RefCell::new(HashMap::new());

    /// Ids whose entry is temporarily held **outside** the registry during event dispatch.
    ///
    /// [`dispatch_event`] takes the widget out of `MOUNTED` before calling `handle_event`, so a
    /// handler may re-enter the registry (read its own state, update another control, call
    /// `request_redraw`) without hitting a `RefCell` borrow conflict. While an id is listed here,
    /// [`unregister`] records the removal rather than looking for an entry that is not in the map,
    /// so a handler that destroys the very control being dispatched is honoured instead of being
    /// overwritten by the reinsertion that follows the call.
    #[allow(clippy::missing_const_for_thread_local)]
    static DISPATCHING: RefCell<alloc::collections::BTreeSet<ObjectId>> =
        RefCell::new(alloc::collections::BTreeSet::new());

    /// Ids unregistered while their dispatch was in progress.
    ///
    /// A tombstone for [`DISPATCHING`]: [`dispatch_event`] skips reinsertion for an id listed here,
    /// then clears the entry. Without it, a handler that called `unregister(id)` would have its
    /// destroy silently undone by the dispatch epilogue putting the widget back.
    #[allow(clippy::missing_const_for_thread_local)]
    static DESTROYED_DURING_DISPATCH: RefCell<alloc::collections::BTreeSet<ObjectId>> =
        RefCell::new(alloc::collections::BTreeSet::new());

    /// Widgets currently lent out of [`MOUNTED`] while a frame drives them.
    ///
    /// [`dispatch_event`] and [`with_widget_mut`] take the widget out of `MOUNTED` before they run a
    /// user callback, so the callback may re-enter the registry without a `RefCell` conflict.
    /// `is_mounted` can answer from this loan's presence. Reads of the same mutably-driven widget are
    /// refused while its exclusive borrow is active.
    ///
    /// This maps the id to a pointer for reentrant reads during shared loans. Exclusive loans are
    /// marked in `LENT_EXCLUSIVE`, and no accessor dereferences their pointer while the caller holds
    /// `&mut`. Nested writes to any active loan are refused.
    ///
    /// # Safety
    ///
    /// The pointer is valid only for the dynamic extent of the driving call that installed it: the
    /// owning frame keeps the widget alive on its stack and removes the entry (via [`LentGuard`])
    /// before it returns or unwinds. Readers hold the pointer only long enough to call `&self`,
    /// which cannot outlive that extent because nothing yields it to the caller.
    #[allow(clippy::missing_const_for_thread_local)]
    static LENT_OUT: RefCell<alloc::collections::BTreeMap<ObjectId, core::ptr::NonNull<dyn Widget>>> =
        RefCell::new(alloc::collections::BTreeMap::new());

    #[allow(clippy::missing_const_for_thread_local)]
    static LENT_EXCLUSIVE: RefCell<alloc::collections::BTreeSet<ObjectId>> =
        RefCell::new(alloc::collections::BTreeSet::new());

    /// Monotonic id source for mounted widgets.
    ///
    /// Starts high so a mounted id cannot collide with a platform-allocated
    /// widget id (those come from `BackendState`, which counts up from 1).
    ///
    /// The counter is seeded per thread but advances in a **globally unique** range:
    /// each thread that wants ids reserves a block with [`reserve_id_block`] and hands
    /// them out locally. A purely per-thread counter would give two threads the same
    /// ids, and some stores that hold widget state are process-wide (the control
    /// backend's, for one), so the second thread's window would read the first thread's
    /// record — a window reporting another window's client size. See [`reserve_id_block`].
    #[allow(clippy::missing_const_for_thread_local)]
    static NEXT_ID: RefCell<ObjectId> = const { RefCell::new(0) };

    /// The end of the id block `NEXT_ID` is handing out from.
    ///
    /// Zero means "no block yet", which is what makes the first allocation reserve one.
    #[allow(clippy::missing_const_for_thread_local)]
    static NEXT_ID_LIMIT: RefCell<ObjectId> = const { RefCell::new(0) };

    /// Maps a mounted `Window` widget id to the host window the platform built
    /// for it.
    ///
    /// A window exists in two id spaces: the widget registry's id (what the
    /// library's `create_window` returns and every accessor accepts) and the
    /// platform's own id (what `mount_surface` resolves a parent through, because
    /// only the platform can reach a native `HWND`/`X11` window/`NSWindow`).
    /// Without this link the two never met, so mounting a control on a window the
    /// caller had just created was refused — the library's own window could not
    /// carry the library's own controls.
    #[allow(clippy::missing_const_for_thread_local)]
    static HOST_WINDOWS: RefCell<HashMap<ObjectId, ObjectId>> = RefCell::new(HashMap::new());

    /// The authoritative keyboard-focus owner for this thread's widget tree.
    ///
    /// Before this existed, [`crate::event::FocusManager`] was fully implemented
    /// (tab order, wrap-around, traversal strategies, a11y callback) but **never
    /// instantiated by any production code** — so pressing Tab moved nothing, and
    /// `Event::FocusGained` / `FocusLost` had no producer anywhere, which made
    /// every control's focus branch unreachable. Holding the manager here, beside
    /// the registry, gives focus one owner that can also see the widgets: routing
    /// a key event to "the focused widget" needs both facts in the same place.
    #[allow(clippy::missing_const_for_thread_local)]
    static FOCUS: RefCell<crate::event::FocusManager> =
        RefCell::new(crate::event::FocusManager::new());

    /// The widget the pointer is currently over, for hover enter/leave synthesis.
    ///
    /// Needed because those two events are otherwise unproduced: a backend can see
    /// "the pointer moved inside my surface" but not "it crossed onto another
    /// control", which is a fact about the widget tree. Storing the previous target
    /// is what makes the pair balanced (see `dispatch_hover_transition`).
    #[allow(clippy::missing_const_for_thread_local)]
    static HOVERED: RefCell<Option<ObjectId>> = const { RefCell::new(None) };

    /// Whether the last [`tick_animations`] sweep left a **mounted** control in flight.
    ///
    /// Kept across frames because the frame that observes a control *settling* is one the
    /// sweep reports `false` for, and a loop that stopped there would never paint that frame.
    /// See [`animation_bus_needs_another_frame`].
    ///
    /// The trailing `#[allow]` is **not** redundant with the one above it. Clippy accepts
    /// `const { Cell::new(false) }` as a const initializer only on some toolchains — on the
    /// OpenHarmony target it rejects exactly this shape while accepting the `RefCell` ones — so
    /// the spelling above has to stay as it is and the lint is silenced per entry, which is what
    /// every other non-`const` entry in this block already does.
    #[allow(clippy::missing_const_for_thread_local)]
    static LAST_SWEEP_HAD_UNSETTLED_MOUNTED: std::cell::Cell<bool> = std::cell::Cell::new(false);

    /// Whether a **host-owned** control was advanced this frame and has not settled.
    ///
    /// A control held as a `Box<dyn Widget>` is not in [`MOUNTED`], so the sweep cannot see
    /// it; its owner reports the fact instead. See
    /// [`animation_bus_note_host_owned_animating`]. The `#[allow]` is a per-target
    /// toolchain difference — see `LAST_SWEEP_HAD_UNSETTLED_MOUNTED` above.
    #[allow(clippy::missing_const_for_thread_local)]
    static HOST_OWNED_ANIMATING: std::cell::Cell<bool> = std::cell::Cell::new(false);

    /// The widget that has captured the pointer, if any.
    ///
    /// While a control holds capture it receives every pointer event regardless of
    /// where the pointer is — that is what makes a drag work when the cursor leaves
    /// the control it started on. [`crate::event::PointerCaptureManager`] implemented
    /// this but had no production caller, so a drag could not survive leaving its
    /// origin widget.
    #[allow(clippy::missing_const_for_thread_local)]
    static CAPTURE: RefCell<crate::event::PointerCaptureManager> =
        RefCell::new(crate::event::PointerCaptureManager::new());

    /// Stack of currently-active modal dialog ids, innermost last.
    ///
    /// While this stack is non-empty, input outside the top modal dialog's subtree
    /// is suppressed: [`dispatch_event`], [`dispatch_pointer_event`] and
    /// [`focus_widget`] all ask [`modal_blocks`] before acting. This is the one
    /// place modality is enforced, so a modal dialog actually blocks its owner —
    /// the `modal` flag on each dialog widget records the *intent*, and the stack
    /// is what makes that intent real (principle #5: no uninforced flag).
    #[allow(clippy::missing_const_for_thread_local)]
    static MODAL: RefCell<alloc::vec::Vec<ObjectId>> = const { RefCell::new(alloc::vec::Vec::new()) };
}

/// How many ids one thread reserves at a time.
///
/// Large enough that the reservation is rare (a thread creating a whole window's worth of
/// controls reserves once) and small enough that the address space is not wasted.
const ID_BLOCK: ObjectId = 0x1_0000;

/// Where the globally unique id space begins.
///
/// Starts high so a mounted id cannot collide with a platform-allocated widget id
/// (those come from `BackendState`, which counts up from 1).
const ID_BASE: ObjectId = 0x5345_4C46_0000_0000;

/// The high-water mark of every block handed out so far.
///
/// Process-wide, and the **only** piece of id allocation that is: the per-thread counter
/// caches what this hands out, so the common path stays a thread-local read with no
/// synchronisation.
static ID_HIGH_WATER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(ID_BASE);

/// Reserves a block of ids for the calling thread and returns the first id in it.
///
/// # Why blocks rather than a plain per-thread counter
///
/// Widgets are `!Send`, so the *registry* is thread-local and a per-thread counter is the
/// obvious fit. But not every store keyed by widget id is thread-local: the control
/// backend keeps its host-side maps process-wide (it is a `OnceLock` singleton). With a
/// per-thread counter two threads mint the **same** ids, so the second thread's window
/// reads the first thread's record — concretely, a newly created window reporting
/// another window's client size. Reserving disjoint blocks makes an id identify one
/// window for the whole process without giving up the lock-free local path.
fn reserve_id_block() -> Option<ObjectId> {
    // `fetch_add` on the high-water mark is the rendezvous point. Uniqueness comes from
    // it being a read-modify-write, so two threads can never be handed overlapping
    // blocks, and no lock is needed on the per-allocation path.
    let start = ID_HIGH_WATER.fetch_add(ID_BLOCK, std::sync::atomic::Ordering::Relaxed);
    // A released thread's ids are not reclaimed: a store may still hold a record for one
    // and a later reader must not find it under a fresh window. Wrapping would do exactly
    // that, so exhaustion is reported instead of reusing the space.
    start.checked_add(ID_BLOCK)?;
    NEXT_ID.try_with(|next| *next.borrow_mut() = start).ok()?;
    NEXT_ID_LIMIT.try_with(|limit| *limit.borrow_mut() = start.wrapping_add(ID_BLOCK)).ok()?;
    Some(start)
}

/// Hands out the next id for this thread, reserving a block when the current one runs out.
///
/// `Err` means this thread has no registry (no UI thread), matching [`register`]'s contract.
fn next_widget_id() -> Result<ObjectId, ()> {
    NEXT_ID
        .try_with(|next| {
            let id = *next.borrow();
            let limit = NEXT_ID_LIMIT.try_with(|limit| *limit.borrow()).unwrap_or(0);
            if id < limit {
                *next.borrow_mut() = id.wrapping_add(1);
                return Ok(id);
            }
            // Exhausted (or never reserved): take the next block. `reserve_id_block`
            // seeds `NEXT_ID`/`NEXT_ID_LIMIT`, so the id to return is the block's first.
            let start = reserve_id_block().ok_or(())?;
            *next.borrow_mut() = start.wrapping_add(1);
            Ok(start)
        })
        .unwrap_or(Err(()))
}

/// Hands ownership of `widget` to the registry and returns its display id.
///
/// Returns `None` when the calling thread has no registry — i.e. it is not the
/// thread that drives the UI. Callers must surface that as "cannot display
/// here" rather than dropping the widget silently.
pub fn register(widget: Box<dyn Widget>) -> Option<ObjectId> {
    let id = next_widget_id();
    let Ok(id) = id else { return None };
    let stored = MOUNTED.try_with(|map| {
        map.borrow_mut().insert(id, Mounted { widget });
    });
    if stored.is_err() {
        return None;
    }
    // Record the widget's own id -> the registry id, so a producer that only has the
    // former (notably `request_redraw`, called from `&self`) can address the tracker.
    // Read through `with_widget` because the id lives on the widget, and this runs
    // before any caller can hold a borrow.
    if let Some(own_id) = with_widget(id, |widget| widget.base().id()) {
        let _ = OWN_IDS.try_with(|map| {
            map.borrow_mut().insert(own_id, id);
        });
    }
    // Join the tab order if the control says it is focusable. Asked of the widget
    // itself (see `Widget::is_focusable`) rather than of a table of kinds, so a
    // control the library has never heard of participates by answering `true`.
    let focusable = with_widget(id, |widget| widget.is_focusable()).unwrap_or(false);
    if focusable {
        register_focusable(id);
    }
    // Ask the auto-decision whether regioning pays off for this control. This is the
    // only automatic call site: `register` runs as soon as a control is mounted, so a
    // widget reaches the auto-decision exactly once, at the moment its geometry and its
    // children are both known — and a control that mounts *as* a child, or whose
    // constructor mounts children, is judged again on its own mount.
    //
    // The cost of the question is two map probes and one thread-local geometry read;
    // the cost of the answer is only ever paid when the answer is `yes`, because the
    // mode it selects is the self-correcting one. See `should_track_damage`.
    let _ = enable_damage_tracking_if_useful(id);
    // Accessibility submit point 1 of BLUE24 §6.3: a control that has just been mounted is given a
    // node in the accessibility tree, derived from the control itself through `A11yState::from_widget`
    // (that is stage ①, which already existed). Without this the three platform bridges had zero
    // production callers, so a screen reader on any of them received nothing.
    //
    // Read through `with_widget` rather than keeping a borrow: the derive reads the same property
    // contract `accessible_value` does, and both go through the registry this function has just
    // written to.
    if let Some(state) = with_widget(id, crate::platform::accessibility::A11yState::from_widget) {
        crate::widget::a11y_submit::submit_mounted(id, &state);
    }
    Some(id)
}

/// Hands ownership of `widget` to the registry under `declared_id`, a **reserved** id.
///
/// # Why a caller needs to choose the id
///
/// `register` assigns an id from the runtime's own counter. A caller that holds a document's
/// `"id"` — the JSON layout loader — needs the control to be mounted under *that* id, or every
/// name lookup resolves to an id the runtime never issued. Reserving the id is what makes a
/// declarative document's names and the runtime's registry the same id space.
///
/// # Why it can fail
///
/// The id may already be taken. Returning a *different* id would be worse than failing: the
/// caller would record the control under a name whose handle addresses somebody else's widget.
/// `Err(occupied)` therefore names the id that was in the way, and the caller decides — it
/// must not silently fall back to a fresh id.
///
/// A `declared_id` of `0` is refused for the same reason: `0` is the API's "no widget"
/// sentinel, so mounting a live control there would make it unreachable by design.
pub fn register_with_id(
    widget: Box<dyn Widget>,
    declared_id: ObjectId,
) -> Result<ObjectId, ObjectId> {
    if declared_id == 0 {
        return Err(0);
    }
    // A host with no widget runtime cannot hold the control; say so rather than
    // reporting a success that `with_widget` would then deny.
    if MOUNTED.try_with(|_| ()).is_err() {
        return Err(declared_id);
    }

    // The reservation has to be atomic with respect to the duplicate check: the map is
    // thread-local, so a single borrow covers both the "is it free?" question and the
    // "then it is mine" answer. Asking and then inserting would let a nested mount take
    // the id in between, which is exactly the collision this function exists to prevent.
    let reserved = MOUNTED.try_with(|map| {
        let mut map = map.borrow_mut();
        if map.contains_key(&declared_id) {
            return Err(declared_id);
        }
        map.insert(declared_id, Mounted { widget });
        Ok(declared_id)
    });
    match reserved {
        Ok(Ok(id)) => {
            let _ = id;
        }
        Ok(Err(occupied)) => return Err(occupied),
        Err(_) => return Err(declared_id),
    }

    // The reservation must not be undone by a later `next_widget_id` handing the same id to
    // another producer, so the allocator is told the id is spent: if the counter is sitting on
    // exactly this id, it advances past it. Ids below the counter are already spent, and an id
    // far above it is reserved correctly on its own (the counter will walk up to it and find it
    // occupied), so advancing past it here would only skip ids for no reason.
    let _ = NEXT_ID.try_with(|next| {
        let counter = next.borrow();
        if *counter == declared_id {
            drop(counter);
            *next.borrow_mut() = declared_id.wrapping_add(1);
        }
    });

    // Every step `register` does after the insert, repeated here rather than extracted, so
    // the two entry points cannot drift: a caller reading `register` sees the same list.
    // See `register` for why each one exists.
    if let Some(own_id) = with_widget(declared_id, |widget| widget.base().id()) {
        let _ = OWN_IDS.try_with(|map| {
            map.borrow_mut().insert(own_id, declared_id);
        });
    }
    let focusable = with_widget(declared_id, |widget| widget.is_focusable()).unwrap_or(false);
    if focusable {
        register_focusable(declared_id);
    }
    let _ = enable_damage_tracking_if_useful(declared_id);
    if let Some(state) =
        with_widget(declared_id, crate::platform::accessibility::A11yState::from_widget)
    {
        crate::widget::a11y_submit::submit_mounted(declared_id, &state);
    }
    Ok(declared_id)
}

/// Removes a mounted widget, dropping it. Returns whether it was present.
pub fn unregister(id: ObjectId) -> bool {
    // Drop any host-window association with the widget it belonged to, so a
    // recycled or reused id cannot inherit a stale host window.
    let _ = HOST_WINDOWS.try_with(|map| map.borrow_mut().remove(&id));
    // A widget that is gone must not stay in the tab order: `focus_next` would
    // hand focus to an id that resolves to nothing, and the key that triggered
    // the move would be swallowed. The manager also clears focus if this id owned
    // it, so the next Tab starts from the beginning rather than from a dead id.
    let _ = FOCUS.try_with(|focus| focus.borrow_mut().unregister_focusable(id));
    // Likewise it must not stay the hover target, or the next pointer move would
    // send `MouseLeave` to an id that no longer exists and skip the real one.
    let _ = HOVERED.try_with(|hovered| {
        let mut hovered = hovered.borrow_mut();
        if *hovered == Some(id) {
            *hovered = None;
        }
    });
    // And it must not keep pointer capture: routing would send every subsequent
    // pointer event to an id that resolves to nothing.
    let _ = CAPTURE.try_with(|capture| {
        let mut capture = capture.borrow_mut();
        if capture.capturing_widget() == Some(id) {
            capture.release_capture();
        }
    });
    // The cached frame and any pending damage describe this widget, so both must go
    // with it: a reused id would otherwise start from the previous control's pixels,
    // and a stale damage rect would repaint a region that no longer exists.
    forget_cached_frame(id);
    let _ = REPAINT.try_with(|map| map.borrow_mut().remove(&id));
    // And the own-id reverse mapping, or a later widget built with the same
    // `BaseWidget::id()` would resolve to this dead registry id and file its damage
    // against a widget that no longer exists.
    let own_id = MOUNTED
        .try_with(|map| map.borrow().get(&id).map(|mounted| mounted.widget.base().id()))
        .ok()
        .flatten();
    if let Some(own_id) = own_id {
        let _ = OWN_IDS.try_with(|map| map.borrow_mut().remove(&own_id));
    }
    // Accessibility submit point 2 of BLUE24 §6.3: the control is gone, so its node must be too.
    // Posted only when the widget was actually present, so an `unregister` of an id that was never
    // mounted does not tear down a node a live control still owns.
    //
    // The dispatching case is separate because the entry is **not** in `MOUNTED`: [`dispatch_event`]
    // took it out so a handler could re-enter the registry. Recording a tombstone lets the dispatch
    // epilogue skip reinsertion, which is what makes a handler's `unregister` of the very control it
    // is handling actually destroy that control instead of being undone a moment later.
    if DISPATCHING.try_with(|set| set.borrow().contains(&id)).unwrap_or(false) {
        let _ = DESTROYED_DURING_DISPATCH.try_with(|set| {
            set.borrow_mut().insert(id);
        });
        crate::widget::a11y_submit::submit_unmounted(id);
        return true;
    }
    let removed = MOUNTED.try_with(|map| map.borrow_mut().remove(&id).is_some()).unwrap_or(false);
    if removed {
        crate::widget::a11y_submit::submit_unmounted(id);
    }
    removed
}

// ---------------------------------------------------------------------------
// Keyboard focus
// ---------------------------------------------------------------------------

/// Returns the widget that currently owns keyboard focus, if any.
pub fn focused_widget() -> Option<ObjectId> {
    FOCUS.try_with(|focus| focus.borrow().focused_widget()).unwrap_or(None)
}

/// Returns whether `id` currently owns keyboard focus.
pub fn has_focus(id: ObjectId) -> bool {
    FOCUS.try_with(|focus| focus.borrow().has_focus(id)).unwrap_or(false)
}

/// Moves keyboard focus to `id`, telling the previously focused widget it lost it.
///
/// Delivers the `FocusLost` / `FocusGained` pair itself rather than expecting each
/// backend to synthesise them: focus is a library-level concept here, and relying on
/// four separate backends to emit a matching pair is how the events ended up with no
/// producer at all (see [`crate::event::FocusManager`]).
///
/// The platform's IME bridge is told about the change too, so a candidate window knows
/// which control is being edited. Without it the bridge's focused-widget field stayed
/// `None` forever and the IME had nowhere to place its candidates.
///
/// Returns whether focus moved. Already-focused ids report `false`, so a repeated
/// click does not re-emit the pair.
pub fn focus_widget(id: ObjectId) -> bool {
    focus_widget_with_reason(id, FocusReason::Programmatic)
}

/// Moves keyboard focus to `id`, recording *why* it moved.
///
/// [`focus_widget`] is this function with [`FocusReason::Programmatic`], which is the
/// honest default for a caller that has no user gesture to point at: an explicit
/// `focus_widget` call is the application choosing a control, not the user navigating.
///
/// The reason travels with the `FocusGained` payload so an individual control can
/// decide whether to paint a focus ring **at the moment it handles the event**. A
/// shared `current_focus_reason()` query would be the wrong shape: by the time a third
/// control asked, the answer could describe a move that had already been superseded,
/// and a draw pass happens later still.
///
/// Returns whether focus moved. Already-focused ids report `false`, so a repeated
/// click does not re-emit the pair.
pub fn focus_widget_with_reason(id: ObjectId, reason: FocusReason) -> bool {
    // Read the outgoing owner *before* the manager switches, so the pair is
    // `previous -> id` and not `id -> id`.
    let previous = focused_widget();
    let moved = FOCUS
        .try_with(|focus| {
            let mut focus = focus.borrow_mut();
            if focus.focused_widget() == Some(id) {
                return false;
            }
            // Focus on an unmounted id would be an unobservable lie: the key
            // router would find nothing to deliver to. Refuse it instead.
            if !is_mounted(id) {
                return false;
            }
            // A modal dialog owns focus while it is up: focusing a widget outside
            // its subtree would let the keyboard type into a window the user cannot
            // otherwise reach, so it is refused the same way an unmounted id is.
            if modal_blocks(id) {
                return false;
            }
            focus.set_focus(id);
            true
        })
        .unwrap_or(false);
    if !moved {
        return false;
    }
    // Outside the manager borrow: both deliveries reach into MOUNTED, and a widget
    // handling `FocusLost` may itself read focus state.
    if let Some(previous) = previous {
        notify_ime_focus_out(previous);
        let _ = dispatch_event(previous, &Event::FocusLost);
    }
    notify_ime_focus_in(id);
    let _ = dispatch_event(id, &Event::FocusGained { reason });
    true
}

/// Focuses `id` because a pointer press landed on it.
///
/// The reason is [`FocusReason::Pointer`], which suppresses the focus ring: the
/// pointer already shows the user where they are, and a ring under the cursor reads
/// as a stuck highlight. This is the entry point pointer routing should call instead
/// of [`focus_widget`], so no call site has to remember the distinction.
pub fn focus_on_pointer_press(id: ObjectId) -> bool {
    focus_widget_with_reason(id, FocusReason::Pointer)
}

/// Focuses `id` because a keyboard accelerator or shortcut activated it.
///
/// `Shortcut` **does** draw the ring: the user is on the keyboard, and if the control
/// is now the keyboard's target the ring is how that fact becomes visible.
pub fn focus_on_keyboard_activation(id: ObjectId) -> bool {
    focus_widget_with_reason(id, FocusReason::Shortcut)
}

/// Tells the platform's IME bridge that `id` is now being edited.
///
/// No-op when the build has no platform singleton (`mini`) or the backend binds no
/// IME bridge — the honest "this host has no IME" case, not a silent failure.
fn notify_ime_focus_in(id: ObjectId) {
    #[cfg(not(alloc_frugal))]
    if let Some(bridge) = crate::platform::platform_facts().ime_bridge() {
        bridge.focus_in(id);
    }
    #[cfg(alloc_frugal)]
    let _ = id;
}

/// Tells the platform's IME bridge that `id` is no longer being edited.
fn notify_ime_focus_out(id: ObjectId) {
    #[cfg(not(alloc_frugal))]
    if let Some(bridge) = crate::platform::platform_facts().ime_bridge() {
        bridge.focus_out(id);
    }
    #[cfg(alloc_frugal)]
    let _ = id;
}

/// Clears keyboard focus, telling the previous owner it lost it.
pub fn clear_focus() -> bool {
    let previous = focused_widget();
    let cleared = FOCUS
        .try_with(|focus| {
            let mut focus = focus.borrow_mut();
            if focus.focused_widget().is_none() {
                return false;
            }
            focus.clear_focus();
            true
        })
        .unwrap_or(false);
    if !cleared {
        return false;
    }
    if let Some(previous) = previous {
        notify_ime_focus_out(previous);
        let _ = dispatch_event(previous, &Event::FocusLost);
    }
    true
}

/// Moves focus to the next focusable widget in tab order (wraps around).
///
/// Returns the newly focused id. `forward == false` moves backwards (Shift-Tab).
/// The `FocusLost` / `FocusGained` pair is delivered for the moved pair, which is
/// what makes a Tab press observable to the controls themselves.
pub fn focus_next(forward: bool) -> Option<ObjectId> {
    let previous = focused_widget();
    let next = FOCUS
        .try_with(|focus| {
            let mut focus = focus.borrow_mut();
            if forward {
                focus.focus_next()
            } else {
                focus.focus_previous()
            }
        })
        .ok()
        .flatten()?;
    if let Some(previous) = previous.filter(|&p| p != next) {
        notify_ime_focus_out(previous);
        let _ = dispatch_event(previous, &Event::FocusLost);
    }
    notify_ime_focus_in(next);
    let reason = if forward { FocusReason::Tab } else { FocusReason::BackTab };
    let _ = dispatch_event(next, &Event::FocusGained { reason });
    Some(next)
}

/// Registers `id` as focusable (adds it to the tab order).
pub fn register_focusable(id: ObjectId) {
    let _ = FOCUS.try_with(|focus| focus.borrow_mut().register_focusable(id));
}

/// Returns the tab order as it currently stands.
pub fn focusable_widgets() -> Vec<ObjectId> {
    FOCUS.try_with(|focus| focus.borrow().focusable_widgets().to_vec()).unwrap_or_default()
}

/// Runs `f` with the focus manager, for the backends and the a11y bridge.
pub fn with_focus_manager<R>(f: impl FnOnce(&mut crate::event::FocusManager) -> R) -> Option<R> {
    FOCUS.try_with(|focus| f(&mut focus.borrow_mut())).ok()
}

/// Chooses how Tab orders the focusable widgets.
///
/// `TabOrder` (the default) is registration order; `RowMajor` and `ColumnMajor`
/// re-sort by the positions recorded via [`set_focusable_position`]. Returns `false`
/// on a thread with no focus manager, which is the same honest-answer rule the rest
/// of this module follows.
///
/// The strategy was fully implemented in [`crate::event::FocusManager`] but never
/// exposed, so a grid-like UI had no way to ask for row-major Tab movement.
pub fn set_focus_traversal(strategy: crate::event::FocusTraversalStrategy) -> bool {
    FOCUS
        .try_with(|focus| {
            focus.borrow_mut().set_traversal_strategy(strategy);
        })
        .is_ok()
}

/// Records where a focusable widget sits, for row/column-major traversal.
///
/// Reorders immediately when a non-default strategy is active, so a caller can set
/// positions in any order. No-op for a widget that is not focusable, because a
/// position the traversal will never consult is not worth storing.
pub fn set_focusable_position(id: ObjectId, x: i32, y: i32) -> bool {
    FOCUS
        .try_with(|focus| {
            let mut focus = focus.borrow_mut();
            if !focus.focusable_widgets().contains(&id) {
                return false;
            }
            focus.set_widget_position(id, x, y);
            true
        })
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Hit testing: point -> widget
// ---------------------------------------------------------------------------

/// Returns the widget that should receive a pointer event at `point`.
///
/// # Why this exists
///
/// [`dispatch_event`] takes a widget id the caller already knows, which left the
/// `point -> widget` step to each backend. On every desktop backend the operating
/// system's own window/view hierarchy performed it, so a control only ever received
/// events when the host had given it a native surface of its own — the library could
/// not answer "which control is under this pixel?". This function answers it, by
/// walking the widget tree that [`crate::widget::Widget::children`] already
/// describes.
///
/// # Coordinates
///
/// `point` is in the **same space as the widgets' geometry**, which in this library
/// is absolute: the layout engine hands each child a rect derived from its parent's
/// absolute rect (see `src/layout/box_layout.rs`), and controls call
/// `contains_point` with raw event positions (see
/// `src/widget/media_widgets/video_player.rs`). No origin subtraction happens at any
/// level — nesting is already baked into each rect, so a deeper widget simply has a
/// smaller absolute rect inside its parent's.
///
/// # Order
///
/// Children are visited **last-to-first**, so a later sibling (drawn on top) wins —
/// the same "topmost wins" rule the renderer paints by. The search descends to the
/// deepest hit, so a click inside a control inside a container resolves to the
/// control, not the container.
///
/// Invisible widgets are skipped: they are not drawn, so they must not swallow a
/// click either. Disabled widgets are still returned — hit testing reports *what is
/// there*, and whether a disabled control reacts is the control's decision (it can
/// report it declined, the same honest-answer rule used everywhere else).
///
/// Returns `None` for an unmounted `root` or a tree with no hit.
///
/// # The root's own bounds, and the one case where they are not consulted
///
/// Every **non-root** node is tested against `point` normally. The root is the one exception, and
/// the reason is a coordinate-space fact rather than an oversight: a window's geometry holds the
/// `x`/`y` the caller asked the operating system for (see `frame_origin`), while its children are
/// written in client coordinates. Those are two different spaces, so testing the window's rect
/// against a client point rejected every click on the window.
///
/// Skipping the test entirely is not the fix either, and that is what this function used to do: a
/// point far outside the root then fell through the child search and returned the **root** as the
/// deepest hit, so a click hundreds of pixels off the window still reached a widget. The two spaces
/// only differ by the root's own origin, so the bound is applied **relative to that origin**: a
/// point is inside the root when `point - origin` lies within the root's rect. When the root is a
/// client-space container (`origin == (0, 0)`, which is the case for every tree built through the
/// layout engine and for the tests below) this is exactly the plain containment test, and for a
/// window it is containment in client coordinates — which is the space `point` is documented to be
/// in above.
pub fn widget_at(root: ObjectId, point: Point) -> Option<ObjectId> {
    let origin = with_widget(root, |widget| widget.geometry())?;
    let local = Point::new(point.x - origin.x, point.y - origin.y);
    let root_rect = Rect::new(0, 0, origin.width, origin.height);
    let mut current = root;
    loop {
        let children = with_widget(current, |widget| widget.children().to_vec())?;
        // A **root** is a container whose geometry is written in a different space from its
        // children's (see the doc comment), so its bound is applied in the root's own space via the
        // `local` point captured above. Every other node is tested normally: a control is addressed
        // in its parent's space, which is the space its own rectangle is written in.
        if current == root {
            if !root_rect.contains_point(local) {
                return None;
            }
        } else if !widget_accepts_point(current, point) {
            return None;
        }
        // Topmost-first: a later sibling paints over an earlier one.
        let deepest = children
            .iter()
            .rev()
            .copied()
            .find(|child| is_visible(*child) && widget_accepts_point(*child, point));
        match deepest {
            Some(child) => current = child,
            // No child claims the point, so this widget is the deepest hit.
            None => return Some(current),
        }
    }
}

/// Whether a mounted widget's own bounds accept `point` (in its local space).
///
/// Asks the widget rather than comparing rectangles, so each control keeps its own
/// hit rule — the touch-target expansion in `contains_point`, or a shape narrower
/// than the bounding box. Returns `false` for an unmounted id.
fn widget_accepts_point(id: ObjectId, point: Point) -> bool {
    with_widget(id, |widget| widget.contains_point(point)).unwrap_or(false)
}

/// Whether a mounted widget is visible. Unmounted ids report `false`.
fn is_visible(id: ObjectId) -> bool {
    with_widget(id, |widget| widget.is_visible()).unwrap_or(false)
}

/// Delivers `event` to whatever widget is under `point`.
///
/// Because widget geometry is absolute here (see [`widget_at`]), the event's position
/// is already in the space the target expects, so it is forwarded unchanged — a
/// coordinate rewrite would introduce an off-by-parent-origin on every nested control.
///
/// A pointer event also drives hover: moving onto a widget synthesises
/// [`Event::MouseEnter`] for it and [`Event::MouseLeave`] for the one left behind.
/// Without that, no control could ever show a hover state, because no backend produces
/// those two events.
///
/// A widget that holds pointer capture receives the event even when the pointer is not
/// over it, so a drag can continue past its origin widget.
///
/// The router itself owns the capture for the duration of a press gesture (D09-EVT-01):
/// the widget the press lands on becomes the gesture owner, and every subsequent move and
/// the final release are delivered to it regardless of where the pointer is. Without that,
/// releasing after dragging off a control left its own press latch armed, so a *later*
/// unrelated release on the control could fire a spurious click. Capture is released once
/// the gesture-ending event has been delivered, so the next press takes a fresh owner.
///
/// Returns whether a widget accepted the event.
pub fn dispatch_pointer_event(root: ObjectId, event: &Event, point: Point) -> bool {
    let target = widget_at(root, point);
    dispatch_hover_transition(target, point);
    // A control that captured the pointer keeps receiving events even when the
    // cursor leaves it — that is what lets a drag continue past its origin widget.
    // Hover still follows the true position, so highlights stay honest.
    //
    // A *new* gesture-start event always re-targets: the pointer going down again is a
    // fresh press, so any leftover capture from a previous gesture is dropped first and
    // the press is hit-tested normally. Without that, a capture that outlived its gesture
    // (for example a host delivered a press but never a release) would swallow every
    // later press, and nothing could ever take the pointer again.
    let starts = event.starts_pointer_gesture();
    if starts && capturing_widget().is_some() {
        let _ = release_pointer_capture();
    }
    if let Some(captured) = capturing_widget() {
        if is_mounted(captured) && !modal_blocks(captured) {
            // A gesture-ending event closes the capture *after* delivery, so this is the
            // last event the capturer sees under this ownership. The control's own latch
            // (`pressed`/`grabbed`) is cleared by its handler, and the router then forgets
            // the capture so the next press can re-target.
            let handled = dispatch_event(captured, event);
            if event.ends_pointer_gesture() {
                let _ = release_pointer_capture();
            }
            return handled;
        }
        // The capturer is gone (or blocked by a modal); drop the capture rather
        // than routing into nothing.
        let _ = release_pointer_capture();
        return false;
    }
    match target {
        Some(target) if !modal_blocks(target) => {
            // The widget under a press becomes the gesture owner for its whole duration,
            // even if the pointer leaves before the release (D09-EVT-01). A control may also
            // call `capture_pointer` itself for a longer-lived drag; the router only needs to
            // guarantee that a plain press→drag→release always completes on the same widget.
            if starts {
                let _ = capture_pointer(target);
            }
            dispatch_event(target, event)
        }
        _ => false,
    }
}

/// Gives `id` capture of the pointer until released.
///
/// Returns `false` for an unmounted id or when it already holds capture, so a caller
/// can tell "nothing changed" from "capture moved". Capture is how a drag survives the
/// pointer leaving the widget that started it.
pub fn capture_pointer(id: ObjectId) -> bool {
    if !is_mounted(id) {
        return false;
    }
    CAPTURE.try_with(|capture| capture.borrow_mut().set_capture(id)).unwrap_or(false)
}

/// Releases the pointer capture, if any. Returns whether there was one to release.
pub fn release_pointer_capture() -> bool {
    CAPTURE.try_with(|capture| capture.borrow_mut().release_capture()).unwrap_or(false)
}

/// Returns the widget currently holding pointer capture, if any.
pub fn capturing_widget() -> Option<ObjectId> {
    CAPTURE.try_with(|capture| capture.borrow().capturing_widget()).unwrap_or(None)
}

/// Returns whether `id` currently holds pointer capture.
pub fn has_pointer_capture(id: ObjectId) -> bool {
    CAPTURE.try_with(|capture| capture.borrow().has_capture(id)).unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Modal dialog enforcement
// ---------------------------------------------------------------------------

/// Returns whether `descendant` is `ancestor` or anywhere below it in the widget
/// tree, walking the [`crate::widget::Widget::parent`] links.
///
/// A widget is its own descendant for this purpose: a modal dialog's own controls
/// (and the dialog itself) must keep receiving input while the modal is up.
fn is_descendant_of(ancestor: ObjectId, descendant: ObjectId) -> bool {
    if ancestor == descendant {
        return true;
    }
    let mut cursor = with_widget(descendant, |widget| widget.parent());
    while let Some(current) = cursor.flatten() {
        if current == ancestor {
            return true;
        }
        cursor = with_widget(current, |widget| widget.parent());
    }
    false
}

/// Returns the top of the modal stack, i.e. the dialog that currently owns input.
pub fn active_modal() -> Option<ObjectId> {
    MODAL.try_with(|stack| stack.borrow().last().copied()).unwrap_or(None)
}

/// Returns whether any modal dialog is currently active.
pub fn is_modal_active() -> bool {
    MODAL.try_with(|stack| !stack.borrow().is_empty()).unwrap_or(false)
}

/// Returns whether `id` is outside the active modal dialog's subtree and therefore
/// must not receive input.
///
/// This is the single predicate both event dispatch and focus routing consult, so
/// the rule "a modal blocks everything except itself and its descendants" is stated
/// once rather than re-derived at each call site. When no modal is active, nothing
/// is blocked.
pub fn modal_blocks(id: ObjectId) -> bool {
    let Some(modal) = active_modal() else {
        return false;
    };
    // The modal itself and its subtree stay live; everything else is blocked. An
    // unmounted id is also blocked — it cannot be part of the live dialog.
    !is_descendant_of(modal, id)
}

/// Pushes `dialog_id` onto the modal stack so it becomes the input owner.
///
/// Returns `false` for an unmounted id, so a caller cannot install a modal that no
/// event can ever reach. Re-pushing an already-active id is a no-op that reports
/// `true`: the caller asked for "make this modal", and it already is.
pub fn enter_modal(dialog_id: ObjectId) -> bool {
    if !is_mounted(dialog_id) {
        return false;
    }
    MODAL
        .try_with(|stack| {
            let mut stack = stack.borrow_mut();
            if stack.last() == Some(&dialog_id) {
                return true;
            }
            stack.push(dialog_id);
            true
        })
        .unwrap_or(false)
}

/// Removes the topmost occurrence of `dialog_id` from the modal stack.
///
/// A dialog that is dismissed pops itself; this is also how a caller closes a modal
/// it opened. Returns whether the stack changed.
pub fn exit_modal(dialog_id: ObjectId) -> bool {
    MODAL
        .try_with(|stack| {
            let mut stack = stack.borrow_mut();
            if let Some(pos) = stack.iter().rposition(|&id| id == dialog_id) {
                stack.remove(pos);
                true
            } else {
                false
            }
        })
        .unwrap_or(false)
}

/// Closes *every* active modal dialog, leaving the stack empty.
///
/// A hard reset for a host that is tearing down a window tree or an application
/// shutdown, where the incremental pop of [`exit_modal`] would leave a stale id
/// behind if the caller lost track of the open order.
pub fn clear_modals() {
    let _ = MODAL.try_with(|stack| stack.borrow_mut().clear());
}

/// Sends the enter/leave pair for a pointer that is now over `hovered`.
///
/// The library synthesises these because no backend does: a backend knows "the mouse
/// moved in my surface", not "the pointer crossed onto a different control", and
/// hover is a property of the widget tree. Tracking the previous target here keeps
/// the pair balanced — exactly one `MouseLeave` for the widget left, one
/// `MouseEnter` for the widget entered, and neither when the pointer stays put.
fn dispatch_hover_transition(hovered: Option<ObjectId>, point: Point) {
    HOVERED.with(|last| {
        let previous = *last.borrow();
        if previous == hovered {
            return;
        }
        *last.borrow_mut() = hovered;
        // Deliver outside the cell borrow: a control handling `MouseLeave` may itself
        // read or write hover state.
        if let Some(previous) = previous {
            let _ = dispatch_event(previous, &Event::MouseLeave { pos: point });
        }
        if let Some(hovered) = hovered {
            let _ = dispatch_event(hovered, &Event::MouseEnter { pos: point });
        }
    });
}

/// Clears the hover target, sending `MouseLeave` to whatever was hovered.
///
/// Called when the pointer leaves the surface entirely, which is the one case a
/// coordinate-based transition cannot observe: there is no widget under the pointer,
/// so the previous hover would otherwise stay highlighted forever.
pub fn clear_hover(point: Point) {
    dispatch_hover_transition(None, point);
}

/// Returns the widget the pointer is currently over, if any.
pub fn hovered_widget() -> Option<ObjectId> {
    HOVERED.with(|last| *last.borrow())
}

/// Records the host window the platform built for the mounted window `id`.
///
/// Called on the creation path once `Platform::create_window` has returned, so
/// that [`host_window_for`] can resolve a library window id to the id the host
/// layer understands. Storing an association for an id that is not mounted is a
/// programming error and is ignored, because a mapping to a window that does not
/// exist could only produce a mount onto nothing.
pub fn set_host_window(id: ObjectId, host: ObjectId) -> bool {
    let stored = HOST_WINDOWS.try_with(|map| {
        if MOUNTED.try_with(|m| m.borrow().contains_key(&id)).unwrap_or(false) {
            map.borrow_mut().insert(id, host);
            true
        } else {
            false
        }
    });
    stored.unwrap_or(false)
}

/// Returns the host window associated with a mounted window widget `id`.
///
/// `None` means "this id is not a window the platform built a host object for" —
/// either it is not a window at all, or the backend has no host windows to build
/// (a state-only backend), in which case the caller must report that it cannot
/// display rather than guessing.
pub fn host_window_for(id: ObjectId) -> Option<ObjectId> {
    HOST_WINDOWS.try_with(|map| map.borrow().get(&id).copied()).unwrap_or(None)
}

/// The widget id whose host window is `host`.
///
/// The inverse of [`host_window_for`], and the translation a platform backend needs
/// whenever an OS callback hands it *its own* window id: the widget registry keys
/// everything by the widget id, and `queue_resize_trigger` refuses an id that
/// addresses no widget. A backend that reported the platform id instead would have
/// every resize silently dropped.
///
/// Returns `None` when no widget names this host, which is correct for a window the
/// platform built before any widget was associated with it.
pub fn widget_id_for_host_window(host: ObjectId) -> Option<ObjectId> {
    HOST_WINDOWS
        .try_with(|map| map.borrow().iter().find(|(_, h)| **h == host).map(|(w, _)| *w))
        .unwrap_or(None)
}

/// Returns whether `id` refers to a mounted self-drawn widget.
///
/// # Why a `try_borrow` and not a `borrow`
///
/// This is asked from inside the paint path — [`crate::widget::draw_bridge::draw_of`] uses it to
/// tell a control the registry owns from one the host owns — and the paint path is reached while
/// [`for_each_mounted_widget`] already holds the registry mutably. A plain `borrow()` panics there
/// ("RefCell already mutably borrowed"), turning an ordinary question into a crash.
///
/// Answering `true` on a borrow conflict is the safe reading rather than a guess: the only caller
/// holding the registry open is the sweep iterating it, so the widget *is* mounted. The alternative
/// answer would make the paint path advance a control the frame loop is also advancing — the
/// double-step this function exists to prevent.
pub fn is_mounted(id: ObjectId) -> bool {
    let direct = MOUNTED
        .try_with(|map| map.try_borrow().map(|map| map.contains_key(&id)).unwrap_or(true))
        .unwrap_or(false);
    if direct {
        return true;
    }
    // A widget lent out to its own driving callback is still mounted: answering `false` here would
    // tell that callback its object had been destroyed, which is exactly the "cannot tell a live
    // control from a gone one" confusion BLUE-issue E-18 names. The check is by **registry** id,
    // matching how the loan is keyed.
    if LENT_OUT.with(|map| map.borrow().contains_key(&id)) {
        return true;
    }
    // The paint path asks with the widget's *own* id (`BaseWidget::id()`), which is a second id
    // space, not the registry key. Resolve it so the answer is the same whichever id the caller
    // holds. This also restores the previous behaviour where the enclosing `with_widget_mut` borrow
    // made the direct check answer `true`; now the answer is derived from the actual loan rather
    // than from a borrow conflict.
    if let Some(registry_id) = registry_id_of(id) {
        let mounted = MOUNTED
            .try_with(|map| {
                map.try_borrow().map(|map| map.contains_key(&registry_id)).unwrap_or(true)
            })
            .unwrap_or(false);
        if mounted || LENT_OUT.with(|map| map.borrow().contains_key(&registry_id)) {
            return true;
        }
    }
    false
}

/// Returns whether the widget mounted under `id` can carry a tri-state value.
///
/// Asked of the widget itself rather than of a table of kinds: checkability is a
/// capability of the control's own property set, so any type that declares
/// `checked` in [`crate::widget::WidgetProperties::property_names`] answers
/// `true` here — including a third-party widget the library has never heard of.
/// Hosts use this to decide whether a `set_widget_tristate` request is
/// meaningful (principle #37: a request the control cannot honour is refused,
/// never silently stored).
pub fn widget_is_checkable(id: ObjectId) -> bool {
    with_widget(id, |widget| {
        crate::widget::capability::properties_trait::widget_property_names(widget)
            .is_some_and(|names| names.contains(&"checked"))
    })
    .unwrap_or(false)
}

/// Returns the number of widgets mounted on this thread.
pub fn mounted_count() -> usize {
    MOUNTED.try_with(|map| map.borrow().len()).unwrap_or(0)
}

/// Runs `f` against every widget mounted on this thread.
///
/// # Why this exists
///
/// Some operations change a *global* fact rather than one control — switching the
/// active theme, or toggling the high-contrast override — and those have to reach
/// the controls that already exist, not just the ones created afterwards.
/// Enumerating here keeps the registry's internals private: a caller asks for the
/// sweep rather than reaching into the map.
///
/// The visit order is unspecified, and `f` must not mount or unmount widgets (the
/// map is borrowed for the duration).
pub fn for_each_mounted_widget<R>(mut f: impl FnMut(ObjectId, &mut dyn Widget) -> R) {
    let _ = MOUNTED.try_with(|map| {
        for (id, entry) in map.borrow_mut().iter_mut() {
            f(*id, entry.widget.as_mut());
        }
    });
}

/// What one call to [`drive_frame`] did, kept for diagnostics and tests.
///
/// # Why this is a record and not a `bool`
///
/// "Did anything happen?" cannot answer the only question a frame loop ever has to
/// answer -- *should I schedule another frame?* -- without over-scheduling. A hover
/// that has finished still needs **one** more frame to be painted in its settled
/// state, and then no more; a window with nothing moving needs none. Both cases
/// return `false` from a bare `bool`, so a loop built on one either spins forever or
/// drops the frame that draws the settle. [`FrameOutcome::needs_another_frame`] is
/// computed from the bus *after* this frame's work, so the frame that observes a
/// settle reports `true` and the one after it reports `false`.
///
/// The remaining fields exist because "this frame cost something" should be
/// answerable *by cause*: how many events woke it, how many controls interpolated,
/// how many platform repaints went out. That is the same grouping BLUE24 §8 asks of
/// `FrameStats`, measured one second earlier in the pipeline.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FrameOutcome {
    /// Events drained from the trigger queue and dispatched this frame.
    pub events_dispatched: usize,
    /// Controls that answered `is_animating()` and were advanced by `delta_ms`.
    pub controls_ticked: usize,
    /// Repaint requests submitted to the platform this frame.
    pub repaints_submitted: usize,
    /// Whether the host should schedule another frame.
    pub needs_another_frame: bool,
}

/// The decode accounting for a build with no decoder linked in: always zero.
///
/// # Why a real type and not `(0, 0, 0)`
///
/// `drive_frame` reads the cache counters twice per frame and takes the difference. On a build
/// without `feature = "image"` (`android`, `embedded`) there is no `crate::image` module to ask, and
/// naming it did not compile. The three readings could have been written as three separate `cfg`
/// blocks with literal zeros, but a type keeps the two readings structurally identical to the
/// gated arm: the same field names, the same subtraction below, one `cfg` on each read.
///
/// The zero is the *true* answer rather than a placeholder. With no decoder compiled in, no decode
/// can occur, so a frame's share is genuinely zero -- the same reasoning
/// `avatar::resolved_image_source` records for its own no-decoder arm. It is not a "we could not
/// measure this" stand-in, which would be a dishonest number in exactly the place this crate's
/// frame ledger exists to be honest about.
#[cfg(not(all(feature = "image", not(alloc_frugal))))]
#[derive(Default)]
struct NoDecoderStats {
    requests: u64,
    hits: u64,
    misses: u64,
}

/// A frame's cost, grouped by **what produced it** rather than as one total.
///
/// # Why not a duration
///
/// "This frame took 12 ms" cannot be acted on: it might be one control repainting the whole
/// surface, a damage merge that failed, or an animation running more frames than it needs. So
/// the ledger groups by **consumer** -- who was advanced, who was redrawn, how much merging
/// saved -- which is the form a reader can act on (BLUE24 §8.1).
///
/// # Why it is a second type beside [`FrameOutcome`]
///
/// [`FrameOutcome`] answers the frame loop's one question (*schedule another frame?*) and is
/// `Copy` because a loop holds it every iteration. This carries a `Vec` of causes, so it is
/// not `Copy` and is taken **on demand** -- a host that wants the account asks for it, and a
/// host that only drives frames never pays for the allocation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FrameStats {
    /// Monotonic frame counter, so two readings can be compared without a clock.
    pub index: u64,
    /// The delta this frame advanced animations by.
    pub delta_ms: u32,
    /// Events drained and dispatched this frame.
    pub events: usize,
    /// Controls that answered `is_animating()` and were advanced.
    pub controls_ticked: usize,
    /// Surfaces submitted for repaint this frame (after coalescing).
    pub controls_drawn: usize,
    /// Repaint requests **folded into** an earlier request for the same surface this frame.
    ///
    /// The saving, not the work: five requests for one surface submit once and coalesce four.
    pub repaints_coalesced: usize,
    /// Why each repainted surface was repainted, last cause first per surface.
    ///
    /// One entry per surface -- the reason it was repainted -- so a reader can answer "why is
    /// this still redrawing?" without a log. A surface with no entry is one that was not
    /// repainted, which is why "no anonymous repaint" (BLUE24 §8 criterion 4) is a statement
    /// about this list being complete rather than about it being non-empty.
    pub last_repaint_reason: alloc::vec::Vec<(ObjectId, RepaintReason)>,
    /// Image decodes the frame avoided, by sharing a decode an earlier frame already did.
    ///
    /// # Why an image decode belongs in a frame's account
    ///
    /// A decode is the most expensive thing a control can do inside `draw` — a full PNG inflate, or
    /// a JPEG pass, on the thread that is supposed to be presenting. "This frame was slow" is not
    /// answerable without knowing whether it decoded a photograph, and "is the cache helping" is not
    /// answerable without knowing whether the decodes went away. Both are one number.
    ///
    /// # These are deltas, and the counters they come from are cumulative
    ///
    /// [`crate::image::cache::stats`] is process-wide and monotonic, because it answers "what has
    /// this process saved". A frame reports its own share: the difference between the two readings
    /// taken around the frame's work. `decode_hits + decode_misses <= decode_requests` holds within a
    /// frame; across the process the counters balance exactly.
    ///
    /// A build without the `image` feature reports zeros rather than omitting the fields, so a host
    /// that reads them does not have to be compiled differently to do it.
    pub decode_requests: u64,
    /// Decode requests answered without decoding.
    pub decode_hits: u64,
    /// Decode requests that had to decode — the ones that cost this frame real time.
    pub decode_misses: u64,
}

/// The frame account as text, so it can leave the process.
///
/// # Why this is the exportable half of BLUE24 §12 U-8
///
/// U-8 (a remote / off-screen renderer) asks for the frame account to be a **product** rather than
/// an in-memory value: pixels can be sent to another machine, but "why this frame looks like this"
/// can only be transmitted if the account has a form that survives leaving the process. A `Debug`
/// derive is not that form — it is a debugger's view, unstable across versions and unreadable in a
/// log. This is the stable one: the fields in a fixed order, the causes by their published tokens.
///
/// It is also the answer to a defect that exists **today, in this process**: `last_frame_stats()`
/// had no consumer anywhere in the crate, so the ledger's whole purpose — answering "why is this
/// still redrawing?" — was reachable only from a Rust expression. A host logging a slow frame now
/// has something to log.
///
/// # Why one line and not JSON
///
/// The crate's JSON path is hand-written (`capability::designer_manifest`), and adding a second
/// serializer for a value with no JSON consumer would be a second mechanism for one question
/// (principle #101). A single line of `key=value` is what a log wants, diffs cleanly, and needs no
/// dependency in a `no_std` build.
impl core::fmt::Display for FrameStats {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "frame={} delta_ms={} events={} ticked={} drawn={} coalesced={} decode={}/{}/{}",
            self.index,
            self.delta_ms,
            self.events,
            self.controls_ticked,
            self.controls_drawn,
            self.repaints_coalesced,
            self.decode_requests,
            self.decode_hits,
            self.decode_misses,
        )?;
        // The causes are the part a reader scans for, so they are named rather than counted: a frame
        // that says "drawn=3" without saying why is the anonymous repaint BLUE24 §8 criterion 4
        // exists to prevent.
        for (surface, reason) in &self.last_repaint_reason {
            write!(f, " repaint[{}]={}", surface, reason.as_str())?;
        }
        Ok(())
    }
}

/// Performs every library-side task of one frame, in a fixed order, exactly once.
///
/// # Why a *frame* and not just [`tick_animations`]
///
/// Three entry points each did part of a frame, in an order that differed per platform:
/// [`crate::drain_triggers`] emptied the input queue, [`tick_animations`] advanced the
/// animation bus, and the paint path (`draw_bridge::draw_of`) advanced a control *again*
/// as a side effect of drawing it. So how many times a control was interpolated in one
/// frame depended on how many layers the host happened to call, when the only correct
/// answer is **once**, and **before** painting -- otherwise every frame paints the state
/// it had one frame ago and the animation visibly lags its own input.
///
/// This function is the one place that answers that ordering, so the answer is the same
/// on every backend.
///
/// # The order, and why no step may move
///
/// 0. **Refresh the device facts.** One snapshot per frame, read before anything else, so every
///    control in this frame sees the same text scale, motion preference and direction. A host
///    that changed a system setting sees it apply on the next frame, never part-way through a
///    paint (see [`crate::style::environment`]'s module docs).
/// 1. **Drain input.** Pointer, key and focus events that arrived since the last frame
///    land first, because an animation's *target* comes from state and state comes from
///    these events. Reversed, a control would not begin reacting until the following
///    frame -- the input latency the ordering exists to remove.
/// 2. **Advance the animation bus once.** Controls answering `is_animating()` take
///    `delta_ms`. Because this precedes painting, the frame that a hover starts on is
///    already one step in.
/// 3. **Report whether another frame is owed.** Taken *after* steps 1-2, which is what
///    makes the frame that observes a control settling report `true` (so the settle gets
///    painted) and the next one report `false` (so an idle window stops paying).
///
/// # `repaints_submitted`: why it is counted rather than performed here
///
/// Damage is submitted where the damage is *discovered* -- `request_repaint`,
/// `mark_dirty_rect`, and the platform's own native redraw path -- so that a control
/// which redraws mid-frame does not wait for the next one. This function therefore
/// accounts for the submissions made during this frame's steps 1-2 rather than making
/// them itself; a frame loop learns "this frame invalidated N surfaces" without the
/// library having to buffer damage it has nowhere to wait for.
///
/// # Static frames are free
///
/// With nothing queued and nothing animating, this is two `try_with` lookups plus a
/// registry sweep of `is_animating()`, returns `needs_another_frame == false`, and the
/// host sleeps until the next event. That property is what lets the loop run at the
/// display's rate while the window is still, and it is asserted by this module's tests.
pub fn drive_frame(delta_ms: u32) -> FrameOutcome {
    // The decode counters, read before anything else in the frame so this frame's share is exactly
    // the work done between here and the reading below -- and not whatever a previous frame left.
    //
    // # Why this is two `cfg` arms rather than one call
    //
    // `crate::image` is gated on `feature = "image"`, while this function is not: `full_widgets`
    // profiles like `android` and `embedded` have the widget tree but not the decoder. Naming
    // `crate::image::cache::stats()` unconditionally therefore failed to *compile* on those targets
    // (`unresolved module image`), which is why `check_android_cross.sh` reported a cross-target
    // break on `aarch64-linux-android` while every host build was green.
    //
    // The zero is not a placeholder. With no decoder compiled in, no decode *can* happen, so
    // "this frame decoded nothing" is the true count rather than a stand-in for an unknown one --
    // the same reasoning `avatar::resolved_image_source` uses for its no-decoder arm.
    #[cfg(all(feature = "image", not(alloc_frugal)))]
    let decodes_before = crate::image::cache::stats();
    #[cfg(not(all(feature = "image", not(alloc_frugal))))]
    let decodes_before = NoDecoderStats::default();

    // Step 0 -- the device facts, so every control in this frame sees one set of them.
    crate::style::environment::refresh_environment();

    // Step 1 -- input first, so this frame's animation targets are this frame's state.
    let events_dispatched = crate::drain_triggers();

    // Step 2 -- exactly one advance per animating control, before any paint.
    tick_animations(delta_ms);
    let controls_ticked = count_animating_widgets();

    // Step 3 -- the bus answers for the *next* frame, so a settle is painted once more
    // and then scheduling stops.
    let needs_another_frame = animation_bus_needs_another_frame();

    // Step 4 -- translations that changed on disk, so an edited catalogue reaches the
    // screen without a restart. This runs *after* the animation step and before the
    // repaint counts are taken, because applying a reload can invalidate text and thus
    // submit a repaint; taking the counts first would attribute that repaint to the
    // next frame and make this frame's ledger understate its own work.
    //
    // It is unconditionally cheap when hot reload is off: `pump_hot_reload` is one
    // mutex acquisition and a `None` check. That matters because every platform loop
    // calls `drive_frame` on a timer, and a `cfg` here would fork the frame driver per
    // profile for a saving that is not measurable.
    #[cfg(feature = "i18n")]
    crate::i18n::pump_hot_reload();

    // The numbers the frame ledger will report. Taken together so the counts and the causes
    // describe the same frame: taking them apart would let a repaint be attributed to the
    // frame after the one that submitted it.
    let repaints_submitted = take_frame_repaint_count();
    let repaints_coalesced = take_frame_coalesced_count();
    let last_repaint_reason = take_frame_repaint_reasons();
    let index = FRAME_INDEX.try_with(|frame| frame.replace(frame.get() + 1)).unwrap_or(0);

    // This frame's share of the process-wide decode accounting. A delta rather than the totals,
    // because the question a frame ledger answers is about *this* frame; see `FrameStats`.
    //
    // Read **after** the draw work rather than with the repaint numbers above, because a decode
    // happens inside `draw` and the whole point is to account for it. (The repaint counts are taken
    // before painting for the opposite reason: they report what the *input* steps invalidated, and a
    // submission made while painting belongs to the frame that will paint it.)
    #[cfg(all(feature = "image", not(alloc_frugal)))]
    let decodes_after = crate::image::cache::stats();
    #[cfg(not(all(feature = "image", not(alloc_frugal))))]
    let decodes_after = NoDecoderStats::default();
    let decode_requests = decodes_after.requests.saturating_sub(decodes_before.requests);
    let decode_hits = decodes_after.hits.saturating_sub(decodes_before.hits);
    let decode_misses = decodes_after.misses.saturating_sub(decodes_before.misses);

    let _ = LAST_FRAME_STATS.try_with(|slot| {
        slot.replace(Some(FrameStats {
            index,
            delta_ms,
            events: events_dispatched,
            controls_ticked,
            controls_drawn: repaints_submitted,
            repaints_coalesced,
            last_repaint_reason,
            decode_requests,
            decode_hits,
            decode_misses,
        }));
    });

    FrameOutcome { events_dispatched, controls_ticked, repaints_submitted, needs_another_frame }
}

thread_local! {
    /// The most recent frame's ledger, for [`last_frame_stats`].
    ///
    /// Stored rather than returned because [`drive_frame`]'s return type is part of the frame
    /// contract a loop calls every iteration (and is `Copy`); a host that wants the account
    /// reads it separately, so a host that does not want it pays nothing.
    #[allow(clippy::missing_const_for_thread_local)]
    static LAST_FRAME_STATS: core::cell::RefCell<Option<FrameStats>> =
        const { core::cell::RefCell::new(None) };
}

/// The ledger for the most recent [`drive_frame`], or `None` when no frame has run.
///
/// # Why "why" is answerable at all
///
/// Because every repaint submission in the crate names a [`RepaintReason`] at its one point of
/// submission, and this returns those reasons grouped by surface. A frame that repainted
/// seven surfaces because an animation is in flight says so; if instead it says nothing, no
/// repaint happened, which is the still-frame guarantee being *observable* rather than asserted
/// (BLUE24 §8 criterion 1).
pub fn last_frame_stats() -> Option<FrameStats> {
    LAST_FRAME_STATS.try_with(|slot| slot.borrow().clone()).ok().flatten()
}

/// Counts mounted controls that currently report themselves as animating.
///
/// Split out so the two readers of the same fact -- [`drive_frame`]'s diagnostic count
/// and [`has_animating_widgets`]'s boolean -- cannot drift: both walk the registry once
/// and ask the same predicate.
fn count_animating_widgets() -> usize {
    let mut count = 0usize;
    for_each_mounted_widget(|_, widget| {
        if widget.is_animating() {
            count += 1;
        }
    });
    count
}

thread_local! {
    /// Repaint requests submitted since the last [`drive_frame`].
    ///
    /// A counter rather than a log: the frame only needs "how many", and the reasons
    /// belong to the control that asked (BLUE24 §8's `RepaintReason` is where that
    /// question is answered, not here). Reset by [`take_frame_repaint_count`].
    #[allow(clippy::missing_const_for_thread_local)]
    static FRAME_REPAINTS: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };

    /// Repaint requests that were **folded into an earlier request for the same surface**
    /// this frame, so they cost the platform nothing extra.
    ///
    /// A coalesced request is not a lost one: the surface is already going to be repainted,
    /// so asking again would be a second submission of the same work. Counting it is what
    /// lets a frame answer "how much did merging save?" rather than only "how many went
    /// out?" -- BLUE24 §8 criterion 3 (five controls asking for one rectangle submit once
    /// and coalesce four).
    #[allow(clippy::missing_const_for_thread_local)]
    static FRAME_REPAINTS_COALESCED: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };

    /// Whether each mounted surface has already had a repaint requested this frame.
    ///
    /// Keyed by the repaint's **target surface** rather than by control, because that is
    /// what coalescing is about: two controls on the same surface produce one submission.
    /// Cleared by [`take_frame_repaint_count`], so "this frame" is exactly the span between
    /// two `drive_frame` calls.
    #[allow(clippy::missing_const_for_thread_local)]
    static FRAME_REPAINTED_SURFACES: core::cell::RefCell<alloc::vec::Vec<ObjectId>> =
        const { core::cell::RefCell::new(alloc::vec::Vec::new()) };

    /// The last reason each surface was repainted, for BLUE24 §8's `FrameStats`.
    ///
    /// One entry per surface, overwritten (not appended), so a surface repainted fifty times
    /// in a frame reads as "the reason it was repainted" rather than fifty rows. `Explicit`
    /// means "a caller asked, and named no cause" — which is itself a fact worth being able
    /// to see, because it is the one reason a gate cannot attribute to a mechanism.
    #[allow(clippy::missing_const_for_thread_local)]
    static FRAME_REPAINT_REASONS: core::cell::RefCell<alloc::vec::Vec<(ObjectId, RepaintReason)>> =
        const { core::cell::RefCell::new(alloc::vec::Vec::new()) };

    /// Monotonic frame counter, incremented once per [`drive_frame`].
    ///
    /// A counter rather than a clock: two readings of [`FrameStats`] are comparable by
    /// subtracting indices, which needs no `SystemTime` and therefore works under `mini`
    /// (BLUE24 §4's "no device fact from a wall clock" rule applies to the frame ledger too).
    #[allow(clippy::missing_const_for_thread_local)]
    static FRAME_INDEX: core::cell::Cell<u64> = const { core::cell::Cell::new(0) };
}

/// Why a surface was asked to repaint.
///
/// # Why a reason and not just a count
///
/// "This frame submitted seven repaints" cannot be acted on. "Seven repaints, all because an
/// animation is still in flight" says the animation is the cost; "seven, all because a control
/// changed its theme state" says the styles are; "seven, all `Explicit`" says a caller is
/// repainting by hand and no library mechanism can explain it. BLUE24 §8 asks the frame ledger
/// to answer by **cause**, and this is the cause.
///
/// The set is deliberately closed, and each variant is a mechanism a reader can go and find:
/// an implementation that adds a repaint must pick the variant that names *why*, so the ledger
/// cannot silently grow an "other" bucket that explains nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepaintReason {
    /// A control's self-driven animation advanced and needs to be seen.
    Animation,
    /// A control's interaction or semantic state changed (`widget_state` / `semantic_state`).
    State,
    /// An overlay's content changed (a tooltip, a popup, a menu).
    Overlay,
    /// A caller asked directly (a property write, an imperative redraw) and named no mechanism.
    Explicit,
    /// The platform itself asked for its surface to be redrawn.
    ///
    /// Distinct from every variant above because it is the *other* world in a mixed
    /// native/self-painted window (BLUE24 §7): the platform owns the pixels there, and this is
    /// how the library comes to know about it.
    Native,
}

impl RepaintReason {
    /// Whether this reason means the surface needs another frame after this one.
    ///
    /// Only [`RepaintReason::Animation`] does: it is the one cause that keeps producing new
    /// pixels frame after frame. The others describe a change that is now complete, and a
    /// frame loop that scheduled another frame for them would spin on a still window.
    pub fn keeps_animating(self) -> bool {
        matches!(self, RepaintReason::Animation)
    }

    /// The reason's stable spelling, for a frame account that leaves the process.
    ///
    /// # Why a cause needs a name at all
    ///
    /// [`FrameStats`] carries `last_repaint_reason` — one entry per repainted surface — because
    /// "why is this still redrawing?" is the question the ledger exists to answer. But until this
    /// function existed the answer could not be **written down**: the reason is an enum, and a host
    /// logging the account or showing it in a diagnostics pane had no spelling to print. The field
    /// was therefore complete for a Rust reader and useless to any other kind.
    ///
    /// The tokens are lower-case and stable, because they are what a log line or an exported
    /// account will be read and grepped for. They match [`RepaintReason::parse`], so the two cannot
    /// drift into a spelling that only one of them accepts.
    pub fn as_str(self) -> &'static str {
        match self {
            RepaintReason::Animation => "animation",
            RepaintReason::State => "state",
            RepaintReason::Overlay => "overlay",
            RepaintReason::Explicit => "explicit",
            RepaintReason::Native => "native",
        }
    }

    /// Parses a token produced by [`RepaintReason::as_str`].
    ///
    /// `None` rather than a default: an account that named a cause the library does not publish is
    /// a fact about a version mismatch, and silently folding it into `Explicit` would make a reader
    /// believe the library asked for a repaint it did not. The same rule the crate's other token
    /// parsers follow (`BevelDirection::parse`, `Elevation::parse`).
    pub fn parse(token: &str) -> Option<Self> {
        match token {
            "animation" => Some(RepaintReason::Animation),
            "state" => Some(RepaintReason::State),
            "overlay" => Some(RepaintReason::Overlay),
            "explicit" => Some(RepaintReason::Explicit),
            "native" => Some(RepaintReason::Native),
            _ => None,
        }
    }
}

/// Records that this frame submitted one repaint to the platform, for `reason` on `surface`.
///
/// Called from the damage-tracking paths, which are the single places a repaint is
/// requested, so the count cannot miss a submission made through the library.
///
/// # Coalescing
///
/// A second request for a surface already repainted this frame is **counted as coalesced
/// rather than submitted**. That is what makes BLUE24 §8 criterion 3 true: five controls
/// announcing damage on one surface cost the platform one submission, and the frame can
/// report the four it saved. The surface, not the control, is the unit because a submission
/// is per surface -- two controls drawing into one window are one repaint.
///
/// The reason recorded is the one from the **first** request for that surface this frame:
/// it is the cause that already made the frame happen, and overwriting it with a later, more
/// incidental reason would make the ledger describe the last caller rather than the cost.
pub(crate) fn note_frame_repaint_reason(surface: ObjectId, reason: RepaintReason) {
    let already = FRAME_REPAINTED_SURFACES
        .try_with(|surfaces| {
            let mut surfaces = surfaces.borrow_mut();
            if surfaces.contains(&surface) {
                true
            } else {
                surfaces.push(surface);
                false
            }
        })
        .unwrap_or(false);

    if already {
        let _ = FRAME_REPAINTS_COALESCED.try_with(|count| count.set(count.get().saturating_add(1)));
        return;
    }

    let _ = FRAME_REPAINTS.try_with(|count| count.set(count.get().saturating_add(1)));
    let _ = FRAME_REPAINT_REASONS.try_with(|reasons| {
        let mut reasons = reasons.borrow_mut();
        match reasons.iter_mut().find(|(id, _)| *id == surface) {
            Some(entry) => entry.1 = reason,
            None => reasons.push((surface, reason)),
        }
    });
}

/// Records that this frame submitted one repaint, naming no surface.
///
/// The pre-BLUE24 shape, kept for the callers that genuinely have no surface to name — a
/// repaint whose target the platform resolved itself. It records [`RepaintReason::Explicit`]
/// against a synthetic surface, so a bare submission still appears in the ledger rather than
/// being anonymous.
#[allow(dead_code)]
pub(crate) fn note_frame_repaint() {
    note_frame_repaint_reason(0, RepaintReason::Explicit);
}

/// Takes (and clears) the number of repaints submitted since the last call.
fn take_frame_repaint_count() -> usize {
    FRAME_REPAINTS.try_with(|count| count.replace(0)).unwrap_or(0)
}

/// Takes (and clears) the number of repaints folded into an earlier one this frame.
fn take_frame_coalesced_count() -> usize {
    FRAME_REPAINTS_COALESCED.try_with(|count| count.replace(0)).unwrap_or(0)
}

/// Takes (and clears) why each surface was repainted this frame, and resets the surfaces set.
///
/// The surfaces set is cleared here rather than in [`take_frame_repaint_count`] so the two
/// takers are called together by [`drive_frame`] and the coalescing window is exactly one
/// frame: clearing it early would let a second request for the same surface be counted as a
/// fresh submission within the same frame.
fn take_frame_repaint_reasons() -> alloc::vec::Vec<(ObjectId, RepaintReason)> {
    let _ = FRAME_REPAINTED_SURFACES.try_with(|surfaces| surfaces.borrow_mut().clear());
    FRAME_REPAINT_REASONS
        .try_with(|reasons| reasons.borrow_mut().drain(..).collect())
        .unwrap_or_default()
}

/// Advances every animating control by `delta_ms`, reporting whether another frame is needed.
///
/// # Why this is the crate's *only* frame driver
///
/// `src/style/animation.rs` and eleven controls' own `tick` state machines were all fully
/// implemented and all unreachable: nothing in `src/widget/`, `src/app/`, `src/render/` or
/// `src/platform/` ever called one, so a hover faded nowhere and a caret never blinked. The
/// missing piece is a single driver, and "who drives" has two wrong answers:
///
/// * **a timer per control** -- a hundred controls, a hundred timers, none of them aligned to
///   the frame, and each one a chance to leak;
/// * **each backend driving** -- the same button advanced twice in one frame, so its animation
///   runs at a speed that depends on how many layers happened to call in.
///
/// So the driver is this one function, called once per frame by the host *before* it paints.
/// The set of controls advanced is whatever answers `true` to its own
/// [`Widget::is_animating`] rather than a registry the runtime maintains: a registry would
/// have a "registered but never unregistered" leak, while self-reporting cannot -- an
/// unmounted control simply is not in the map any more.
///
/// # The return value is the whole point
///
/// `true` means "at least one control still owes frames", which is exactly when the host
/// should schedule another one. A window showing only resting controls therefore settles at
/// `false` and pays nothing per frame -- a still application does not burn a core, which is
/// the half of "smooth" that is easy to forget.
///
/// # Where a control can be, and why the sweep has to cover both
///
/// A control lives in exactly one of two places, and they are reached by completely
/// different APIs:
///
/// * **mounted** on the [`MOUNTED`] registry, which is how a host that built its tree
///   through [`crate::app`] holds every control; the window tree sweeps it;
/// * **owned by the caller**, as the `Box<dyn Widget>` that
///   [`crate::widget::WidgetFactory::create`] returns and that the documented embedding
///   pattern holds directly.
///
/// The first version of this driver swept only the registry. That is wrong for the owned
/// case, and wrong in the worst possible way: a control that is not mounted was never
/// advanced, yet nobody notices, because the control still *draws* -- it simply draws its
/// start state forever. A `CheckBox` ticked on program output, a `Switch` set from a
/// settings file, a caret in a directly-held `LineEdit` all sat motionless and reported no
/// error. The `census`/snapshot path in this very crate holds controls that way
/// (`draw_bridge::draw_of` takes `&mut dyn Widget`), which is why the gap is reachable from
/// the crate's own code and not only from a host's.
///
/// So a control that is advanced while the registry is being swept is recorded here, and
/// anything that subsequently asks *"should the next frame be scheduled?"* gets the union
/// of the two populations. That is what makes
/// [`crate::widget::draw_bridge::draw_of`] -- the single entry point for painting a
/// directly-owned control -- able to drive the frames such a control needs. Without it the
/// animation bus would be complete for mounted trees and silently inert for owned ones.
pub fn tick_animations(delta_ms: u32) -> bool {
    let mut still_animating = false;
    for_each_mounted_widget(|_, widget| {
        // `is_animating` first, so a resting control (the common case) is not asked to
        // interpolate at all: this is what keeps a static frame free.
        if widget.is_animating() {
            // `tick` also reports "moving"; either answer keeps the frame coming, because a
            // control can be mid-flight while its own `is_animating` is a coarser fact.
            if widget.tick(delta_ms) || widget.is_animating() {
                still_animating = true;
            }
        }
    });
    // The latch is written **both ways**, and that is the whole point.
    //
    // # The defect this replaces
    //
    // It used to be set when `still_animating` and never cleared. The doc above explains what it
    // is for: scheduling the one frame that paints a control's *settled* state. But a flag whose
    // only clearer is the teardown function (`animation_bus_reset_host_owned`) is not a "one more
    // frame" request — it is a latch that turns `needs_another_frame` into a permanent `true`
    // from the first frame in which anything moved. A window that had ever shown a spinner could
    // never sleep again, which is the exact opposite of what `drive_frame` promises
    // (BLUE24 §1: "the cost of a still frame is one emptiness check").
    //
    // Writing `still_animating` unconditionally makes the flag mean what its name and its doc
    // say: *this* sweep found something unsettled. The settle frame still gets scheduled, because
    // the answer is read **after** the sweep: the last frame in which a control moved sets the
    // flag and is told `true`, the next sweep finds nothing and clears it, so the frame after
    // that is free. That is one extra frame, not an infinite stream.
    //
    // It cannot clobber the host-owned fact: `HOST_OWNED_ANIMATING` is a separate cell, written by
    // `draw_bridge` when it advances an owned control, and `animation_bus_needs_another_frame` ORs
    // the two.
    let _ = LAST_SWEEP_HAD_UNSETTLED_MOUNTED.try_with(|flag| flag.set(still_animating));
    still_animating
}

/// Records that a **host-owned** control was advanced this frame, and reports whether the
/// animation bus should currently consider one to be in flight.
///
/// # Why this is a pair of free functions and not a method
///
/// [`tick_animations`] hands a control `delta_ms` and receives "do I need another frame?"
/// back. A host that owns its controls and calls their `tick` directly never goes through
/// that function, so it has no way to tell it what it saw. These two functions are that
/// channel: the control's owner reports the fact, and the bus folds it into the answer a
/// frame loop asks for.
///
/// The state is deliberately **not** cleared by [`tick_animations`]: a frame loop that calls
/// the bus for its mounted tree and calls `tick` on its owned controls usually asks the
/// question *after* tickling them, so clearing on the sweep would erase the answer the
/// caller had just reported. It is cleared when a host-owned control is observed to have
/// settled ([`animation_bus_note_host_owned_settled`]) or by
/// [`animation_bus_reset_host_owned`].
pub fn animation_bus_note_host_owned_animating(animating: bool) {
    let _ = HOST_OWNED_ANIMATING.try_with(|flag| flag.set(animating));
}

/// Clears the host-owned in-flight fact once such a control has settled.
pub fn animation_bus_note_host_owned_settled() {
    let _ = HOST_OWNED_ANIMATING.try_with(|flag| flag.set(false));
}

/// Forgets every host-owned in-flight fact, including the record of the last registry sweep.
///
/// A frame loop that has torn down its controls calls this so a settled window cannot be kept
/// awake by a control that no longer exists.
pub fn animation_bus_reset_host_owned() {
    let _ = HOST_OWNED_ANIMATING.try_with(|flag| flag.set(false));
    let _ = LAST_SWEEP_HAD_UNSETTLED_MOUNTED.try_with(|flag| flag.set(false));
}

/// Whether the animation bus should schedule another frame right now.
///
/// # What it covers, and why it is not just [`has_animating_widgets`]
///
/// Two populations can be animating, and a host that owns some of its controls has to be
/// able to hear about both:
///
/// * the **mounted registry**, answered by [`has_animating_widgets`];
/// * a **host-owned** control that was advanced this frame, which the host reports with
///   [`animation_bus_note_host_owned_animating`] -- and, on the frame it settles, which is
///   the frame the old answer was `true` for a control that has since stopped, which is why
///   [`LAST_SWEEP_HAD_UNSETTLED_MOUNTED`] is kept: it is the only way to schedule the frame
///   that observes the settle.
///
/// ["smooth"](super) has two halves and this function is what keeps the second one honest:
/// a host asks *this*, not a constant `true`, so a window with nothing moving pays nothing.
pub fn animation_bus_needs_another_frame() -> bool {
    let host_owned = HOST_OWNED_ANIMATING.try_with(|flag| flag.get()).unwrap_or(false);
    let sweep_unsettled =
        LAST_SWEEP_HAD_UNSETTLED_MOUNTED.try_with(|flag| flag.get()).unwrap_or(false);
    host_owned || sweep_unsettled || has_animating_widgets()
}

/// Whether any mounted control is currently animating.
///
/// A host can ask this before deciding whether to enter a continuous-frame mode, without
/// paying for the sweep [`tick_animations`] performs.
pub fn has_animating_widgets() -> bool {
    let mut animating = false;
    for_each_mounted_widget(|_, widget| {
        if widget.is_animating() {
            animating = true;
        }
    });
    animating
}

/// Returns the geometry of a mounted widget, or `None` when it is not mounted.
///
/// A widget currently being driven by a mutable callback **is** mounted, but its geometry is not
/// re-read through an aliasing shared reference. Reads of other mounted widgets remain available.
pub fn geometry_of(id: ObjectId) -> Option<Rect> {
    let mounted = MOUNTED
        .try_with(|map| map.borrow().get(&id).map(|entry| entry.widget.geometry()))
        .ok()
        .flatten();
    mounted.or_else(|| lent_out_widget(id, |widget| widget.geometry()))
}

/// The origin a control's own coordinates are relative to.
///
/// # Why a window's origin is `(0, 0)`
///
/// A window's geometry is recorded in **screen** coordinates — `create_window` mounts it
/// at the `x`/`y` the caller asked the operating system for — while every control inside
/// it is placed in **client** coordinates. Those are two different spaces, and using the
/// window's screen position as the tree's origin mixes them.
///
/// The mixture was not harmless. `render_frame_tree` subtracts this origin from every
/// widget before drawing, so a window created at `(100, 100)` shifted each child by
/// `(-100, -100)`: a combo box at client `(20, 142)` was drawn at `(-80, 42)`, outside the
/// canvas and therefore clipped away. The window's own fill used its absolute rect and
/// came back to `(0, 0)`, so the frame was **a correct background with no controls on
/// it** — controls whose style was resolved correctly, whose geometry was correct, and
/// which were still invisible. The window's border stroke additionally landed across the
/// whole frame, which is why a corner of the window read as the border colour.
///
/// So a root contributes no offset: its children's coordinates already start at the
/// window's top-left. A window created at `(0, 0)` behaved by accident before; every
/// window behaves now.
///
/// # Why a non-window keeps its own position
///
/// A control that paints itself is addressed in **its parent's** space, and
/// [`render_frame`] is called for that control's own surface, so its rectangle must be
/// translated back to its own origin. That is the case this subtraction exists for.
fn frame_origin(id: ObjectId) -> (i32, i32) {
    match MOUNTED.try_with(|map| {
        map.borrow().get(&id).map(|entry| (entry.widget.kind(), entry.widget.geometry()))
    }) {
        Ok(Some((crate::widget::WidgetKind::Window, _))) | Ok(None) | Err(_) => (0, 0),
        Ok(Some((_, geometry))) => (geometry.x, geometry.y),
    }
}

/// Updates the geometry of a mounted widget. Returns whether it was found.
pub fn set_geometry(id: ObjectId, geometry: Rect) -> bool {
    let updated = MOUNTED.try_with(|map| {
        map.borrow_mut().get_mut(&id).map(|entry| entry.widget.set_geometry(geometry)).is_some()
    });
    updated.unwrap_or(false)
}

/// Runs `f` with mutable access to a mounted widget.
///
/// # Why the widget is detached before `f` runs
///
/// The borrow is scoped to the *map operation*, never to `f`. A property setter runs as `f` and emits
/// the control's signal synchronously, so a user callback runs while `f` is still on the stack; if the
/// `RefCell` were borrowed for all of `f`, that callback's read of any control (its own property, or
/// another control) hit `already borrowed` and panicked. This is the property-write path's version of
/// the defect `dispatch_event` fixed for input (BLUE-issue E-17).
///
/// While `f` runs, other controls remain accessible and `is_mounted(id)` remains true. Reads and
/// writes of this same widget through another registry path are refused while the active `&mut`
/// live `&mut`.
///
/// Returns `None` when `id` is not mounted, or when a nested call targets the id this call is already
/// mutating.
pub fn with_widget_mut<R>(id: ObjectId, f: impl FnOnce(&mut dyn Widget) -> R) -> Option<R> {
    // A nested mutable access to a widget already lent out for mutation would alias the live `&mut`,
    // so it is refused explicitly. The outer call's marker is a mutable-borrow marker distinct from a
    // read-only lent entry; see `LENT_MUTATING`.
    if lent_mutating(id) {
        return None;
    }
    let taken = MOUNTED.try_with(|map| map.borrow_mut().remove(&id)).ok().flatten();
    let mut mounted = taken?;
    // Mark the id in-flight for the duration, exactly as `dispatch_event` does, so a callback that
    // **destroys** this control (a property setter that closes its own window) has its `unregister`
    // recorded as a tombstone rather than silently undone by the reinsertion below. The guard clears
    // the marker on both the normal return and an unwind.
    let mut in_flight = InFlightGuard::install(id);
    let _lent = LentGuard::install(
        id,
        mounted.widget.as_mut(),
        /* mutating = */ true,
        /* exclusive = */ true,
    );
    let result = f(mounted.widget.as_mut());
    drop(_lent);
    let destroyed = in_flight.finish();
    if !destroyed {
        // Reinsert unless a callback replaced this id while `f` ran (the callback's own registration
        // wins); a tombstone means the callback destroyed it, so it must not come back.
        let _ = MOUNTED.try_with(|map| {
            let mut map = map.borrow_mut();
            map.entry(id).or_insert(mounted);
        });
    }
    Some(result)
}

/// Owns the in-flight marker for one registry drive that is not a dispatch, so a destroy inside the
/// drive still sticks and the marker is cleared on an unwind.
///
/// The input dispatch path has [`DispatchGuard`]; `with_widget_mut` needs the same bookkeeping for
/// the same reason (a property setter can emit a signal whose callback destroys the control), so the
/// two share the `DISPATCHING`/`DESTROYED_DURING_DISPATCH` mechanism rather than each inventing one.
struct InFlightGuard {
    id: ObjectId,
    finished: bool,
}

impl InFlightGuard {
    fn install(id: ObjectId) -> Self {
        let _ = DISPATCHING.try_with(|set| {
            set.borrow_mut().insert(id);
        });
        Self { id, finished: false }
    }

    /// Clears the marker and consumes any destroy tombstone, reporting whether the control was
    /// destroyed during the drive.
    fn finish(&mut self) -> bool {
        self.finished = true;
        let _ = DISPATCHING.try_with(|set| {
            set.borrow_mut().remove(&self.id);
        });
        DESTROYED_DURING_DISPATCH.try_with(|set| set.borrow_mut().remove(&self.id)).unwrap_or(false)
    }
}

impl Drop for InFlightGuard {
    fn drop(&mut self) {
        if !self.finished {
            let _ = DISPATCHING.try_with(|set| {
                set.borrow_mut().remove(&self.id);
            });
            let _ = DESTROYED_DURING_DISPATCH.try_with(|set| {
                set.borrow_mut().remove(&self.id);
            });
        }
    }
}

/// Runs `f` with shared access to a mounted widget.
///
/// # Why the widget is detached before `f` runs (BLUE-issue E-30)
///
/// The borrow is scoped to the *map lookup*, never to `f`. A caller may read a widget's state and then
/// synchronously trigger its signal — a legitimate `&self` operation — and the slot that runs is a user
/// callback that may update **another** control (set a `Label`, hide a `Panel`). When `f` ran inside
/// `map.borrow().get(...).map(|entry| f(...))`, that callback's `with_widget_mut` (for a different id)
/// hit `already borrowed` on the same `RefCell` and panicked. Detaching first means the registry is free
/// while `f` runs, exactly as [`with_widget_mut`] and [`dispatch_event`] already do for their entries.
///
/// While `f` runs the entry is lent out **read-only**, so a nested read of this same id still resolves
/// (see [`LENT_OUT`]) and a nested **write** to it is refused. Reads are unavailable while an outer
/// mutable operation or event dispatch holds the widget.
///
/// Returns `None` when `id` is not mounted, or when a nested call targets the id this call is reading.
pub fn with_widget<R>(id: ObjectId, f: impl FnOnce(&dyn Widget) -> R) -> Option<R> {
    // A read may nest a read of the same id (a getter that calls a getter), but a read must not be
    // turned into a write of the same id while this shared borrow is live. `with_widget_mut` already
    // refuses nested mutation of a lent-out id via `lent_mutating`; a read loan is recorded the same way
    // so the refusal is symmetric.
    if lent_present(id) {
        if lent_exclusive(id) {
            return None;
        }
        // Already lent out (an outer read of this same id): resolve through the loan, no re-detach.
        return lent_out_widget(id, f);
    }
    let taken = MOUNTED.try_with(|map| map.borrow_mut().remove(&id)).ok().flatten();
    let mounted = taken?;
    let mut in_flight = InFlightGuard::install(id);
    let _lent = LentGuard::install(
        id,
        mounted.widget.as_ref(),
        /* mutating = */ true,
        /* exclusive = */ false,
    );
    // `mutating = true` marks the id as *unavailable for nested mutation* for the loan's duration.
    // The pointer itself is shared (`&dyn Widget`), so reads still resolve through `LENT_OUT`.
    let result = f(mounted.widget.as_ref());
    drop(_lent);
    let destroyed = in_flight.finish();
    if !destroyed {
        let _ = MOUNTED.try_with(|map| {
            let mut map = map.borrow_mut();
            map.entry(id).or_insert(mounted);
        });
    }
    Some(result)
}

/// Whether `id` currently has a lent-out entry (read or mutating).
fn lent_present(id: ObjectId) -> bool {
    LENT_OUT.with(|map| map.borrow().contains_key(&id))
}

/// Runs `f` with a **read-only** view of a widget currently lent out of [`MOUNTED`].
///
/// Returns `None` when no widget is lent out under `id`. See [`LENT_OUT`] for why this exists and why
/// no mutating accessor may use it.
fn lent_out_widget<R>(id: ObjectId, f: impl FnOnce(&dyn Widget) -> R) -> Option<R> {
    if lent_exclusive(id) {
        return None;
    }
    // The pointer is copied out under a short borrow, then dereferenced with no `RefCell` borrow held:
    // the borrowed-from frame keeps the widget alive for this whole call (it will not return until the
    // callback does), so the pointer is valid here. `f` runs to completion before any other code can
    // invalidate it, so the shared reference never escapes this call.
    let ptr = LENT_OUT.with(|map| map.borrow().get(&id).copied());
    // SAFETY: the entry exists only while the owning frame is on the stack with the widget alive; the
    // shared reference produced here is consumed entirely within `f` and cannot outlive this call.
    ptr.map(|ptr| unsafe { f(ptr.as_ref()) })
}

/// Whether `id` is currently lent out **for mutation**.
///
/// A read-only lent entry may be read re-entrantly; a mutating one may not, because a nested write
/// would alias the `&mut` the driving frame holds. [`with_widget_mut`] refuses such a nested write by
/// answering `None` — an explicit "not available for writing right now" rather than an aliasing bug
/// or a silent no-op.
fn lent_mutating(id: ObjectId) -> bool {
    LENT_MUTATING.with(|set| set.borrow().contains(&id))
}

fn lent_exclusive(id: ObjectId) -> bool {
    LENT_EXCLUSIVE.with(|set| set.borrow().contains(&id))
}

/// Marks a widget as lent out of [`MOUNTED`] for the guard's lifetime, restoring the read-only path
/// and (for a mutating loan) clearing the nested-write refusal on drop.
///
/// A `Drop` guard rather than code after the call, so the loan is undone on **both** the normal return
/// and an unwind out of a user callback. A callback that panics during dispatch or a property write no
/// longer leaves the widget permanently lent out and unreachable — the shape BLUE-issue E-19 records
/// for dispatch (it applied equally to `with_widget_mut`).
struct LentGuard {
    id: ObjectId,
    mutating: bool,
    exclusive: bool,
}

impl LentGuard {
    fn install(id: ObjectId, widget: &dyn Widget, mutating: bool, exclusive: bool) -> Self {
        let ptr: core::ptr::NonNull<dyn Widget> = core::ptr::NonNull::from(widget);
        let _ = LENT_OUT.try_with(|map| {
            map.borrow_mut().insert(id, ptr);
        });
        if mutating {
            let _ = LENT_MUTATING.try_with(|set| {
                set.borrow_mut().insert(id);
            });
        }
        if exclusive {
            let _ = LENT_EXCLUSIVE.try_with(|set| {
                set.borrow_mut().insert(id);
            });
        }
        Self { id, mutating, exclusive }
    }
}

impl Drop for LentGuard {
    fn drop(&mut self) {
        let _ = LENT_OUT.try_with(|map| {
            map.borrow_mut().remove(&self.id);
        });
        if self.mutating {
            let _ = LENT_MUTATING.try_with(|set| {
                set.borrow_mut().remove(&self.id);
            });
        }
        if self.exclusive {
            let _ = LENT_EXCLUSIVE.try_with(|set| {
                set.borrow_mut().remove(&self.id);
            });
        }
    }
}

// Ids lent out for **mutation**, so a nested write to the same id can be refused.
thread_local! {
    #[allow(clippy::missing_const_for_thread_local)]
    static LENT_MUTATING: RefCell<alloc::collections::BTreeSet<ObjectId>> =
        RefCell::new(alloc::collections::BTreeSet::new());
}

/// Forwards a platform event into a mounted widget's `EventHandler`.
///
/// Returns whether the widget was found. Backends call this to deliver raw
/// platform input; coordinate translation into widget-local space is the
/// widget's responsibility (see `position_at_point`).
///
/// A modal dialog blocks delivery to anything outside its own subtree: when a modal
/// is active and `id` is not the modal (or one of its descendants), the event is
/// is dropped and `false` is returned — the same "not found" answer a hit outside any
/// widget gives, so the backend treats it as unowned input rather than an error.
pub fn dispatch_event(id: ObjectId, event: &Event) -> bool {
    if modal_blocks(id) {
        return false;
    }
    // Detach the widget from the registry for the duration of the call.
    //
    // # The re-entrancy defect this closes
    //
    // A control's `handle_event` emits its own signal synchronously when it detects the user action
    // (a `Button` emitting `clicked` on pointer release). A slot on that signal is a user callback,
    // and a user callback legitimately reads or updates widgets: it may read the button's own state,
    // set text on a `Label`, or close a window. Every one of those goes through `with_widget` /
    // `with_widget_mut`, which borrow the very `RefCell` this function used to hold mutably across
    // `handle_event` — so the callback panicked with `already borrowed`, not only for the control
    // being dispatched but for any control in the same registry. `request_redraw` (called by nearly
    // every setter) re-enters too, via `top_level_window_of`, so even a callback that touched nothing
    // could trip it.
    //
    // Taking the entry out before the call and putting it back after means the borrow is held only
    // for the two map operations, never across user code. A handler that destroys the control (or
    // remounts under the same id) is respected: see the tombstone check below.
    let taken = MOUNTED.try_with(|map| map.borrow_mut().remove(&id)).ok().flatten();
    let Some(mut mounted) = taken else {
        return false;
    };
    // Mark the id in-flight so `unregister` records a tombstone instead of searching the map.
    let _ = DISPATCHING.try_with(|set| {
        set.borrow_mut().insert(id);
    });
    // Mark the widget as exclusively lent out. `is_mounted` can still report its presence, but
    // accessors must not dereference its pointer while `handle_event` holds `&mut Widget`.
    let mut guard = DispatchGuard::install(id, mounted.widget.as_mut());

    // The handler runs outside the registry borrow. Its return type is `()`, and the contract of
    // this function answers "was the widget found?" — `true`, because the entry was present when we
    // detached it.
    //
    // # Why the cleanup is a guard and not code after the call (BLUE-issue E-19)
    //
    // A callback may unwind (the host `catch_unwind`s it). Plain cleanup after `handle_event` would
    // then be skipped: the id would stay in `DISPATCHING`, a tombstone would never be consumed, and
    // the widget would never be reinserted — so `is_mounted` answered `false` while `unregister`
    // still reported the id present. [`DispatchGuard`] runs the same cleanup on the normal return and
    // on an unwind, so the registry is consistent either way.
    guard.run(&mut mounted, event);

    let destroyed = guard.finish();
    if destroyed {
        // A handler unregistered this control. The authoritative cleanup (focus, hover, capture,
        // cached frame, own-id map) already ran inside `unregister`; only the owned widget remains,
        // and dropping it here is what actually frees the control.
        return true;
    }

    // Put it back unless a handler remounted something under the same id in the meantime — in which
    // case the handler's own registration wins and is left untouched.
    let _ = MOUNTED.try_with(|map| {
        let mut map = map.borrow_mut();
        map.entry(id).or_insert(mounted);
    });
    true
}

/// Owns the in-flight bookkeeping for one [`dispatch_event`] call, so it is undone even on an unwind.
///
/// Installs the exclusive loan ([`LENT_OUT`]), marks the id in [`DISPATCHING`], and on completion
/// clears the marker, consumes any destroy tombstone, and — for a surviving widget — removes the loan
/// so the entry can be reinserted by the caller. See BLUE-issue E-18 (self-reads) and E-19 (unwind).
struct DispatchGuard {
    id: ObjectId,
    finished: bool,
}

impl DispatchGuard {
    fn install(id: ObjectId, widget: &mut dyn Widget) -> Self {
        let ptr: core::ptr::NonNull<dyn Widget> = core::ptr::NonNull::from(widget);
        let _ = LENT_OUT.try_with(|map| {
            map.borrow_mut().insert(id, ptr);
        });
        let _ = LENT_EXCLUSIVE.try_with(|set| {
            set.borrow_mut().insert(id);
        });
        Self { id, finished: false }
    }

    /// Runs the event handler. Separated from construction so the loan is installed before the call
    /// and definitely removed after it (or during an unwind).
    fn run(&mut self, mounted: &mut Mounted, event: &Event) {
        mounted.widget.handle_event(event);
    }

    /// Completes the dispatch bookkeeping, returning whether a handler destroyed the control.
    fn finish(&mut self) -> bool {
        let _ = DISPATCHING.try_with(|set| {
            set.borrow_mut().remove(&self.id);
        });
        let destroyed = DESTROYED_DURING_DISPATCH
            .try_with(|set| set.borrow_mut().remove(&self.id))
            .unwrap_or(false);
        // The loan is released here on the normal path; the `Drop` below is the unwind path.
        let _ = LENT_OUT.try_with(|map| {
            map.borrow_mut().remove(&self.id);
        });
        let _ = LENT_EXCLUSIVE.try_with(|set| {
            set.borrow_mut().remove(&self.id);
        });
        self.finished = true;
        destroyed
    }
}

impl Drop for DispatchGuard {
    fn drop(&mut self) {
        // On the normal path `finish` already ran; this branch is the unwind path (a panicking
        // callback), where we still clear the loan and the in-flight marker so the registry is left
        // consistent. The tombstone is intentionally left for `unregister` to have recorded, and is
        // consumed by the next dispatch cleanup or the destroy itself.
        if !self.finished {
            let _ = LENT_OUT.try_with(|map| {
                map.borrow_mut().remove(&self.id);
            });
            let _ = LENT_EXCLUSIVE.try_with(|set| {
                set.borrow_mut().remove(&self.id);
            });
            let _ = DISPATCHING.try_with(|set| {
                set.borrow_mut().remove(&self.id);
            });
        }
    }
}

/// Tells `id` and every mounted descendant that their container became `width` by `height`.
///
/// # Why a subtree and not just the resized control
///
/// [`Event::Resize`] documents "the new content size in logical pixels", and the control whose
/// box actually changed is rarely the one that cares: a layout manager resizes the window, but
/// the code editor inside it is what must re-measure its visible rows. Delivering only to the
/// window would leave every nested control holding the geometry it computed for the old size —
/// exactly the staleness the event exists to announce. Each descendant receives the size of the
/// **resized container**, not of itself: the event answers "my world changed", and a control
/// reads its own rectangle through [`crate::widget_geometry`] if it needs the narrower fact.
///
/// # Why this is not `dispatch_event` in a loop by the caller
///
/// Walking the mounted tree requires the registry, which lives here. A caller that reimplemented
/// the walk would be a second, drifting definition of "the subtree".
///
/// Returns the number of controls the event reached, so a caller can tell "nothing was mounted"
/// from "everything was told".
#[cfg(not(alloc_frugal))]
pub fn dispatch_resize(id: ObjectId, width: u32, height: u32) -> usize {
    let event = Event::resize(width, height);
    let mut reached = 0;
    // The descendants are collected before delivery so a handler that mounts or destroys
    // controls cannot make the walk observe a half-updated registry.
    let mut targets = alloc::vec::Vec::new();
    collect_subtree_ids(id, &mut targets);
    for target in targets {
        if dispatch_event(target, &event) {
            reached += 1;
        }
    }
    reached
}

/// Collects `id` and every mounted descendant into `out`, parents before children.
///
/// The traversal goes through [`crate::widget::Widget::children`] (via [`direct_children_of`]),
/// which is the single definition of "the mounted tree" — the same source the hit-testing and
/// damage walks use, so the three cannot disagree about what a subtree is.
#[cfg(not(alloc_frugal))]
fn collect_subtree_ids(id: ObjectId, out: &mut alloc::vec::Vec<ObjectId>) {
    out.push(id);
    for child in direct_children_of(id) {
        collect_subtree_ids(child, out);
    }
}

/// An input fact a platform backend knows about a control it drew itself.
///
/// # Why a native backend reports rather than the library probing
///
/// A native control's hover, press and focus are the *platform's* facts: GTK knows them
/// through `enter-notify-event`, Win32 through `WM_MOUSEMOVE`, AppKit through `mouseEntered:`.
/// The library cannot discover them — it does not own the pixels (BLUE24 §7.1) — but it can
/// be *told*, and this enum is the vocabulary.
///
/// # Why "report" is not "guess"
///
/// The backend already has these facts, because it must handle input to work at all. So this
/// is a report of something known, not an inference: the backend is the authority on its own
/// control's state, exactly as [`crate::widget::BaseWidget`] is the authority on a
/// self-painted control's.
///
/// # Why this is not the whole [`crate::event::Event`] vocabulary
///
/// Because the platform is *not* delivering an event to the library — the control is native
/// and its own toolkit consumed the event. What crosses the boundary is only the state that
/// the library needs to answer `widget_state()`, which is what makes a theme's
/// `"<kind>:hover"` apply to a native control. A backend that wants to deliver a real event
/// uses [`dispatch_event`] instead; the two are complementary.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateFact {
    /// The pointer entered (`true`) or left (`false`) the control.
    Hovered(bool),
    /// The control is being held down (`true`) or was released (`false`).
    Pressed(bool),
    /// The control gained (`true`) or lost (`false`) keyboard focus.
    Focused(bool),
    /// The control was enabled (`true`) or disabled (`false`).
    Enabled(bool),
}

/// Reports an input fact a platform backend observed about a control it drew itself.
///
/// See [`StateFact`] for why a backend reports rather than the library probing. Returns
/// whether the fact was applied, i.e. whether `id` is a mounted control; a backend that
/// reports on a control the library does not know about learns that immediately rather than
/// silently having the fact dropped.
///
/// # What it changes
///
/// It writes the same [`crate::widget::BaseWidget`] fields that a self-painted control's own
/// event path writes, so from that point on `widget_state()` is as true for a native control
/// as for a self-painted one and the theme's `<kind>:<state>` overrides apply to both worlds.
/// A control that has already been told the same fact is **not** changed again, so a backend
/// that reports on every mouse move costs one comparison rather than a restyle per sample.
pub fn report_state(id: ObjectId, fact: StateFact) -> bool {
    let Some(changed) = with_widget_mut(id, |widget| {
        let base = widget.base_mut();
        match fact {
            StateFact::Hovered(hovered) => {
                if base.is_hovered() == hovered {
                    return false;
                }
                base.set_hovered(hovered);
            }
            StateFact::Pressed(pressed) => {
                if base.is_pressed() == pressed {
                    return false;
                }
                base.set_pressed(pressed);
            }
            StateFact::Focused(focused) => {
                let already = base.focus_reason().is_some();
                if already == focused {
                    return false;
                }
                // `Programmatic` because the library did not observe the navigation that
                // moved focus -- the native toolkit did. Claiming `Tab` would assert the user
                // pressed Tab, and claiming `Pointer` would suppress the ring; "the
                // application (here: the platform) moved focus" is the honest reading, and it
                // is the variant that keeps the ring's meaning intact.
                base.set_focus_reason(if focused {
                    Some(crate::event::FocusReason::Programmatic)
                } else {
                    None
                });
            }
            StateFact::Enabled(enabled) => {
                if base.is_enabled() == enabled {
                    return false;
                }
                base.set_enabled(enabled);
            }
        }
        true
    }) else {
        return false;
    };

    // A state change the theme can see is a repaint worth requesting, and it is also a change
    // a screen reader should hear about (BLUE24 §6.3's submit points 4/5 are the same event
    // for a self-painted control). Reporting the fact is therefore not complete until both
    // have been told, which is why they are here rather than at each backend's call site: a
    // backend that forgot one would make its control the only one whose hover neither painted
    // nor announced.
    if changed {
        // A backend reports into `BaseWidget` directly, which bypasses the `Widget::set_enabled`
        // default that re-resolves the theme — so the `"<kind>:disabled"` key would be reachable
        // for a self-painted control and unreachable for a native one, from the same fact. This
        // makes the native path go through the same door the self-painted path does, rather than
        // relying on a backend to remember a second call.
        with_widget_mut(id, crate::style::reapply_active_theme_state);
        request_repaint_because(id, RepaintReason::State);
        crate::widget::a11y_submit::submit_state_changed(id);
    }
    true
}

/// Opens `menu_id` as a context menu at `position`, clamped to `viewport`.
///
/// This is the one operation a right-click needs, and it lives here rather than in
/// each widget because a context menu is opened *at a pointer position on another
/// widget*: the target widget knows the position, the menu owns the popup, and the
/// registry is the only thing that can reach both.
///
/// Returns `false` when `menu_id` is not a mounted menu, or when it is not a menu
/// at all — the honest answer, reported instead of a silent no-op, so a caller
/// wiring a right-click handler learns immediately that it pointed at the wrong id.
///
/// Gated with the menu widget itself: a profile that compiles `Menu` out has no
/// context menu to open, and reporting that at compile time is more useful than a
/// function that could only ever return `false`.
#[cfg(full_widgets)]
pub fn open_context_menu(menu_id: ObjectId, position: Point, viewport: Rect) -> bool {
    with_widget_mut(menu_id, |widget| {
        let Some(menu) = (widget as &mut dyn core::any::Any).downcast_mut::<crate::Menu>() else {
            log::warn!(
                "widget::runtime: id {menu_id} is not a menu, so a context menu cannot be opened \
                 at {position:?}"
            );
            return false;
        };
        menu.open_at(position, viewport);
        true
    })
    .unwrap_or_else(|| {
        log::warn!("widget::runtime: no widget is mounted as id {menu_id}");
        false
    })
}

/// Opens the context menu at the pointer position of a secondary-button press.
///
/// Convenience for the common wiring: a widget forwards its right-clicks here and
/// the menu appears where the user clicked. Returns `false` for any event that is
/// not a secondary-button press, or when the menu cannot be opened — so a caller
/// can pass every event through without testing the button itself.
#[cfg(full_widgets)]
pub fn open_context_menu_for_event(menu_id: ObjectId, event: &Event, viewport: Rect) -> bool {
    let Event::MousePress { pos, button, .. } = event else {
        return false;
    };
    if *button != crate::event::mouse_button::SECONDARY {
        return false;
    }
    open_context_menu(menu_id, *pos, viewport)
}

/// Asks the platform to repaint a mounted widget.
///
/// Call this after mutating a widget through [`with_widget_mut`] so the change
/// becomes visible. Backends route it to their own invalidation (`setNeedsDisplay:`
/// on macOS, `InvalidateRect` on Windows, `queue_draw` on GTK); a backend that
/// never mounted the widget simply does nothing.
///
/// # It is the `Full` arm of the same submission `mark_dirty_rect` makes
///
/// A control in [`RepaintMode::Full`] -- the default, and the mode a control starts in
/// -- repaints everything, so it has no rectangle to record and reaches the platform
/// here directly. Both arms therefore count against the frame at their one point of
/// submission; doing it in a wrapper instead would leave the dirty-rect arm counted
/// twice.
pub fn request_repaint(id: ObjectId) {
    request_repaint_because(id, RepaintReason::Explicit);
}

/// Returns the top-level **window** widget that `id` lives under, if any.
///
/// Walks the parent links up to the root and reports it only when the root is a
/// `WidgetKind::Window`. A widget mounted with no window above it (a test fixture, a
/// surface the host parented itself) answers `None`, which is the honest result: there
/// is no window whose invalidation would reveal the change.
///
/// The walk is bounded by `max_depth` steps so a corrupted parent chain — a cycle, or a
/// link to an id that was recycled — cannot hang a paint path. Hitting the bound is
/// reported as `None` rather than guessed at.
pub fn top_level_window_of(id: ObjectId) -> Option<ObjectId> {
    // A widget tree is shallow (window → containers → controls); 64 is far past any real
    // depth and still a bound rather than a loop that trusts the data.
    const MAX_DEPTH: usize = 64;
    let mut current = id;
    for _ in 0..MAX_DEPTH {
        let (kind, parent) = with_widget(current, |widget| (widget.kind(), widget.parent()))?;
        if kind == crate::widget::WidgetKind::Window {
            return Some(current);
        }
        current = parent?;
    }
    None
}

/// Repaints a widget **and the window it lives in**.
///
/// # Why invalidating the control alone is not enough
///
/// Since 2.0 the library paints every `WidgetKind` itself, so most controls have no
/// native surface of their own and `invalidate_surface(control)` reaches nothing. On a
/// backend whose window paints its whole child list (Windows, Linux), the thing that
/// must be invalidated is the **window**: its `WM_PAINT` / `connect_draw` redraws the
/// tree the control belongs to.
///
/// A mounted surface is still invalidated too — it paints itself, and on macOS that is
/// the only path a control has. Both calls are made and neither is treated as a failure
/// when it answers `false`: which of the two the backend can honour is the backend's
/// business, not this function's.
pub fn request_repaint_subtree(id: ObjectId) {
    // The window first, so a backend that coalesces per frame folds the control's own
    // request into the frame the window is already going to repaint.
    if let Some(window) = top_level_window_of(id) {
        request_repaint_because(window, RepaintReason::Explicit);
    }
    request_repaint_because(id, RepaintReason::Explicit);
}

/// Asks the platform to repaint a mounted widget, naming **why** it is being asked.
///
/// # Why the reason is a parameter and not inferred
///
/// A caller knows the cause and the runtime does not: a hover finished (state), a value
/// interpolation advanced (animation), an overlay appeared (overlay). Inferring it here would
/// mean guessing from a stack that has already returned, and a wrong reason is worse than none
/// because the frame ledger's whole purpose is to let a reader act on it (BLUE24 §8).
///
/// # Coalescing
///
/// A request for a surface already repainted this frame is folded into it and counted as
/// coalesced; see [`note_frame_repaint_reason`].
pub fn request_repaint_because(id: ObjectId, reason: RepaintReason) {
    if crate::invalidate_surface(id) {
        note_frame_repaint_reason(id, reason);
    }
}

/// Tells the library that a **platform-owned surface** needs to be redrawn.
///
/// # Why the platform must come through here
///
/// A native control owns its own pixels (BLUE24 §7.1), so the platform can and must ask for
/// its own repaint. What it must not do is ask *without telling the library*, because three
/// things then stop being true at once:
///
/// 1. `performance::render_dirty_regions` computes damage the frame never actually submitted,
///    so "what did this frame paint?" has no answer;
/// 2. the still-frame guarantee (BLUE24 §1 criterion 2 — an idle window submits nothing) can
///    no longer be shown, so "smooth is not paid for with a burning core" is unprovable;
/// 3. the self-painted and native worlds each keep their own count, so one interaction is
///    submitted twice.
///
/// So a backend routes its own redraw requests through this function. It is the *same* ledger
/// [`request_repaint`] writes to, so a frame that mixed the two worlds still reports one
/// coherent account.
///
/// `rect` is the damaged region when the platform can name one. It is **not** used to narrow
/// the submission (the platform has already decided what it needs to repaint, and second-
/// guessing it here would be the library inventing a claim about pixels it does not own), but
/// it is recorded, so the ledger can distinguish a full-surface redraw from a partial one.
pub fn notify_native_redraw(id: ObjectId, rect: Option<Rect>) {
    // The platform has already invalidated its own surface; this call exists so the *library*
    // learns about it. Recording the region keeps the account complete even though the
    // submission is the platform's.
    let _ = rect;
    note_frame_repaint_reason(id, RepaintReason::Native);
}

/// How much of a frame the render loop repaints.
///
/// # Why this is a policy rather than a switch
///
/// Damage tracking is not unconditionally faster. It wins when a few controls
/// change and the window is large, and it *loses* when the whole surface is moving
/// — an animation, a scroll, a video — because then the union of damage rects grows
/// to the full frame while the tracker still pays to merge and clip regions. A
/// boolean would force every caller to know which case it is in; this type lets the
/// library decide, and lets `Adaptive` learn from what actually happened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RepaintMode {
    /// Repaint the whole surface every frame, ignoring damage. The historical
    /// behaviour, and the default.
    #[default]
    Full,
    /// Repaint only the damage regions, merging overlapping ones.
    Dirty,
    /// Start in [`Self::Dirty`] and fall back to [`Self::Full`] for a frame whose
    /// damage covers most of the surface.
    ///
    /// The fallback is per-frame rather than sticky: a window that animates for a
    /// second and then settles returns to damage-tracked repaints on its own,
    /// which a one-way latch could not do.
    Adaptive,
}

/// Damage tracked since the last frame, and the policy that decides how to use it.
///
/// Held per mounted widget, beside the widget itself, so a damage region cannot
/// outlive the control it describes.
struct RepaintState {
    mode: RepaintMode,
    tracker: crate::performance::DirtyRegionTracker,
    /// Consecutive frames whose damage covered too much of the surface to be worth
    /// regioning, while the mode was [`RepaintMode::Adaptive`].
    ///
    /// # What this counter is for
    ///
    /// `Adaptive` and `Dirty` are not the same policy, and before this counter they
    /// behaved identically: both delegated to `render_dirty_regions`, which decides
    /// per frame whether to fall back. The difference is what each mode knows.
    ///
    /// `Dirty` means the caller has already decided that damage tracking is worth it,
    /// so every frame is measured against the damage. `Adaptive` means the caller does
    /// not know, and expects the library to work it out — so a run of frames whose
    /// damage covers the surface is evidence that regioning cannot pay off *here*, and
    /// measuring each of them again is work whose answer is already known.
    ///
    /// After [`ADAPTIVE_LARGE_DAMAGE_RUN`] such frames the next frame skips the
    /// regioning entirely and paints whole. One frame with small damage resets the
    /// counter, so settling back into a few changing controls returns to regioning on
    /// its own rather than staying latched.
    large_damage_run: u32,
}

/// Consecutive over-threshold frames in [`RepaintMode::Adaptive`] before it stops
/// measuring and paints whole.
///
/// Three, because two could be a coincidence — a resize legitimately damages
/// everything once or twice — while a fourth measurement of the same answer is pure
/// overhead. The counter is reset by any frame whose damage is small, so the cost of
/// guessing wrong here is one extra full paint.
pub const ADAPTIVE_LARGE_DAMAGE_RUN: u32 = 3;

impl RepaintState {
    fn new() -> Self {
        Self {
            mode: RepaintMode::default(),
            tracker: crate::performance::DirtyRegionTracker::new(),
            large_damage_run: 0,
        }
    }
}

/// Records that a widget asked to be repainted, resolving its registry id.
///
/// # Why the id needs resolving
///
/// A widget knows its own `BaseWidget::id()` (its `Object`'s counter), but the runtime
/// registry keys widgets by an id it allocates in [`register`]. The two spaces are
/// **not** the same number: a freshly built control reports `1` while the registry
/// handed out `0x5345_4C46_0000_0001`. So a damage record keyed on the widget's own id
/// would be filed under a widget that does not exist, be silently dropped, and leave
/// partial repaint unreachable — which is exactly what happened before
/// [`register`] started recording the mapping.
///
/// # Why a lookup rather than passing the id down
///
/// [`BaseWidget::request_redraw`](crate::widget::BaseWidget::request_redraw) takes
/// `&self` and is called from ~1000 places that have no idea what the registry called
/// them. Threading a registry id through all of them is what would make partial repaint
/// a list someone must keep complete; resolving it here keeps the producer at one
/// chokepoint.
///
/// Returns `true` when the damage was recorded (i.e. the widget opted in and is
/// registered).
pub(crate) fn mark_widget_damage(own_id: ObjectId, rect: Rect) -> bool {
    let Some(registry_id) = registry_id_of(own_id) else {
        // Not registered yet: a control being constructed, or one a test built and never
        // mounted. There is no surface to repaint, so there is nothing to record — and
        // nothing to remember either, because these run before `register`.
        return false;
    };
    mark_dirty_rect(registry_id, rect)
}

/// The registry id for a widget that reported `own_id` as its `BaseWidget::id()`.
///
/// `None` when the widget was never registered. See `mark_widget_damage` for why the
/// two id spaces exist and why this lookup is necessary.
pub fn registry_id_of(own_id: ObjectId) -> Option<ObjectId> {
    OWN_IDS.try_with(|map| map.borrow().get(&own_id).copied()).ok().flatten()
}

/// Enables damage-tracked repaint for `id`, returning whether it took effect.
///
/// # The auto-decision entry point
///
/// [`RepaintMode::Adaptive`] is the mode to use when you do not know whether regioning
/// pays off: the library consults the damage each frame and stops measuring after a run
/// of frames whose damage covers the surface — an animation, a scroll, a video — where
/// the union of regions grows to the full frame anyway. It resumes regioning as soon as
/// one frame reports small damage, so a window that animates briefly and then settles
/// returns to partial repaints on its own.
///
/// Returns `false` when `id` is not a mounted widget, which is the same condition
/// [`set_repaint_mode`] reports.
pub fn set_repaint_mode_adaptive(id: ObjectId) -> bool {
    set_repaint_mode(id, RepaintMode::Adaptive)
}

/// Whether damage-tracked repaint is worth enabling for `id` — the library's own
/// decision, so a caller does not have to guess.
///
/// # The judgement, and why it is this shape
///
/// Damage tracking is not unconditionally faster. It wins when a few controls change in
/// a large surface, and it *loses* on a small one: the tracker still pays to merge, sort
/// and clip regions, and once damage covers most of the frame the clip discards work
/// that was already done — so the regioning costs more than the pixels it saves.
///
/// The decision is deliberately **two-sided**:
///
/// * **Too few controls** — with one control, damage is that control's whole rect, which
///   is the whole frame; regioning buys nothing and costs the bookkeeping.
/// * **Too small a surface** — below [`AUTO_REPAINT_MIN_PIXELS`] the per-frame cost of
///   merging and clipping regions is a meaningful fraction of just painting everything.
///
/// # Why it is safe to say "yes" by default
///
/// Saying yes selects [`RepaintMode::Adaptive`], which is **self-correcting**: a frame
/// whose damage covers too much of the surface falls back to a whole paint for that
/// frame, and a run of such frames stops the measurement entirely until the damage
/// shrinks. So a wrong "yes" costs a bounded amount of bookkeeping on the frames that
/// follow, never a wrong frame — and the pixels are identical either way, which
/// `an_incremental_repaint_matches_a_full_repaint` asserts.
///
/// # Who calls it
///
/// [`register`] does, once per control, the moment it is mounted. That is the only
/// automatic call site: it is the first point at which the control's geometry and its
/// children are both known, and it costs the caller nothing. Every control on a device
/// profile therefore answers this question exactly once, without a host having to know
/// its own frame pattern in advance.
///
/// Nothing is enabled for a control the library judged not worth it: it keeps `Full`,
/// and `mark_widget_damage` is a single map lookup that returns `false`. A host that
/// disagrees can call [`set_repaint_mode`] directly and get exactly what it asked for,
/// which is why the threshold is a named constant rather than a magic number.
pub fn should_track_damage(id: ObjectId) -> bool {
    // A record is only worth keeping for a control that ever asked to be repainted,
    // because a surface nothing redraws gains nothing from a region clip and still pays
    // the bookkeeping. The flag is read off the widget, not from a table keyed by
    // registry id: a control whose constructor prepares its first frame asks *before*
    // `register` runs, when no registry id exists to file the request against.
    if !has_ever_requested_redraw(id) {
        return false;
    }

    let Some(geometry) = geometry_of(id) else {
        return false;
    };
    let pixels = u64::from(geometry.width) * u64::from(geometry.height);
    if pixels < AUTO_REPAINT_MIN_PIXELS {
        return false;
    }

    // A control with no children is one rect: damage is the whole control, so the clip
    // cannot narrow anything. Counted through the widget rather than the tree so a
    // caller need not build one.
    let has_children =
        with_widget(id, |widget| !widget.base().children().is_empty()).unwrap_or(false);
    has_children
}

/// Pixels below which damage tracking is not offered by [`should_track_damage`].
///
/// A quarter megapixel — roughly 500×500. Below it the merge/sort/clip bookkeeping is a
/// measurable share of the cost of painting the whole surface, and the surface is small
/// enough that painting it whole is already cheap. The value is a judgement rather than a
/// measurement, so it is named and exposed: a caller who disagrees can call
/// [`set_repaint_mode`] directly and get exactly what it asked for.
pub const AUTO_REPAINT_MIN_PIXELS: u64 = 250_000;

/// Whether `id`'s widget has ever asked to be repainted.
///
/// The flag is read from the widget rather than kept in a table keyed by registry id,
/// because a request can arrive before there is a registry id to file it against — a
/// constructor that prepares its own first frame calls `request_redraw` while the
/// control is still being built. A table could only be written after `register`, so such
/// a control would be judged "silent" for the rest of its life. Asking the widget
/// answers the same question the request actually made.
fn has_ever_requested_redraw(id: ObjectId) -> bool {
    with_widget(id, |widget| widget.has_ever_requested_redraw()).unwrap_or(false)
}

/// Enables damage tracking for `id` **if the library judges it worthwhile**, returning
/// whether it did.
///
/// This is the one-call form of [`should_track_damage`] + [`set_repaint_mode_adaptive`],
/// for a host that wants the benefit without analysing its own frame pattern:
///
/// ```no_run
/// # use rust_widgets::widget::runtime::*;
/// # fn example(window: rust_widgets::core::ObjectId) {
/// if enable_damage_tracking_if_useful(window) {
///     // partial repaints from here on; `render_frame_incremental` uses them
/// }
/// # }
/// ```
///
/// A `false` return is not an error — it means the whole-frame path is already the right
/// answer for this widget, so there is nothing to gain and no bookkeeping to pay for.
pub fn enable_damage_tracking_if_useful(id: ObjectId) -> bool {
    if !should_track_damage(id) {
        return false;
    }
    set_repaint_mode_adaptive(id)
}

thread_local! {
    /// The widget registry id for a widget's own `BaseWidget::id()`.
    ///
    /// # Two id spaces, one lookup
    ///
    /// `register` allocates a registry id and keys [`MOUNTED`] by it, while a widget's
    /// `BaseWidget::id()` comes from its own `Object` counter. Those numbers differ (a
    /// fresh control reports `1`; the registry hands out
    /// `0x5345_4C46_0000_0001`), so a call that only has the widget's own id —
    /// `request_redraw`, called from `&self` in ~1000 places — cannot address the
    /// registry without this map.
    ///
    /// Kept here rather than on the widget so it cannot go stale on a move, and so a
    /// widget that is dropped with the registry still holding it cannot be resurrected.
    #[allow(clippy::missing_const_for_thread_local)]
    static OWN_IDS: RefCell<HashMap<ObjectId, ObjectId>> = RefCell::new(HashMap::new());

    /// Per-widget repaint state, keyed by the same id as `MOUNTED`.
    ///
    /// A separate cell rather than a field on `Mounted` so the damage tracker can
    /// be mutated while a widget is borrowed mutably — the render path holds a
    /// `&mut dyn Widget` across the whole draw, and would otherwise deadlock.
    #[allow(clippy::missing_const_for_thread_local)]
    static REPAINT: RefCell<HashMap<ObjectId, RepaintState>> = RefCell::new(HashMap::new());

    /// The most recently rendered frame per widget, so an incremental repaint has
    /// something to carry forward.
    ///
    /// # Why this lives here rather than in each backend
    ///
    /// Every backend that draws a mounted widget needs the previous frame to seed a
    /// partial repaint, and all three would otherwise keep their own copy — three
    /// caches answering the same question, each free to forget to invalidate on a
    /// resize. Keeping it beside the damage tracker means the frame and the damage it
    /// describes cannot get out of step.
    ///
    /// # Why the frame is shared, not owned (D09-RENDER-04)
    ///
    /// The frame is held behind an [`Rc`] so handing it to an incremental repaint —
    /// or answering a frame that has no damage — is a pointer clone, not a `width * height * 4`
    /// copy. Before this, `render_frame_cached` cloned the whole buffer to obtain `previous`,
    /// then `render_frame_incremental` copied it again to return it, then the result was cloned
    /// once more into this cache: three full-frame copies for a frame that drew nothing.
    #[allow(clippy::missing_const_for_thread_local)]
    static LAST_FRAME: RefCell<HashMap<ObjectId, (Size, Rc<Vec<u8>>)>> =
        RefCell::new(HashMap::new());
}

// Counts full-frame buffer copies performed by the incremental frame cache. Test-only.
//
// # Why a counter rather than a custom allocator (D09-RENDER-04)
//
// The defect is a *count* — a no-damage frame copied its RGBA buffer three times. A global
// `GlobalAlloc` shim would count every allocation in the process, including the renderer's own
// scratch buffers, and could not separate the cache's copies from them. The cache performs a
// small, known set of full-buffer copies, so counting exactly those is the precise witness the
// regression test asserts on. Compiled only under `cfg(test)` (principle #28).
#[cfg(test)]
thread_local! {
    #[allow(clippy::missing_const_for_thread_local)]
    static FRAME_CACHE_COPIES: core::cell::Cell<usize> = const { core::cell::Cell::new(0) };
}

/// Records one full-frame copy made by the incremental cache. (D09-RENDER-04)
#[cfg(test)]
fn note_frame_cache_copy() {
    FRAME_CACHE_COPIES.with(|cell| cell.set(cell.get() + 1));
}

/// Resets and returns the full-frame copy counter. (D09-RENDER-04)
#[cfg(test)]
pub(crate) fn take_frame_cache_copies() -> usize {
    FRAME_CACHE_COPIES.with(|cell| cell.replace(0))
}

/// No-op stand-in so non-test builds compile the same call sites. (D09-RENDER-04)
#[cfg(not(test))]
#[inline(always)]
fn note_frame_cache_copy() {}

/// Sets the repaint policy for a mounted widget.
///
/// Returns `false` when `id` is not mounted, so a caller can tell "policy set" from
/// "there was nothing to set it on". Switching to [`RepaintMode::Full`] clears any
/// accumulated damage, so a later switch back to [`RepaintMode::Dirty`] does not
/// repaint a region that stopped being interesting several frames ago.
pub fn set_repaint_mode(id: ObjectId, mode: RepaintMode) -> bool {
    let mounted = MOUNTED.try_with(|m| m.borrow().contains_key(&id)).unwrap_or(false);
    if !mounted {
        return false;
    }
    let _ = REPAINT.try_with(|map| {
        let mut map = map.borrow_mut();
        let state = map.entry(id).or_insert_with(RepaintState::new);
        state.mode = mode;
        if mode == RepaintMode::Full {
            state.tracker.clear();
        }
    });
    true
}

/// The repaint policy in force for `id`.
///
/// A widget with no recorded policy reports [`RepaintMode::Full`], which is what it
/// actually gets, rather than a "not configured" state a caller would have to
/// translate.
pub fn repaint_mode(id: ObjectId) -> RepaintMode {
    REPAINT
        .try_with(|map| map.borrow().get(&id).map(|state| state.mode))
        .ok()
        .flatten()
        .unwrap_or_default()
}

/// Marks `rect` as needing repaint on the next frame.
///
/// A no-op for a widget in [`RepaintMode::Full`], because that mode repaints
/// everything anyway and accumulating rects it will never read would be waste.
///
/// # It also tells the platform
///
/// Tracking damage and repainting it are two halves of one feature. The tracker says
/// *what* to redraw when the library renders the frame; the platform call says *when*
/// to redraw at all. Without the second half a caller would record damage that nothing
/// ever asked to be shown.
///
/// The platform call is [`crate::platform::Platform::invalidate_surface_rect`], which
/// narrows the repaint when the backend can. When it cannot — and the default cannot —
/// the whole control is invalidated instead, because a correct repaint is worth more
/// than a narrow one.
///
/// Returns `true` when the damage was recorded.
///
/// # The region count is bounded here (D09-RENDER-01)
///
/// The tracker a widget accumulates damage in has a `max_regions` limit, but that limit only
/// took effect in `optimize()` — which this module never calls — so a widget invalidating many
/// small rectangles in one frame grew the tracker without bound. Downstream that meant a
/// quadratic `merge`, and up to one full widget-tree traversal per region. The bound is applied
/// at the point damage is recorded: past the limit, the tracked regions are folded into their
/// single bounding rectangle, which keeps one region and loses no pixels. `merge` and the
/// per-region repaint then each stay bounded.
///
/// The fold happens rather than an early return because dropping damage would be a wrong
/// picture — see [`crate::performance::DirtyRegionTracker::add_coalescing_beyond_capacity`].
pub fn mark_dirty_rect(id: ObjectId, rect: Rect) -> bool {
    let recorded = REPAINT
        .try_with(|map| {
            let mut map = map.borrow_mut();
            let Some(state) = map.get_mut(&id) else {
                return false;
            };
            if state.mode == RepaintMode::Full {
                return false;
            }
            state.tracker.add_coalescing_beyond_capacity(rect);
            true
        })
        .ok()
        .unwrap_or(false);

    if recorded {
        // Narrow when the backend can express it; otherwise fall back to invalidating
        // the whole control. `request_repaint` is the same call the `Full` path uses,
        // so the fallback needs no special handling here.
        if !crate::invalidate_surface_rect(id, rect) {
            crate::invalidate_surface(id);
        }
        // Account for it against this frame, so `drive_frame`'s `repaints_submitted`
        // reports what the frame actually cost rather than a second bookkeeping pass
        // that would have to re-derive it. A damage rectangle is a state change by
        // construction: the caller is telling the library which pixels it just invalidated.
        note_frame_repaint_reason(id, RepaintReason::State);
    }
    recorded
}

/// The damage accumulated for `id` since the last frame, as rectangles.
///
/// Exposed so a backend can hand the regions to its own compositor instead of
/// using `render_frame_incremental` — a GPU backend wants scissor rects, not a
/// software repaint.
pub fn dirty_rects(id: ObjectId) -> Vec<Rect> {
    let mut tracker = REPAINT
        .try_with(|map| {
            map.borrow().get(&id).map(|state| {
                let mut copy = crate::performance::DirtyRegionTracker::new();
                for region in state.tracker.regions() {
                    copy.add(region.rect);
                }
                copy
            })
        })
        .ok()
        .flatten()
        .unwrap_or_default();
    tracker.merge();
    tracker.regions().iter().map(|region| region.rect).collect()
}

/// Renders one frame, repainting only the damage when the policy allows it.
///
/// # Why the full frame is still returned
///
/// The return value is a complete `size.width * size.height * 4` buffer in every
/// mode, because a caller presents a frame and cannot present a rectangle. The
/// saving is in what is *drawn*, not in what is *returned*: in `Dirty` mode only the
/// damaged area is re-rasterised, and the untouched pixels are whatever the previous
/// frame left. Rebuilding the whole buffer per frame would give up that saving,
/// so `previous` carries the last frame in.
///
/// `previous` must be a buffer from an earlier call for the same widget and size.
/// Passing `None` forces a full paint, which is the honest answer when there is no
/// frame to preserve.
pub fn render_frame_incremental(
    id: ObjectId,
    size: Size,
    clear: crate::core::Color,
    previous: Option<&[u8]>,
) -> Option<Vec<u8>> {
    if size.width == 0 || size.height == 0 {
        return None;
    }

    let mode = repaint_mode(id);
    let expected = size.width as usize * size.height as usize * 4;
    // A buffer of the wrong size cannot be carried forward, so treat it as absent
    // rather than reading past its end.
    let carried = previous.filter(|buffer| buffer.len() == expected);

    let use_dirty = mode != RepaintMode::Full && carried.is_some() && !dirty_rects(id).is_empty();
    if mode == RepaintMode::Full || carried.is_none() {
        if let Some(frame) = render_frame(id, size, clear) {
            let _ = REPAINT.try_with(|map| {
                if let Some(state) = map.borrow_mut().get_mut(&id) {
                    state.tracker.clear();
                    // A full paint is not "large damage" evidence: it may be the first
                    // frame, or a resize. Resetting here keeps `Adaptive` from reading
                    // its own fallbacks as proof that damage tracking is hopeless.
                    state.large_damage_run = 0;
                }
            });
            return Some(frame);
        }
        return None;
    }

    // Measured *before* the regions are handed to `render_dirty_regions`, which clears
    // the tracker as it paints. Both the `Adaptive` decision and the run counter need
    // this frame's coverage, and after the call there is nothing left to measure.
    let covered_too_much = {
        let frame_area = u64::from(size.width) * u64::from(size.height);
        let covered: u64 =
            dirty_rects(id).iter().map(|rect| u64::from(rect.width) * u64::from(rect.height)).sum();
        frame_area == 0
            || (covered as f32)
                >= (frame_area as f32) * crate::performance::render_dirty::FULL_REPAINT_AREA_RATIO
    };

    // `Adaptive` decides for itself whether measuring is worth it.
    //
    // This is the whole difference between `Adaptive` and `Dirty`. `Dirty` means the
    // caller has already decided, so every frame is measured. `Adaptive` means the
    // caller does not know, so a run of frames whose damage covers the surface is
    // taken as evidence that regioning cannot pay off here.
    //
    // # Why the run is checked *and* this frame's damage is measured
    //
    // The first version skipped regioning whenever the run was full, without looking
    // at the current frame — so a single small change after three large ones still
    // painted whole, and the run could never be cleared because the code that clears
    // it was never reached. The mode latched. Checking both conditions means the run
    // is only trusted while it is still true: as soon as a frame's damage is small,
    // that frame is measured (and resets the run), and the next frame regions again.
    if mode == RepaintMode::Adaptive {
        let learned = REPAINT
            .try_with(|map| {
                map.borrow()
                    .get(&id)
                    .is_some_and(|state| state.large_damage_run >= ADAPTIVE_LARGE_DAMAGE_RUN)
            })
            .unwrap_or(false);
        if learned && covered_too_much {
            if let Some(frame) = render_frame(id, size, clear) {
                let _ = REPAINT.try_with(|map| {
                    if let Some(state) = map.borrow_mut().get_mut(&id) {
                        state.tracker.clear();
                    }
                });
                return Some(frame);
            }
            return None;
        }
    }

    if !use_dirty {
        // Nothing was damaged: the previous frame is still correct, and redrawing
        // it would be work for no visible change.
        //
        // This is also the reset point for the `Adaptive` run: a frame with no damage
        // is proof the surface has settled.
        let _ = REPAINT.try_with(|map| {
            if let Some(state) = map.borrow_mut().get_mut(&id) {
                state.large_damage_run = 0;
            }
        });
        return Some(carried?.to_vec());
    }

    let mut backend = SoftwarePaintBackend::new(size, 1.0);
    // Seed the backend with the previous frame so the regions this pass does not
    // touch keep their pixels.
    backend.seed_from(carried?);

    // The widget draws in absolute coordinates and the frame is its own box, so the
    // frame origin is subtracted (see `render_frame`). This must be pushed *before*
    // the clip rectangles, which are also absolute, so that both translate together.
    let origin = frame_origin(id);

    let mut tracker = REPAINT
        .try_with(|map| {
            map.borrow_mut().get_mut(&id).map(|state| {
                // Feed the `Adaptive` run counter — **only** in `Adaptive`. Updating it
                // in `Dirty` too was the first version of this code, and it made the two
                // modes observably identical again from the outside: `Dirty` reported a
                // growing run while its contract says it never learns. The counter is
                // `Adaptive`'s memory, so only `Adaptive` may write it.
                if mode == RepaintMode::Adaptive {
                    state.large_damage_run =
                        if covered_too_much { state.large_damage_run.saturating_add(1) } else { 0 };
                }
                let mut taken = crate::performance::DirtyRegionTracker::new();
                for region in state.tracker.regions() {
                    taken.add(region.rect);
                }
                state.tracker.clear();
                taken
            })
        })
        .ok()
        .flatten()?;
    tracker.merge();

    let painted = with_widget_mut(id, |widget| {
        let Some(drawable) = widget.as_draw_mut() else {
            return false;
        };
        {
            let mut context = RenderContext::new(&mut backend);
            context.push_offset(-origin.0, -origin.1);
            crate::performance::render_dirty_regions(&mut tracker, &mut context, |ctx| {
                drawable.draw(ctx);
            });
            context.pop_offset();
        }
        // Present the back buffer this pass drew into. Without this the frame read
        // below comes from the front buffer, which still holds the *pre-seed* state
        // — the seed went into `back`, so the untouched regions would read as blank
        // instead of as the previous frame.
        backend.end_frame();
        true
    })?;
    if !painted {
        return None;
    }
    Some(backend.frame_rgba().to_vec())
}

/// Renders the next frame of a mounted widget, reusing the previous one when the
/// repaint policy allows.
///
/// This is the entry point a backend's paint callback should call, and it is the one
/// that makes [`RepaintMode`] reach the screen. It differs from
/// [`render_frame_incremental`] in owning the previous frame: the caller passes only
/// the widget and the size, and this function remembers what it last produced.
///
/// # Why the cache is keyed by size
///
/// A frame of the wrong size cannot seed a repaint — it would be copied into a larger
/// surface leaving the tail untouched, or truncated. Storing the size beside the frame
/// means a resize is detected here and turns into a full paint automatically, without
/// the caller having to remember to tell anyone.
///
/// # Return value
///
/// The complete frame, always. A backend presents a frame and cannot present a
/// rectangle, so the saving is in what is *drawn*, not in what is returned. Returns
/// `None` when the widget is unmounted, has no `Draw` impl, or the size is empty.
pub fn render_frame_cached(id: ObjectId, size: Size, clear: crate::core::Color) -> Option<Vec<u8>> {
    if size.width == 0 || size.height == 0 {
        return None;
    }

    // Take a shared handle to the previous frame — a pointer clone, not a pixel copy. A frame of
    // the wrong size is treated as absent so the callee falls back to a full paint.
    // (D09-RENDER-04)
    let previous = LAST_FRAME
        .try_with(|map| {
            map.borrow()
                .get(&id)
                .filter(|(stored, _)| *stored == size)
                .map(|(_, frame)| Rc::clone(frame))
        })
        .ok()
        .flatten();

    // # No-damage fast path (D09-RENDER-04)
    //
    // When the mode repaints only damage and nothing is damaged, the previous frame *is* the
    // frame. The old code still ran the incremental machinery: it copied the cached buffer into
    // `previous`, copied it again in `render_frame_incremental` via `carried.to_vec()`, and copied
    // it a third time back into the cache. Here the cache is left exactly as it is and only the
    // single copy needed to hand an owned buffer to the caller is made. `Full` mode is excluded
    // because it must repaint regardless, and a missing previous cannot take this path.
    if let Some(previous) = &previous {
        if repaint_mode(id) != RepaintMode::Full && dirty_rects(id).is_empty() {
            // A frame with no damage also proves the surface settled, which is the `Adaptive`
            // mode's reset point — `render_frame_incremental` clears the run on this path, and
            // this fast path must do the same or `Adaptive` would stay latched after an animation
            // ends (the exact failure the run counter exists to avoid).
            let _ = REPAINT.try_with(|map| {
                if let Some(state) = map.borrow_mut().get_mut(&id) {
                    state.large_damage_run = 0;
                }
            });
            note_frame_cache_copy(); // the single copy that becomes the caller's frame
            return Some(previous.as_ref().clone());
        }
    }

    let frame =
        render_frame_incremental(id, size, clear, previous.as_deref().map(|rc| rc.as_slice()))?;

    // The freshly produced frame must be both cached and returned; wrapping it in an `Rc` for the
    // cache shares the buffer and costs the one unavoidable clone that hands an owned buffer to
    // the caller. (D09-RENDER-04)
    note_frame_cache_copy();
    let _ = LAST_FRAME.try_with(|map| {
        map.borrow_mut().insert(id, (size, Rc::new(frame.clone())));
    });
    Some(frame)
}

/// Forgets the cached frame for `id`.
///
/// Called when a widget is unmounted, so a frame cannot outlive the control it
/// describes — and so its id, if reused, does not start from someone else's pixels.
pub fn forget_cached_frame(id: ObjectId) {
    let _ = LAST_FRAME.try_with(|map| map.borrow_mut().remove(&id));
}

/// The size of the cached frame for `id`, if one is held.
///
/// Exposed so a backend can tell "I have a frame for this size" from "the next paint
/// will be full", which is what a resize handler needs to know.
pub fn cached_frame_size(id: ObjectId) -> Option<Size> {
    LAST_FRAME.try_with(|map| map.borrow().get(&id).map(|(size, _)| *size)).ok().flatten()
}

/// How many consecutive over-threshold frames [`RepaintMode::Adaptive`] has seen.
///
/// # Why this is public
///
/// `Adaptive` differs from `Dirty` only in this memory, so it is the only way to tell
/// the two policies apart from outside — and a policy that cannot be observed cannot
/// be tested. A host can also read it to decide whether to switch a widget to `Full`
/// itself, which is the honest use of the number.
///
/// Zero for a widget in any other mode, and for one that is not mounted.
pub fn adaptive_large_damage_run(id: ObjectId) -> u32 {
    REPAINT
        .try_with(|map| map.borrow().get(&id).map(|state| state.large_damage_run))
        .ok()
        .flatten()
        .unwrap_or(0)
}

/// Renders one frame of a mounted widget at `size` and returns the RGBA bytes.
///
/// `bytes.len() == size.width * size.height * 4`, top-down, straight (non
/// premultiplied) alpha — the layout all three desktop backends consume.
/// Returns `None` when `id` is not mounted or the size is empty.
///
/// # Why the widget's own origin is subtracted
///
/// Widget geometry is **absolute**: a control's rect is its position in the window, and
/// every control draws at those absolute coordinates (the same model the event router
/// uses, see [`widget_at`]). The frame here is only `size.width * size.height` — the
/// control's own box — so drawing at the absolute origin of a control placed at, say,
/// `(260, 42)` would land 260 px right and 42 px down inside its own buffer: the
/// top-left band stays clear and the bottom-right is clipped away. Pushing the negated
/// origin makes the control's absolute coordinates land on its own frame origin, which
/// is the only interpretation that can be correct for every control already written.
pub fn render_frame(id: ObjectId, size: Size, clear: crate::core::Color) -> Option<Vec<u8>> {
    if size.width == 0 || size.height == 0 {
        return None;
    }
    // The frame is the control's own box, so it has to be drawn at the box's origin
    // rather than at the control's absolute position.
    let origin = frame_origin(id);
    let mut backend = SoftwarePaintBackend::new(size, 1.0);
    let painted = with_widget_mut(id, |widget| {
        let Some(drawable) = widget.as_draw_mut() else {
            return false;
        };
        backend.begin_frame(clear);
        {
            let mut context = RenderContext::new(&mut backend);
            context.push_offset(-origin.0, -origin.1);
            drawable.draw(&mut context);
            context.pop_offset();
        }
        backend.end_frame();
        true
    })?;
    if !painted {
        return None;
    }
    Some(backend.frame_rgba().to_vec())
}

/// Renders one frame of a mounted widget using its own geometry as the size.
///
/// Convenience wrapper for backends that size the native canvas from the
/// widget's geometry rather than from the OS-reported rectangle.
pub fn render_frame_at_geometry(id: ObjectId, clear: crate::core::Color) -> Option<Vec<u8>> {
    let geometry = geometry_of(id)?;
    render_frame(id, Size::new(geometry.width, geometry.height), clear)
}

/// Renders one frame of a widget **and its descendants**, returning RGBA bytes.
///
/// # Why this exists
///
/// [`render_frame`] paints exactly one widget into its own box. That is right for a
/// self-drawn control mounted as a surface, but it means a widget that **contains** other
/// widgets paints none of them: a window drawn this way shows its own chrome over an empty
/// client area. A window whose children are ordinary library controls — a button, a check
/// box, a label — is the case that matters, and those children are never mounted as
/// surfaces of their own, so nothing painted them.
///
/// This walks the child list depth-first and draws each child that implements
/// [`Draw`][crate::widget::Draw], in tree order, so a later sibling paints over an earlier
/// one — the same order a container's own `draw` would use.
///
/// # Coordinates
///
/// Geometry is absolute (see [`render_frame`]), and the frame's origin is `id`'s own
/// position, so the negated origin is pushed once. Children draw at their own absolute
/// coordinates, which that single translation maps into this frame.
///
/// # What is skipped, and why silently
///
/// A child is skipped when it is not visible, when it is not in the registry, or when it
/// does not implement `Draw`. Skipping is not an error because all three are ordinary: a
/// hidden page, a child whose id was recycled, and a control that is a pure model for a
/// host to materialise are each a normal state, and reporting them would make a correct
/// tree look broken.
///
/// Returns `None` when `id` is not mounted or the size is empty.
pub fn render_frame_tree(id: ObjectId, size: Size, clear: crate::core::Color) -> Option<Vec<u8>> {
    if size.width == 0 || size.height == 0 {
        return None;
    }
    let origin = frame_origin(id);
    let mut backend = SoftwarePaintBackend::new(size, 1.0);

    // The root's own painting is part of the frame: a window draws its background and
    // chrome, which the children then sit on top of.
    let mut painted = with_widget_mut(id, |widget| {
        let Some(drawable) = widget.as_draw_mut() else {
            return false;
        };
        backend.begin_frame(clear);
        {
            let mut context = RenderContext::new(&mut backend);
            context.push_offset(-origin.0, -origin.1);
            drawable.draw(&mut context);
            context.pop_offset();
        }
        true
    })
    .unwrap_or(false);

    if painted {
        // Children are drawn into the same frame, so the traversal only issues draw calls;
        // the frame was begun above and is ended once below.
        let mut stack: Vec<ObjectId> = direct_children_of(id);
        // Reversed so the traversal visits children in declaration order: `pop` takes the
        // last element, so pushing the children reversed makes the first one first.
        stack.reverse();
        while let Some(current) = stack.pop() {
            if !is_visible(current) {
                continue;
            }
            let drew = with_widget_mut(current, |widget| {
                let Some(drawable) = widget.as_draw_mut() else {
                    return false;
                };
                let mut context = RenderContext::new(&mut backend);
                context.push_offset(-origin.0, -origin.1);
                drawable.draw(&mut context);
                context.pop_offset();
                true
            })
            .unwrap_or(false);
            if drew {
                painted = true;
            }
            let mut nested = direct_children_of(current);
            nested.reverse();
            stack.extend(nested);
        }
    }

    if !painted {
        return None;
    }
    backend.end_frame();
    Some(backend.frame_rgba().to_vec())
}

/// The direct children of `id`, or an empty list when it is not mounted.
///
/// Read through [`with_widget`] so a caller sees the same widget the traversal will.
fn direct_children_of(id: ObjectId) -> Vec<ObjectId> {
    with_widget(id, |widget| widget.base().children().to_vec()).unwrap_or_default()
}

/// The direct children of `id`, as a public read-only view of the mounted tree.
///
/// # Why this is public
///
/// The self-drawn backend positions and paints a window by walking this child list, so
/// "what does this window actually contain?" is a question a host, a test, and a designer
/// all need to ask. Only the private traversal could answer it before, which meant a
/// caller diagnosing a control that did not appear had to guess from creation order
/// instead of reading the tree (principle #100: designer readiness has to be inspectable,
/// not described).
///
/// Returns an empty vector for an unmounted id, matching
/// [`geometry_of`]: an id that addresses nothing has no children, and `[]` is the honest
/// answer rather than an error the caller must distinguish from "no children".
pub fn children_of(id: ObjectId) -> Vec<ObjectId> {
    direct_children_of(id)
}

/// Test module for the runtime registry and self-drawn frame rendering.
///
/// Runs only in `full_widgets` profiles: the tests exercise the self-drawn bridge
/// through concrete widgets in `special_widgets`, which is itself gated on
/// `full_widgets` (defined in `build.rs`). Gating on plain `test` alone would
/// make a stripped-down profile try to resolve types that are compiled out.
#[cfg(all(test, full_widgets))]
mod tests {
    use super::*;
    use crate::core::{Color, Point};
    use crate::platform::accessibility::AccessibilityBridge as _;
    use crate::widget::special_widgets::code_editor::CodeEditor;

    // ── BLUE23 §3.3 -- the animation bus ────────────────────────────────────────

    /// A hovered button *is* animating, and the bus advances it to rest.
    ///
    /// The whole point of the bus: before it, the button's `interaction_progress`
    /// interpolated forever in principle and never in practice, because nothing called
    /// `tick`. This drives it through the one runtime entry point.
    #[test]
    fn the_bus_advances_a_hovered_button_to_rest() {
        let id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);
        // Deliver the hover the same way the runtime does, rather than reaching into the
        // registry: this goes through the public dispatch the pointer path uses.
        assert!(dispatch_event(id, &crate::event::Event::MouseEnter { pos: Point::new(5, 5) }));
        // The control now owes frames, which is what lets a host schedule one.
        assert!(has_animating_widgets(), "a hovered button is animating");
        // Step until the bus reports rest, bounded so a transition that never settles fails
        // the test rather than hanging on it. The exact duration is a theme token, so the
        // assertion is "it ends", not a specific number of frames.
        let mut frames = 0;
        while tick_animations(50) {
            frames += 1;
            assert!(frames < 100, "the hover transition must settle, not run forever");
        }
        assert!(frames > 0, "a hover must take more than one frame, or it did not animate");
        assert!(!has_animating_widgets(), "and the control must report resting afterwards");
    }

    /// A frame with only resting controls costs nothing.
    ///
    /// This is the half of "smooth" that decides whether it is bought with a burning
    /// core: an idle window must report `false` so the host stops scheduling frames.
    #[test]
    fn the_bus_reports_no_frames_for_a_resting_control() {
        let id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);
        assert!(!has_animating_widgets(), "a resting button animates nothing");
        assert!(!tick_animations(16), "so the bus returns false and the host stops");
    }

    // ── BLUE24 §1 -- the frame driver ───────────────────────────────────────────

    /// A frame with a hovered control reports the work it did and asks for another frame.
    ///
    /// BLUE24 §1 criterion 1. The shape matters more than the numbers: the outcome must
    /// name **which** control moved (`controls_ticked == 1`) and must ask for the next frame,
    /// because a transition that has not settled is exactly the case a host has to keep
    /// scheduling for. A driver that returned `false` here would paint one step of the
    /// animation and then freeze, which is the failure the driver exists to prevent.
    #[test]
    fn drive_frame_ticks_a_hovered_control_and_asks_for_another_frame() {
        let id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        assert!(
            dispatch_event(id, &crate::event::Event::MouseEnter { pos: Point::new(5, 5) }),
            "the hover must reach the control, or there is nothing to animate"
        );

        let outcome = drive_frame(16);
        assert_eq!(outcome.controls_ticked, 1, "exactly the hovered button advanced");
        assert!(
            outcome.needs_another_frame,
            "a transition still in flight means the host must schedule another frame"
        );
    }

    /// A static frame costs nothing and submits nothing.
    ///
    /// BLUE24 §1 criterion 2, and the plan calls this **more important than the animation
    /// itself**: it is the property that decides whether a continuously-running loop is
    /// affordable. A resting tree must report no ticks and no repaint submissions, so an
    /// idle window pays for a sweep and nothing else.
    #[test]
    fn drive_frame_on_a_resting_tree_submits_nothing() {
        let id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        // Drain anything a previous test on this thread left behind, so the frame is
        // measured from a clean queue.
        let _ = drive_frame(16);

        let outcome = drive_frame(16);
        assert_eq!(outcome.controls_ticked, 0, "nothing on this tree is moving");
        assert_eq!(outcome.repaints_submitted, 0, "and nothing asked to be repainted");
        assert!(!outcome.needs_another_frame, "so the host may stop scheduling frames");
    }

    /// Input drained by this frame is visible to this frame's advance.
    ///
    /// BLUE24 §1 criterion 3, the ordering assertion: the plan fixes
    /// `drain -> advance -> report` and gives the reason -- an animation's *target* comes
    /// from state, state comes from events, so a frame that advanced before draining would
    /// not begin reacting until the following frame.
    ///
    /// # Why the observable fact is a callback and not a control's geometry
    ///
    /// The event has to arrive through the **trigger queue**, because only input that comes
    /// that way can be "drained by this frame" -- so the payload is a
    /// [`crate::platform::WidgetTriggerKind`]. There is no `Hovered` kind yet, and the kinds
    /// that exist carry no pointer position, so what a queued trigger observably does is run
    /// the handler the host registered for it. That handler is this test's clock: it records
    /// "drained", `drive_frame` then records nothing of its own, and the assertion is that
    /// the handler ran **inside** the frame that also reported `events_dispatched == 1`.
    /// A frame drains input, and reports what it drained, as its **first** step.
    ///
    /// # Why this test no longer asserts that its own event reached its handler
    ///
    /// It used to, and it was flaky -- roughly one run in twenty, across four successive theories, each
    /// one deleting the last:
    ///
    /// 1. `events_dispatched == 1` measured the process rather than the driver (the queue is
    ///    process-wide). Fixed by comparing deltas.
    /// 2. The handler flag stayed false because a frame dispatched other tests' events and never reached
    ///    this one's. A bounded retry loop narrowed the window and did **not** close it: measured, 1
    ///    failure in 20 runs.
    /// 3. `drain_widget_triggers_for` returned 0 right after `inject` returned `true`, because a
    ///    concurrent frame had taken the event in between.
    ///
    /// The conclusion is not "find a cleverer assertion" but "this claim is not testable here":
    /// `drive_frame` drains the **process-wide** queue, and every other test in the binary is draining
    /// the same one. No ordering of inject / drain / assert inside this test can exclude that.
    ///
    /// So the test asserts the part that **is** a property of the driver:
    ///
    /// * the frame reports a non-zero drain when work is queued for it, and
    /// * the drain is step 1, which is observable because `events_dispatched` is computed before
    ///   `tick_animations` runs and is returned unchanged by it.
    ///
    /// The delivery half -- "a drained event reaches the handler" -- is pinned where it is genuinely
    /// testable, in `platform::state`'s own queue test and in `dispatch_trigger`'s callers, rather than
    /// through a queue that other tests own shares of.
    #[test]
    fn drive_frame_drains_input_before_advancing() {
        let id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        // Register the handler the way a host does, so the production dispatch path is exercised even
        // though this test does not assert on it.
        thread_local! {
            #[allow(clippy::missing_const_for_thread_local)]
            static DRAINED: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
        }
        DRAINED.with(|flag| flag.set(false));
        crate::app::handle_set_widget_value_callback(
            id,
            std::rc::Rc::new(RefCell::new(|_text: String| DRAINED.with(|flag| flag.set(true)))),
        );

        // A quiescent frame first, so `before` is this test's own baseline rather than a number that
        // includes whatever another test left queued.
        crate::drain_widget_triggers_for(id);
        let before = drive_frame(0).events_dispatched;
        assert!(
            crate::inject_widget_trigger_event(
                id,
                crate::platform::WidgetTriggerKind::ValueChanged
            ),
            "the backend must accept the injected trigger"
        );
        let outcome = drive_frame(16);

        // The frame's own account of step 1. A delta, because the queue is shared: what this asserts is
        // that the frame **counted what its drain took**, not that it took exactly one thing.
        //
        // # Why this is not `outcome.events_dispatched > before`
        //
        // That is what it used to assert, and it was **flaky under the full suite** while passing
        // in isolation: `events_dispatched` is the process-wide count, and the sibling tests in this
        // module (`drive_frame_ticks_a_hovered_control_and_asks_for_another_frame`,
        // `drive_frame_on_a_resting_tree_submits_nothing`, `drive_frame_advances_each_control_once_per_frame`,
        // `drive_frame_accounts_for_repaints_and_clears_the_count`) each call `drive_frame` too. A
        // concurrent test's frame can drain this test's injected trigger first, so the count this test
        // compares against moves for a reason that has nothing to do with the claim.
        //
        // The claim is about *this* frame having drained *this* control's trigger, and that is
        // observable without the global counter: the handler runs during the drain, so the widget's
        // own value callback having fired is the per-control evidence that step 1 happened. It is
        // also the stronger assertion -- a frame that dispatched *someone else's* trigger would still
        // satisfy `> before` but cannot satisfy this.
        assert!(
            DRAINED.with(|flag| flag.get()),
            "the injected trigger must have reached its handler during the frame's drain \
             (dispatched={}, before={before})",
            outcome.events_dispatched
        );

        // And the drain is the *first* step, which is what the original claim was about: the count is
        // taken before any control is advanced, so a frame that advanced first and drained after would
        // report the same number but a control that became dirty this frame would not be advanced until
        // the next one. `controls_ticked` is the observable that separates those: a frame that drained
        // a change and then advanced its controls is the one that reports both.
        assert!(
            outcome.controls_ticked <= count_animating_widgets(),
            "the advance is bounded by what the drain left animating"
        );

        // The negative half, on the targeted drain: this control's own queue is empty now, so a second
        // drain of it dispatches nothing. Read here rather than on a frame for the reason above.
        assert_eq!(
            crate::drain_widget_triggers_for(id),
            0,
            "the control's own queue is empty after the frame drained it"
        );
    }

    /// Each control is advanced exactly once per frame.
    ///
    /// BLUE24 §1 criterion 4. The failure it guards is the one the plan names in §1.1: a
    /// frame that ticks a control through two layers moves it at a speed that depends on
    /// how many layers happened to call in, not on the duration the theme asked for.
    ///
    /// The measurement is **total travel per frame**: with one advance per frame, the sum
    /// of a control's per-frame travel equals its total travel. Two advances in a frame
    /// would double it, so summing and comparing against the end-to-end travel catches the
    /// defect without needing a counting double.
    #[test]
    fn drive_frame_advances_each_control_once_per_frame() {
        use crate::widget::display_widgets::switch::Switch;

        let mut switch = Switch::new(Rect::new(0, 0, 60, 30));
        let switch_id = switch.id();
        switch.set_checked(true);
        // A host-owned control: the paint path reports it to the bus, which is the path
        // `drive_frame` folds in. Mounting it would be a second population and blur the
        // count this test is measuring.
        assert!(!is_mounted(switch_id));

        let start = switch.travel_progress();
        let mut per_frame_total = 0.0f32;
        let mut frames = 0;
        while switch.is_animating() {
            assert!(frames < 200, "the travel must settle, not run forever");
            let before = switch.travel_progress();
            // One frame, advanced through the driver the same way a host does it: report
            // what this host-owned control is doing, then let the frame run.
            let dynamic: &mut dyn Widget = &mut switch;
            if dynamic.tick(16) || dynamic.is_animating() {
                animation_bus_note_host_owned_animating(true);
            } else {
                animation_bus_note_host_owned_settled();
            }
            let _ = drive_frame(16);
            per_frame_total += (switch.travel_progress() - before).abs();
            frames += 1;
        }
        let end_to_end = (switch.travel_progress() - start).abs();
        assert!(end_to_end > 0.0, "the fixture must actually have travelled");
        // Exact equality is right here: both sums add the same `f32` deltas in the same
        // order, so any second advance in a frame shows up as a doubled total, not a
        // rounding difference.
        assert_eq!(
            per_frame_total, end_to_end,
            "the per-frame travel must add up to the total, which holds only if each \
             frame moves the control once"
        );
        assert!(
            frames > 1,
            "the travel must have taken more than one frame, or it did not animate"
        );
    }

    // ── BLUE24 §4 -- the environment facts ──────────────────────────────────────

    /// A host-installed provider is what a frame reads, and the frame refreshes it.
    ///
    /// BLUE24 §4 criteria 3 and 5. Two properties in one frame: the installed provider's
    /// answers reach `environment()`, and installing one changes what the library reports
    /// **without** any control knowing where the fact came from. The provider is removed
    /// before the assertions finish so a failure cannot leak it into a later test on this
    /// thread (the install is thread-local, so that is a real risk).
    #[test]
    fn a_frame_reads_the_installed_environment_provider() {
        use crate::style::environment::{
            environment, install_environment, uninstall_environment, EnvironmentProvider,
        };
        use crate::style::MotionPreference;

        struct Fixture;
        impl EnvironmentProvider for Fixture {
            fn text_scale(&self) -> f32 {
                2.0
            }
            fn motion_preference(&self) -> MotionPreference {
                MotionPreference::ReduceMotion
            }
        }

        let previous = install_environment(Box::new(Fixture));
        let snapshot = environment();
        assert_eq!(snapshot.text_scale, 2.0, "the provider's text scale reaches the read point");
        assert!(snapshot.prefers_reduced_motion(), "and its motion preference too");
        assert_eq!(snapshot.effective_text_scale(), 2.0, "and survives the clamp");

        // A frame refreshes the snapshot from the provider, so the fact is what the frame
        // used rather than what was installed before it.
        let _ = drive_frame(16);
        assert_eq!(environment().text_scale, 2.0, "still true after a frame");

        // Restore: remove the fixture and prove the default came back. The assertion is on the
        // **text scale**, which the fixture set to a value no default can produce, rather than on
        // the motion preference -- that one could already be set by a provider a neighbouring test
        // installed, so it cannot distinguish "the fixture is gone" from "someone else asked for
        // the same thing".
        let _ = uninstall_environment();
        assert_ne!(
            environment().text_scale,
            2.0,
            "removing the fixture restores whatever was installed before it"
        );
        if let Some(previous) = previous {
            // A previous provider existed only if an earlier test leaked one; put it back so
            // this test does not silently discard another test's state.
            install_environment(previous);
        }
    }

    /// The environment is constant across every control in one frame.
    ///
    /// BLUE24 §4 criterion 3. The guarantee is not "the snapshot never changes" -- a host that
    /// changes a system setting between frames must be seen, and `refresh_environment` re-reads it
    /// at the start of each frame for exactly that reason. The guarantee is that the refresh
    /// happens **once per frame**, so two controls painted in the same frame cannot disagree about
    /// the text scale.
    ///
    /// That is measured by counting the provider's reads. A frame that asked once per control (the
    /// shape the snapshot exists to prevent) would read many times; taking one snapshot reads
    /// exactly once for the frame. The count is what distinguishes the two, which no value
    /// assertion could.
    #[test]
    fn the_environment_is_read_once_per_frame() {
        use crate::style::environment::{
            environment, install_environment, uninstall_environment, EnvironmentProvider,
        };

        /// A provider that counts how many times it was asked.
        struct Counting {
            reads: std::rc::Rc<core::cell::Cell<u32>>,
        }
        impl EnvironmentProvider for Counting {
            fn text_scale(&self) -> f32 {
                self.reads.set(self.reads.get() + 1);
                // A value that changes per read, so "the frame saw one value" is visible in the
                // picture as well as in the count.
                self.reads.get() as f32
            }
        }

        let reads = std::rc::Rc::new(core::cell::Cell::new(0));
        let previous =
            install_environment(Box::new(Counting { reads: std::rc::Rc::clone(&reads) }));
        let before = reads.get();

        // One frame. `drive_frame` refreshes the snapshot once, which asks the provider once for
        // each of its eight facts -- but `text_scale` is read exactly once per refresh, so the
        // delta is 1. A per-control read would make it grow with the number of mounted widgets.
        let _ = drive_frame(16);
        let after_first = reads.get();
        assert_eq!(
            after_first - before,
            1,
            "one frame must ask the provider for the text scale exactly once"
        );

        // And the snapshot every control in that frame saw is one value, not one per control.
        let snapshot = environment();
        assert_eq!(snapshot.text_scale, after_first as f32);

        let _ = uninstall_environment();
        if let Some(previous) = previous {
            install_environment(previous);
        }
    }

    /// Reduced motion collapses every transition to one frame, and the end state is the same.
    ///
    /// BLUE24 §4 criterion 2. The pair is the point: it is not "the animation is skipped" (which
    /// would leave the control at its start) but "the animation arrives immediately". So the
    /// control must stop animating after the first frame **and** have reached the geometry a
    /// normal-preference run reaches at its end.
    ///
    /// The switch's travel is used because it is the clearest two-ended property in the crate,
    /// and its target is derived from a latch rather than from a pointer, so the test needs no
    /// event delivery.
    #[test]
    fn reduced_motion_reaches_the_end_in_one_frame() {
        use crate::style::environment::{
            install_environment, uninstall_environment, EnvironmentProvider,
        };
        use crate::style::MotionPreference;
        use crate::widget::display_widgets::switch::Switch;

        struct Reduced;
        impl EnvironmentProvider for Reduced {
            fn motion_preference(&self) -> MotionPreference {
                MotionPreference::ReduceMotion
            }
        }

        // The end the normal preference reaches, measured first so the comparison is against a
        // real run rather than against a literal.
        let mut full = Switch::new(Rect::new(0, 0, 60, 30));
        full.set_checked(true);
        let mut guard = 0;
        while full.tick(16) {
            guard += 1;
            assert!(guard < 200, "the travel must settle");
        }
        let full_end = full.travel_progress();

        let previous = install_environment(Box::new(Reduced));
        // A frame first, because the frame is what refreshes the snapshot the token read consults.
        let _ = drive_frame(16);

        let mut reduced = Switch::new(Rect::new(0, 0, 60, 30));
        reduced.set_checked(true);
        // One tick: with the preference in force the duration is zero, so the travel arrives now.
        let moving = reduced.tick(16);
        assert!(!moving, "a zero-duration transition settles on the first frame");
        assert_eq!(
            reduced.travel_progress(),
            full_end,
            "and it has arrived at the *same* place a full run reaches, not half way"
        );

        let _ = uninstall_environment();
        if let Some(previous) = previous {
            install_environment(previous);
        }
    }

    /// A repaint request made during a frame is counted against that frame.
    ///
    /// BLUE24 §1.2's `repaints_submitted` has to be an account of what the frame cost, so
    /// the count is taken **and cleared** by the driver: a frame loop reads the same number
    /// the frame produced, and the next frame starts from zero rather than accumulating.
    ///
    /// The platform is substituted with the crate's own recording double, because the
    /// question "was this submission counted?" is only answerable where a submission can
    /// be observed. The default backend on a headless host mounts nothing and reports
    /// `false`, which would make this test measure the backend rather than the driver.
    #[test]
    fn drive_frame_accounts_for_repaints_and_clears_the_count() {
        use crate::platform::with_recorded_invalidations;
        use crate::platform::RecordingInvalidations;

        let id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        static RECORDER: std::sync::OnceLock<RecordingInvalidations> = std::sync::OnceLock::new();
        let recorder = RECORDER.get_or_init(RecordingInvalidations::new);
        recorder.clear();

        with_recorded_invalidations(recorder, || {
            // Settle and clear first, so only the submission below is measured.
            let _ = drive_frame(16);

            request_repaint(id);
            let first = drive_frame(16);
            assert!(first.repaints_submitted >= 1, "the request belongs to this frame's account");

            let second = drive_frame(16);
            assert_eq!(second.repaints_submitted, 0, "and the count was cleared, not accumulated");
        });
    }

    /// A control the **caller owns** is advanced and reported by the paint path.
    /// A host-owned control whose motion was started by something else is advanced by the paint
    /// path.
    ///
    /// # The defect this pins
    ///
    /// [`tick_animations`] sweeps the mounted registry. A control held as a
    /// `Box<dyn Widget>` -- which is what [`crate::widget::WidgetFactory::create`] returns,
    /// what `census` and `examples/export_control_svgs.rs` hold, and what this crate's own
    /// front-page example documents -- is not in that registry, so nothing advanced it. A
    /// `Switch` toggled ON and then painted drew its thumb at the **off** end on every frame,
    /// forever, and reported no error: its `travel_progress` stayed where it started while
    /// `is_checked` said `true`.
    ///
    /// A `Switch` is used as the fixture because its own `tick` does **not** request a repaint,
    /// which is what `manages_own_repaint` reports -- so it is the case the paint path has to
    /// handle. The `Button`/`Spinner` split is covered by its own test below.
    #[test]
    fn the_paint_path_advances_a_host_owned_control() {
        use crate::widget::display_widgets::switch::Switch;
        use crate::widget::draw_bridge::draw_of;

        let mut switch = Switch::new(Rect::new(0, 0, 60, 30));
        assert!(!is_mounted(switch.id()), "the fixture must not be in the registry");
        switch.set_checked(true);
        assert!(switch.is_animating(), "a freshly toggled switch owes frames");
        assert!(
            !switch.manages_own_repaint(),
            "and it does not repaint itself, so only the paint path can advance it"
        );

        let start = switch.travel_progress();
        let mut positions = vec![start];
        // 200 frames at the paint path's 16 ms step is 3.2 s of virtual time, past the `Slow`
        // token the travel runs on. The bound makes a transition that never settles fail here
        // instead of looping; the assertions are about the shape of the travel, not its length.
        let mut frames = 0;
        let mut bus_asked_for_a_frame = false;
        while switch.is_animating() {
            assert!(frames < 200, "the travel must settle, not run forever");
            frames += 1;
            let dynamic: &mut dyn Widget = &mut switch;
            let _ = draw_of(dynamic);
            positions.push(switch.travel_progress());
            if switch.is_animating() {
                bus_asked_for_a_frame |= animation_bus_needs_another_frame();
            }
        }
        assert!(frames > 1, "a travel must take more than one frame, or it did not animate");
        assert!(
            bus_asked_for_a_frame,
            "while it was in flight the bus had to say another frame is needed"
        );
        assert!(
            positions.last().copied().unwrap() > start,
            "painting an owned switch must advance its travel, not repaint a frozen frame"
        );
        assert!(
            positions.windows(2).all(|pair| pair[1] >= pair[0]),
            "the travel must be monotonic: {positions:?}"
        );
        assert!(
            positions.iter().any(|position| *position > 0.0 && *position < 1.0),
            "and it must pass through the middle, or it jumped rather than slid"
        );
        assert!(
            (positions.last().copied().unwrap() - 1.0).abs() < f32::EPSILON,
            "and it must arrive on the target, not one step short of it: {:?}",
            positions.last()
        );
    }

    /// A control that repaints itself is **not** advanced by repeated paints.
    ///
    /// # The second defect this pins, and it is worse than the first
    ///
    /// The first version of the paint path advanced every unmounted control. A `Spinner` is
    /// unmounted in the snapshot export, and its `tick` requests a repaint, so this was a
    /// feedback loop: every paint advanced it and every advance asked for the next paint, so
    /// `spinner.svg` differed between two consecutive exports of an unchanged build. A snapshot
    /// that is not reproducible cannot show a regression, which is the whole reason the export
    /// exists.
    ///
    /// `Spinner` is the free-running case: at rest its `tick` still returns `true` (it turns at a
    /// fixed rate forever), so "two paints of a resting spinner are identical" is exactly the
    /// property under test. A `Button` is the opposite case and is checked in the same test, so
    /// the rule is shown to cut between the two rather than exclude animation wholesale.
    ///
    /// # The one step a free-runner still takes, and why that is correct
    ///
    /// A control can only declare that it repaints itself by painting, so the frame that paints
    /// it for the first time is also the frame on which the declaration is made — and that frame
    /// is advanced. Leaving it out would mean the gate could never be satisfied for a control
    /// whose first frame *is* its declaration. The step is bounded (one per control, not one per
    /// paint) and does not break reproducibility, because the export paints each control several
    /// times and only the first of those moves it: measured on `spinner.svg`, two consecutive
    /// export runs are byte-identical.
    #[test]
    fn the_paint_path_skips_a_control_that_repaints_itself() {
        use crate::widget::display_widgets::spinner::Spinner;
        use crate::widget::draw_bridge::draw_of;

        let mut spinner = Spinner::new(Rect::new(0, 0, 120, 120));
        assert!(spinner.is_animating(), "the fixture must have something to advance");
        paint_owned(&mut spinner);
        assert!(
            spinner.manages_own_repaint(),
            "painting a spinner must declare that its frames are its own"
        );

        let settled = spinner.angle();
        for _ in 0..5 {
            paint_owned(&mut spinner);
        }
        assert!(
            (spinner.angle() - settled).abs() < f32::EPSILON,
            "once it has declared itself, further paints must not advance it: {} -> {}",
            settled,
            spinner.angle()
        );

        // The other side of the same gate: a `Button` is *not* excluded, so the rule is about who
        // repaints rather than about animation in general.
        let mut button =
            crate::widget::Button::new("ok".to_string(), crate::core::Rect::new(0, 0, 80, 32));
        button.set_hovered(true);
        assert!(!button.manages_own_repaint(), "an ordinary control must not claim its frames");
        assert!(button.is_animating(), "while still owing frames for the hover");
        let _ = draw_of(&mut button as &mut dyn Widget);
        assert!(
            button.is_animating() || button.widget_state() == crate::style::WidgetState::Hover,
            "the paint path advanced the button's interaction transition"
        );
    }

    /// Paints a host-owned control the way a host would: **through** [`draw_of`], into a surface.
    ///
    /// Doing the draw rather than only asking for the painting channel matters here, because the
    /// declaration a free-running control makes lives in its `draw`. A helper that stopped at
    /// `draw_of` would test the wrong thing.
    fn paint_owned(widget: &mut dyn Widget) {
        use crate::render::{PaintBackend, RenderContext, SoftwarePaintBackend};
        let Some(drawable) = crate::widget::draw_bridge::draw_of(widget) else {
            return;
        };
        let mut surface = SoftwarePaintBackend::new(Size::new(240, 120), 1.0);
        surface.begin_frame(Color::WHITE);
        {
            let mut context = RenderContext::new(&mut surface);
            drawable.draw(&mut context);
        }
        surface.end_frame();
    }

    /// An owned control that has settled keeps the bus quiet.
    ///
    /// The other half of [`the_paint_path_advances_a_host_owned_control`]: advancing must not
    /// become a reason to repaint a still window forever.
    #[test]
    fn an_owned_control_at_rest_does_not_keep_the_bus_awake() {
        use crate::widget::display_widgets::switch::Switch;
        use crate::widget::draw_bridge::draw_of;

        animation_bus_reset_host_owned();
        let mut resting = Switch::new(Rect::new(0, 0, 60, 30));
        let dynamic: &mut dyn Widget = &mut resting;
        let _ = draw_of(dynamic);
        assert!(
            !animation_bus_needs_another_frame(),
            "painting a resting owned control must not ask for another frame"
        );
    }

    /// A mounted control is advanced **once** per frame, not twice.
    ///
    /// `tick_animations` and the paint path are two different drivers, and a control that both
    /// registered itself and was then painted would otherwise run its animation at double speed —
    /// the failure `tick_animations`' own documentation calls out. The paint path therefore skips
    /// anything the registry owns.
    #[test]
    fn a_mounted_control_is_not_advanced_by_the_paint_path() {
        use crate::widget::display_widgets::switch::Switch;
        use crate::widget::draw_bridge::draw_of;

        let mut mounted = Switch::new(Rect::new(0, 0, 60, 30));
        mounted.set_checked(true);
        // Advanced by hand up to a mid-travel position, so the control *is* in flight and still
        // has somewhere to go — which is what makes "a paint must not move it" a real assertion
        // rather than one a settled control would pass vacuously.
        let mid_flight = mounted.tick(30);
        let id = register(Box::new(mounted)).expect("mount");
        let _unmount = MountGuard(id);
        let before = with_widget_mut(id, widget_travel).unwrap_or(-1.0);
        assert!(mid_flight, "the fixture must still owe frames to be worth stepping");
        assert!(
            before > 0.0 && before < 1.0,
            "the fixture must be mid-travel, or the test proves nothing: {before}"
        );

        // Painting it must not move it. `draw_of` takes `&mut dyn Widget`, so the mounted widget
        // has to be reached the way the frame loop reaches it.
        with_widget_mut(id, |widget| {
            for _ in 0..5 {
                let _ = draw_of(widget);
            }
        });
        let after = with_widget_mut(id, widget_travel).unwrap_or(-1.0);
        assert!(
            (before - after).abs() < f32::EPSILON,
            "a mounted control must be advanced only by the bus: {before} -> {after}"
        );

        // And the bus does move it, so the fixture was genuinely animating.
        let stepped = with_widget_mut(id, |widget| {
            widget.tick(100);
            widget_travel(widget)
        })
        .unwrap_or(-1.0);
        assert!(
            stepped > after,
            "the same control advanced directly must move: {after} -> {stepped}"
        );
    }

    /// Unmounts a widget registered by a test, even on panic.
    struct MountGuard(ObjectId);
    impl Drop for MountGuard {
        fn drop(&mut self) {
            let _ = unregister(self.0);
        }
    }

    /// The travel of a mounted switch, or `-1.0` when `widget` is not one.
    ///
    /// Read through the widget's own accessor rather than a test-only field, so the
    /// measurement is of the same fact the draw site reads to place the thumb.
    fn widget_travel(widget: &mut dyn Widget) -> f32 {
        use crate::widget::display_widgets::switch::Switch;
        (widget as &mut dyn std::any::Any)
            .downcast_mut::<Switch>()
            .map(|switch| switch.travel_progress())
            .unwrap_or(-1.0)
    }

    /// Downcasts a mounted widget to the concrete editor type.
    fn editor_of(widget: &mut dyn Widget) -> Option<&mut CodeEditor> {
        (widget as &mut dyn std::any::Any).downcast_mut::<CodeEditor>()
    }

    /// The auto-decision refuses a control too small for the bookkeeping to pay off.
    #[test]
    fn the_auto_decision_refuses_a_small_surface() {
        let small = register(Box::new(CodeEditor::new(Rect::new(0, 0, 100, 100)))).expect("r");
        let big = register(sample_editor("fn main() {}")).expect("r");
        // Both fixtures are below the threshold; the point is that the refusal is by
        // area, and that the threshold really is above them.
        const { assert!(100u64 * 100 < AUTO_REPAINT_MIN_PIXELS) };
        const { assert!(320u64 * 200 < AUTO_REPAINT_MIN_PIXELS) };
        assert!(!should_track_damage(small), "a 100x100 surface is not worth regioning");
        assert!(!should_track_damage(big), "320x200 is below the threshold as well");

        // Above the threshold **and** carrying children, it is accepted. A bare
        // `CodeEditor` is refused whatever its size, because it has no children and so
        // has only one rect to damage — which is the whole surface.
        let large = register(auto_accepted_surface()).expect("r");
        assert!(should_track_damage(large), "800x600 with children must be accepted");

        unregister(small);
        unregister(big);
        unregister(large);
    }

    /// A childless control is one rect, so regioning cannot narrow anything.
    #[test]
    fn the_auto_decision_refuses_a_control_with_no_children() {
        let lone = register(Box::new(CodeEditor::new(Rect::new(0, 0, 800, 600)))).expect("r");
        assert!(
            with_widget(lone, |widget| widget.base().children().is_empty()).unwrap_or(false),
            "the fixture must have no children"
        );
        assert!(
            !should_track_damage(lone),
            "a control with no children has one rect, which is the whole surface"
        );
        unregister(lone);
    }

    /// The one-call form does both halves, and reports honestly.
    #[test]
    fn enable_if_useful_is_a_no_op_where_it_would_not_help() {
        let small = register(Box::new(CodeEditor::new(Rect::new(0, 0, 80, 60)))).expect("r");
        assert!(!enable_damage_tracking_if_useful(small));
        assert_eq!(
            repaint_mode(small),
            RepaintMode::Full,
            "a refused enable must leave the mode alone"
        );

        // And an unregistered id is refused rather than silently accepted.
        assert!(!enable_damage_tracking_if_useful(0xDEAD_BEEF));
        unregister(small);
    }

    /// Enabling through the auto-decision really produces damage-tracked frames.
    #[test]
    fn a_widget_enabled_by_the_auto_decision_tracks_damage() {
        // A surface the library accepted at mount time comes up already tracking, with
        // no call from the host — which is the whole point of the automatic call site.
        let id = register(auto_accepted_surface()).expect("r");
        assert_eq!(repaint_mode(id), RepaintMode::Adaptive, "register must accept this surface");

        with_widget(id, |widget| widget.base().request_redraw()).expect("widget");
        assert_eq!(
            dirty_rects(id).len(),
            1,
            "the enabled widget must record damage from request_redraw"
        );

        // And the explicit one-call form still exists for a host that wants to ask
        // again after changing its geometry. It is refused for a control that has never
        // asked to be repainted, and accepted once one has.
        unregister(id);
        let explicit = register(container_with_child()).expect("r");
        assert!(set_geometry(explicit, Rect::new(0, 0, 800, 600)));
        assert!(
            !enable_damage_tracking_if_useful(explicit),
            "a control that never asked to repaint must be refused"
        );
        with_widget(explicit, |widget| widget.request_redraw()).expect("widget");
        assert!(enable_damage_tracking_if_useful(explicit));
        assert_eq!(repaint_mode(explicit), RepaintMode::Adaptive);
        unregister(explicit);
    }

    /// A control that never asked to repaint is left alone by the auto-decision.
    ///
    /// This is the cost side of the trade-off: enabling a surface that nothing redraws
    /// would only make it pay the bookkeeping. `register` therefore refuses a control
    /// that has not gone through `request_redraw` at least once.
    #[test]
    fn the_auto_decision_leaves_a_silent_control_alone() {
        let silent = register(auto_accepted_surface()).expect("r");
        assert_eq!(repaint_mode(silent), RepaintMode::Adaptive, "fixture sanity");
        unregister(silent);

        // With the mode cleared by hand (which is what a `Full` mode looks like), the
        // decision refuses until the control actually asks for a repaint.
        let id = register(container_with_child()).expect("r");
        assert!(set_geometry(id, Rect::new(0, 0, 800, 600)));
        assert!(set_repaint_mode(id, RepaintMode::Full));
        assert!(!should_track_damage(id), "a silent control must not be enabled");

        with_widget(id, |widget| widget.base().request_redraw()).expect("widget");
        assert!(should_track_damage(id), "after asking for a repaint it becomes eligible");
        unregister(id);
    }

    /// Forgetting a widget drops its auto-decision evidence with it.
    #[test]
    fn unregistering_clears_the_auto_decision_state() {
        let id = register(auto_accepted_surface()).expect("r");
        assert_eq!(repaint_mode(id), RepaintMode::Adaptive);
        assert!(should_track_damage(id));

        unregister(id);
        assert!(!should_track_damage(id), "a dead id must not be judged as trackable");
        assert_eq!(repaint_mode(id), RepaintMode::Full, "nor keep a stale mode");
    }

    /// The reverse mapping is cleaned up with the widget, so a recycled own-id cannot
    /// file damage against a dead registry id.
    #[test]
    fn unregister_forgets_the_own_id_mapping() {
        let id = register(sample_editor("fn main() {}")).expect("r");
        let own = with_widget(id, |widget| widget.base().id()).expect("widget");
        assert_eq!(registry_id_of(own), Some(id));

        unregister(id);
        assert_eq!(registry_id_of(own), None, "the reverse map must not outlive the widget");
    }

    #[test]
    fn diag_container() {
        let id = register(auto_accepted_surface()).expect("r");
        let geometry = geometry_of(id).expect("geometry");
        let kids = with_widget(id, |w| w.base().children().len()).unwrap_or(999);
        assert_eq!(geometry.width, 800, "geometry must survive registration");
        assert_eq!((geometry.width, geometry.height), (800, 600));
        assert_eq!(kids, 1, "children must survive registration");
        assert_eq!(repaint_mode(id), RepaintMode::Adaptive);
        unregister(id);
    }

    /// The `Adaptive` run counter for a widget, for the tests that assert on *why* a
    /// frame painted whole rather than only that it did.
    fn large_damage_run_of(id: ObjectId) -> u32 {
        REPAINT
            .try_with(|map| map.borrow().get(&id).map(|state| state.large_damage_run))
            .ok()
            .flatten()
            .unwrap_or(0)
    }

    /// A container large enough and structured enough for the auto-decision to accept.
    ///
    /// The children matter: a childless control has one rect, so regioning cannot
    /// narrow anything and `should_track_damage` refuses it. `add_child` records the
    /// nesting the criterion reads.
    fn container_with_child() -> Box<dyn Widget> {
        let mut group =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 320, 200));
        group.base_mut().add_child(7);
        Box::new(group)
    }

    /// The shape of a real window: large, with children, and it has asked to repaint.
    ///
    /// The third part is not incidental. `register` enables tracking for a control the
    /// library judges worth it — but only for a control that has actually asked to be
    /// repainted, because enabling a surface nothing redraws is pure cost. A real window
    /// asks while its first frame is being prepared, which is before it is mounted; a
    /// constructor that does so is modelled here by calling `request_redraw` directly.
    fn auto_accepted_surface() -> Box<dyn Widget> {
        let mut group =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 800, 600));
        group.base_mut().add_child(7);
        group.base_mut().request_redraw();
        Box::new(group)
    }

    fn sample_editor(text: &str) -> Box<dyn Widget> {
        let mut editor = CodeEditor::new(Rect::new(0, 0, 320, 200));
        editor.set_text(text);
        Box::new(editor)
    }

    // ── Damage producers: `request_redraw` must record damage ────────────────
    //
    // Before these existed, `mark_dirty_rect` had **no production caller** — the
    // tracker, the platform invalidation and `render_frame_incremental` were all
    // complete and reachable from tests only, so partial repaint could never happen in
    // a real program. `request_redraw` is the single point every appearance change
    // converges on (~1000 call sites), which is what makes recording damage *there*
    // correct by construction rather than a list of paths someone must keep complete.

    /// `request_redraw` records damage once the widget has opted in.
    #[test]
    fn request_redraw_records_damage_when_adaptive() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode_adaptive(id));
        assert!(dirty_rects(id).is_empty(), "nothing has asked to repaint yet");

        with_widget(id, |widget| widget.base().request_redraw()).expect("widget");

        let damaged = dirty_rects(id);
        assert_eq!(damaged.len(), 1, "request_redraw must record exactly one region: {damaged:?}");
        assert_eq!(damaged[0], Rect::new(0, 0, 320, 200), "the control's own geometry");
        unregister(id);
    }

    /// A widget that never opted in records nothing, so the producer costs it nothing.
    #[test]
    fn request_redraw_records_nothing_in_full_mode() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert_eq!(repaint_mode(id), RepaintMode::Full, "Full is the default");

        with_widget(id, |widget| widget.base().request_redraw()).expect("widget");

        assert!(dirty_rects(id).is_empty(), "Full mode must not accumulate damage");
        unregister(id);
    }

    /// The producer is a no-op for an unregistered widget, so the transient controls
    /// tests build (never registered) cannot panic or leak state.
    #[test]
    fn request_redraw_on_an_unregistered_widget_is_a_no_op() {
        let editor = CodeEditor::new(Rect::new(0, 0, 40, 20));
        editor.base().request_redraw();
        assert!(dirty_rects(editor.base().id()).is_empty());
    }

    /// Every frame that repaints must clear the damage, or the next frame repaints the
    /// same region forever and the tracker grows without bound.
    #[test]
    fn a_painted_frame_consumes_the_damage() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode_adaptive(id));
        let size = Size::new(320, 200);

        // First frame has no previous buffer, so it paints whole and clears.
        let first = render_frame_incremental(id, size, Color::WHITE, None).expect("frame");
        assert!(dirty_rects(id).is_empty(), "a full paint resets the damage");

        with_widget(id, |widget| widget.base().request_redraw()).expect("widget");
        assert_eq!(dirty_rects(id).len(), 1);

        let second = render_frame_incremental(id, size, Color::WHITE, Some(&first)).expect("frame");
        assert_eq!(second.len(), first.len(), "the frame keeps its size");
        assert!(dirty_rects(id).is_empty(), "the incremental paint consumed the damage");
        unregister(id);
    }

    /// `Adaptive` stops measuring after a run of frames whose damage covers the surface,
    /// then resumes when the damage shrinks.
    ///
    /// The assertion is on `large_damage_run`, which is the mode's whole difference from
    /// `Dirty`: a latch would keep painting whole after the animation ended, while this
    /// returns to regioning because one small-damage frame resets the counter.
    #[test]
    fn adaptive_learns_from_full_surface_damage_and_recovers() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode_adaptive(id));
        let size = Size::new(320, 200);
        let full = Rect::new(0, 0, 320, 200);

        // A first frame so later ones have something to carry forward.
        let mut frame = render_frame_incremental(id, size, Color::WHITE, None).expect("frame");

        // Damage covering the whole surface, repeatedly.
        for _ in 0..ADAPTIVE_LARGE_DAMAGE_RUN {
            assert!(mark_dirty_rect(id, full));
            frame = render_frame_incremental(id, size, Color::WHITE, Some(&frame)).expect("frame");
        }
        assert_eq!(
            large_damage_run_of(id),
            ADAPTIVE_LARGE_DAMAGE_RUN,
            "a run of whole-surface frames must be counted"
        );

        // One small-damage frame clears it, which is what keeps the mode from latching.
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 4, 4)));
        let _ = render_frame_incremental(id, size, Color::WHITE, Some(&frame)).expect("frame");
        assert_eq!(large_damage_run_of(id), 0, "small damage must reset the run");
        unregister(id);
    }

    /// The rendered pixels must be *correct*, not merely cheap: a region-limited repaint
    /// has to produce the same frame as a full one.
    ///
    /// This is the assertion that makes the feature safe to enable. A tracker that
    /// recorded the wrong rectangle would still return `Some(frame)` and still report a
    /// consumed region — only comparing pixels catches a partial paint that painted the
    /// wrong part (or left a stale one).
    #[test]
    fn an_incremental_repaint_matches_a_full_repaint() {
        // Frames are compared byte for byte, and a control's chrome reads the active theme, so the
        // appearance has to be pinned for the comparison to be about the repaint strategy rather
        // than about whichever theme a concurrently-running test left selected.
        let _guard = crate::style::theme_test_guard();
        crate::widget::census::install_preset_appearances();
        crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);
        let size = Size::new(320, 200);

        // Reference: paint whole every time.
        let full_id = register(sample_editor("fn main() {}")).expect("registry");
        let baseline = render_frame_incremental(full_id, size, Color::WHITE, None).expect("frame");
        let mut expected = baseline.clone();
        let full_second =
            render_frame_incremental(full_id, size, Color::WHITE, Some(&baseline)).expect("frame");
        assert_eq!(full_second, baseline, "a full repaint of unchanged state is identical");
        expected.clone_from(&full_second);

        // Same control, damage-tracked.
        let dirty_id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode_adaptive(dirty_id));
        let first = render_frame_incremental(dirty_id, size, Color::WHITE, None).expect("frame");
        assert!(mark_dirty_rect(dirty_id, Rect::new(8, 8, 24, 12)));
        let second =
            render_frame_incremental(dirty_id, size, Color::WHITE, Some(&first)).expect("frame");

        assert_eq!(second.len(), expected.len());
        assert_eq!(
            second, expected,
            "a region-limited repaint must produce the same pixels as a full one"
        );
        unregister(full_id);
        unregister(dirty_id);
    }

    #[test]
    fn register_then_unregister_round_trips() {
        let before = mounted_count();
        let id = register(sample_editor("fn main() {}")).expect("ui thread has a registry");
        assert!(is_mounted(id));
        assert_eq!(mounted_count(), before + 1);
        assert!(unregister(id));
        assert!(!is_mounted(id));
        assert_eq!(mounted_count(), before);
    }

    #[test]
    fn unregister_unknown_id_is_false() {
        assert!(!unregister(0xDEAD_BEEF));
    }

    /// A widget defaults to `Full`, so adopting damage tracking is opt-in and no
    /// existing caller's behaviour changes without asking.
    #[test]
    fn repaint_defaults_to_full() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert_eq!(repaint_mode(id), RepaintMode::Full);
        unregister(id);
    }

    /// Setting a policy on something that is not mounted must report the failure
    /// rather than silently succeeding on a key that addresses nothing.
    #[test]
    fn set_repaint_mode_rejects_an_unmounted_id() {
        assert!(!set_repaint_mode(0xDEAD_BEEF, RepaintMode::Dirty));
    }

    /// Damage is only recorded in the modes that read it, so a `Full` widget does
    /// not accumulate rects it will never consume.
    #[test]
    fn damage_is_recorded_only_when_a_mode_will_read_it() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let rect = Rect::new(10, 10, 40, 20);

        assert!(!mark_dirty_rect(id, rect), "Full mode must not accumulate damage");
        assert!(dirty_rects(id).is_empty());

        assert!(set_repaint_mode(id, RepaintMode::Dirty));
        assert!(mark_dirty_rect(id, rect), "Dirty mode must record the damage");
        assert_eq!(dirty_rects(id), vec![rect]);

        unregister(id);
    }

    /// Recording damage must also ask the platform to repaint, or the damage would be
    /// tracked and never shown.
    ///
    /// # How this is observed
    ///
    /// The test backend records its invalidations, so the assertion is on what the
    /// backend was asked to do — not on a return value. A `mark_dirty_rect` that only
    /// updated the tracker would leave the invalidation log empty and fail here.
    #[test]
    fn recording_damage_asks_the_platform_to_repaint() {
        use crate::platform::RecordingInvalidations;

        let id = register(sample_editor("fn main() {}")).expect("registry");
        // `Box::leak` because the override holds a `&'static dyn Platform`: it must
        // outlive the call, and a test process is short-lived, so the leak is bounded
        // by the number of tests that install one.
        let log: &'static RecordingInvalidations =
            alloc::boxed::Box::leak(alloc::boxed::Box::new(RecordingInvalidations::new()));
        assert!(set_repaint_mode(id, RepaintMode::Dirty));

        let rect = Rect::new(4, 8, 16, 16);
        let recorded =
            crate::platform::with_recorded_invalidations(log, || mark_dirty_rect(id, rect));

        assert!(recorded, "the damage must still be recorded");
        assert_eq!(
            log.calls(),
            vec![(id, Some(rect))],
            "the platform must be told about the damage, narrowed to the rect when it can"
        );

        // `Full` mode records nothing, so it must not invalidate either — the caller is
        // expected to drive a whole-frame repaint itself.
        assert!(set_repaint_mode(id, RepaintMode::Full));
        log.clear();
        assert!(!crate::platform::with_recorded_invalidations(log, || {
            mark_dirty_rect(id, rect)
        }));
        assert!(log.calls().is_empty(), "a refused mark must not reach the platform");

        unregister(id);
    }

    /// A backend that cannot narrow must still be told to repaint, or the fallback
    /// would leave the surface stale.
    ///
    /// The recorder is asked to refuse narrowing, and the assertion is that a
    /// whole-surface invalidation arrived instead — so this pins the fallback itself,
    /// not merely that some call was made.
    #[test]
    fn a_backend_that_cannot_narrow_gets_a_whole_surface_repaint() {
        use crate::platform::RecordingInvalidations;

        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));

        let log: &'static RecordingInvalidations = alloc::boxed::Box::leak(alloc::boxed::Box::new(
            RecordingInvalidations::refusing_narrowing(),
        ));
        let rect = Rect::new(2, 2, 8, 8);
        assert!(crate::platform::with_recorded_invalidations(log, || mark_dirty_rect(id, rect)));

        assert_eq!(
            log.calls(),
            vec![(id, None)],
            "a backend that refuses narrowing must receive a whole-surface invalidation"
        );

        unregister(id);
    }

    /// Switching back to `Full` drops stale damage: a region that stopped mattering
    /// several frames ago must not be repainted when `Dirty` is re-selected.
    #[test]
    fn switching_to_full_forgets_accumulated_damage() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 10, 10)));
        assert_eq!(dirty_rects(id).len(), 1);

        assert!(set_repaint_mode(id, RepaintMode::Full));
        assert!(dirty_rects(id).is_empty(), "Full must clear what it will not replay");

        unregister(id);
    }

    /// A no-damage cached frame must not copy the full RGBA buffer three times. (D09-RENDER-04)
    ///
    /// # What this pins
    ///
    /// `render_frame_cached` cloned `LAST_FRAME` into `previous`, `render_frame_incremental`
    /// copied the carried buffer again to return it, and the result was cloned a third time back
    /// into the cache — three full-frame copies for a frame that drew nothing. The copy counter
    /// observes the cache's own full-buffer copies, so this asserts the count directly rather
    /// than inferring it from timing.
    #[test]
    fn an_undamaged_cached_frame_copies_the_buffer_once() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(96, 64);

        // First paint fills the cache (a full paint; its cost is not what this test bounds).
        let first = render_frame_cached(id, size, Color::rgb(3, 3, 3)).expect("first frame");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));

        // No damage: the cached frame is returned unchanged, with a single copy.
        let _ = take_frame_cache_copies();
        let second = render_frame_cached(id, size, Color::rgb(3, 3, 3)).expect("second frame");
        let copies = take_frame_cache_copies();

        assert_eq!(second, first, "an undamaged frame must not change a pixel");
        assert_eq!(
            copies, 1,
            "a no-damage cached frame must copy its buffer once (for the owned return), not three times"
        );

        unregister(id);
    }

    /// `Full` mode must not deep-copy a previous frame it will not read. (D09-RENDER-04)
    #[test]
    fn full_mode_does_not_copy_an_unused_previous_frame() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(64, 48);

        // Prime the cache, then force `Full`: every call repaints whole and ignores `previous`.
        render_frame_cached(id, size, Color::rgb(1, 1, 1)).expect("first frame");
        assert!(set_repaint_mode(id, RepaintMode::Full));

        let _ = take_frame_cache_copies();
        render_frame_cached(id, size, Color::rgb(1, 1, 1)).expect("second frame");
        let copies = take_frame_cache_copies();

        // A full paint makes one copy for the cache/return, but the *unused* previous frame is
        // not cloned on top of that. Three was the old count.
        assert!(
            copies <= 1,
            "Full mode must not clone the previous frame it ignores; copied {copies} times"
        );

        unregister(id);
    }

    /// The cached no-damage fast path must keep `Adaptive`'s reset behaviour. (D09-RENDER-04)
    ///
    /// # Why this is a regression test and not just a copy count
    ///
    /// The no-damage fast path in `render_frame_cached` returns the cached frame without going
    /// through `render_frame_incremental`. That callee clears the `Adaptive` run counter on a
    /// no-damage frame — its documented proof that the surface settled. If the fast path had
    /// skipped the reset, `Adaptive` would latch after a burst of large damage and never return to
    /// regioning, which is the exact failure the run counter exists to prevent.
    #[test]
    fn cached_no_damage_frame_still_resets_the_adaptive_run() {
        let size = Size::new(160, 120);
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(id, RepaintMode::Adaptive));

        // Build up the run with whole-surface damage through the cached entry point.
        render_frame_cached(id, size, Color::rgb(1, 1, 1)).expect("first frame");
        for _ in 0..ADAPTIVE_LARGE_DAMAGE_RUN {
            assert!(mark_dirty_rect(id, Rect::new(0, 0, 160, 120)));
            render_frame_cached(id, size, Color::rgb(1, 1, 1)).expect("frame");
        }
        assert_eq!(adaptive_large_damage_run(id), ADAPTIVE_LARGE_DAMAGE_RUN);

        // No damage: the cached fast path runs, and it must clear the run.
        let _ = render_frame_cached(id, size, Color::rgb(1, 1, 1)).expect("frame");
        assert_eq!(
            adaptive_large_damage_run(id),
            0,
            "a no-damage cached frame must reset the Adaptive run, or the mode latches"
        );

        unregister(id);
    }

    /// High-cardinality damage recorded through `mark_dirty_rect` must be bounded at record time,
    /// so the frame does not do one widget-tree traversal per region. (D09-RENDER-01)
    ///
    /// # What this pins
    ///
    /// The tracker's `max_regions` limit was only applied by `optimize()`, which the runtime
    /// never called, so a widget invalidating hundreds of small rectangles grew the tracker
    /// without bound and the repaint loop issued up to that many full draws. `mark_dirty_rect` now
    /// folds the damage into one covering region once the limit is reached, and this asserts the
    /// bounded count that results.
    #[test]
    fn many_small_damage_rects_are_bounded_and_keep_all_damage() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));

        // Far more rects than the default capacity (100).
        for i in 0..500 {
            assert!(mark_dirty_rect(id, Rect::new(i, 0, 1, 1)));
        }

        let regions = dirty_rects(id);
        assert!(
            regions.len() <= 100,
            "exceeding the region capacity must bound the region count, got {}",
            regions.len()
        );
        // No damage was dropped: the union of the returned regions covers every recorded rect
        // (they span x = 0..=499, y = 0).
        let union =
            regions.iter().copied().reduce(|a, b| a.union(&b)).expect("at least one region");
        assert!(union.x <= 0, "the union must start at the leftmost damage: {union:?}");
        assert!(
            union.right() >= 500,
            "the union must reach the rightmost damage (x=499): {union:?}"
        );

        unregister(id);
    }

    /// The record-time bound must not change what is repainted: a bounded frame matches a full
    /// repaint pixel for pixel. (D09-RENDER-01)
    #[test]
    fn bounded_high_cardinality_repaint_matches_a_full_repaint() {
        let _guard = crate::style::theme_test_guard();
        crate::widget::census::install_preset_appearances();
        crate::theme::global_theme_manager().set_appearance(crate::theme::AppearanceMode::Light);
        let size = Size::new(120, 80);

        let full_id = register(sample_editor("fn main() {}")).expect("registry");
        let expected = render_frame_cached(full_id, size, Color::WHITE).expect("frame");

        let dirty_id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(dirty_id, RepaintMode::Dirty));
        let first = render_frame_cached(dirty_id, size, Color::WHITE).expect("frame");
        assert_eq!(first, expected, "the first frame is a full paint either way");

        // Damage far exceeding capacity, spread over the surface.
        for i in 0..400i32 {
            assert!(mark_dirty_rect(dirty_id, Rect::new(i % 120, (i / 120) * 20, 1, 1)));
        }
        let second = render_frame_cached(dirty_id, size, Color::WHITE).expect("frame");
        assert_eq!(
            second, expected,
            "a capacity-bounded repaint must produce the same pixels as a full repaint"
        );

        unregister(full_id);
        unregister(dirty_id);
    }

    /// A frame rendered with no damage must return the previous frame's pixels
    /// unchanged, which is the whole saving: no draw calls, same result.
    #[test]
    fn an_undamaged_frame_returns_the_previous_pixels() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(64, 48);

        let first = render_frame(id, size, Color::rgb(10, 20, 30)).expect("first frame");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));

        // No damage recorded, so the second frame is the first frame.
        let second = render_frame_incremental(id, size, Color::rgb(10, 20, 30), Some(&first))
            .expect("second frame");
        assert_eq!(second, first, "an undamaged frame must not change any pixel");

        unregister(id);
    }

    /// Without a previous frame there is nothing to preserve, so the call falls back
    /// to a full paint rather than returning a buffer it cannot fill.
    #[test]
    fn a_missing_previous_frame_forces_a_full_paint() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(64, 48);
        assert!(set_repaint_mode(id, RepaintMode::Dirty));
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 8, 8)));

        let frame = render_frame_incremental(id, size, Color::rgb(1, 2, 3), None)
            .expect("a frame is still produced");
        assert_eq!(frame.len(), size.width as usize * size.height as usize * 4);

        unregister(id);
    }

    /// `render_frame_cached` must remember the frame it produced, so the next call
    /// can carry it forward instead of asking the caller to.
    ///
    /// This is the property that makes `RepaintMode` reach the screen: a backend's
    /// paint callback passes only the widget and the size, so if nothing remembered
    /// the previous frame every paint would fall back to full.
    #[test]
    fn the_cached_renderer_remembers_its_frame() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(64, 48);

        assert_eq!(cached_frame_size(id), None, "nothing is cached before a first paint");

        let first = render_frame_cached(id, size, Color::rgb(9, 9, 9)).expect("first frame");
        assert_eq!(
            cached_frame_size(id),
            Some(size),
            "the frame must be remembered, keyed by the size it was rendered at"
        );

        // A second paint with no damage returns the remembered frame byte for byte.
        assert!(set_repaint_mode(id, RepaintMode::Dirty));
        let second = render_frame_cached(id, size, Color::rgb(9, 9, 9)).expect("second frame");
        assert_eq!(second, first, "an undamaged repaint must not change a pixel");

        unregister(id);
        assert_eq!(cached_frame_size(id), None, "unmounting must drop the frame");
    }

    /// A control placed away from the surface origin must paint into its own frame.
    ///
    /// Regression: `render_frame` created a buffer the size of the control's own box but
    /// asked it to draw at the control's **absolute** coordinates, with no translation.
    /// A control at `(12, 42)` therefore painted from `(12, 42)` inside a 200×120 buffer:
    /// the top band stayed blank and the bottom-right of the control was clipped away.
    /// Every fixture in this module used `Rect::new(0, 0, ..)`, so the whole suite was
    /// blind to it — only a control with a non-zero origin can catch it.
    #[test]
    fn a_control_offset_from_the_origin_paints_into_its_own_frame() {
        let geometry = Rect::new(12, 42, 200, 160);
        let mut chart =
            crate::widget::special_widgets::finance::candlestick_chart::CandlestickChart::new(
                geometry,
            );
        let mut series = crate::widget::special_widgets::finance::types::PriceSeries::new();
        for index in 0..20 {
            let open = 100.0 + index as f64;
            series.push(crate::widget::special_widgets::finance::types::Bar::new(
                open,
                open + 2.0,
                open - 2.0,
                open + 1.0,
                1000.0,
            ));
        }
        chart.set_series(series);
        let id = register(Box::new(chart)).expect("registry");

        let size = Size::new(geometry.width, geometry.height);
        let frame = render_frame(id, size, Color::BLACK).expect("frame");

        // The panel background is a dark slate, not the clear colour, and the control
        // fills its plot area — so the frame must be substantially painted rather than
        // carrying a blank band as tall as the geometry's y offset.
        let painted =
            frame.as_chunks::<4>().0.iter().filter(|pixel| **pixel != [0, 0, 0, 255]).count();
        let total = size.width as usize * size.height as usize;
        assert!(
            painted > total / 2,
            "a control offset by ({}, {}) painted only {painted}/{total} pixels",
            geometry.x,
            geometry.y
        );
        // And the blank band above the first paint must be the control's own top margin
        // (a few pixels), not its absolute y offset. Before the translation was applied
        // this band was as tall as `geometry.y`, which is the failure this pins.
        let mut blank_rows = 0usize;
        for row in 0..size.height as usize {
            let start = row * size.width as usize * 4;
            let blank = frame[start..start + size.width as usize * 4]
                .as_chunks::<4>()
                .0
                .iter()
                .all(|pixel| *pixel == [0, 0, 0, 255]);
            if !blank {
                break;
            }
            blank_rows += 1;
        }
        assert!(
            blank_rows < geometry.y as usize,
            "the blank top band ({blank_rows} rows) must be the control's own margin, \
             not its absolute y offset ({})",
            geometry.y
        );

        unregister(id);
    }

    /// A cached frame of the wrong size must not be used, or a resize would leave part
    /// of the surface holding the previous layout's pixels.
    #[test]
    fn a_resize_discards_the_cached_frame() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let small = Size::new(32, 24);
        let large = Size::new(96, 72);

        render_frame_cached(id, small, Color::rgb(1, 1, 1)).expect("small frame");
        assert_eq!(cached_frame_size(id), Some(small));

        let resized = render_frame_cached(id, large, Color::rgb(1, 1, 1)).expect("large frame");
        assert_eq!(
            resized.len(),
            large.width as usize * large.height as usize * 4,
            "a resize must produce a frame of the new size"
        );
        assert_eq!(
            cached_frame_size(id),
            Some(large),
            "the cache must follow the resize rather than keep the old frame"
        );

        unregister(id);
    }

    /// Damage recorded on a removed widget must not survive it: a reused id would
    /// otherwise repaint a region that no longer exists.
    #[test]
    fn unmounting_drops_the_damage_too() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 4, 4)));
        assert_eq!(dirty_rects(id).len(), 1);

        unregister(id);
        assert!(dirty_rects(id).is_empty(), "the damage must go with the widget");
    }

    /// `Adaptive` and `Dirty` must not be the same policy.
    ///
    /// # What separates them
    ///
    /// `Dirty` means the caller has already decided damage tracking is worth it, so
    /// every frame is measured. `Adaptive` means the caller does not know, so a run of
    /// frames whose damage covers the surface is taken as evidence that regioning
    /// cannot pay off here — and from then on it paints whole instead of measuring the
    /// same answer again.
    ///
    /// Asserting on the run counter is asserting on that decision, because the counter
    /// *is* the mode's memory. A version that treated the two modes alike would leave
    /// it at zero forever, which is exactly what this test fails on.
    #[test]
    fn adaptive_learns_from_a_run_of_large_damage_but_dirty_does_not() {
        let size = Size::new(200, 200);
        // Damage covering the whole frame, so every frame is over the ratio.
        let whole = Rect::new(0, 0, 200, 200);

        // `Dirty`: measured every frame, never accumulates a run.
        let dirty_id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(dirty_id, RepaintMode::Dirty));
        let mut frame = render_frame(dirty_id, size, Color::rgb(1, 1, 1)).expect("first frame");
        for _ in 0..(ADAPTIVE_LARGE_DAMAGE_RUN + 2) {
            assert!(mark_dirty_rect(dirty_id, whole));
            frame = render_frame_incremental(dirty_id, size, Color::rgb(1, 1, 1), Some(&frame))
                .expect("frame");
        }
        assert_eq!(
            adaptive_large_damage_run(dirty_id),
            0,
            "Dirty must not learn: the caller already decided, so every frame is measured"
        );
        unregister(dirty_id);

        // `Adaptive`: the same input accumulates the run.
        let adaptive_id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(adaptive_id, RepaintMode::Adaptive));
        let mut frame = render_frame(adaptive_id, size, Color::rgb(1, 1, 1)).expect("first frame");
        assert_eq!(
            adaptive_large_damage_run(adaptive_id),
            0,
            "a full paint is not evidence either way"
        );

        for expected in 1..=(ADAPTIVE_LARGE_DAMAGE_RUN as usize) {
            assert!(mark_dirty_rect(adaptive_id, whole));
            frame = render_frame_incremental(adaptive_id, size, Color::rgb(1, 1, 1), Some(&frame))
                .expect("frame");
            assert_eq!(
                adaptive_large_damage_run(adaptive_id) as usize,
                expected,
                "each over-threshold frame must advance the run"
            );
        }
        unregister(adaptive_id);
    }

    /// A frame with small damage resets the `Adaptive` run, so the mode settles back
    /// into regioning after an animation ends instead of staying latched.
    #[test]
    fn adaptive_recovers_when_the_damage_shrinks() {
        let size = Size::new(200, 200);
        let id = register(sample_editor("fn main() {}")).expect("registry");
        assert!(set_repaint_mode(id, RepaintMode::Adaptive));
        let mut frame = render_frame(id, size, Color::rgb(1, 1, 1)).expect("first frame");

        for _ in 0..ADAPTIVE_LARGE_DAMAGE_RUN {
            assert!(mark_dirty_rect(id, Rect::new(0, 0, 200, 200)));
            frame = render_frame_incremental(id, size, Color::rgb(1, 1, 1), Some(&frame))
                .expect("frame");
        }
        assert_eq!(adaptive_large_damage_run(id), ADAPTIVE_LARGE_DAMAGE_RUN);

        // One small-damage frame is proof the surface settled. Its output is the frame
        // for the *next* call, so it is carried rather than discarded.
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 4, 4)));
        let _settled =
            render_frame_incremental(id, size, Color::rgb(1, 1, 1), Some(&frame)).expect("frame");
        assert_eq!(
            adaptive_large_damage_run(id),
            0,
            "a small-damage frame must clear the run, or the mode would latch"
        );

        unregister(id);
    }

    /// A previous frame of the wrong size cannot be carried forward; the call must
    /// still return a correct, fully sized frame instead of a half-stale one.
    #[test]
    fn a_wrongly_sized_previous_frame_is_ignored() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(64, 48);
        assert!(set_repaint_mode(id, RepaintMode::Dirty));
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 8, 8)));

        let wrong = vec![0u8; 7];
        let frame = render_frame_incremental(id, size, Color::rgb(1, 2, 3), Some(&wrong))
            .expect("a frame is still produced");
        assert_eq!(
            frame.len(),
            size.width as usize * size.height as usize * 4,
            "a mismatched previous frame must not resize the output"
        );

        unregister(id);
    }

    /// Dirty repaint must leave the untouched region holding the previous frame's
    /// pixels, not the clear colour: that is the observable difference between a
    /// partial repaint and a full one.
    #[test]
    fn a_dirty_repaint_preserves_pixels_outside_the_damage() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let size = Size::new(80, 60);
        let clear = Color::rgb(200, 30, 40);

        let first = render_frame(id, size, clear).expect("first frame");
        assert!(set_repaint_mode(id, RepaintMode::Dirty));

        // Damage a region in the top-left only, then repaint with a different clear
        // colour. A full paint would fill the whole frame with the new colour; a
        // dirty paint must leave the far corner alone.
        assert!(mark_dirty_rect(id, Rect::new(0, 0, 8, 8)));
        let second = render_frame_incremental(id, size, Color::rgb(0, 0, 0), Some(&first))
            .expect("second frame");

        let last_pixel = second.len() - 4;
        assert_eq!(
            &second[last_pixel..],
            &first[last_pixel..],
            "the far corner is outside the damage and must keep its pixels"
        );

        unregister(id);
    }

    #[test]
    fn mounted_ids_do_not_collide_with_platform_ids() {
        // Platform-allocated ids count up from 1; mounted ids start far above.
        let id = register(sample_editor("x")).expect("registry");
        assert!(id > 0x5345_4C46_0000_0000, "mounted id {id:#x} must not look platform-issued");
        unregister(id);
    }

    #[test]
    fn with_widget_mut_exposes_the_real_widget() {
        let id = register(sample_editor("fn main() {}")).expect("registry");
        let lines =
            with_widget_mut(id, |widget| editor_of(widget).map(|editor| editor.line_count()))
                .flatten();
        assert_eq!(lines, Some(1));
        unregister(id);
    }

    #[test]
    fn with_widget_mut_on_missing_id_is_none() {
        assert!(with_widget_mut(0x1234_5678, |_| ()).is_none());
    }

    #[test]
    fn geometry_can_be_read_and_written_through_the_registry() {
        let id = register(sample_editor("x")).expect("registry");
        assert_eq!(geometry_of(id).map(|r| (r.width, r.height)), Some((320, 200)));
        assert!(set_geometry(id, Rect::new(5, 6, 400, 300)));
        let geometry = geometry_of(id).expect("mounted");
        assert_eq!((geometry.x, geometry.y, geometry.width, geometry.height), (5, 6, 400, 300));
        unregister(id);
    }

    #[test]
    fn render_frame_returns_rgba_of_the_requested_size() {
        let id = register(sample_editor("fn main() {\n    let x = 1;\n}")).expect("registry");
        let frame = render_frame(id, Size::new(64, 48), Color::WHITE).expect("frame");
        assert_eq!(frame.len(), 64 * 48 * 4);
        // The editor paints a light background, so at least one pixel must be
        // non-transparent; a fully blank frame means the widget never drew.
        assert!(
            frame.as_chunks::<4>().0.iter().any(|px| px[3] != 0),
            "frame must contain drawn pixels"
        );
        unregister(id);
    }

    #[test]
    fn render_frame_rejects_empty_size_and_missing_ids() {
        let id = register(sample_editor("x")).expect("registry");
        assert!(render_frame(id, Size::new(0, 10), Color::WHITE).is_none());
        assert!(render_frame(0x9999, Size::new(10, 10), Color::WHITE).is_none());
        unregister(id);
    }

    /// **Every control the demo places must actually paint.**
    ///
    /// The tree walk skips a child that is not visible or has no `Draw`, and it does so
    /// silently — which is right for a hidden page but wrong for a control the caller
    /// placed on purpose. A control that never paints is invisible on screen while every
    /// geometry check passes, so this checks the *frame* rather than the geometry.
    ///
    /// Each widget is rendered on its own, at its own size, and the frame must contain at
    /// least one pixel that differs from the clear colour. A control whose whole
    /// appearance happens to equal the clear colour fails this, which is deliberate: from
    /// the user's side that control is not there either.
    #[test]
    fn every_control_kind_the_demo_uses_paints_something() {
        use crate::widget::WidgetFactory;

        // The kinds the control demo places, by factory name.
        let kinds = [
            "button",
            "checkbox",
            "radio_button",
            "spin_box",
            "combo_box",
            "line_edit",
            "slider",
            "progress_bar",
            "label",
        ];

        // A colour no widget's own palette uses, so "did it paint" cannot be confused
        // with "it painted a colour that happens to match".
        let clear = Color::rgb(255, 0, 255);
        let factory = WidgetFactory::new_with_defaults();
        let mut unpainted = Vec::new();

        for name in kinds {
            let Some(widget) = factory.create(name, Rect::new(0, 0, 120, 40), "sample") else {
                unpainted.push(format!("{name} (factory produced nothing)"));
                continue;
            };
            let Some(id) = register(widget) else {
                unpainted.push(format!("{name} (registration refused)"));
                continue;
            };
            set_geometry(id, Rect::new(0, 0, 120, 40));

            let painted = render_frame(id, Size::new(120, 40), clear)
                .map(|frame| {
                    frame
                        .as_chunks::<4>()
                        .0
                        .iter()
                        .any(|px| px[0] != 255 || px[1] != 0 || px[2] != 255)
                })
                .unwrap_or(false);
            if !painted {
                unpainted.push(name.to_string());
            }
            unregister(id);
        }

        assert!(
            unpainted.is_empty(),
            "these control kinds painted nothing, so they are invisible on screen: {unpainted:?}"
        );
    }

    #[test]
    fn render_frame_at_geometry_uses_widget_geometry() {
        let id = register(sample_editor("abc")).expect("registry");
        let frame = render_frame_at_geometry(id, Color::WHITE).expect("frame");
        assert_eq!(frame.len(), 320 * 200 * 4);
        unregister(id);
    }

    /// Every widget that paints itself must be mountable in a host surface.
    ///
    /// `Widget::as_draw_mut` defaults to `None`, so a widget can implement
    /// `Draw` and still be invisible when mounted — which is exactly how a
    /// mounted `Chip` silently produced no frame. This guards the contract for
    /// the widgets the demos and the factory expose.
    #[test]
    fn custom_widgets_report_the_draw_bridge() {
        use crate::widget::special_widgets::chip::Chip;
        use crate::widget::special_widgets::color_picker::ColorPicker;
        use crate::widget::special_widgets::gantt_widget::GanttWidget;
        use crate::widget::special_widgets::snackbar::Snackbar;
        use crate::widget::special_widgets::terminal_view::TerminalView;

        fn assert_mountable(name: &str, widget: &mut dyn Widget) {
            assert!(
                widget.as_draw_mut().is_some(),
                "{name} implements Draw but does not report itself via Widget::as_draw_mut, \
                 so mounting it in a window would paint nothing"
            );
        }

        assert_mountable("CodeEditor", &mut CodeEditor::new(Rect::new(0, 0, 80, 60)));
        assert_mountable("Chip", &mut Chip::new(Rect::new(0, 0, 80, 24)));
        assert_mountable("ColorPicker", &mut ColorPicker::new(Rect::new(0, 0, 200, 150)));
        assert_mountable("GanttWidget", &mut GanttWidget::new(Rect::new(0, 0, 200, 150)));
        assert_mountable("Snackbar", &mut Snackbar::new(Rect::new(0, 0, 200, 40)));
        assert_mountable("TerminalView", &mut TerminalView::new(Rect::new(0, 0, 200, 150)));
    }

    /// A built-in control must report itself as paintable.
    ///
    /// This assertion is the inverse of the one that used to live here, which
    /// required `Button` to return `None` because the control was expected to be
    /// an OS widget. Every control is now painted by the library (BLUE15 #55), so
    /// a control that still answers `None` paints a blank surface — the exact
    /// regression this test exists to catch.
    #[test]
    fn built_in_controls_claim_the_draw_bridge() {
        use crate::widget::base_widgets::button::Button;
        use crate::widget::base_widgets::checkbox::CheckBox;
        use crate::widget::base_widgets::label::Label;

        let mut button = Button::new("ok".to_string(), Rect::new(0, 0, 80, 30));
        assert!(
            button.as_draw_mut().is_some(),
            "Button implements Draw, so mounting it must paint instead of showing a blank surface"
        );

        let mut checkbox = CheckBox::new(Rect::new(0, 0, 120, 24));
        assert!(checkbox.as_draw_mut().is_some(), "CheckBox must be paintable");

        let mut label = Label::new("hello".to_string(), Rect::new(0, 0, 80, 20));
        assert!(label.as_draw_mut().is_some(), "Label must be paintable");
    }

    #[test]
    fn dispatch_event_reaches_the_widget() {
        use crate::event::Event;
        let mut editor = CodeEditor::new(Rect::new(0, 0, 320, 200));
        editor.set_text("hello");
        let id = register(Box::new(editor)).expect("registry");
        // A click inside the text area must move the caret away from 0:0.
        let delivered = dispatch_event(
            id,
            &Event::MousePress { pos: Point::new(150, 90), button: 1, modifiers: 0 },
        );
        assert!(delivered, "event must reach the mounted widget");
        let cursor =
            with_widget_mut(id, |widget| editor_of(widget).map(|editor| editor.cursor())).flatten();
        assert!(cursor.is_some(), "widget must still be the editor");
        unregister(id);
    }

    /// A secondary-button press opens the menu at the pointer, clamped to the
    /// viewport — the whole right-click path in one assertion.
    #[cfg(full_widgets)]
    #[test]
    fn a_secondary_press_opens_the_mounted_context_menu() {
        let mut menu = crate::Menu::new("Edit", Rect::new(0, 0, 160, 100));
        menu.add_action("Copy");
        let id = register(Box::new(menu)).expect("registry");

        let viewport = Rect::new(0, 0, 500, 400);
        let opened = open_context_menu_for_event(
            id,
            &Event::MousePress {
                pos: Point::new(120, 90),
                button: crate::event::mouse_button::SECONDARY,
                modifiers: 0,
            },
            viewport,
        );

        assert!(opened, "a secondary press must open the context menu");
        let geometry = geometry_of(id).expect("mounted");
        assert_eq!((geometry.x, geometry.y), (120, 90));
        assert!(is_mounted(id));
        unregister(id);
    }

    /// The convenience wrapper must ignore every event that is not a secondary
    /// press, so a caller can forward its whole event stream without testing the
    /// button itself.
    #[cfg(full_widgets)]
    #[test]
    fn non_secondary_events_do_not_open_the_context_menu() {
        let mut menu = crate::Menu::new("Edit", Rect::new(0, 0, 160, 100));
        menu.add_action("Copy");
        let id = register(Box::new(menu)).expect("registry");
        let viewport = Rect::new(0, 0, 500, 400);

        assert!(!open_context_menu_for_event(
            id,
            &Event::MousePress {
                pos: Point::new(10, 10),
                button: crate::event::mouse_button::PRIMARY,
                modifiers: 0
            },
            viewport,
        ));
        assert!(!open_context_menu_for_event(
            id,
            &Event::MouseMove { pos: Point::new(10, 10) },
            viewport
        ));
        unregister(id);
    }

    /// Pointing the helper at an id that is not a menu must report failure rather
    /// than silently doing nothing, which is how a mis-wired right-click handler
    /// would otherwise go unnoticed.
    #[cfg(full_widgets)]
    #[test]
    fn opening_a_context_menu_on_a_non_menu_reports_failure() {
        let label = crate::widget::base_widgets::label::Label::new(
            "hi".to_string(),
            Rect::new(0, 0, 80, 24),
        );
        let id = register(Box::new(label)).expect("registry");

        assert!(!open_context_menu(id, Point::new(5, 5), Rect::new(0, 0, 400, 400)));
        assert!(!open_context_menu(9_999, Point::new(5, 5), Rect::new(0, 0, 400, 400)));
        unregister(id);
    }

    // -----------------------------------------------------------------------
    // Hit testing (point -> widget)
    // -----------------------------------------------------------------------

    /// Builds a container with two children, exercising the parent/children link
    /// the hit test walks. Returns `(parent, first, second)`.
    fn tree_with_two_children() -> (ObjectId, ObjectId, ObjectId) {
        let mut parent =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 300, 300));
        let first = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "first".to_string(),
            Rect::new(0, 0, 100, 50),
        )))
        .expect("registry");
        let second = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "second".to_string(),
            Rect::new(0, 0, 100, 50),
        )))
        .expect("registry");
        parent.add_child(first);
        parent.add_child(second);
        let parent = register(Box::new(parent)).expect("registry");
        (parent, first, second)
    }

    /// A point over a child must resolve to that child, not to the container.
    ///
    /// This is the capability that did not exist: before `widget_at`, the library
    /// could only deliver to an id the caller already knew.
    #[test]
    fn hit_test_descends_to_the_child_under_the_point() {
        let (parent, first, second) = tree_with_two_children();

        assert!(set_geometry(first, Rect::new(10, 10, 100, 50)));
        assert!(set_geometry(second, Rect::new(150, 10, 100, 50)));

        assert_eq!(widget_at(parent, Point::new(20, 20)), Some(first));
        assert_eq!(widget_at(parent, Point::new(160, 20)), Some(second));

        unregister(parent);
        unregister(first);
        unregister(second);
    }

    /// A point inside the container but outside every child resolves to the
    /// container — the search stops at the deepest hit, and "no child" is not
    /// the same as "no hit".
    #[test]
    fn hit_test_falls_back_to_the_container() {
        let (parent, first, second) = tree_with_two_children();
        set_geometry(first, Rect::new(10, 10, 100, 50));
        set_geometry(second, Rect::new(150, 10, 100, 50));

        assert_eq!(widget_at(parent, Point::new(250, 250)), Some(parent));

        unregister(parent);
        unregister(first);
        unregister(second);
    }

    /// A point outside the root resolves to nothing. Without this bound a click
    /// far outside the window would still land on whatever happened to be last.
    #[test]
    fn hit_test_returns_none_outside_the_root() {
        let (parent, first, second) = tree_with_two_children();
        assert_eq!(widget_at(parent, Point::new(5_000, 5_000)), None);
        unregister(parent);
        unregister(first);
        unregister(second);
    }

    /// An unmounted root must report no hit rather than panicking.
    #[test]
    fn hit_test_on_an_unmounted_root_is_none() {
        assert_eq!(widget_at(0xDEAD_BEEF, Point::new(0, 0)), None);
    }

    /// Later siblings paint on top, so they must also win the hit test. Reversing
    /// this order would make the visually-topmost control unclickable.
    #[test]
    fn hit_test_prefers_the_topmost_overlapping_child() {
        let (parent, first, second) = tree_with_two_children();
        // Both fully overlap; `second` is added last, so it draws on top.
        set_geometry(first, Rect::new(10, 10, 100, 50));
        set_geometry(second, Rect::new(10, 10, 100, 50));

        assert_eq!(widget_at(parent, Point::new(20, 20)), Some(second));

        unregister(parent);
        unregister(first);
        unregister(second);
    }

    /// A hidden child is not drawn, so it must not swallow a click.
    #[test]
    fn hit_test_skips_hidden_children() {
        let (parent, first, second) = tree_with_two_children();
        set_geometry(first, Rect::new(10, 10, 100, 50));
        set_geometry(second, Rect::new(10, 10, 100, 50));
        with_widget_mut(second, |widget| widget.hide());

        // `second` covers `first` but is hidden, so the click reaches `first`.
        assert_eq!(widget_at(parent, Point::new(20, 20)), Some(first));

        unregister(parent);
        unregister(first);
        unregister(second);
    }

    /// A container's children carry absolute rects (the layout engine derives a
    /// child's rect from its parent's absolute rect), so moving the container does
    /// not move its children in this model. The point of this test is that the walk
    /// composes down the tree by *containment*, not by summing parent origins —
    /// getting that wrong would offset every nested control.
    #[test]
    fn hit_test_finds_a_nested_child_through_two_levels() {
        let inner =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(20, 20, 100, 100));
        let inner = register(Box::new(inner)).expect("registry");
        let leaf = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "leaf".to_string(),
            Rect::new(30, 30, 40, 20),
        )))
        .expect("registry");
        with_widget_mut(inner, |widget| widget.add_child(leaf));

        let outer =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 300, 300));
        let outer = register(Box::new(outer)).expect("registry");
        with_widget_mut(outer, |widget| widget.add_child(inner));

        // (40, 40) is inside outer -> inner -> leaf, so the deepest widget wins.
        assert_eq!(widget_at(outer, Point::new(40, 40)), Some(leaf));
        // (25, 25) is inside outer and inner, but above the leaf.
        assert_eq!(widget_at(outer, Point::new(25, 25)), Some(inner));
        // (250, 250) is inside only the outer container.
        assert_eq!(widget_at(outer, Point::new(250, 250)), Some(outer));

        unregister(outer);
        unregister(inner);
        unregister(leaf);
    }

    /// The pointer-event helper must deliver to the widget under the point. Because
    /// geometry is absolute here, the event's own position needs no rewrite.
    #[test]
    fn dispatch_pointer_event_reaches_the_widget_under_the_point() {
        let mut parent =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 400, 300));
        let editor = register(sample_editor("fn main() {}\nlet a = 1;\nlet b = 2;")).expect("r");
        set_geometry(editor, Rect::new(100, 100, 320, 200));
        parent.add_child(editor);
        let parent = register(Box::new(parent)).expect("registry");

        let delivered = dispatch_pointer_event(
            parent,
            &Event::MousePress { pos: Point::new(150, 130), button: 1, modifiers: 0 },
            Point::new(150, 130),
        );
        assert!(delivered, "the editor under the point must receive the click");

        // Outside the editor but inside the container, the container is the target.
        assert_eq!(widget_at(parent, Point::new(380, 20)), Some(parent));

        unregister(parent);
        unregister(editor);
    }

    /// A click on empty space must be reported as undelivered, so a host knows
    /// nothing consumed it instead of assuming success.
    #[test]
    fn dispatch_pointer_event_outside_the_root_is_false() {
        let (parent, first, second) = tree_with_two_children();
        let delivered = dispatch_pointer_event(
            parent,
            &Event::MousePress { pos: Point::new(9_000, 9_000), button: 1, modifiers: 0 },
            Point::new(9_000, 9_000),
        );
        assert!(!delivered);
        unregister(parent);
        unregister(first);
        unregister(second);
    }

    // -----------------------------------------------------------------------
    // Keyboard focus
    // -----------------------------------------------------------------------

    /// Focus must have exactly one owner, and moving it must be observable both
    /// through the query and through the events the previous owner receives.
    #[test]
    fn focus_moves_and_reports_the_new_owner() {
        let first = register(sample_editor("a")).expect("registry");
        let second = register(sample_editor("b")).expect("registry");

        assert!(focus_widget(first));
        assert_eq!(focused_widget(), Some(first));
        assert!(has_focus(first));
        assert!(!has_focus(second));

        assert!(focus_widget(second));
        assert_eq!(focused_widget(), Some(second));
        assert!(!has_focus(first), "the previous owner must lose focus when another takes it");

        unregister(first);
        unregister(second);
    }

    /// Re-focusing the current owner is a no-op, so a repeated click cannot emit a
    /// second `FocusGained` for a widget that never lost focus.
    #[test]
    fn focus_on_the_current_owner_reports_no_move() {
        let id = register(sample_editor("a")).expect("registry");
        assert!(focus_widget(id));
        assert!(!focus_widget(id), "focus did not move, so the call must report false");
        unregister(id);
    }

    /// Focus on an id that is not mounted would be an unobservable lie: the key
    /// router would look for a widget that does not exist. It must be refused.
    #[test]
    fn focus_on_an_unmounted_widget_is_refused() {
        assert!(!focus_widget(0xDEAD_BEEF));
        assert_eq!(focused_widget(), None);
    }

    /// Clearing focus must tell the owner it lost it, and a second clear must not
    /// claim anything happened.
    #[test]
    fn clearing_focus_is_reported_once() {
        let id = register(sample_editor("a")).expect("registry");
        focus_widget(id);

        assert!(clear_focus());
        assert_eq!(focused_widget(), None);
        assert!(!clear_focus(), "there was no focus to clear the second time");

        unregister(id);
    }

    /// A widget that leaves the tree must leave the tab order too, or Tab would
    /// hand focus to an id that resolves to nothing.
    #[test]
    fn unregistering_a_focused_widget_drops_it_from_the_tab_order() {
        let first = register(sample_editor("a")).expect("registry");
        let second = register(sample_editor("b")).expect("registry");
        register_focusable(first);
        register_focusable(second);
        focus_widget(first);

        unregister(first);

        assert_eq!(focused_widget(), None, "the removed widget must not stay focused");
        assert!(!focusable_widgets().contains(&first));

        unregister(second);
    }

    /// Tab must actually move focus. Before the manager was wired into the
    /// registry this moved nothing, which is the defect these tests pin.
    #[test]
    fn tab_order_moves_focus_and_wraps() {
        let a = register(sample_editor("a")).expect("registry");
        let b = register(sample_editor("b")).expect("registry");
        set_focus_order_for_test(&[a, b]);

        assert_eq!(focus_next(true), Some(a));
        assert_eq!(focused_widget(), Some(a));
        assert_eq!(focus_next(true), Some(b));
        // Wrap-around: past the end comes back to the start.
        assert_eq!(focus_next(true), Some(a));
        // Backwards, and wrap-around in that direction too.
        assert_eq!(focus_next(false), Some(b));
        assert_eq!(focus_next(false), Some(a));

        unregister(a);
        unregister(b);
    }

    /// `Platform::route_pointer_event` must resolve the point against the widget tree
    /// rather than handing the event to the root.
    ///
    /// This is the wiring test for the whole chain: before it, the runtime could
    /// hit-test (`widget_at`) but nothing called it, so a click on a child still went
    /// to whichever widget owned the surface.
    #[test]
    #[cfg(full_widgets)]
    fn platform_pointer_routing_reaches_a_nested_child() {
        let mut parent =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 300, 300));
        let child = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "child".to_string(),
            Rect::new(40, 40, 80, 30),
        )))
        .expect("registry");
        parent.add_child(child);
        let parent = register(Box::new(parent)).expect("registry");

        let backend = crate::platform::platform_facts();

        // Inside the child: the route must descend past the parent.
        assert!(
            backend.route_pointer_event(
                parent,
                &Event::MousePress { pos: Point::new(50, 50), button: 1, modifiers: 0 },
                Point::new(50, 50),
            ),
            "a click inside the child must be delivered to it"
        );

        // Outside every child but inside the root: still delivered, to the root.
        assert!(
            backend.route_pointer_event(
                parent,
                &Event::MousePress { pos: Point::new(250, 250), button: 1, modifiers: 0 },
                Point::new(250, 250),
            ),
            "a click inside the root must still be delivered"
        );

        // Entirely outside the root: nothing accepts it, and that is reported.
        assert!(
            !backend.route_pointer_event(
                parent,
                &Event::MousePress { pos: Point::new(9_000, 9_000), button: 1, modifiers: 0 },
                Point::new(9_000, 9_000),
            ),
            "a click outside the root must report that nothing accepted it"
        );

        unregister(parent);
        unregister(child);
    }

    /// D09-POINTER-01: the stylus event family reaches a control through
    /// `Platform::route_pointer_event` end to end.
    ///
    /// This is the producer/consumer boundary made testable without a device: a host (or this
    /// test) constructs `PointerPress`/`PointerMove`/`PointerRelease` and routes them through
    /// the public platform entry point; the `SignaturePad` under the point must consume the
    /// whole lifecycle and retain the pressure. Before the fix the pad began strokes only from
    /// `MousePress`/`TouchBegin`, so this route delivered a press the pad ignored.
    #[test]
    #[cfg(full_widgets)]
    fn platform_pointer_routing_delivers_stylus_events_to_a_signature_pad() {
        let mut parent =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 300, 300));
        let pad_id =
            register(Box::new(crate::widget::special_widgets::signature_pad::SignaturePad::new(
                Rect::new(40, 40, 200, 120),
            )))
            .expect("registry");
        set_geometry(pad_id, Rect::new(40, 40, 200, 120));
        parent.add_child(pad_id);
        let parent = register(Box::new(parent)).expect("registry");

        let backend = crate::platform::platform_facts();

        // A pen contact inside the pad: press, move, release, all through the public route.
        assert!(
            backend.route_pointer_event(
                parent,
                &Event::pointer_press(Point::new(60, 80), 1, 0.3, 0.0, 0.0),
                Point::new(60, 80),
            ),
            "the press must be accepted by the pad under the point"
        );
        backend.route_pointer_event(
            parent,
            &Event::pointer_move(Point::new(120, 100), 0.8, 0.0, 0.0),
            Point::new(120, 100),
        );
        backend.route_pointer_event(
            parent,
            &Event::pointer_release(Point::new(120, 100), 1, 0.6),
            Point::new(120, 100),
        );

        // The pad consumed the sequence: one committed stroke whose first point is the press
        // position and whose per-point pressures were retained. The release's own pressure is the
        // last datum the device sent, so it becomes the pad's retained `last_pressure` even though
        // it adds no point (the lift-off position is the last accepted move).
        with_widget(pad_id, |widget| {
            let pad = (widget as &dyn core::any::Any)
                .downcast_ref::<crate::widget::special_widgets::signature_pad::SignaturePad>()
                .expect("the registered widget is a SignaturePad");
            assert_eq!(pad.stroke_count(), 1, "the routed stylus gesture must commit one stroke");
            let stroke = &pad.strokes()[0];
            assert_eq!(stroke.points()[0], Point::new(60, 80));
            assert!(
                (stroke.pressures()[0] - 0.3).abs() < 1e-6,
                "the press pressure must be recorded on the stroke's first point"
            );
            assert!(
                (stroke.last_pressure() - 0.8).abs() < 1e-6,
                "the move pressure must be recorded on the stroke's last point"
            );
            assert!((pad.last_pressure() - 0.6).abs() < 1e-6, "the release datum was retained");
        })
        .expect("the pad is mounted");

        unregister(parent);
        unregister(pad_id);
    }

    /// Establishes a deterministic tab order for a test, independent of whatever
    /// other widgets the shared thread-local registry happens to hold.
    fn set_focus_order_for_test(ids: &[ObjectId]) {
        with_focus_manager(|focus| {
            focus.set_focus_order(ids.to_vec());
            focus.clear_focus();
        })
        .expect("ui thread has a focus manager");
    }

    // -----------------------------------------------------------------------
    // Hover enter/leave synthesis
    // -----------------------------------------------------------------------

    /// Two overlapping widgets in one container, so the pointer can cross from one
    /// to the other. Returns `(parent, inner, outer)` where `inner` is nested inside
    /// `outer`'s area... actually both are leaves; `left` and `right` are side by side.
    fn two_siblings() -> (ObjectId, ObjectId, ObjectId) {
        let mut parent =
            crate::widget::container_widgets::groupbox::GroupBox::new(Rect::new(0, 0, 300, 300));
        let left = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "left".to_string(),
            Rect::new(0, 0, 100, 50),
        )))
        .expect("registry");
        let right = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "right".to_string(),
            Rect::new(0, 0, 100, 50),
        )))
        .expect("registry");
        set_geometry(left, Rect::new(10, 10, 100, 50));
        set_geometry(right, Rect::new(150, 10, 100, 50));
        parent.add_child(left);
        parent.add_child(right);
        let parent = register(Box::new(parent)).expect("registry");
        (parent, left, right)
    }

    /// Moving the pointer onto a widget must report it as hovered. No backend
    /// produces `MouseEnter`, so without this the state is unreachable and every
    /// hover highlight in the library is dead code.
    #[test]
    fn pointer_movement_sets_and_clears_the_hover_target() {
        let (parent, left, right) = two_siblings();
        clear_hover(Point::new(0, 0));
        assert_eq!(hovered_widget(), None);

        dispatch_pointer_event(
            parent,
            &Event::MouseMove { pos: Point::new(20, 20) },
            Point::new(20, 20),
        );
        assert_eq!(hovered_widget(), Some(left), "the pointer is over `left`");

        dispatch_pointer_event(
            parent,
            &Event::MouseMove { pos: Point::new(160, 20) },
            Point::new(160, 20),
        );
        assert_eq!(hovered_widget(), Some(right), "crossing onto `right` must move hover");

        // Leaving the surface entirely clears it, so a stale highlight cannot persist.
        clear_hover(Point::new(0, 0));
        assert_eq!(hovered_widget(), None);

        unregister(parent);
        unregister(left);
        unregister(right);
    }

    /// A control that receives `MouseEnter` must actually be told, because that is
    /// what flips its own hover flag. This is the end of the chain the backends could
    /// not reach before.
    #[test]
    fn entering_a_button_makes_it_report_hover() {
        let parent = register(Box::new(crate::widget::container_widgets::groupbox::GroupBox::new(
            Rect::new(0, 0, 300, 300),
        )))
        .expect("registry");
        let mut button = crate::widget::base_widgets::button::Button::new(
            "ok".to_string(),
            Rect::new(20, 20, 80, 30),
        );
        button.set_geometry(Rect::new(20, 20, 80, 30));
        let button_id = register(Box::new(button)).expect("registry");
        with_widget_mut(parent, |widget| widget.add_child(button_id));

        clear_hover(Point::new(0, 0));
        dispatch_pointer_event(
            parent,
            &Event::MouseMove { pos: Point::new(30, 30) },
            Point::new(30, 30),
        );
        let hovered = with_widget(button_id, |widget| {
            (widget as &dyn core::any::Any)
                .downcast_ref::<crate::widget::base_widgets::button::Button>()
                .map(|b| b.is_hovered())
        })
        .flatten();
        assert_eq!(hovered, Some(true), "MouseEnter must reach the button's hover flag");

        clear_hover(Point::new(0, 0));
        unregister(parent);
        unregister(button_id);
    }

    /// A widget removed while hovered must not remain the target, or the next
    /// movement would send `MouseLeave` to a dead id and skip the live one.
    #[test]
    fn unregistering_a_hovered_widget_clears_the_target() {
        let (parent, left, right) = two_siblings();
        dispatch_pointer_event(
            parent,
            &Event::MouseMove { pos: Point::new(20, 20) },
            Point::new(20, 20),
        );
        assert_eq!(hovered_widget(), Some(left));

        unregister(left);
        assert_eq!(hovered_widget(), None);

        unregister(parent);
        unregister(right);
    }

    /// Moving focus must tell the platform's IME bridge which control is being edited.
    ///
    /// Before this, `ImeBridge::focus_in` had **no caller anywhere**, so a backend's
    /// bridge never learned which widget was active and had no widget to place its
    /// candidate window against. This drives the real registry against a recording
    /// bridge and asserts the calls arrive.
    #[test]
    #[cfg(not(alloc_frugal))]
    fn moving_focus_notifies_the_ime_bridge() {
        let first = register(sample_editor("a")).expect("registry");
        let second = register(sample_editor("b")).expect("registry");
        clear_focus();

        // Drive the notification helper directly, because the bridge the *active*
        // backend exposes is a private implementation without a readback accessor.
        // The helper is the single place the runtime calls out to the IME, so this
        // covers the wiring that was missing.
        let recorder = RecordingImeBridge::default();
        {
            use crate::platform::ime::ImeBridge as _;
            recorder.focus_in(first);
            recorder.focus_out(first);
            recorder.focus_in(second);
        }
        assert_eq!(
            recorder.calls(),
            vec![("in", first), ("out", first), ("in", second)],
            "the IME bridge must be told about every focus change"
        );

        // And the real path must reach *some* bridge, exercising the call site.
        let backend = crate::platform::platform_facts();
        if backend.ime_bridge().is_some() {
            assert!(focus_widget(first));
            assert_eq!(focused_widget(), Some(first));
            assert!(clear_focus());
        }

        unregister(first);
        unregister(second);
    }

    /// Row-major traversal must order Tab by on-screen position, not registration.
    ///
    /// `FocusTraversalStrategy` was fully implemented but unreachable — nothing outside
    /// `FocusManager` could select one, so a grid could only ever tab in registration
    /// order.
    #[test]
    fn row_major_traversal_orders_tab_by_position() {
        let a = register(sample_editor("a")).expect("registry");
        let b = register(sample_editor("b")).expect("registry");
        let c = register(sample_editor("c")).expect("registry");

        // Register them in an order that disagrees with the layout: c, a, b.
        set_focus_order_for_test(&[c, a, b]);
        // Two rows: a and b on the top row, c below-left.
        assert!(set_focusable_position(a, 10, 10));
        assert!(set_focusable_position(b, 200, 10));
        assert!(set_focusable_position(c, 10, 100));

        assert!(set_focus_traversal(crate::event::FocusTraversalStrategy::RowMajor));
        assert_eq!(
            focusable_widgets(),
            vec![a, b, c],
            "row-major must visit the top row left-to-right before the row below"
        );

        // A non-focusable widget has no position to record.
        assert!(!set_focusable_position(0xDEAD_BEEF, 0, 0));

        // Back to registration order for the rest of the suite, which shares this
        // thread-local manager.
        assert!(set_focus_traversal(crate::event::FocusTraversalStrategy::TabOrder));
        unregister(a);
        unregister(b);
        unregister(c);
    }

    /// Column-major traversal orders by x first, then y.
    #[test]
    fn column_major_traversal_orders_tab_by_column() {
        let a = register(sample_editor("a")).expect("registry");
        let b = register(sample_editor("b")).expect("registry");

        set_focus_order_for_test(&[b, a]);
        // `b` is in the right column, `a` in the left, so column-major visits a first.
        assert!(set_focusable_position(a, 10, 300));
        assert!(set_focusable_position(b, 500, 10));

        assert!(set_focus_traversal(crate::event::FocusTraversalStrategy::ColumnMajor));
        assert_eq!(focusable_widgets(), vec![a, b], "column-major must visit left first");

        assert!(set_focus_traversal(crate::event::FocusTraversalStrategy::TabOrder));
        unregister(a);
        unregister(b);
    }

    /// Capture must make a widget receive pointer events wherever the pointer is.
    #[test]
    fn captured_widget_receives_pointer_events_off_itself() {
        let (parent, left, right) = two_siblings();
        release_pointer_capture();

        assert!(capture_pointer(left));
        assert_eq!(capturing_widget(), Some(left));
        assert!(has_pointer_capture(left));

        // (160, 20) is over `right`, but `left` holds capture, so it wins.
        assert!(
            dispatch_pointer_event(
                parent,
                &Event::MouseMove { pos: Point::new(160, 20) },
                Point::new(160, 20),
            ),
            "a captured widget must receive the event even when the pointer left it"
        );
        // Hover still tracks the true position, so highlights stay honest.
        assert_eq!(hovered_widget(), Some(right));

        assert!(release_pointer_capture());
        assert_eq!(capturing_widget(), None);
        assert!(!release_pointer_capture(), "a second release has nothing to release");

        unregister(parent);
        unregister(left);
        unregister(right);
    }

    /// Capture on an id that is not mounted would route every later pointer event into
    /// nothing, so it is refused — the same honest-answer rule used for focus.
    #[test]
    fn capturing_an_unmounted_widget_is_refused() {
        release_pointer_capture();
        assert!(!capture_pointer(0xDEAD_BEEF));
        assert_eq!(capturing_widget(), None);
    }

    /// A capture holder that is removed must not keep swallowing pointer events.
    #[test]
    fn unregistering_a_captured_widget_releases_capture() {
        let (parent, left, right) = two_siblings();
        assert!(capture_pointer(left));

        unregister(left);

        assert_eq!(capturing_widget(), None, "a removed widget must not keep capture");
        release_pointer_capture();
        unregister(parent);
        unregister(right);
    }

    /// D09-EVT-01: a press that drags off the control and is released elsewhere must
    /// still be delivered *back* to the control that owns the gesture, so its own press
    /// latch is cleared by the release rather than left armed.
    ///
    /// Before this the runtime resolved every release against the current position, so a
    /// release outside the button never reached it. The button kept its `grabbed`/`pressed`
    /// latch set, and a *later*, unrelated release that happened to land on the button
    /// then fired a spurious `clicked`. This test drives the full runtime sequence the
    /// issue's acceptance criterion names: press on A → move out over B → release over the
    /// blank → release again on A. Neither release may activate anything, and after the
    /// first (outside) release the button must hold no grab and no capture.
    #[test]
    fn a_press_released_off_the_control_is_delivered_back_and_clears_its_latch() {
        use crate::event::mouse_button;

        release_pointer_capture();
        let parent = register(Box::new(crate::widget::container_widgets::groupbox::GroupBox::new(
            Rect::new(0, 0, 300, 300),
        )))
        .expect("registry");

        // Two buttons side by side, plus a blank area to the right to release into.
        let mut a = crate::widget::base_widgets::button::Button::new(
            "A".to_string(),
            Rect::new(20, 20, 80, 30),
        );
        a.set_geometry(Rect::new(20, 20, 80, 30));
        let a = register(Box::new(a)).expect("registry");
        with_widget_mut(parent, |widget| widget.add_child(a));

        let mut b = crate::widget::base_widgets::button::Button::new(
            "B".to_string(),
            Rect::new(130, 20, 80, 30),
        );
        b.set_geometry(Rect::new(130, 20, 80, 30));
        let b = register(Box::new(b)).expect("registry");
        with_widget_mut(parent, |widget| widget.add_child(b));

        let clicks_a = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let counter_a = std::sync::Arc::clone(&clicks_a);
        with_widget_mut(a, |widget| {
            widget.base().clicked.connect(move || {
                counter_a.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            });
        });
        let clicks_b = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let counter_b = std::sync::Arc::clone(&clicks_b);
        with_widget_mut(b, |widget| {
            widget.base().clicked.connect(move || {
                counter_b.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            });
        });

        // Press inside A: A takes the gesture.
        assert!(dispatch_pointer_event(
            parent,
            &Event::MousePress {
                pos: Point::new(40, 35),
                button: mouse_button::PRIMARY,
                modifiers: 0
            },
            Point::new(40, 35),
        ));
        assert_eq!(capturing_widget(), Some(a), "the pressed control must own the gesture");

        // Drag out over B, then release on the blank at (280, 280) — over no child.
        dispatch_pointer_event(
            parent,
            &Event::MouseMove { pos: Point::new(160, 35) },
            Point::new(160, 35),
        );
        assert!(
            dispatch_pointer_event(
                parent,
                &Event::MouseRelease { pos: Point::new(280, 280), button: mouse_button::PRIMARY },
                Point::new(280, 280),
            ),
            "the off-widget release must be routed back to the gesture owner, not dropped"
        );

        // The gesture ended: no capture remains, A holds no grab, and nothing activated.
        assert_eq!(capturing_widget(), None, "the gesture-ending release must release the capture");
        assert!(
            !with_widget_mut(a, |w| w.base().is_grabbed()).unwrap_or(true),
            "A's grab must be cleared by the release that ended its gesture"
        );
        assert_eq!(clicks_a.load(std::sync::atomic::Ordering::SeqCst), 0);
        assert_eq!(clicks_b.load(std::sync::atomic::Ordering::SeqCst), 0);

        // Re-enter and release on A again with no matching press. Because the earlier
        // gesture was properly closed, this stray release must not fire A's `clicked`.
        dispatch_pointer_event(
            parent,
            &Event::MouseMove { pos: Point::new(40, 35) },
            Point::new(40, 35),
        );
        dispatch_pointer_event(
            parent,
            &Event::MouseRelease { pos: Point::new(40, 35), button: mouse_button::PRIMARY },
            Point::new(40, 35),
        );
        assert_eq!(
            clicks_a.load(std::sync::atomic::Ordering::SeqCst),
            0,
            "a stray release must not activate a control whose earlier gesture was cancelled"
        );

        unregister(a);
        unregister(b);
        unregister(parent);
    }

    // -----------------------------------------------------------------------
    // Modal dialog enforcement
    // -----------------------------------------------------------------------

    /// Builds a window with a modal dialog and an unrelated control, wiring the
    /// `parent` links that [`is_descendant_of`] walks (the same links the real mount
    /// path sets via `mount_named_widget`). Returns `(window, modal, outside)`, where
    /// the modal is a top-level dialog and `outside` is another widget the modal
    /// must block.
    fn modal_fixture() -> (ObjectId, ObjectId, ObjectId) {
        let window = register(Box::new(crate::widget::container_widgets::groupbox::GroupBox::new(
            Rect::new(0, 0, 400, 400),
        )))
        .expect("window");
        let modal = register(Box::new(crate::widget::dialog::message_box::MessageBox::new(
            Rect::new(50, 50, 200, 100),
        )))
        .expect("modal");
        let outside = register(Box::new(crate::widget::base_widgets::label::Label::new(
            "outside".to_string(),
            Rect::new(0, 0, 100, 20),
        )))
        .expect("outside");
        // The dialog and the label both belong to the window's frame of reference;
        // neither is a *child* of the other, so the modal must block the label.
        with_widget_mut(modal, |w| w.set_parent(Some(window)));
        with_widget_mut(outside, |w| w.set_parent(Some(window)));
        with_widget_mut(window, |w| {
            w.add_child(modal);
            w.add_child(outside);
        });
        (window, modal, outside)
    }

    #[test]
    fn no_modal_blocks_nothing() {
        let (window, modal, outside) = modal_fixture();
        assert!(!is_modal_active());
        assert!(!modal_blocks(window));
        assert!(!modal_blocks(modal));
        assert!(!modal_blocks(outside));
        unregister(window);
        unregister(modal);
        unregister(outside);
    }

    #[test]
    fn an_active_modal_blocks_input_outside_its_subtree() {
        let (window, modal, outside) = modal_fixture();

        assert!(enter_modal(modal));
        assert!(is_modal_active());
        assert_eq!(active_modal(), Some(modal));

        // The dialog itself stays live; everything else (the window chrome, an
        // unrelated control) is blocked.
        assert!(!modal_blocks(modal));
        assert!(modal_blocks(window));
        assert!(modal_blocks(outside));

        // Event delivery follows the same rule.
        let event = crate::event::Event::mouse_press(10, 10, 1);
        assert!(!dispatch_event(outside, &event), "a blocked widget must not receive events");
        assert!(dispatch_event(modal, &event), "the modal dialog must receive events");

        exit_modal(modal);
        assert!(!is_modal_active());
        assert!(!modal_blocks(outside), "after dismissal nothing is blocked");

        unregister(window);
        unregister(modal);
        unregister(outside);
    }

    #[test]
    fn a_modal_blocks_focus_outside_its_subtree() {
        let (window, modal, outside) = modal_fixture();
        clear_focus();

        enter_modal(modal);
        assert!(focus_widget(modal));
        // Focus elsewhere is refused while the modal is up.
        assert!(!focus_widget(outside));
        assert_eq!(focused_widget(), Some(modal));

        // After the modal is dismissed, focus can move to the formerly blocked widget.
        exit_modal(modal);
        assert!(focus_widget(outside));
        assert_eq!(focused_widget(), Some(outside));

        clear_focus();
        unregister(window);
        unregister(modal);
        unregister(outside);
    }

    #[test]
    fn an_unmounted_modal_cannot_be_entered() {
        clear_modals();
        assert!(!enter_modal(0xDEAD_BEEF));
        assert!(!is_modal_active());
    }

    #[test]
    fn clear_modals_drops_the_whole_stack() {
        let (_, modal, _) = modal_fixture();
        assert!(enter_modal(modal));
        assert!(is_modal_active());
        clear_modals();
        assert!(!is_modal_active());
        unregister(modal);
    }

    /// A recording IME bridge, for asserting the focus calls arrive in order.
    #[derive(Default)]
    struct RecordingImeBridge {
        calls: crate::compat::Mutex<Vec<(&'static str, ObjectId)>>,
    }

    impl RecordingImeBridge {
        fn calls(&self) -> Vec<(&'static str, ObjectId)> {
            self.calls.lock().unwrap().clone()
        }
    }

    impl crate::platform::ime::ImeBridge for RecordingImeBridge {
        fn focus_in(&self, widget_id: ObjectId) {
            self.calls.lock().unwrap().push(("in", widget_id));
        }
        fn focus_out(&self, widget_id: ObjectId) {
            self.calls.lock().unwrap().push(("out", widget_id));
        }
        fn commit_text(&self, _text: &str) {}
        fn set_composition(&self, _composition: &crate::platform::ime::ImeComposition) {}
        fn set_candidate_window_position(
            &self,
            _position: crate::platform::ime::ImeCandidatePosition,
        ) {
        }
        fn is_active(&self) -> bool {
            true
        }
    }

    // ── BLUE24 §6 -- the accessibility pump ──────────────────────────────────────

    /// A bridge that records what the submit points pushed, so the mount path can be asserted.
    ///
    /// `Mutex` rather than `RefCell` because `AccessibilityBridge` is `Send + Sync`, which a real
    /// platform bridge satisfies by being posted to from threads the platform owns.
    struct A11yRecorder {
        names: std::sync::Mutex<Vec<(ObjectId, String)>>,
        states: std::sync::Mutex<Vec<ObjectId>>,
        /// D09-A11Y-02: the complete state submitted per node, readable back through `node_state`.
        nodes: std::sync::Mutex<
            std::collections::HashMap<ObjectId, crate::platform::accessibility::A11yState>,
        >,
    }

    impl A11yRecorder {
        fn new() -> Self {
            Self {
                names: std::sync::Mutex::new(Vec::new()),
                states: std::sync::Mutex::new(Vec::new()),
                nodes: std::sync::Mutex::new(std::collections::HashMap::new()),
            }
        }
    }

    impl crate::platform::accessibility::AccessibilityBridge for A11yRecorder {
        fn set_accessibility_name(&self, id: ObjectId, name: &str) {
            self.names.lock().unwrap().push((id, name.to_string()));
        }
        fn accessibility_name(&self, id: ObjectId) -> Option<String> {
            self.names
                .lock()
                .unwrap()
                .iter()
                .rev()
                .find(|(recorded, _)| *recorded == id)
                .map(|(_, name)| name.clone())
        }
        fn notify_name_changed(&self, _id: ObjectId) {}
        fn notify_value_changed(&self, _id: ObjectId) {}
        fn notify_state_changed(&self, id: ObjectId) {
            self.states.lock().unwrap().push(id);
        }
        fn notify_focus_changed(&self, _id: ObjectId) {}
        // D09-A11Y-02/D09-A11Y-03: the substitute keeps the full node store the platform bridges
        // keep, so a test can read the whole submitted state back and watch the store return to
        // baseline across mount/unmount cycles — the observable assertions the defects require.
        fn submit_node_state(
            &self,
            id: ObjectId,
            state: &crate::platform::accessibility::A11yState,
        ) {
            self.names.lock().unwrap().push((id, state.label.clone()));
            self.nodes.lock().unwrap().insert(id, state.clone());
        }
        fn node_state(&self, id: ObjectId) -> Option<crate::platform::accessibility::A11yState> {
            self.nodes.lock().unwrap().get(&id).cloned()
        }
        fn unregister_node(&self, id: ObjectId) {
            self.names.lock().unwrap().retain(|(recorded, _)| *recorded != id);
            self.nodes.lock().unwrap().remove(&id);
        }
        fn node_count(&self) -> usize {
            self.nodes.lock().unwrap().len()
        }
    }

    /// Installs a recording bridge for one test, removing it on the way out even on panic.
    struct A11yGuard;
    impl Drop for A11yGuard {
        fn drop(&mut self) {
            let _ = crate::widget::a11y_submit::uninstall_bridge();
        }
    }

    /// BLUE24 §6 criterion 1 and §11 criterion 23: mounting controls creates their nodes.
    ///
    /// # Why the real `register` path
    ///
    /// A test that called `submit_mounted` directly would prove the submit function works and
    /// nothing about whether anything calls it — which is exactly the gap BLUE24 §0A.1 measured
    /// (three platform bridges, zero production callers). So this mounts through `register`, the
    /// same entry point every control in the crate uses, and asserts the bridge saw it.
    #[test]
    fn mounting_controls_creates_their_nodes() {
        let recorder: &'static A11yRecorder = Box::leak(Box::new(A11yRecorder::new()));
        crate::widget::a11y_submit::install_bridge(recorder);
        let _guard = A11yGuard;

        let label = register(Box::new(crate::widget::Label::new(
            "Hello".to_string(),
            crate::core::Rect::new(0, 0, 80, 24),
        )))
        .expect("mount a label");
        let _unmount_label = MountGuard(label);
        let button = register(Box::new(crate::widget::Button::new(
            "Save".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount a button");
        let _unmount_button = MountGuard(button);
        let checkbox =
            register(Box::new(crate::widget::CheckBox::new(crate::core::Rect::new(0, 0, 24, 24))))
                .expect("mount a check box");
        let _unmount_checkbox = MountGuard(checkbox);

        let names = recorder.names.lock().unwrap().clone();
        assert_eq!(names.len(), 3, "three controls mounted, so three names were pushed: {names:?}");
        assert!(
            names.iter().any(|(id, name)| *id == label && name == "Hello"),
            "a label's accessible name is its text: {names:?}"
        );
        assert!(
            names.iter().any(|(id, name)| *id == button && name == "Save"),
            "a button's accessible name is its title: {names:?}"
        );
        let states = recorder.states.lock().unwrap().clone();
        assert_eq!(states.len(), 3, "and each node's creation was reported: {states:?}");

        // D09-A11Y-02: the node the bridge received carries the derived *role*, not only the name.
        // Before the full-state contract, the mount path sent `label` alone, so a screen reader
        // could read "Save" but not know it was a button.
        assert_eq!(
            recorder.node_state(label).map(|s| s.role),
            Some(crate::platform::accessibility::A11yRole::Label),
            "a label's role reaches the bridge"
        );
        assert_eq!(
            recorder.node_state(button).map(|s| s.role),
            Some(crate::platform::accessibility::A11yRole::Button),
            "a button's role reaches the bridge"
        );
        assert_eq!(
            recorder.node_state(checkbox).map(|s| s.role),
            Some(crate::platform::accessibility::A11yRole::CheckBox),
            "a check box's role reaches the bridge"
        );
        // And the check box's checked state, which the label-only contract could never carry.
        assert_eq!(
            recorder.node_state(checkbox).and_then(|s| s.checked),
            Some(false),
            "an unchecked box reports `Some(false)`, not `None`"
        );
    }

    /// D09-A11Y-03: repeated mount/unmount cycles return the bridge's node store to baseline.
    ///
    /// The defect was a name map that blanked to `""` on unmount and kept one entry per historical
    /// widget id. Because the runtime allocates a fresh monotonically increasing id per mount, the
    /// counts must be compared across *distinct* ids — a cycle reusing one id would pass even if the
    /// store grew.
    #[test]
    fn repeated_mount_unmount_returns_the_bridge_store_to_baseline() {
        let recorder: &'static A11yRecorder = Box::leak(Box::new(A11yRecorder::new()));
        crate::widget::a11y_submit::install_bridge(recorder);
        let _guard = A11yGuard;

        let baseline = recorder.node_count();
        assert_eq!(baseline, 0, "a fresh bridge records no nodes");

        for cycle in 0..5 {
            let id = register(Box::new(crate::widget::Label::new(
                format!("cycle-{cycle}"),
                crate::core::Rect::new(0, 0, 80, 24),
            )))
            .expect("mount");
            assert_eq!(recorder.node_count(), baseline + 1, "one live node in cycle {cycle}");
            assert!(
                recorder.node_state(id).is_some(),
                "the mounted node is recorded in cycle {cycle}"
            );
            assert!(unregister(id), "the mounted id is present in cycle {cycle}");
            assert_eq!(
                recorder.node_count(),
                baseline,
                "the store returns to baseline after cycle {cycle}"
            );
            assert!(
                recorder.node_state(id).is_none(),
                "and the node itself is gone after cycle {cycle}"
            );
        }

        let names = recorder.names.lock().unwrap();
        assert!(names.is_empty(), "no historical id left a blanked name entry behind: {names:?}");
    }

    /// Unmounting a control tears its node down; re-registering a never-mounted id does not.
    ///
    /// The second half matters: a removal posted for an id that was never mounted would tear down
    /// a node a live control still owns, which is a silent loss for a screen reader.
    #[test]
    fn unmounting_a_control_tears_down_its_node() {
        let recorder: &'static A11yRecorder = Box::leak(Box::new(A11yRecorder::new()));
        crate::widget::a11y_submit::install_bridge(recorder);
        let _guard = A11yGuard;

        let id = register(Box::new(crate::widget::Label::new(
            "Bye".to_string(),
            crate::core::Rect::new(0, 0, 80, 24),
        )))
        .expect("mount");
        let before = recorder.states.lock().unwrap().len();
        assert!(unregister(id), "the mounted id is present");
        let after = recorder.states.lock().unwrap().len();
        assert_eq!(after, before + 1, "unmounting posted one teardown");

        // A second unmount of the same id finds nothing, so it posts nothing.
        assert!(!unregister(id), "the id is gone");
        assert_eq!(
            recorder.states.lock().unwrap().len(),
            after,
            "an unmount of a never-mounted id must not post a teardown"
        );
    }

    /// A check box's three states all travel the submit path.
    ///
    /// BLUE24 §6 criterion 3. The state is read back through the bridge substitute — not from the
    /// control — so the assertion covers the whole pump: derive (stage ①) and the submission.
    #[test]
    fn a_check_boxs_three_states_travel_the_submit_path() {
        use crate::platform::accessibility::A11yState;

        for (check, expected_checked, expected_mixed) in
            [(false, Some(false), false), (true, Some(true), false)]
        {
            let mut cb = crate::widget::CheckBox::new(crate::core::Rect::new(0, 0, 24, 24));
            cb.set_checked(check);
            let state = A11yState::from_widget(&cb);
            assert_eq!(state.checked, expected_checked, "checked={check}");
            assert_eq!(state.mixed, expected_mixed, "checked={check}");
        }

        // The mixed state is the tri-state spelling, which cannot be said with a bool.
        let mut cb = crate::widget::CheckBox::new(crate::core::Rect::new(0, 0, 24, 24));
        cb.set_tristate_enabled(true);
        cb.set_state(crate::widget::CheckState::PartiallyChecked);
        let state = A11yState::from_widget(&cb);
        assert_eq!(state.checked, Some(true), "a mixed box is on");
        assert!(state.mixed, "and separately mixed, which is the only way to say it");
    }

    // ── BLUE24 §7 -- native state reporting and redraw ───────────────────────────

    /// BLUE24 §7 criterion 1: a reported hover makes `widget_state()` true for a control the
    /// library did not see the input for.
    ///
    /// The defect this pins is the two-worlds problem: a native control's hover is the
    /// platform's fact, so `BaseWidget::is_hovered` stayed `false`, `widget_state()` reported
    /// `Normal`, and a theme's `"<kind>:hover"` was unreachable for every native control.
    /// Reporting the fact is what closes it, and the assertion is the state the theme keys on.
    #[test]
    fn a_reported_hover_reaches_widget_state() {
        use crate::style::WidgetState;

        let id = register(Box::new(crate::widget::Button::new(
            "native".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        assert_eq!(
            with_widget(id, |w| w.widget_state()),
            Some(WidgetState::Normal),
            "a freshly mounted control is at rest"
        );
        assert!(report_state(id, StateFact::Hovered(true)), "the fact reaches a mounted control");
        assert_eq!(
            with_widget(id, |w| w.widget_state()),
            Some(WidgetState::Hover),
            "so `widget_state()` is now true for a control the library never saw input for"
        );

        // Same fact again: no change, so nothing is re-reported (the idempotence §6.3 asks of
        // its own submit points, here for the native path).
        assert!(report_state(id, StateFact::Hovered(true)), "a known id is still found");
        assert_eq!(with_widget(id, |w| w.widget_state()), Some(WidgetState::Hover));

        assert!(report_state(id, StateFact::Hovered(false)), "leaving is a fact too");
        assert_eq!(with_widget(id, |w| w.widget_state()), Some(WidgetState::Normal));
    }

    /// A report about an id the library does not know is refused, not silently dropped.
    #[test]
    fn a_report_about_an_unknown_control_is_refused() {
        assert!(!report_state(0xDEAD_BEEF, StateFact::Hovered(true)));
        assert!(!report_state(0xDEAD_BEEF, StateFact::Pressed(true)));
    }

    /// BLUE24 §7 criterion 2: a native redraw is **counted** by the frame ledger.
    #[test]
    fn a_native_redraw_is_counted_by_the_frame() {
        let id = register(Box::new(crate::widget::Label::new(
            "n".to_string(),
            crate::core::Rect::new(0, 0, 40, 16),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        // Start from a clean frame accounting.
        let _ = drive_frame(0);
        notify_native_redraw(id, Some(crate::core::Rect::new(0, 0, 10, 10)));
        let outcome = drive_frame(0);
        assert_eq!(
            outcome.repaints_submitted, 1,
            "the platform's own redraw request is in the library's account"
        );
    }

    // ── BLUE24 §8 -- the frame ledger ───────────────────────────────────────────

    /// BLUE24 §8 criterion 1: sixty still frames tick nothing and coalesce nothing.
    #[test]
    fn sixty_still_frames_cost_nothing() {
        let id = register(Box::new(crate::widget::Label::new(
            "still".to_string(),
            crate::core::Rect::new(0, 0, 40, 16),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);

        for _ in 0..60 {
            let outcome = drive_frame(16);
            assert_eq!(outcome.controls_ticked, 0, "nothing is animating");
            let stats = last_frame_stats().expect("a frame ran");
            assert_eq!(stats.controls_ticked, 0);
            assert_eq!(
                stats.repaints_coalesced, 0,
                "nothing was requested, so nothing could be merged"
            );
            assert!(stats.last_repaint_reason.is_empty(), "and no surface was repainted");
        }
    }

    /// A control that STOPS animating must let the frame loop stop asking for frames.
    ///
    /// # The defect this pins
    ///
    /// `tick_animations` sets `LAST_SWEEP_HAD_UNSETTLED_MOUNTED` on any frame that found an
    /// animating control, and `animation_bus_needs_another_frame` ORs it in. The flag exists so
    /// the frame that observes a *settle* is scheduled. But nothing consumed it: the only writer
    /// that cleared it was `animation_bus_reset_host_owned`, which a host calls on **teardown**.
    ///
    /// So the first frame in which any mounted control animated turned
    /// `needs_another_frame` into a **permanent `true`** — a window that had ever shown a spinner
    /// or an indeterminate bar could never sleep again. That is the opposite of BLUE24 §1's
    /// central promise ("a still window's frame costs one emptiness check"), and it is invisible
    /// without a control that animates *and then stops*, which is why it survived until a player
    /// that reaches the end of its media was wired up.
    #[test]
    fn a_control_that_stops_animating_lets_the_frame_loop_sleep() {
        use crate::widget::display_widgets::progressbar::ProgressBar;

        let mut bar = ProgressBar::new(crate::core::Rect::new(0, 0, 160, 16));
        bar.set_indeterminate(true);
        let id = register(Box::new(bar)).expect("mount");
        let _unmount = MountGuard(id);

        // While it animates the loop is owed another frame.
        let running = drive_frame(16);
        assert_eq!(running.controls_ticked, 1);
        assert!(running.needs_another_frame, "an animating control keeps the loop awake");

        // Stop it. The very next frame must tick nothing, and the one after that must be free:
        // a settle is painted once and then scheduling stops.
        with_widget_mut(id, |widget| {
            if let Some(bar) =
                crate::widget::capability::coercion::widget_as_mut::<ProgressBar>(widget)
            {
                bar.set_indeterminate(false);
            }
        });

        let settled = drive_frame(16);
        assert_eq!(settled.controls_ticked, 0, "nothing is animating now");
        let after = drive_frame(16);
        assert!(
            !after.needs_another_frame,
            "a window whose animation has settled must stop being scheduled"
        );
        assert_eq!(after.controls_ticked, 0);
        assert_eq!(after.repaints_submitted, 0, "and a still frame costs no submission");
    }

    /// A mounted, playing `MediaPlayer` advances through the frame loop and then stops it.
    ///
    /// # The defect this pins, and why it belongs in **this** module's tests
    ///
    /// `MediaPlayer` had a `position_ms`, a progress ratio, a `position_changed` signal and a
    /// progress rule in `draw` — and nothing that moved the position. The missing piece was not
    /// inside the control (a `tick` is) but at the **seam**: the frame loop is what turns "this
    /// control would advance" into "this control advanced", and it only does so for a mounted
    /// control that answers [`Widget::is_animating`]. So the test that proves the seam is closed
    /// belongs here, next to `drive_frame`, rather than only in the control's unit tests —
    /// a `tick` nobody calls is exactly the shape BLUE24 §0A.1 measurement 1 is about.
    #[test]
    fn a_playing_media_player_advances_through_the_frame_loop() {
        use crate::widget::special_widgets::media_player::MediaPlayer;

        let mut player = MediaPlayer::new(crate::core::Rect::new(0, 0, 320, 200));
        player.set_source("clip.mp4", 1_000);
        assert!(player.play());
        let id = register(Box::new(player)).expect("mount");
        let _unmount = MountGuard(id);

        // One frame of the frame loop's own delta must move the control, and the loop must be
        // told it still owes another frame.
        let outcome = drive_frame(16);
        assert_eq!(outcome.controls_ticked, 1, "the player is the one control animating");
        assert!(outcome.needs_another_frame, "a playing player keeps the loop awake");
        assert_eq!(
            with_widget(id, |widget| widget.is_animating()),
            Some(true),
            "and it says so through the trait, not only through its own methods"
        );

        // The next frames are the media's own duration: at the loop's 16 ms delta it takes 63
        // frames to cover the 1_000 ms, so the bound below has margin and the assertion is about
        // "it stops at all", not about the exact frame it stops on. What must not happen is the
        // loop staying awake for ever, which is the failure a missing end condition produces.
        let mut stopped_at = None;
        for frame in 1..=120 {
            let outcome = drive_frame(16);
            if !outcome.needs_another_frame {
                stopped_at = Some(frame);
                break;
            }
        }
        assert!(
            stopped_at.is_some(),
            "playback must end on its own, not keep the frame loop awake for ever"
        );
        let stats = last_frame_stats().expect("a frame ran");
        assert_eq!(
            stats.controls_ticked, 0,
            "the frame that observed the end no longer ticks the player"
        );
    }

    /// BLUE24 §8 criterion 3: five requests for one surface submit once and coalesce four.
    #[test]
    fn one_surface_is_submitted_once_and_the_rest_are_coalesced() {
        let surface = register(Box::new(crate::widget::Label::new(
            "s".to_string(),
            crate::core::Rect::new(0, 0, 40, 16),
        )))
        .expect("mount");
        let _unmount = MountGuard(surface);

        // A clean frame boundary, so the five requests belong to one window.
        let _ = drive_frame(0);
        for _ in 0..5 {
            notify_native_redraw(surface, None);
        }
        let outcome = drive_frame(0);
        assert_eq!(outcome.repaints_submitted, 1, "one surface, one submission");
        let stats = last_frame_stats().expect("a frame ran");
        assert_eq!(stats.repaints_coalesced, 4, "and the other four were merged into it");
    }

    /// BLUE24 §8 criterion 4: every repainted surface has a cause in the ledger.
    #[test]
    fn every_repaint_names_a_reason() {
        let id = register(Box::new(crate::widget::Button::new(
            "why".to_string(),
            crate::core::Rect::new(0, 0, 80, 32),
        )))
        .expect("mount");
        let _unmount = MountGuard(id);
        let _ = drive_frame(0);

        notify_native_redraw(id, None);
        let _ = drive_frame(0);

        let stats = last_frame_stats().expect("a frame ran");
        assert!(
            !stats.last_repaint_reason.is_empty(),
            "a frame that submitted a repaint must be able to say why"
        );
        assert_eq!(
            stats.last_repaint_reason.iter().find(|(sid, _)| *sid == id).map(|(_, r)| *r),
            Some(RepaintReason::Native),
            "a platform redraw is attributed to the platform: {:?}",
            stats.last_repaint_reason
        );
    }

    /// The ledger attributes a repaint to the cause that **made the frame happen**.
    ///
    /// When two causes name one surface in one frame, the first wins: the later one is folded
    /// into a submission that was already going out, so recording it would describe the last
    /// caller rather than the cost. This is asserted through the state path, which is the one
    /// whose submission goes through the library's own invalidation.
    #[test]
    fn two_causes_on_one_surface_record_the_first() {
        use crate::platform::{with_recorded_invalidations, RecordingInvalidations};

        // A recording backend makes `invalidate_surface` succeed, so the state path submits
        // (and is therefore counted) exactly as it is on a real host.
        let recorder: &'static RecordingInvalidations =
            Box::leak(Box::new(RecordingInvalidations::default()));
        with_recorded_invalidations(recorder, || {
            let id = register(Box::new(crate::widget::Button::new(
                "first".to_string(),
                crate::core::Rect::new(0, 0, 80, 32),
            )))
            .expect("mount");
            let _unmount = MountGuard(id);
            let _ = drive_frame(0);

            request_repaint_because(id, RepaintReason::Animation);
            request_repaint_because(id, RepaintReason::State);
            let outcome = drive_frame(0);

            assert_eq!(outcome.repaints_submitted, 1, "one surface, one submission");
            let stats = last_frame_stats().expect("a frame ran");
            assert_eq!(stats.repaints_coalesced, 1, "and the second request was merged");
            assert_eq!(
                stats.last_repaint_reason.iter().find(|(sid, _)| *sid == id).map(|(_, r)| *r),
                Some(RepaintReason::Animation),
                "the cause that made the frame happen is the one recorded"
            );
        });
    }

    /// Only an animation keeps producing frames; the other causes describe a finished change.
    #[test]
    fn only_animation_keeps_asking_for_frames() {
        assert!(RepaintReason::Animation.keeps_animating());
        assert!(!RepaintReason::State.keeps_animating());
        assert!(!RepaintReason::Overlay.keeps_animating());
        assert!(!RepaintReason::Explicit.keeps_animating());
        assert!(!RepaintReason::Native.keeps_animating());
    }

    // ── The window-level tree painter (BLUE24 §0A.1) ─────────────────────────

    /// A window's tree frame must contain its **children's** pixels, not just the background.
    ///
    /// # The defect this pins
    ///
    /// Since 2.0 the library paints every `WidgetKind` itself, so a control created through
    /// the ordinary `create_*` path has no native control of its own. On Windows the only
    /// painter was the canvas child window that `mount_surface` creates, so a window whose
    /// children came from `create_button` / `create_checkbox` / … had **nothing drawing
    /// them**: the window opened and showed an empty client area — a blank white board.
    ///
    /// The fix is a window-level painter that walks the child list (`render_frame_tree`).
    /// This test pins the property that painter depends on, at the level where it can be
    /// checked without a display: a window with mounted children yields a frame whose pixels
    /// are **not all the clear colour**. A regression that broke the traversal — an empty
    /// child list, a skipped `is_visible`, a missing draw bridge — would produce a uniform
    /// frame and fail here rather than only on a screen nobody is looking at.
    #[test]
    fn a_window_tree_frame_contains_its_children_not_just_the_background() {
        let window_id = register(Box::new(crate::widget::window::Window::new(
            "t".to_string(),
            Rect::new(0, 0, 200, 120),
        )))
        .expect("mount the window");
        let _unmount_window = MountGuard(window_id);

        // A child at a known place, added through the window's own `add_child` so both
        // directions of the link are written — a one-sided link is the other way a child
        // becomes unreachable from the root.
        let child_id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            Rect::new(10, 40, 80, 32),
        )))
        .expect("mount the button");
        let _unmount_child = MountGuard(child_id);
        assert!(with_widget_mut(window_id, |window| {
            window.add_child(child_id);
            true
        })
        .unwrap_or(false));

        let clear = Color::rgb(255, 255, 255);
        let frame = render_frame_tree(window_id, Size::new(200, 120), clear)
            .expect("a window with a drawable child must produce a frame");

        // Every pixel identical to the clear colour means nothing was drawn over the
        // background — the blank-board symptom, expressed as a fact about the frame.
        let clear_rgba = [clear.r, clear.g, clear.b, 255];
        let painted = frame.as_chunks::<4>().0.iter().filter(|pixel| **pixel != clear_rgba).count();
        assert!(
            painted > 0,
            "the window's own chrome or its child must paint something; \
             a uniform frame is the blank-board defect"
        );
    }

    /// The child-list traversal a window painter depends on must actually reach a child.
    ///
    /// `render_frame_tree` walks `direct_children_of`, so a child that is mounted but absent
    /// from that list is invisible to every painter — the failure mode is silent, which is
    /// why the list is asserted rather than the resulting picture alone.
    #[test]
    fn a_mounted_child_is_reachable_through_the_window_child_list() {
        let window_id = register(Box::new(crate::widget::window::Window::new(
            "t".to_string(),
            Rect::new(0, 0, 200, 120),
        )))
        .expect("mount the window");
        let _unmount_window = MountGuard(window_id);

        let child_id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            Rect::new(5, 5, 40, 20),
        )))
        .expect("mount the button");
        let _unmount_child = MountGuard(child_id);

        assert!(
            !direct_children_of(window_id).contains(&child_id),
            "the premise: mounting a child does not by itself enlist it with the window"
        );
        assert!(with_widget_mut(window_id, |window| {
            window.add_child(child_id);
            true
        })
        .unwrap_or(false));
        assert!(
            direct_children_of(window_id).contains(&child_id),
            "after `add_child` the window painter must be able to find it"
        );
    }

    /// `Event::Resize` used to be published with a constructor and **no producer**: nothing
    /// in the library ever delivered it, so a nested control that handled it (the code
    /// editor refreshes its visible rows) never heard that its container changed size.
    #[test]
    fn a_container_resize_reaches_a_nested_child() {
        let window_id = register(Box::new(crate::widget::window::Window::new(
            "t".to_string(),
            Rect::new(0, 0, 200, 120),
        )))
        .expect("mount the window");
        let _unmount_window = MountGuard(window_id);

        let panel_id = register(Box::new(crate::widget::Panel::new(Rect::new(0, 0, 200, 120))))
            .expect("mount the panel");
        let _unmount_panel = MountGuard(panel_id);
        with_widget_mut(window_id, |window| window.add_child(panel_id));

        let editor_id = register(Box::new(crate::widget::Button::new(
            "ok".to_string(),
            Rect::new(0, 0, 40, 20),
        )))
        .expect("mount the button");
        let _unmount_editor = MountGuard(editor_id);
        with_widget_mut(panel_id, |panel| panel.add_child(editor_id));

        // The window and both descendants are told, deepest included.
        let reached = dispatch_resize(window_id, 640, 480);
        assert_eq!(reached, 3, "window + panel + button");

        // An id that addresses nothing tells nobody rather than panicking.
        assert_eq!(dispatch_resize(u64::MAX, 10, 10), 0);
    }

    /// A synchronous event callback may re-enter the registry without panicking.
    ///
    /// # What this pins (BLUE-issue E-09)
    ///
    /// A control emits its own signal **synchronously** while `handle_event` runs (a `Button`
    /// emits `base.clicked` on release). A slot on that signal is a user callback, and a normal
    /// callback updates other widgets — sets a label's text, moves a panel, etc. Every one of those
    /// goes through `with_widget` / `with_widget_mut`, which borrow the `MOUNTED` `RefCell`.
    /// `dispatch_event` used to hold that `borrow_mut` across `handle_event`, so the callback hit
    /// `already borrowed: BorrowMutError` and panicked. The entry is now detached for the duration
    /// of the call, so the borrow is held only for the two map operations.
    #[test]
    fn a_click_callback_may_update_other_widgets_without_panicking() {
        use crate::core::Point;
        use crate::event::mouse_button;

        let button_id = register(Box::new(crate::widget::Button::new(
            "go".to_string(),
            Rect::new(0, 0, 60, 24),
        )))
        .expect("mount the button");
        let _button_guard = MountGuard(button_id);

        let label_id = register(Box::new(crate::widget::Label::new(
            "before".to_string(),
            Rect::new(0, 0, 80, 20),
        )))
        .expect("mount the label");
        let _label_guard = MountGuard(label_id);

        // The handler mutates a *different* control — the exact shape the issue names as risky.
        let ran = std::sync::Arc::new(core::sync::atomic::AtomicBool::new(false));
        let ran_slot = std::sync::Arc::clone(&ran);
        with_widget_mut(button_id, |button| {
            button.base_mut().clicked.connect(move || {
                // Re-enters the registry through the same borrow that used to be held.
                assert!(set_geometry(label_id, Rect::new(5, 5, 120, 20)));
                let _ = with_widget(label_id, |_| ());
                ran_slot.store(true, core::sync::atomic::Ordering::SeqCst);
            });
        });

        // Drive a real press + release through `dispatch_event`, which is where the borrow was held.
        dispatch_event(
            button_id,
            &crate::event::Event::MousePress {
                pos: Point::new(10, 10),
                button: mouse_button::PRIMARY,
                modifiers: 0,
            },
        );
        dispatch_event(
            button_id,
            &crate::event::Event::MouseRelease {
                pos: Point::new(10, 10),
                button: mouse_button::PRIMARY,
            },
        );

        assert!(
            ran.load(core::sync::atomic::Ordering::SeqCst),
            "the click callback must have run to completion rather than panicking"
        );
        assert_eq!(with_widget(label_id, |label| label.geometry().width), Some(120));
    }

    /// A callback that destroys the control it is handling must actually destroy it.
    ///
    /// # What this pins
    ///
    /// `dispatch_event` detaches the entry before the call and reinserts it after. Without a
    /// tombstone for a handler that called `unregister` on the in-flight id, the reinsertion would
    /// silently resurrect a widget the handler had just destroyed. The tombstone check is what makes
    /// the destroy stick.
    #[test]
    fn a_callback_may_destroy_the_widget_it_is_handling() {
        use crate::core::Point;
        use crate::event::mouse_button;

        let button_id = register(Box::new(crate::widget::Button::new(
            "self-destruct".to_string(),
            Rect::new(0, 0, 80, 24),
        )))
        .expect("mount the button");

        let self_id = button_id;
        with_widget_mut(button_id, |button| {
            button.base_mut().clicked.connect(move || {
                assert!(unregister(self_id), "the handler's unregister must take effect");
            });
        });

        dispatch_event(
            button_id,
            &crate::event::Event::MousePress {
                pos: Point::new(10, 10),
                button: mouse_button::PRIMARY,
                modifiers: 0,
            },
        );
        dispatch_event(
            button_id,
            &crate::event::Event::MouseRelease {
                pos: Point::new(10, 10),
                button: mouse_button::PRIMARY,
            },
        );

        assert!(
            !is_mounted(button_id),
            "the widget must not be resurrected by the dispatch epilogue"
        );
    }

    /// A property write that emits a signal must let the callback re-enter the registry.
    ///
    /// # The defect this pins (BLUE-issue E-17)
    ///
    /// `with_widget_mut` held the registry's `RefCell` mutably across `f`. A property setter runs as
    /// `f` and emits the control's signal synchronously, so the user callback ran while that borrow was
    /// live and any `with_widget` / `geometry_of` inside it hit `already borrowed`. The borrow is now
    /// scoped to the map operations only, so the callback runs with the registry free.
    #[test]
    fn a_property_write_callback_may_read_the_registry_without_panicking() {
        use crate::widget::capability::access::write_widget_property_by_id;
        use crate::widget::capability::CapabilityValue;
        use crate::widget::Slider;

        let slider_id = register(Box::new(Slider::new(Rect::new(0, 0, 200, 30)))).expect("mount");
        let _guard = MountGuard(slider_id);
        let other_id = register(Box::new(crate::widget::Label::new(
            "other".to_string(),
            Rect::new(0, 0, 60, 20),
        )))
        .expect("mount the label");
        let _other_guard = MountGuard(other_id);

        // Subscribing to the slider's dynamic `value_changed` and reading the registry inside the
        // handler is exactly the shape that panicked.
        let observed = std::sync::Arc::new(std::sync::Mutex::new(None::<(bool, bool)>));
        let observed_slot = std::sync::Arc::clone(&observed);
        with_widget_mut(slider_id, |widget| {
            let reference = widget.event_signal_dyn("value_changed").expect("published");
            reference.subscribe(Box::new(move |_payload| {
                let other_is_readable = geometry_of(other_id).is_some();
                let self_is_readable = geometry_of(slider_id).is_some();
                *observed_slot.lock().expect("lock") = Some((other_is_readable, self_is_readable));
            }));
        });

        write_widget_property_by_id(slider_id, "value", CapabilityValue::Int(42))
            .expect("the slider accepts a value write");

        assert_eq!(
            *observed.lock().expect("lock"),
            Some((true, false)),
            "the callback may read other widgets, but must not alias the widget still held mutably"
        );
    }

    /// A callback that destroys the control during a property write must actually destroy it.
    ///
    /// The `with_widget_mut` drive marks its id in-flight for the same reason `dispatch_event` does:
    /// a setter's callback may destroy the control, and the reinsertion must not resurrect it.
    #[test]
    fn a_property_write_callback_may_destroy_the_control() {
        use crate::widget::capability::access::write_widget_property_by_id;
        use crate::widget::capability::CapabilityValue;
        use crate::widget::Slider;

        let slider_id = register(Box::new(Slider::new(Rect::new(0, 0, 200, 30)))).expect("mount");

        let self_id = slider_id;
        with_widget_mut(slider_id, |widget| {
            let reference = widget.event_signal_dyn("value_changed").expect("published");
            reference.subscribe(Box::new(move |_payload| {
                assert!(unregister(self_id), "the callback's unregister must take effect");
            }));
        });

        write_widget_property_by_id(slider_id, "value", CapabilityValue::Int(7))
            .expect("the slider accepts a value write");

        assert!(
            !is_mounted(slider_id),
            "a destroy during a property write must not be undone by the drive's reinsertion"
        );
    }

    /// A callback can identify a mutably-driven control without aliasing it.
    ///
    /// # The defect this pins (BLUE-issue E-18)
    ///
    /// `dispatch_event` holds a mutable widget reference while `handle_event` synchronously emits
    /// signals. Reborrowing the widget from a callback would violate Rust's aliasing rules, so its
    /// geometry read is refused during dispatch while `is_mounted` still reports true.
    #[test]
    fn a_callback_does_not_alias_a_widget_while_it_is_mutably_driven() {
        use crate::core::Point;
        use crate::event::mouse_button;

        let button_id = register(Box::new(crate::widget::Button::new(
            "go".to_string(),
            Rect::new(0, 0, 80, 24),
        )))
        .expect("mount the button");
        let _guard = MountGuard(button_id);

        let self_read = std::sync::Arc::new(std::sync::Mutex::new(None::<(bool, bool)>));
        let record = std::sync::Arc::clone(&self_read);
        with_widget_mut(button_id, |button| {
            button.base_mut().clicked.connect(move || {
                // The id remains mounted, but its widget cannot be reborrowed while handle_event owns it.
                let mounted_by_registry_id = is_mounted(button_id);
                let geometry = geometry_of(button_id);
                *record.lock().expect("lock") = Some((mounted_by_registry_id, geometry.is_some()));
            });
        });

        dispatch_event(
            button_id,
            &crate::event::Event::MousePress {
                pos: Point::new(10, 10),
                button: mouse_button::PRIMARY,
                modifiers: 0,
            },
        );
        dispatch_event(
            button_id,
            &crate::event::Event::MouseRelease {
                pos: Point::new(10, 10),
                button: mouse_button::PRIMARY,
            },
        );

        let observed = *self_read.lock().expect("lock");
        assert_eq!(
            observed,
            Some((true, false)),
            "a callback must see the control as mounted without creating an aliased shared reference"
        );
    }

    /// A panicking input callback must not leave the registry with a stale in-flight marker.
    ///
    /// # The defect this pins (BLUE-issue E-19)
    ///
    /// `dispatch_event` removed the widget and marked it in-flight, then ran `handle_event`. If the
    /// callback unwound (the host `catch_unwind`s), the cleanup after the call was skipped: the id
    /// stayed in the in-flight set, so `is_mounted` answered `false` but `unregister` still reported
    /// the id present. Cleanup is now a guard, so both answers agree after an unwind.
    #[test]
    fn a_panicking_input_callback_leaves_no_stale_dispatch_state() {
        use crate::core::Point;
        use crate::event::mouse_button;

        let button_id = register(Box::new(crate::widget::Button::new(
            "boom".to_string(),
            Rect::new(0, 0, 80, 24),
        )))
        .expect("mount the button");
        // No `MountGuard`: the widget is intentionally left unmounted after the unwind path.
        let _unmount = MountGuard(button_id);

        with_widget_mut(button_id, |button| {
            button.base_mut().clicked.connect(|| {
                panic!("deliberate unwind from an input callback");
            });
        });

        let press = crate::event::Event::MousePress {
            pos: Point::new(10, 10),
            button: mouse_button::PRIMARY,
            modifiers: 0,
        };
        let release = crate::event::Event::MouseRelease {
            pos: Point::new(10, 10),
            button: mouse_button::PRIMARY,
        };
        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            dispatch_event(button_id, &press);
            dispatch_event(button_id, &release);
        }));
        assert!(caught.is_err(), "the callback must have unwound");

        // The registry must be consistent: if the widget is gone, `unregister` must say so rather
        // than reporting a stale in-flight entry as present.
        assert!(
            !is_mounted(button_id),
            "the lookup must not resolve a widget dropped by the unwind"
        );
        assert!(
            !unregister(button_id),
            "a popped dispatch must not report the id as present via a leftover in-flight marker"
        );
    }

    /// A closure reading control A may emit A's signal, whose callback writes control B.
    ///
    /// # The defect this pins (BLUE-issue E-30)
    ///
    /// `with_widget` ran its closure inside `map.borrow()`, so a closure that read A's state and
    /// synchronously emitted A's signal \u2014 a legitimate `&self` operation \u2014 ran a callback that
    /// then wrote B via `with_widget_mut`, which needed `map.borrow_mut()`. That was `already
    /// borrowed`, not a nested write of A. `with_widget` now detaches A before running the closure, so
    /// the registry is free for the callback to write another control.
    #[test]
    fn a_read_closure_may_emit_a_signal_whose_callback_writes_another_control() {
        let a_id = register(Box::new(crate::widget::Button::new(
            "a".to_string(),
            Rect::new(0, 0, 60, 24),
        )))
        .expect("mount A");
        let _a_guard = MountGuard(a_id);
        let b_id = register(Box::new(crate::widget::Label::new(
            "before".to_string(),
            Rect::new(0, 0, 80, 20),
        )))
        .expect("mount B");
        let _b_guard = MountGuard(b_id);

        let ran = std::sync::Arc::new(core::sync::atomic::AtomicBool::new(false));
        let ran_slot = std::sync::Arc::clone(&ran);
        with_widget_mut(a_id, |widget| {
            widget.base_mut().clicked.connect(move || {
                // Writes a *different* control from inside the slot.
                assert!(set_geometry(b_id, Rect::new(3, 4, 120, 20)));
                ran_slot.store(true, core::sync::atomic::Ordering::SeqCst);
            });
        });

        // A read closure on A that emits A's own signal synchronously.
        let result = with_widget(a_id, |widget| {
            widget.base().clicked.emit();
            widget.geometry().width
        });

        assert_eq!(result, Some(60), "the read closure must return normally, not panic");
        assert!(
            ran.load(core::sync::atomic::Ordering::SeqCst),
            "the slot must have run and written the other control without a RefCell panic"
        );
        assert_eq!(with_widget(b_id, |label| label.geometry().width), Some(120));
    }

    #[test]
    fn unregister_during_a_read_loan_is_not_undone_by_reinsertion() {
        let id = register(Box::new(crate::widget::Label::new(
            "remove".to_string(),
            Rect::new(0, 0, 60, 20),
        )))
        .expect("mount");

        let removed = with_widget(id, |_| unregister(id));

        assert_eq!(removed, Some(true), "unregister must see the in-flight read loan");
        assert!(!is_mounted(id), "the read-loan epilogue must not resurrect the widget");
        assert!(!unregister(id), "the id must already be fully unregistered");
    }

    // ── Host-window id translation (the P-05 seam) ──────────────────────────────

    /// A window widget's host id round-trips: `window -> host -> window`.
    ///
    /// The `macos_objc2`/`windows`/`wayland` backends allocate host ids in a space that is
    /// **disjoint** from the widget id space (the platform counts from 1, the runtime reserves
    /// `0x5345_4C46_…`). An OS callback hands the backend its own host id, and the backend must
    /// translate it back before any registry lookup: `widget_id_for_host_window(host)` is that
    /// inverse. This pins the translation the objc2 render/invalidate path (P-05) depends on,
    /// which no test previously exercised.
    #[test]
    fn a_widget_window_id_round_trips_through_its_host_id() {
        let widget = register(Box::new(crate::widget::Label::new(
            "win".to_string(),
            Rect::new(0, 0, 100, 80),
        )))
        .expect("mount");
        let _unmount = MountGuard(widget);

        // The host number is deliberately in the *platform* space, not the widget space.
        let host: ObjectId = 7;
        assert!(set_host_window(widget, host), "a mounted window must accept a host association");
        assert_eq!(host_window_for(widget), Some(host), "window -> host");
        assert_eq!(widget_id_for_host_window(host), Some(widget), "host -> window");
        // An id the platform never built a host for resolves to nothing, not to a wrong widget.
        assert_eq!(host_window_for(host), None, "a host id is not itself a widget");
        assert_eq!(widget_id_for_host_window(widget), None, "a widget id is not a host id");
    }

    /// The host association is dropped with the widget, so a recycled id cannot inherit it.
    #[test]
    fn unmounting_a_window_clears_its_host_association() {
        let widget = register(Box::new(crate::widget::Label::new(
            "win".to_string(),
            Rect::new(0, 0, 100, 80),
        )))
        .expect("mount");
        let host: ObjectId = 99;
        assert!(set_host_window(widget, host));
        assert_eq!(widget_id_for_host_window(host), Some(widget));

        unregister(widget);

        assert_eq!(host_window_for(widget), None, "the mapping must not outlive the widget");
        assert_eq!(
            widget_id_for_host_window(host),
            None,
            "a later widget reusing this host id must not resolve to the dead one"
        );
    }

    /// An unmounted id cannot be given a host window: a mapping to nothing is refused.
    #[test]
    fn set_host_window_refuses_an_unmounted_id() {
        let ghost: ObjectId = 0x5345_4C46_DEAD_BEEF;
        assert!(!set_host_window(ghost, 1), "only a mounted window may carry a host id");
        assert_eq!(host_window_for(ghost), None);
    }
}