frust-core 0.5.2

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

use std::any::Any;
use std::borrow::Cow;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::num::NonZeroU64;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

/// The per-corner radii and dash-pattern vocabulary [`PaintScene`]'s own
/// signatures name, re-exported from `frust-scene` so a widget calling
/// [`PaintScene::fill_rounded_rect_radii`]/[`PaintScene::push_clip_rounded_radii`]/
/// [`PaintScene::stroke_path_dashed`] can name their arguments through the same
/// paint surface it already paints through (mirrors the crate-root `accesskit`
/// re-export).
pub use frust_scene::{CornerRadii, DashPattern};
use frust_scene::{GlyphRun, SceneBuilder, ShaderProgram};
use kurbo::{Affine, BezPath, Point, Rect, Size};
use peniko::{Brush, Color};

use crate::anim::FrameTime;
use crate::event::{EventCtx, EventResult, ImeState, InputEvent};
use crate::insets::WindowInsets;
use crate::layout::BoxConstraints;
use crate::semantics::SemanticsCtx;

/// The renderer-agnostic paint target a widget draws into.
///
/// This trait was introduced as a **local stand-in** for
/// `frust_scene::SceneBuilder` while the scene crate was still a stub, and the
/// two were later reconciled *additively*: rather than churn the `Widget::paint`
/// signature (and every widget/test written against it), `SceneBuilder` now
/// [implements this trait](#impl-PaintScene-for-SceneBuilder), so widgets keep
/// painting through `&mut dyn PaintScene` while the shell hands them a real
/// `SceneBuilder` whose commands reach the GPU backend.
///
/// The original `fill_rect`/`draw_text` shape is retained for source
/// compatibility with existing recorder-style test scenes; real text rendering
/// goes through [`PaintScene::draw_glyph_run`], which carries shaped glyphs from
/// `frust-text`.
pub trait PaintScene {
    /// Emit a filled axis-aligned rectangle at `origin` with `size`, filled with
    /// the solid `color`.
    fn fill_rect(&mut self, origin: Point, size: Size, color: Color);

    /// Emit a filled axis-aligned rectangle with uniformly rounded corners.
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real rounded-rect command.
    fn fill_rounded_rect(&mut self, _origin: Point, _size: Size, _radius: f64, _color: Color) {}

    /// Emit a filled axis-aligned rectangle with per-corner `radii` — the
    /// shape a uniform [`PaintScene::fill_rounded_rect`] cannot express (a
    /// bottom-anchored sheet with only its top corners rounded, a segmented
    /// control's end caps).
    ///
    /// Defaulted to the uniform call with the *largest* corner rather than to a
    /// no-op: a recorder scene that only implements `fill_rounded_rect` still
    /// sees a rect painted here, in the spirit of
    /// [`PaintScene::fill_rect_brush`]'s "see something rather than nothing"
    /// fallback. The `SceneBuilder` implementation overrides it and records
    /// every corner faithfully.
    fn fill_rounded_rect_radii(
        &mut self,
        origin: Point,
        size: Size,
        radii: CornerRadii,
        color: Color,
    ) {
        self.fill_rounded_rect(origin, size, radii.largest(), color);
    }

    /// Stroke a straight line from `p0` to `p1` with the given `width` and solid
    /// `color`.
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real stroked-line command.
    fn stroke_line(&mut self, _p0: Point, _p1: Point, _width: f64, _color: Color) {}

    /// Push a rectangular clip (at `origin`/`size`) onto the backend clip stack;
    /// subsequent draws are clipped to it until the matching [`PaintScene::pop_clip`].
    ///
    /// Defaulted to a no-op so recorder scenes stay valid; the `SceneBuilder`
    /// implementation honors the clip by recording a push/pop command pair.
    fn push_clip(&mut self, _origin: Point, _size: Size) {}

    /// Push a clip with uniformly rounded corners (at `origin`/`size`, corner
    /// `radius`) onto the backend clip stack; subsequent draws are clipped to
    /// the rounded shape until the matching [`PaintScene::pop_clip`] — the same
    /// pop [`PaintScene::push_clip`] uses, since there is one clip stack.
    ///
    /// Lets paint code express a radiused mask over content a rectangular clip
    /// cannot shape — a rounded bitmap (avatar/thumbnail) being the motivating
    /// case. Defaulted to a no-op so recorder scenes stay valid; the
    /// `SceneBuilder` implementation honors it by recording a real
    /// [`frust_scene::Command::PushClipRounded`]/[`frust_scene::Command::PopClip`]
    /// pair.
    fn push_clip_rounded(&mut self, _origin: Point, _size: Size, _radius: f64) {}

    /// Push a clip with per-corner `radii` onto the backend clip stack, popped
    /// by the same [`PaintScene::pop_clip`] as every other push.
    ///
    /// Defaulted to the uniform [`PaintScene::push_clip_rounded`] with the
    /// largest corner rather than to a no-op — a defaulted *push* against an
    /// implemented *pop* would unbalance a recorder scene's clip stack, so this
    /// one delegates for correctness, not just for visibility (see
    /// [`PaintScene::fill_rounded_rect_radii`]).
    fn push_clip_rounded_radii(&mut self, origin: Point, size: Size, radii: CornerRadii) {
        self.push_clip_rounded(origin, size, radii.largest());
    }

    /// Pop the most recently pushed clip, rectangular or rounded. Defaulted to
    /// a no-op; see [`PaintScene::push_clip`].
    fn pop_clip(&mut self) {}

    /// Emit a run of *unshaped* text anchored at `origin`.
    ///
    /// This records intent only — glyph shaping lives in `frust-text`.
    /// Real rendering uses [`PaintScene::draw_glyph_run`]; the
    /// `SceneBuilder` implementation treats this as a no-op.
    fn draw_text(&mut self, origin: Point, text: &str);

    /// Emit a run of already-shaped glyphs into the scene.
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes (which predate the
    /// text pipeline) stay valid without modification; the `SceneBuilder`
    /// implementation overrides it to record a real glyph-run command.
    fn draw_glyph_run(&mut self, _run: GlyphRun) {}

    /// Draw an already-decoded image, scaled from its natural
    /// (`data.width`x`data.height`) size to fill the absolute `dest` rect.
    ///
    /// A single additive method (added for `frust-widgets::Image`) on this
    /// otherwise layer-2 trait — authorized because `Command::Image`'s
    /// `peniko::ImageData` payload has to reach the scene through the same
    /// `&mut dyn PaintScene` seam every other paint call uses. Defaulted to a
    /// no-op so pre-existing recorder scenes stay valid; the `SceneBuilder`
    /// implementation records a real image command.
    fn draw_image(&mut self, _data: &peniko::ImageData, _dest: Rect) {}

    /// Draw a fragment-shader-filled rectangle, scaled to fill `dest`.
    ///
    /// An additive method (added for the shader-showcase feature) on this otherwise layer-2
    /// trait — authorized because the shader program and destination have to
    /// reach the scene through the same `&mut dyn PaintScene` seam every other
    /// paint call uses. `program` carries the WGSL source and process-unique
    /// id; `time` is seconds, app-supplied. Defaulted to a no-op so pre-existing
    /// recorder scenes stay valid; the `SceneBuilder` implementation records a
    /// real shader-quad command.
    ///
    /// **Renders on the engine renderer** via the external-texture path (see
    /// `crates/frust-engine/src/effects/shader_quad.rs`); there is no CPU-oracle
    /// golden for a user-supplied fragment shader, so engine-side correctness
    /// is proven on a real device instead — see `docs/LIMITATIONS.md`'s
    /// `engine-shader-quad-goldens-uncomparable`.
    ///
    /// # Cache-once contract
    ///
    /// `program` must be a retained, already-created `ShaderProgram` handle
    /// (see `ShaderProgram::new`'s own doc for the full contract) — never a
    /// fresh one minted inline in the call that invokes this method. This
    /// method is reached from [`Widget::paint`], which re-runs every frame,
    /// so a `ShaderProgram::new` call written directly at a `draw_shader`
    /// call site there mints a new process-unique id (and therefore a new
    /// GPU pipeline cache miss) every frame; the same applies to a
    /// [`crate::component::Component`]'s `build`, which re-runs every
    /// rebuild. Build the `ShaderProgram` once — in a `Component`'s `init`,
    /// or other retained widget state — and clone the handle in; a
    /// [`View::build`](crate::view::View::build) call, by contrast, runs
    /// exactly once per widget instance and is a correct place to construct
    /// one.
    fn draw_shader(&mut self, _program: &ShaderProgram, _dest: Rect, _time: f32) {}

    /// Composite a bound scene texture (pre-rendered via [`ExternalPass`](frust_gpu::ExternalPass))
    /// into the scene.
    ///
    /// An additive method on this otherwise layer-2 trait — authorized because the
    /// texture id and destination have to reach the scene through the same
    /// `&mut dyn PaintScene` seam every other paint call uses. `id` is a
    /// `SceneTextureId::get()`; `dest` is in the scene's coordinate space.
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real scene-texture command.
    ///
    /// The engine renders nothing if the id is unbound and warns once per
    /// process. Output is always blended (never replaces). The binding is
    /// established outside this paint call by [`ExternalPass::record`](frust_gpu::ExternalPass::record);
    /// a texture whose pass has not bound anything yet simply draws nothing
    /// that frame, never an error.
    fn draw_scene_texture(&mut self, _id: u64, _dest: Rect) {}

    /// Draw a gaussian-blurred rounded-rectangle elevation shadow (an
    /// approximation of a CSS `box-shadow`) at `origin`/`size`.
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real
    /// [`frust_scene::Command::BlurredRoundedRect`].
    fn draw_shadow(
        &mut self,
        _origin: Point,
        _size: Size,
        _radius: f64,
        _std_dev: f64,
        _color: Color,
    ) {
    }

    /// Emit a filled axis-aligned rectangle at `origin` with `size`, filled
    /// with an arbitrary `brush` (solid color or gradient).
    ///
    /// Default implementation delegates to [`PaintScene::fill_rect`] using
    /// the brush's solid color where possible (a `Brush::Solid` unwraps
    /// directly; a gradient brush falls back to transparent black, since a
    /// pre-existing recorder scene has no gradient concept to approximate
    /// it with) — so callers that only override `fill_rect` still see
    /// *something* painted rather than nothing. The `SceneBuilder`
    /// implementation records the brush faithfully via
    /// [`frust_scene::Command::RoundedRect`]'s zero-radius sibling
    /// (`FillRect`).
    fn fill_rect_brush(&mut self, origin: Point, size: Size, brush: &Brush) {
        let color = match brush {
            Brush::Solid(color) => *color,
            _ => Color::TRANSPARENT,
        };
        self.fill_rect(origin, size, color);
    }

    /// Emit a filled axis-aligned rectangle with uniformly rounded corners,
    /// filled with an arbitrary `brush` (solid color or gradient).
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real
    /// [`frust_scene::Command::RoundedRect`] carrying the brush.
    fn fill_rounded_rect_brush(
        &mut self,
        _origin: Point,
        _size: Size,
        _radius: f64,
        _brush: &Brush,
    ) {
    }

    /// Push a translucent layer (at `origin`/`size`) onto the backend layer
    /// stack; subsequent draws are composited at `alpha` until the matching
    /// [`PaintScene::pop_layer`].
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real
    /// [`frust_scene::Command::PushLayer`]/[`frust_scene::Command::PopLayer`]
    /// pair, nesting correctly with [`PaintScene::push_clip`]/[`PaintScene::pop_clip`].
    fn push_layer(&mut self, _origin: Point, _size: Size, _alpha: f32) {}

    /// Pop the most recently pushed layer. Defaulted to a no-op; see
    /// [`PaintScene::push_layer`].
    fn pop_layer(&mut self) {}

    /// Clear an axis-aligned rectangle (at `origin`/`size`) to full
    /// transparency (alpha 0), erasing everything already painted below it in
    /// this scene — a real destination-clearing composite, not merely skipping
    /// paint over the region.
    ///
    /// The platform-view hole-punch (`frust-widgets`' `PlatformViewWidget`) is
    /// the sole v1 consumer: on a translucent (Mode B) surface a slot punches
    /// its rect so an opaque app backdrop painted below it (the catalog's
    /// `AppBackground`) doesn't seal the hole the hosted native view shows
    /// through. Gated on [`PaintCtx::is_translucent`] by the widget — clearing
    /// on an opaque surface would erase real app content, and the clear is
    /// disregarded there anyway (see [`frust_scene::Command::ClearRect`]).
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation records a real
    /// [`frust_scene::Command::ClearRect`].
    fn clear_rect(&mut self, _origin: Point, _size: Size) {}

    /// Fill an arbitrary vector path (e.g. an arc — see
    /// [`frust_scene::arc_path`]) at `origin`, using the nonzero winding
    /// rule and `brush`.
    ///
    /// `path` is in the widget's local coordinate space; `origin` translates
    /// it into the parent's space, mirroring every other `PaintScene`
    /// method's origin convention. Defaulted to a
    /// no-op so pre-existing recorder scenes stay valid; the `SceneBuilder`
    /// implementation records a real [`frust_scene::Command::Path`].
    fn fill_path(&mut self, _origin: Point, _path: &BezPath, _brush: &Brush) {}

    /// Stroke an arbitrary vector path (e.g. an arc) at `origin` with `width`
    /// and round caps/joins, using `brush`.
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; see
    /// [`PaintScene::fill_path`].
    fn stroke_path(&mut self, _origin: Point, _path: &BezPath, _width: f64, _brush: &Brush) {}

    /// Stroke an arbitrary vector path at `origin` as a dashed line: the same
    /// stroke [`PaintScene::stroke_path`] paints, broken into `dash`'s on/off
    /// runs by the render crate at encode time.
    ///
    /// Defaulted to the solid [`PaintScene::stroke_path`] rather than to a
    /// no-op — dashing is a visual refinement, so a scene that cannot express
    /// it still draws the path.
    fn stroke_path_dashed(
        &mut self,
        origin: Point,
        path: &BezPath,
        width: f64,
        _dash: DashPattern,
        brush: &Brush,
    ) {
        self.stroke_path(origin, path, width, brush);
    }

    /// Push an affine `transform`, composed with the current one, onto the
    /// backend transform stack; subsequent draws are transformed until the
    /// matching [`PaintScene::pop_transform`].
    ///
    /// Defaulted to a no-op so pre-existing recorder scenes stay valid; the
    /// `SceneBuilder` implementation composes and records it. Unlike the
    /// origin-offset convention every other method uses (a pure translation),
    /// this is the one seam that also carries scale/rotation — the
    /// shared-element ("hero") morph is the first consumer, repainting a tagged
    /// subtree under a rect→rect transform (position **and** scale) so it
    /// morphs between two pages during a navigation transition.
    fn push_transform(&mut self, _transform: Affine) {}

    /// Pop the most recently pushed transform, restoring the previous one.
    /// Defaulted to a no-op; see [`PaintScene::push_transform`].
    fn pop_transform(&mut self) {}

    /// Push a snapshot bracket: the body is rasterizable once and cached by
    /// `key` across frames. The `alpha` and `scale` are presentation parameters
    /// applied to the whole cached body (alpha blending, uniform scale).
    ///
    /// The default implementation emulates the presentation for recorders
    /// that don't have a snapshot concept: it pushes a transform (scale about
    /// the rect's center), then a layer (at the rect with the given alpha).
    /// A renderer may cache and apply both as a whole; a recorder sees the
    /// component pieces. The matching [`PaintScene::pop_snapshot`] pops both
    /// in the reverse order.
    ///
    /// [`SceneBuilder`] overrides this to call the snapshot-aware builder
    /// methods directly, which record `Command::PushSnapshot`/`PopSnapshot`
    /// and no extra transform/layer commands.
    fn push_snapshot(&mut self, _key: u64, origin: Point, size: Size, alpha: f32, scale: f64) {
        let center = Point::new(origin.x + size.width / 2.0, origin.y + size.height / 2.0);
        self.push_transform(Affine::scale_about(scale, center));
        self.push_layer(origin, size, alpha);
    }

    /// Pop the most recently pushed snapshot bracket. Defaulted to the reverse
    /// of [`PaintScene::push_snapshot`]'s default: pop layer, then transform.
    /// Recorders that don't override both may see unbalanced stacks if only one
    /// is overridden; the default pair is provided for source compatibility.
    fn pop_snapshot(&mut self) {
        self.pop_layer();
        self.pop_transform();
    }
}

/// A [`PaintScene`] sink that accepts every paint command and records
/// nothing — the zero-GPU-cost target for a subtree that still needs its
/// `paint` pass driven for the pass's *side effects* (hero-rect reporting
/// through [`PaintCtx::with_hero_registry`], other paint-time widget state)
/// even though its pixels will never be composited. The navigator's
/// transition machinery is the motivating case: a page whose resolved alpha
/// is 0 still has to paint to report hero rects and advance animating
/// children, but every command it emits is otherwise wasted GPU work.
///
/// # Guarantee
///
/// No paint command reaches any scene: every [`PaintScene`] method on
/// [`DiscardScene`] is a no-op, whether overridden here directly or
/// inherited from the trait's own no-op (or no-op-delegating) default.
/// Anything driven through [`PaintCtx`] rather than through
/// `&mut dyn PaintScene` — the hero registry, the frame clock, paced-class
/// bubbling — is unaffected, since none of that machinery routes through the
/// scene it's handed.
pub struct DiscardScene;

impl PaintScene for DiscardScene {
    fn fill_rect(&mut self, _origin: Point, _size: Size, _color: Color) {}

    fn draw_text(&mut self, _origin: Point, _text: &str) {}
}

/// Bridges the provisional [`PaintScene`] boundary onto the real
/// `frust_scene::SceneBuilder`.
///
/// Widgets paint through `&mut dyn PaintScene`; the desktop shell
/// hands them a `SceneBuilder`, so filled rectangles and shaped glyph runs land
/// in the display list under the builder's current transform. Unshaped
/// [`PaintScene::draw_text`] is intentionally dropped here — text must be shaped
/// (by `frust-text`) into glyph runs before it can be drawn.
impl PaintScene for SceneBuilder<'_> {
    fn fill_rect(&mut self, origin: Point, size: Size, color: Color) {
        SceneBuilder::fill_rect(self, rect_at(origin, size), Brush::Solid(color));
    }

    fn fill_rounded_rect(&mut self, origin: Point, size: Size, radius: f64, color: Color) {
        SceneBuilder::fill_rounded_rect(self, rect_at(origin, size), radius, Brush::Solid(color));
    }

    fn fill_rounded_rect_radii(
        &mut self,
        origin: Point,
        size: Size,
        radii: CornerRadii,
        color: Color,
    ) {
        SceneBuilder::fill_rounded_rect_radii(
            self,
            rect_at(origin, size),
            radii,
            Brush::Solid(color),
        );
    }

    fn stroke_line(&mut self, p0: Point, p1: Point, width: f64, color: Color) {
        SceneBuilder::stroke_line(self, p0, p1, width, Brush::Solid(color));
    }

    fn push_clip(&mut self, origin: Point, size: Size) {
        SceneBuilder::push_clip(self, rect_at(origin, size));
    }

    fn push_clip_rounded(&mut self, origin: Point, size: Size, radius: f64) {
        SceneBuilder::push_clip_rounded(self, rect_at(origin, size), radius);
    }

    fn push_clip_rounded_radii(&mut self, origin: Point, size: Size, radii: CornerRadii) {
        SceneBuilder::push_clip_rounded_radii(self, rect_at(origin, size), radii);
    }

    fn pop_clip(&mut self) {
        SceneBuilder::pop_clip(self);
    }

    fn draw_text(&mut self, _origin: Point, _text: &str) {
        // Unshaped text is not renderable; real text arrives as glyph runs.
    }

    fn draw_glyph_run(&mut self, run: GlyphRun) {
        SceneBuilder::draw_glyph_run(self, run);
    }

    fn draw_image(&mut self, data: &peniko::ImageData, dest: Rect) {
        SceneBuilder::draw_image(self, data, dest);
    }

    fn draw_shader(&mut self, program: &ShaderProgram, dest: Rect, time: f32) {
        SceneBuilder::draw_shader(self, program, dest, time);
    }

    fn draw_scene_texture(&mut self, id: u64, dest: Rect) {
        SceneBuilder::scene_texture(self, id, dest);
    }

    fn draw_shadow(&mut self, origin: Point, size: Size, radius: f64, std_dev: f64, color: Color) {
        SceneBuilder::draw_blurred_rounded_rect(
            self,
            rect_at(origin, size),
            radius,
            std_dev,
            color,
        );
    }

    fn fill_rect_brush(&mut self, origin: Point, size: Size, brush: &Brush) {
        SceneBuilder::fill_rect(self, rect_at(origin, size), brush.clone());
    }

    fn fill_rounded_rect_brush(&mut self, origin: Point, size: Size, radius: f64, brush: &Brush) {
        SceneBuilder::fill_rounded_rect(self, rect_at(origin, size), radius, brush.clone());
    }

    fn push_layer(&mut self, origin: Point, size: Size, alpha: f32) {
        SceneBuilder::push_layer(self, rect_at(origin, size), alpha);
    }

    fn pop_layer(&mut self) {
        SceneBuilder::pop_layer(self);
    }

    fn clear_rect(&mut self, origin: Point, size: Size) {
        SceneBuilder::clear_rect(self, rect_at(origin, size));
    }

    fn fill_path(&mut self, origin: Point, path: &BezPath, brush: &Brush) {
        SceneBuilder::fill_path(self, path_at(origin, path), brush.clone());
    }

    fn stroke_path(&mut self, origin: Point, path: &BezPath, width: f64, brush: &Brush) {
        SceneBuilder::stroke_path(self, path_at(origin, path), width, brush.clone());
    }

    fn stroke_path_dashed(
        &mut self,
        origin: Point,
        path: &BezPath,
        width: f64,
        dash: DashPattern,
        brush: &Brush,
    ) {
        SceneBuilder::stroke_path_dashed(self, path_at(origin, path), width, dash, brush.clone());
    }

    fn push_transform(&mut self, transform: Affine) {
        SceneBuilder::push_transform(self, transform);
    }

    fn pop_transform(&mut self) {
        SceneBuilder::pop_transform(self);
    }

    fn push_snapshot(&mut self, key: u64, origin: Point, size: Size, alpha: f32, scale: f64) {
        SceneBuilder::push_snapshot(self, key, rect_at(origin, size), alpha, scale);
    }

    fn pop_snapshot(&mut self) {
        SceneBuilder::pop_snapshot(self);
    }
}

/// Build an origin/size pair into the `kurbo::Rect` the scene builder speaks.
fn rect_at(origin: Point, size: Size) -> Rect {
    Rect::new(
        origin.x,
        origin.y,
        origin.x + size.width,
        origin.y + size.height,
    )
}

/// Translates `path` (in the widget's local coordinate space) by `origin`,
/// mirroring [`rect_at`]'s origin/size convention for [`PaintScene::fill_path`]/
/// [`PaintScene::stroke_path`].
fn path_at(origin: Point, path: &BezPath) -> BezPath {
    Affine::translate((origin.x, origin.y)) * path.clone()
}

/// Context passed to [`Widget::layout`].
///
/// Beyond the (still-empty) container seam, it optionally carries the shared,
/// heavyweight text-shaping context the render root threads down for text
/// layout, plus the app's active theme (design tokens).
/// Both resources are **type-erased** (`&mut dyn Any` / `&dyn Any`) so
/// `frust-core` stays independent of `frust-text` (and thus of parley)
/// and of `frust-theme`; text widgets recover the shaping context with
/// [`LayoutCtx::text_context`] and themed widgets recover the theme with
/// [`LayoutCtx::theme_as`].
pub struct LayoutCtx<'a> {
    text_ctx: Option<&'a mut dyn Any>,
    /// The app's active theme, threaded down type-erased by the render root so
    /// this crate needs no `frust-theme` dependency. `None` in bare-core
    /// tests and pre-theme apps — a *supported* state (unlike the text context,
    /// whose absence at a text widget is a wiring bug), so [`LayoutCtx::theme_as`]
    /// returns `Option` rather than panicking.
    theme: Option<&'a dyn Any>,
    /// The window's insets ([`WindowInsets`]), threaded down by the render root
    /// (see [`crate::app::RenderRoot::set_insets`]). Unlike the theme this is a
    /// concrete core-owned type carried by copy — global (origin-independent,
    /// see the [`crate::insets`] module docs), so the single layout context the
    /// render root threads down carries it unchanged to every widget in the
    /// tree — except inside a [`LayoutCtx::with_window_insets`] scope, where a
    /// consuming ancestor (`SafeArea`) installs a reduced value for its subtree.
    /// Defaults to the zero inset in bare-core tests and pre-insets apps.
    window_insets: WindowInsets,
    /// The window's logical size, threaded down by the render root
    /// ([`crate::app::RenderRoot::layout`]) exactly like `window_insets` above —
    /// one layout context reaches the whole tree, so the value is set once at the
    /// root and every widget reads the same one. [`Size::ZERO`] in bare-core
    /// tests and before the first layout, a supported state.
    ///
    /// Its consumer is the overlay portal: a widget that floats a pod
    /// ([`crate::overlay`]) lays that pod out against the *window*, not against
    /// its own constraints, because the pod will be painted at an absolute window
    /// rect rather than inside its owner. See [`LayoutCtx::window_size`].
    window_size: Size,
}

impl<'a> LayoutCtx<'a> {
    /// Create a layout context with no shared resources.
    ///
    /// Used by leaf-only unit tests and by containers that never lay out text.
    pub fn new() -> LayoutCtx<'static> {
        LayoutCtx {
            text_ctx: None,
            theme: None,
            window_insets: WindowInsets::default(),
            window_size: Size::ZERO,
        }
    }

    /// Create a layout context carrying the shared text-shaping context.
    ///
    /// The render root builds this so text widgets can shape their content
    /// during the layout pass; the concrete type is erased to keep this crate
    /// free of a `frust-text` dependency.
    pub fn with_text_context(text_ctx: &'a mut dyn Any) -> Self {
        LayoutCtx {
            text_ctx: Some(text_ctx),
            theme: None,
            window_insets: WindowInsets::default(),
            window_size: Size::ZERO,
        }
    }

    /// Create a layout context carrying both an optional text-shaping context
    /// and an optional type-erased theme.
    ///
    /// The render root uses this to thread both resources it owns into the
    /// layout pass in one shot (see [`crate::app::RenderRoot::layout`]).
    pub fn with_resources(text_ctx: Option<&'a mut dyn Any>, theme: Option<&'a dyn Any>) -> Self {
        LayoutCtx {
            text_ctx,
            theme,
            window_insets: WindowInsets::default(),
            window_size: Size::ZERO,
        }
    }

    /// Attach the app's active theme, type-erased. Chainable builder used by the
    /// render root when it lends a stored theme into the layout pass.
    pub fn with_theme(mut self, theme: &'a dyn Any) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Recover the shared text-shaping context as `&mut T`.
    ///
    /// Panics if no context was threaded into this pass, or if its concrete
    /// type differs from `T` — both are shell-wiring bugs, not runtime-data
    /// conditions.
    pub fn text_context<T: Any>(&mut self) -> &mut T {
        self.text_ctx
            .as_deref_mut()
            .expect("no text context threaded into this layout pass")
            .downcast_mut::<T>()
            .expect("threaded layout resource is not the expected text-context type")
    }

    /// Recover the threaded theme as `&T`, or `None` if no theme was threaded
    /// into this pass (a supported state — bare-core tests and pre-theme apps)
    /// or its concrete type differs from `T`.
    ///
    /// Mirrors [`LayoutCtx::text_context`] but returns `Option` rather than
    /// panicking, because a missing theme is a valid runtime state, not a
    /// wiring bug. Widgets that read `frust_theme::Theme` downcast through
    /// this (or the `Theme::from_layout_ctx` convenience wrapper).
    pub fn theme_as<T: Any>(&self) -> Option<&T> {
        self.theme?.downcast_ref::<T>()
    }

    /// The window's insets ([`WindowInsets`]) for this layout pass (a cheap
    /// copy). Global and origin-independent (see the [`crate::insets`] module
    /// docs), so every widget reads the same value regardless of its position —
    /// save that a consuming ancestor may have narrowed it for its subtree via
    /// [`LayoutCtx::with_window_insets`]; defaults to the zero inset when no
    /// shell pushed one. A `SafeArea` widget insets by [`WindowInsets::padding`].
    pub fn window_insets(&self) -> WindowInsets {
        self.window_insets
    }

    /// Seed the window insets lent by the render root
    /// ([`crate::app::RenderRoot::layout`]). One layout context is threaded down
    /// the whole tree, so this is set once at the root; the insets are global,
    /// so no per-child adjustment is needed.
    pub(crate) fn set_window_insets(&mut self, insets: WindowInsets) {
        self.window_insets = insets;
    }

    /// Run `f` with `insets` installed as this context's window insets, then
    /// restore the previous value and return `f`'s result.
    ///
    /// The window insets are otherwise a single root-seeded, global value that
    /// every widget reads unchanged. This scoped override is how a widget that
    /// has already padded its subtree by some inset edges removes them from
    /// that subtree (Flutter's `MediaQuery.removePadding`): `SafeArea` lays its
    /// child out inside
    /// `ctx.with_window_insets(ctx.window_insets().consuming(..), |ctx| ..)`, so
    /// a self-insetting descendant reads zero padding on the consumed edges
    /// instead of insetting a second time. Pair it with
    /// [`PaintCtx::with_window_insets`] around the matching `paint_child` so a
    /// paint-time read agrees with the layout-time one.
    ///
    /// The restore is a plain assignment after `f` returns — there is no drop
    /// guard, so if `f` panics the override is not undone (the pass is being
    /// unwound anyway).
    pub fn with_window_insets<R>(
        &mut self,
        insets: WindowInsets,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let saved = std::mem::replace(&mut self.window_insets, insets);
        let result = f(self);
        self.window_insets = saved;
        result
    }

    /// The window's logical size for this layout pass (a cheap copy).
    ///
    /// Global and origin-independent like [`LayoutCtx::window_insets`], so every
    /// widget in the tree reads the same value regardless of where it sits or
    /// what constraints its parent handed it; [`Size::ZERO`] when no root has laid
    /// out yet (bare-core leaf tests).
    ///
    /// **The constraint an overlay pod is laid out against.** A widget floating a
    /// pod through [`crate::overlay`] sizes it with
    /// `BoxConstraints::loose(ctx.window_size())` rather than with its own `bc`:
    /// the pod escapes its owner's box entirely, so the owner's constraints say
    /// nothing about how much room the floated surface has, and the window is the
    /// only bound that does.
    pub fn window_size(&self) -> Size {
        self.window_size
    }

    /// Seed the window size lent by the render root
    /// ([`crate::app::RenderRoot::layout`]). One layout context is threaded down
    /// the whole tree, so this is set once at the root and inherited unchanged,
    /// exactly like [`LayoutCtx::set_window_insets`].
    pub(crate) fn set_window_size(&mut self, size: Size) {
        self.window_size = size;
    }
}

impl Default for LayoutCtx<'static> {
    fn default() -> Self {
        Self::new()
    }
}

/// The *class* of a continuation-frame request a widget makes during paint —
/// how urgent the next frame is, so the mobile frame gate can decide whether it
/// may be paced (see [`crate::app::RenderRoot::paint`] and the frame gate).
///
/// A widget continues an animation by asking for another frame during paint
/// ([`PaintCtx::request_frame`] / [`PaintCtx::request_frame_paced`]); this tag
/// says whether that next frame is user-visible motion that must land on the
/// very next vsync ([`TickClass::Transition`]) or a decorative loop whose cadence
/// can be throttled without a perceptible glitch ([`TickClass::CosmeticLoop`]).
///
/// **Aggregation is a max-lattice**: `Transition` dominates `CosmeticLoop`. Over
/// a whole paint pass, ANY [`TickClass::Transition`] request makes the frame
/// unpaced (must run every vsync, today's behavior); only when *every* request
/// this frame is [`TickClass::CosmeticLoop`] may the gate pace it. No request at
/// all leaves the frame as it is today — the class is only meaningful once a
/// frame was actually requested (see [`PaintCtx::frame_class`]).
///
/// A `CosmeticLoop` request may additionally name *how often* it wants to be
/// re-run ([`PaintCtx::request_frame_paced_at`]); those intervals aggregate on
/// their own **MIN**-lattice, orthogonal to this max-lattice over classes (see
/// [`PaintCtx::paced_interval`]).
///
/// The *gate-side* pacing behavior is implemented separately (the mobile frame
/// gate); this type is only the vocabulary a widget uses to declare intent.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TickClass {
    /// A pacable decorative loop (e.g. a skeleton shimmer, an idle pulse) — the
    /// gate may throttle its cadence when this is the *only* class requested
    /// this frame. Never dominates a concurrent [`TickClass::Transition`].
    CosmeticLoop,
    /// User-visible motion that must reproduce every vsync — a page transition,
    /// a fling, a caret blink, a layout animation. Today's `request_frame`
    /// behavior, and the dominant class in the aggregation above.
    Transition,
}

/// Context passed to [`Widget::paint`].
///
/// Carries the widget's resolved geometry (as stored in its pod after layout) so
/// paint code can position itself in the parent coordinate space, plus the v1
/// animation-driver signal ([`PaintCtx::request_frame`]): a widget whose paint
/// advances animation state (e.g. a scroll fling) must call it so the shell keeps
/// scheduling frames even absent external input. The flag bubbles up through
/// [`ChildPod::paint_child`] and out of [`crate::app::RenderRoot::paint`] as a
/// [`PaintOutcome`], mirroring how [`EventCtx::request_redraw`] surfaces through
/// [`crate::event::EventOutcome`].
///
/// A frame request also carries a [`TickClass`] (see [`PaintCtx::request_frame`]
/// vs [`PaintCtx::request_frame_paced`]): the aggregate class over the whole
/// paint pass — Transition-dominates-CosmeticLoop — surfaces on
/// [`PaintOutcome::needs_frame_paced_only`] for the mobile frame gate to pace a
/// purely-cosmetic frame.
pub struct PaintCtx<'a> {
    origin: Point,
    size: Size,
    needs_frame: bool,
    /// Whether a widget whose animation changes its *layout* (not just paint)
    /// asked, via [`PaintCtx::request_layout`], to have layout re-run next frame.
    /// Bubbles up through [`ChildPod::paint_child`] exactly like `needs_frame`
    /// and out of [`crate::app::RenderRoot::paint`] as [`PaintOutcome::needs_layout`],
    /// which folds into the render root's pending [`ChangeFlags`] so the mobile
    /// intra-frame layout skip re-runs layout while the animation is in flight.
    /// Deliberately opt-in: [`PaintCtx::request_frame`] alone never sets it, so
    /// paint-only animations stay layout-free.
    needs_layout: bool,
    /// Whether any continuation-frame request this (sub)paint was
    /// [`TickClass::Transition`] (unpaced, must run every vsync). The
    /// max-lattice half of the tick-class aggregation: it starts `false` and
    /// only ever flips `true` (a [`ChildPod::paint_child`]/
    /// [`PaintCtx::with_hero_registry`] bubble ORs it up), so ANY Transition
    /// request over the whole pass wins. Meaningful only when `needs_frame` is
    /// set: `needs_frame && !frame_unpaced` is the "paced-only" state the frame
    /// gate may throttle (see [`PaintCtx::frame_class`],
    /// [`PaintCtx::needs_frame_paced_only`]). `request_layout` implies
    /// Transition (a layout animation is user-visible motion), and the
    /// unchanged `request_frame` sets it too (today's every-vsync behavior).
    frame_unpaced: bool,
    /// The **MIN** over every paced ([`TickClass::CosmeticLoop`]) request's
    /// named interval this (sub)paint — the tightest cadence anything asked
    /// for. `None` until the first paced request; a bare
    /// [`PaintCtx::request_frame_paced`] contributes [`Duration::ZERO`] ("as
    /// often as the theme cap allows"), which is the MIN-lattice's absorbing
    /// element and therefore dominates any slower explicit request.
    ///
    /// Orthogonal to `frame_unpaced` (the class max-lattice): it is only
    /// *meaningful* while the aggregate class is `CosmeticLoop`, but a later
    /// Transition request never clears it. Bubbles up through
    /// [`ChildPod::paint_child`]/[`PaintCtx::with_hero_registry`] exactly like
    /// `frame_unpaced`, and surfaces on [`PaintOutcome::paced_interval`] for the
    /// mobile frame gate to resolve against the theme's cap.
    paced_interval: Option<Duration>,
    ime_state: Option<ImeState>,
    /// Whether the widget being painted currently holds the focus path — seeded
    /// from its pod's recorded link *on the live session*
    /// ([`ChildPod::holds_live_focus`]'s composition, spelled out inline) by
    /// [`ChildPod::paint_child`], and from [`crate::app::RenderRoot`]'s
    /// `focus_active` at the root. The paint-pass mirror of
    /// [`EventCtx::has_focus`]: an editable gates its focus chrome (accent
    /// border, caret, blink `request_frame`, IME republish) on it, so a
    /// container-routed blur — which clears the pod's focus path without calling
    /// the widget's `event()` — is finally observed here (see
    /// [`PaintCtx::has_focus`]).
    has_focus: bool,
    /// Whether the widget being painted is on the recorded hover path (it or a
    /// descendant holds the link) — seeded from its
    /// pod's recorded hover stamp ([`ChildPod::hover_epoch`], compared against
    /// `hover_epoch` below) by [`ChildPod::paint_child`], and from
    /// [`crate::app::RenderRoot`]'s hover mirror at the root. The paint-pass
    /// mirror of [`EventCtx::is_hovered`] and the *authoritative* hover read for a
    /// widget's own chrome: a pointer that left the widget routes its next move
    /// elsewhere, so the widget's own `event()` never hears about the loss (see
    /// [`PaintCtx::is_hovered`]).
    hovered: bool,
    /// The live hover epoch — the epoch of the last completed hover pass, threaded
    /// from [`crate::app::RenderRoot::paint`] and copied into each child by
    /// [`ChildPod::paint_child`] (global, like the clock). A pod's recorded stamp
    /// counts as hovered only while it equals this; see the [`crate::event`] module
    /// docs for the epoch mechanism.
    hover_epoch: u64,
    /// The live focus epoch — the identity of the focus session the root
    /// currently holds, threaded from [`crate::app::RenderRoot::paint`] and
    /// copied into each child by [`ChildPod::paint_child`] (global, like the
    /// clock and the hover epoch).
    ///
    /// A pod's recorded focus stamp ([`ChildPod::focus_epoch`]) counts as a link
    /// on the live session only while it equals this, which is what strands the
    /// link of a branch the session has left — including one no container can
    /// reach to clear. See [`set_live_focus_session`].
    focus_epoch: u64,
    /// The shell-provided time for this frame, threaded from
    /// [`crate::app::RenderRoot::paint`] and seeded into each child by
    /// [`ChildPod::paint_child`]. Defaults to [`FrameTime::ZERO`] (the "no time
    /// available" fallback) for a paint context built without a clock (leaf unit
    /// tests, recorder scenes). A widget differences it against a stored earlier
    /// value to advance animation state — see [`PaintCtx::frame_time`].
    frame_time: FrameTime,
    /// The app's active theme, threaded down type-erased by the render root
    /// ([`crate::app::RenderRoot::paint`]) and seeded into each child by
    /// [`ChildPod::paint_child`], mirroring how `frame_time`/`has_focus` flow.
    /// `None` in bare-core tests and pre-theme apps — a supported state, so
    /// [`PaintCtx::theme_as`] returns `Option` rather than panicking.
    theme: Option<&'a dyn Any>,
    /// The window's insets ([`WindowInsets`]), threaded down by the render root
    /// ([`crate::app::RenderRoot::paint`]) and seeded into each child by
    /// [`ChildPod::paint_child`], mirroring how `frame_time`/`theme` flow. A
    /// concrete core-owned type carried by copy; global/origin-independent (see
    /// the [`crate::insets`] module docs). Defaults to the zero inset in
    /// bare-core tests and pre-insets apps.
    window_insets: WindowInsets,
    /// The shell's running count of frames the render thread has actually
    /// presented, threaded down by the render root
    /// ([`crate::app::RenderRoot::paint`]) and seeded into each child by
    /// [`ChildPod::paint_child`], mirroring how `frame_time`/`theme`/
    /// `window_insets` flow. `None` when no shell pushed one (bare-core tests,
    /// pre-wiring shells) so a widget can fall back — see
    /// [`PaintCtx::presented_frames`]. Unlike the clock/theme/insets this is a
    /// pure *observation* the render root stores WITHOUT dirtying
    /// [`ChangeFlags`] (see [`crate::app::RenderRoot::set_presented_frames`]), so
    /// a ticking presented count never forces a relayout or feeds the mobile
    /// frame gate.
    presented_frames: Option<u64>,
    /// A tagged-rect ("hero") reporter a container installs over a subtree via
    /// [`PaintCtx::with_hero_registry`], threaded to descendants by
    /// [`ChildPod::paint_child`] like the theme/clock. `None` in the normal
    /// case (no shared-element transition in flight), so
    /// [`PaintCtx::report_hero`] is a no-op returning [`HeroDirective::Normal`].
    hero: Option<&'a RefCell<HeroFrames>>,
    /// The absolute (global-coordinate) rectangle a scroll ancestor is currently
    /// showing, threaded down by [`ChildPod::paint_child`] like the theme/clock so
    /// a container can cull paint of children fully outside it. `None` (the
    /// default) means "no viewport constraint — paint everything", so every
    /// pre-culling behavior is unchanged. A [`ScrollView`](crate::app) sets it to
    /// its viewport via [`PaintCtx::constrain_visible_rect`], which *intersects*
    /// (never widens) a nested rect, so an inner scroll surface can only ever
    /// narrow the visible region an outer one already established. Consulted by
    /// `Flex` (see [`PaintCtx::visible_rect`]); coordinates match
    /// [`PaintCtx::origin`]'s absolute space, so a child's absolute bounds test
    /// directly against it.
    visible_rect: Option<Rect>,
    /// [`PlatformViewFrame`]s published this (sub)paint via
    /// [`PaintCtx::publish_platform_view`], in paint order.
    ///
    /// Unlike `ime_state` above (an `Option` — at most one focused editable
    /// publishes per pass), this is a `Vec`: any number of platform-view slots
    /// can paint in the same pass, so [`ChildPod::paint_child`] must EXTEND it
    /// from each child rather than overwrite, or every slot but the last
    /// child's would silently vanish. See [`PaintCtx::publish_platform_view`].
    platform_views: Vec<PlatformViewFrame>,
    /// Absolute-coordinate z-shield rects reported this (sub)paint via
    /// [`PaintCtx::report_input_shield`], in paint order.
    ///
    /// The same `Vec`-extend discipline as `platform_views` above and for the
    /// same reason: any number of shields can paint in one pass, so
    /// [`ChildPod::paint_child`] EXTENDS rather than overwrites. Consumed by
    /// the shell-side platform-view differ, which intersects them against each
    /// interactive slot's rect — core stays dumb about what a shield means (see
    /// [`PaintCtx::report_input_shield`]).
    input_shields: Vec<Rect>,
    /// Whether the shell created a translucent (alpha-channel, "Mode B") GPU
    /// surface for this frame, threaded down by the render root
    /// ([`crate::app::RenderRoot::paint`], seeded from
    /// [`crate::app::RenderRoot::set_surface_translucent`]) and copied into each
    /// child by [`ChildPod::paint_child`], mirroring `theme`/`window_insets`.
    /// `false` in the normal opaque ("Mode A") case, bare-core tests, and every
    /// desktop app. Read by the platform-view hole-punch (see
    /// [`PaintCtx::is_translucent`]).
    translucent: bool,
}

impl<'a> PaintCtx<'a> {
    /// Create a paint context for a widget at `origin` with `size`.
    ///
    /// The frame time defaults to [`FrameTime::ZERO`] and no theme is threaded
    /// in; the render root seeds the real shell clock via
    /// [`PaintCtx::set_frame_time`] and the active theme via
    /// [`PaintCtx::set_theme`] before painting the root widget, and both flow to
    /// children through [`ChildPod::paint_child`].
    pub fn new(origin: Point, size: Size) -> Self {
        Self {
            origin,
            size,
            needs_frame: false,
            needs_layout: false,
            frame_unpaced: false,
            paced_interval: None,
            ime_state: None,
            has_focus: false,
            hovered: false,
            hover_epoch: 0,
            focus_epoch: 0,
            frame_time: FrameTime::ZERO,
            theme: None,
            window_insets: WindowInsets::default(),
            presented_frames: None,
            hero: None,
            visible_rect: None,
            platform_views: Vec::new(),
            input_shields: Vec::new(),
            translucent: false,
        }
    }

    /// Attach the app's active theme, type-erased. Chainable builder mirroring
    /// [`LayoutCtx::with_theme`] — used by widget unit tests that paint against a
    /// known theme; the render root threads it via [`PaintCtx::set_theme`].
    pub fn with_theme(mut self, theme: &'a dyn Any) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Mark this paint pass as running against a translucent ("Mode B") surface.
    /// Chainable builder mirroring [`PaintCtx::with_theme`] — used by widget unit
    /// tests exercising the platform-view hole-punch; the render root threads the
    /// real flag via [`PaintCtx::set_translucent`] (see
    /// [`PaintCtx::is_translucent`]).
    pub fn with_translucent(mut self, translucent: bool) -> Self {
        self.translucent = translucent;
        self
    }

    /// Build a paint context at `origin`/`size` seeded with an arbitrary
    /// [`FrameTime`], for exercising clock-dependent paint logic (caret blink,
    /// a hand-advanced [`crate::anim::AnimationController`], …) from outside
    /// this crate.
    ///
    /// [`PaintCtx::set_frame_time`] is deliberately `pub(crate)` — only
    /// [`crate::app::RenderRoot::paint`] (the shell-owned clock source) may
    /// advance it in a production build — so an app crate testing a widget
    /// from its own `src/` has no other way to construct a `PaintCtx` at a
    /// chosen time. This constructor is that sanctioned seam. Gated behind
    /// `cfg(test)`/the `test-support` feature so the symbol does not exist in
    /// a normal app build; see the crate's `test-support` feature docs in
    /// `Cargo.toml`.
    #[cfg(any(test, feature = "test-support"))]
    pub fn for_test(origin: Point, size: Size, frame_time: FrameTime) -> Self {
        let mut ctx = Self::new(origin, size);
        ctx.frame_time = frame_time;
        ctx
    }

    /// Recover the threaded theme as `&T`, or `None` if no theme was threaded
    /// into this pass (a supported state — bare-core tests and pre-theme apps)
    /// or its concrete type differs from `T`.
    ///
    /// The paint-pass mirror of [`LayoutCtx::theme_as`]. Widgets that read
    /// `frust_theme::Theme` downcast through this (or the
    /// `Theme::from_paint_ctx` convenience wrapper).
    pub fn theme_as<T: Any>(&self) -> Option<&T> {
        self.theme?.downcast_ref::<T>()
    }

    /// Seed the type-erased theme lent by the render root. Called by
    /// [`crate::app::RenderRoot::paint`] at the root and by
    /// [`ChildPod::paint_child`] for each child, mirroring how `frame_time` is
    /// threaded. The `Option<&dyn Any>` is copied down unchanged so a nested
    /// widget observes the same theme instance without re-borrowing the parent
    /// context.
    pub(crate) fn set_theme(&mut self, theme: Option<&'a dyn Any>) {
        self.theme = theme;
    }

    /// The type-erased theme reference this context carries, for re-lending to a
    /// child context (copied, so it does not hold a borrow of `self`).
    pub(crate) fn theme_ref(&self) -> Option<&'a dyn Any> {
        self.theme
    }

    /// The window's insets ([`WindowInsets`]) for this paint pass (a cheap
    /// copy). The paint-pass mirror of [`LayoutCtx::window_insets`]:
    /// global/origin-independent, so every widget reads the same value (unless a
    /// consuming ancestor narrowed it via [`PaintCtx::with_window_insets`]);
    /// defaults to the zero inset when no shell pushed one.
    pub fn window_insets(&self) -> WindowInsets {
        self.window_insets
    }

    /// Seed the window insets lent by the render root. Called by
    /// [`crate::app::RenderRoot::paint`] at the root and by
    /// [`ChildPod::paint_child`] for each child, mirroring how `theme`/
    /// `frame_time` are threaded (copied down unchanged).
    pub(crate) fn set_window_insets(&mut self, insets: WindowInsets) {
        self.window_insets = insets;
    }

    /// The window insets this context carries, for re-lending to a child context
    /// (copied, so it holds no borrow of `self`).
    pub(crate) fn window_insets_ref(&self) -> WindowInsets {
        self.window_insets
    }

    /// Run `f` with `insets` installed as this context's window insets, then
    /// restore the previous value and return `f`'s result.
    ///
    /// The paint-pass mirror of [`LayoutCtx::with_window_insets`]. The value is
    /// otherwise root-seeded and copied down unchanged by
    /// [`ChildPod::paint_child`]; because `paint_child` copies it from the
    /// parent context it is handed, wrapping `paint_child` in this scope hands
    /// the override to the whole painted subtree. `SafeArea` does exactly that
    /// with the same consumed value it laid its child out under, so a widget
    /// that reads insets at paint time sees what it was laid out with.
    ///
    /// The restore is a plain assignment after `f` returns — there is no drop
    /// guard, so if `f` panics the override is not undone (the pass is being
    /// unwound anyway).
    pub fn with_window_insets<R>(
        &mut self,
        insets: WindowInsets,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let saved = std::mem::replace(&mut self.window_insets, insets);
        let result = f(self);
        self.window_insets = saved;
        result
    }

    /// The shell's running count of frames the render thread has actually
    /// presented, or `None` when no shell wired one in (bare-core tests,
    /// pre-wiring shells) — a supported state, so a widget can fall back to a
    /// paint-cadence measure.
    ///
    /// Under the render-thread split the UI thread paints faster than the render
    /// thread presents (a gate-skipped or coalesced frame is never presented), so
    /// a widget measuring *frames per second* must difference this presented
    /// count — not its own paint count — to report the rate a user actually sees
    /// (`examples/shadertoy`'s HUD is the reference consumer). A widget only ever
    /// *differences* two reads (`wrapping_sub`); the absolute value is a
    /// free-running monotonic counter it must never interpret directly. Seeded
    /// from the shell at the root ([`crate::app::RenderRoot::paint`]) and threaded
    /// unchanged into every child by [`ChildPod::paint_child`], mirroring
    /// `frame_time`.
    pub fn presented_frames(&self) -> Option<u64> {
        self.presented_frames
    }

    /// Seed the shell's presented-frame count. Called by
    /// [`crate::app::RenderRoot::paint`] at the root and by
    /// [`ChildPod::paint_child`] for each child, mirroring how `frame_time`/
    /// `window_insets` are threaded (copied down unchanged).
    pub(crate) fn set_presented_frames(&mut self, presented: Option<u64>) {
        self.presented_frames = presented;
    }

    /// The widget's absolute origin in window-space coordinates.
    ///
    /// This origin is accumulated as the paint pass descends the widget tree:
    /// [`ChildPod::paint_child`] adds the child's parent-relative `origin` to the
    /// parent's already-absolute `ctx.origin()`, threading the result down through
    /// nested levels. Contrast [`ChildPod::origin`], which is parent-relative and
    /// correct as documented, and [`EventCtx::origin`], which is **also**
    /// parent-relative — the event pass translates the event into the child's
    /// local space instead of accumulating the origin. This is therefore the only
    /// context origin an overlay, popup, or reported window-space rect may be
    /// anchored from.
    pub fn origin(&self) -> Point {
        self.origin
    }

    /// The widget's resolved size.
    pub fn size(&self) -> Size {
        self.size
    }

    /// Whether the widget being painted holds the focus path.
    ///
    /// Threaded down from the widget's pod ([`ChildPod::is_focused`], seeded at
    /// the root from `RenderRoot::focus_active`), this is the *authoritative*
    /// focus signal during paint — a widget must prefer it over any focus flag
    /// it tracks internally. A container-routed blur clears the pod's focus path
    /// but never dispatches to the widget's `event()`, so a widget-internal flag
    /// can lag; reading `has_focus()` here (and self-correcting the internal
    /// flag against it) lets the widget converge one frame after the blur.
    /// Mirrors [`EventCtx::has_focus`].
    pub fn has_focus(&self) -> bool {
        self.has_focus
    }

    /// Seed whether the widget being painted holds focus. Called by
    /// [`ChildPod::paint_child`] (from the pod's recorded link, its session stamp
    /// and the chain above it) and by [`crate::app::RenderRoot::paint`] (from
    /// `focus_active`) — the paint mirror of [`EventCtx::set_has_focus`].
    pub(crate) fn set_has_focus(&mut self, has_focus: bool) {
        self.has_focus = has_focus;
    }

    /// Whether the pointer is over the widget being painted **or over a descendant
    /// of it** — i.e. whether this widget is on the recorded hover path.
    ///
    /// A container therefore reads `true` while the pointer is over a claiming
    /// child, the way CSS `:hover` applies to an element while the pointer is over
    /// one of its descendants; a sibling or any other off-path widget reads
    /// `false`.
    ///
    /// This is the **authoritative** hover signal, for the same reason
    /// [`PaintCtx::has_focus`] is authoritative for focus, only more strongly: a
    /// pointer leaving a widget routes its next move to whatever it moved *onto*,
    /// so the widget it left never receives an event telling it so. A hover
    /// consumer keeps its own hover flag (that is what earns it a repaint on entry
    /// — see [`EventCtx::claim_hover`] for the whole contract) and **self-corrects
    /// that flag from this read every paint**, which is what fixes it whenever an
    /// event never came.
    ///
    /// Hover is opt-in: a widget in a tree where nothing ever calls
    /// [`claim_hover`](EventCtx::claim_hover) always reads `false` here.
    pub fn is_hovered(&self) -> bool {
        self.hovered
    }

    /// Seed whether the widget being painted holds the hover link. Called by
    /// [`ChildPod::paint_child`] (from the pod's recorded stamp) and by
    /// [`crate::app::RenderRoot::paint`] (from its hover mirror) — the paint mirror
    /// of [`EventCtx::set_hovered`].
    pub(crate) fn set_hovered(&mut self, hovered: bool) {
        self.hovered = hovered;
    }

    /// Seed the live hover epoch. Called by [`crate::app::RenderRoot::paint`] at
    /// the root and by [`ChildPod::paint_child`] for each child, mirroring how
    /// `frame_time` is threaded (copied down unchanged).
    pub(crate) fn set_hover_epoch(&mut self, epoch: u64) {
        self.hover_epoch = epoch;
    }

    /// The live hover epoch a pod's recorded stamp is compared against.
    pub(crate) fn hover_epoch(&self) -> u64 {
        self.hover_epoch
    }

    /// Seed the live focus epoch. Called by
    /// [`crate::app::RenderRoot::paint`] at the root (and for each floated pod)
    /// and threaded unchanged into every child by [`ChildPod::paint_child`],
    /// mirroring how the hover epoch flows.
    pub(crate) fn set_focus_epoch(&mut self, epoch: u64) {
        self.focus_epoch = epoch;
    }

    /// The live focus epoch: a pod whose recorded stamp equals this holds a link
    /// on the session the root currently has.
    pub(crate) fn focus_epoch(&self) -> u64 {
        self.focus_epoch
    }

    /// The shell-provided time for this frame (monotonic, arbitrary origin).
    ///
    /// This is the single shared clock the whole paint pass sees: seeded from the
    /// shell at the root ([`crate::app::RenderRoot::paint`]) and threaded
    /// unchanged into every child by [`ChildPod::paint_child`], so sibling and
    /// nested animations advance against one consistent timestamp. A widget may
    /// only *difference* it against an earlier `frame_time` it stored (via
    /// [`FrameTime::saturating_sub`] / [`crate::anim::AnimationController::advance`]),
    /// never interpret it absolutely — the origin varies per shell. Defaults to
    /// [`FrameTime::ZERO`] when no clock was threaded in (leaf unit tests).
    pub fn frame_time(&self) -> FrameTime {
        self.frame_time
    }

    /// Seed the shell-provided frame time. Called by
    /// [`crate::app::RenderRoot::paint`] at the root and by
    /// [`ChildPod::paint_child`] for each child, mirroring how `has_focus` is
    /// threaded.
    pub(crate) fn set_frame_time(&mut self, frame_time: FrameTime) {
        self.frame_time = frame_time;
    }

    /// Signal that this paint advanced animation state and needs to be
    /// re-invoked to continue, even with no intervening input event.
    ///
    /// The desktop shell honors this with a `window.request_redraw()` (its
    /// `ControlFlow::Wait` loop would otherwise idle); the mobile shells'
    /// continuous per-frame loops already schedule the next frame and can ignore
    /// it. Mirrors [`EventCtx::request_redraw`].
    ///
    /// This requests a [`TickClass::Transition`] frame — the unpaced,
    /// every-vsync class, unchanged from today's behavior. A widget whose next
    /// frame is a *pacable* decorative loop calls [`Self::request_frame_paced`]
    /// (or [`Self::request_frame_class`]) instead so the mobile frame gate may
    /// throttle it.
    pub fn request_frame(&mut self) {
        self.request_frame_class(TickClass::Transition);
    }

    /// Request a continuation frame whose next tick is a *pacable* decorative
    /// loop ([`TickClass::CosmeticLoop`]) — a shimmer, an idle pulse, a spinner
    /// whose exact cadence is imperceptible.
    ///
    /// Bubbles like [`Self::request_frame`], but leaves the frame paceable: only
    /// if *every* request this frame is `CosmeticLoop` may the frame gate throttle
    /// it (see [`TickClass`]'s max-lattice aggregation). Any concurrent
    /// [`Self::request_frame`]/[`Self::request_layout`] elsewhere in the tree
    /// re-forces every-vsync cadence, so a paced request is never a downgrade of
    /// user-visible motion.
    ///
    /// This names no interval, which means "at the theme's own
    /// `MotionScheme::cosmetic_loop_rate`" — exactly
    /// `request_frame_paced_at(Duration::ZERO)`, since that rate is the cap every
    /// paced request resolves against (see [`Self::request_frame_paced_at`]).
    pub fn request_frame_paced(&mut self) {
        self.request_frame_paced_at(Duration::ZERO);
    }

    /// Request a pacable decorative repaint **no more often than** once per
    /// `interval` — [`Self::request_frame_paced`] with an explicit cadence, for a
    /// loop far slower than the theme's cosmetic rate (a ~500ms caret blink
    /// against a 30Hz shimmer cap).
    ///
    /// Same class as [`Self::request_frame_paced`] ([`TickClass::CosmeticLoop`]);
    /// only the requested cadence differs. Two contracts govern the value:
    ///
    /// - **MIN-lattice aggregation.** Multiple paced requests in one paint pass
    ///   fold to the *tightest* interval, so every requester is repainted at
    ///   least as often as it asked. A 30Hz shimmer (a bare
    ///   [`Self::request_frame_paced`], i.e. [`Duration::ZERO`]) beside a 500ms
    ///   caret paces the frame at 30Hz — the caret is then simply repainted more
    ///   often than it needs, which is visually indistinguishable from its own
    ///   cadence and costs nothing beyond frames the shimmer already forced. That
    ///   asymmetry is by design: a *slow* request can never starve a fast one.
    /// - **The theme rate is a ceiling, not a target.** The frame gate resolves
    ///   the aggregate against `1 / MotionScheme::cosmetic_loop_rate` and takes
    ///   the *longer* of the two, so an interval tighter than the cap is clamped
    ///   to it. Motion that genuinely must run every vsync is not cosmetic —
    ///   use [`Self::request_frame`] ([`TickClass::Transition`]) for that.
    ///
    /// `frust-core` never reads a clock or a theme, so neither the MIN-lattice
    /// fold above nor the shell-side theme-cap clamp happens here: the
    /// aggregate rides out on [`PaintOutcome::paced_interval`] and the shell's
    /// frame gate resolves it.
    ///
    /// One clamp DOES happen here, though: `interval` is capped at
    /// [`Self::MAX_PACED_INTERVAL`] before it is folded in, so no caller
    /// (buggy or otherwise) can push a runaway value out to the shell's
    /// pacing arithmetic. See that constant's doc comment for the full
    /// rationale. This is a pure ceiling, never a target — every real cadence
    /// in this codebase (a bare [`Duration::ZERO`] "theme rate" request, the
    /// ~500ms caret blink above, or any plausible slow pulse) sits far below
    /// it and passes through completely unchanged.
    pub fn request_frame_paced_at(&mut self, interval: Duration) {
        self.needs_frame = true;
        self.merge_paced_interval(interval.min(Self::MAX_PACED_INTERVAL));
    }

    /// Ceiling on the `interval` [`Self::request_frame_paced_at`] accepts.
    ///
    /// 10 seconds comfortably clears every real cosmetic cadence in this
    /// codebase — a bare [`Duration::ZERO`] "theme rate" request, the ~500ms
    /// caret blink, muxr's ~550ms blink, or any plausible slow pulse — while
    /// keeping the shell's downstream pacing arithmetic
    /// (`frust-shell-common::frame_gate`'s `interval * 2` /
    /// `interval.as_nanos() as u64`, `frust-shell-desktop::paced_wake`'s
    /// `Instant + interval`) far below overflow or truncation even at the
    /// widest legal input. [`Self::request_frame_paced_at`] is the single
    /// entry point every paced interval flows through (see
    /// [`Self::merge_paced_interval`]'s doc comment), so clamping here bounds
    /// every downstream consumer for free — this must never change behavior
    /// for any existing caller, since every shipped cadence is orders of
    /// magnitude under it.
    pub const MAX_PACED_INTERVAL: Duration = Duration::from_secs(10);

    /// Request a continuation frame of an explicit [`TickClass`] — the general
    /// form behind [`Self::request_frame`] (Transition) and
    /// [`Self::request_frame_paced`] (CosmeticLoop, at the theme's own rate).
    ///
    /// Always sets `needs_frame`; a [`TickClass::Transition`] request additionally
    /// marks the aggregate unpaced (the max-lattice OR — see [`TickClass`]). A
    /// `CosmeticLoop` request never clears an already-unpaced aggregate, and —
    /// naming no interval — folds [`Duration::ZERO`] into the MIN-lattice like
    /// [`Self::request_frame_paced`] does.
    pub fn request_frame_class(&mut self, class: TickClass) {
        match class {
            TickClass::Transition => {
                self.needs_frame = true;
                self.frame_unpaced = true;
            }
            TickClass::CosmeticLoop => self.request_frame_paced(),
        }
    }

    /// Fold one paced request's interval into this context's MIN-lattice
    /// aggregate — the single mutation point for `paced_interval`, called
    /// directly by [`Self::request_frame_paced_at`] and, for an already-`Some`
    /// bubbled interval, by [`Self::absorb_paced_interval`] (the two paint
    /// bubble sites' shared entry point).
    fn merge_paced_interval(&mut self, interval: Duration) {
        self.paced_interval = Some(match self.paced_interval {
            Some(current) => current.min(interval),
            None => interval,
        });
    }

    /// Fold a bubbled child's paced interval into this context's own
    /// MIN-lattice aggregate — the one rule shared by both paced-interval
    /// absorb sites ([`ChildPod::paint_child`], [`Self::with_hero_registry`]):
    /// skip entirely when the child named none, rather than defaulting to
    /// [`Duration::ZERO`] (the lattice's own tightest/absorbing element,
    /// meaning "at the theme's own rate"). Folding that default in for a
    /// child that named no interval at all would silently re-tighten this
    /// context to the theme cap even though nothing downstream actually asked
    /// for a frame at all — see [`Self::request_frame_paced_at`]'s MIN-lattice
    /// contract.
    fn absorb_paced_interval(&mut self, interval: Option<Duration>) {
        if let Some(interval) = interval {
            self.merge_paced_interval(interval);
        }
    }

    /// Whether a continuation frame was requested during this (sub)paint.
    pub fn needs_frame(&self) -> bool {
        self.needs_frame
    }

    /// The aggregate [`TickClass`] requested during this (sub)paint, or `None`
    /// if no frame was requested.
    ///
    /// Follows the [`TickClass`] max-lattice: [`TickClass::Transition`] if any
    /// request this pass was Transition-class (unpaced), else
    /// [`TickClass::CosmeticLoop`] when at least one paced request was made and
    /// no Transition one was. `None` means "as today — no continuation frame".
    pub fn frame_class(&self) -> Option<TickClass> {
        if !self.needs_frame {
            None
        } else if self.frame_unpaced {
            Some(TickClass::Transition)
        } else {
            Some(TickClass::CosmeticLoop)
        }
    }

    /// Whether a frame was requested and *every* request this (sub)paint was
    /// [`TickClass::CosmeticLoop`] — the paced-only state the mobile frame gate
    /// may throttle. Convenience for
    /// `frame_class() == Some(TickClass::CosmeticLoop)`.
    pub fn needs_frame_paced_only(&self) -> bool {
        self.needs_frame && !self.frame_unpaced
    }

    /// The tightest (MIN) interval any paced request named during this
    /// (sub)paint, or `None` if no paced request was made at all.
    ///
    /// [`Duration::ZERO`] — what a bare [`Self::request_frame_paced`] folds in —
    /// means "at the theme's own `cosmetic_loop_rate`", so `Some(Duration::ZERO)`
    /// and `None` resolve identically at the frame gate; the distinction is only
    /// whether *any* paced request was made. Meaningful only while
    /// [`Self::frame_class`] is [`TickClass::CosmeticLoop`] — a concurrent
    /// Transition request makes the whole frame unpaced, at which point no
    /// interval applies (see [`PaintOutcome::paced_interval`]).
    pub fn paced_interval(&self) -> Option<Duration> {
        self.paced_interval
    }

    /// Signal that this paint advanced animation state that changes the widget's
    /// *layout* (not just its paint), so layout must re-run next frame.
    ///
    /// This is the layout counterpart to [`Self::request_frame`]: a widget whose
    /// animation only repaints (a color fade, a caret blink) calls
    /// `request_frame` alone and stays layout-free under the mobile intra-frame
    /// layout skip, whereas a widget whose animation resizes/repositions its
    /// children (an expanding accordion) calls this so layout is re-run while the
    /// animation is in flight. The flag bubbles up through
    /// [`ChildPod::paint_child`] exactly like `needs_frame` and out of
    /// [`crate::app::RenderRoot::paint`] as [`PaintOutcome::needs_layout`], which
    /// folds into the render root's pending [`crate::view::ChangeFlags`]
    /// (`LAYOUT`) so the *next* frame relayouts.
    ///
    /// Calling this also implies [`Self::request_frame`] (a widget animating its
    /// layout necessarily wants another frame), so a caller needs only one call
    /// per animating-layout frame. That implied frame is
    /// [`TickClass::Transition`] (unpaced): a layout animation is user-visible
    /// motion, so it never leaves the frame paceable.
    pub fn request_layout(&mut self) {
        self.needs_layout = true;
        // A widget animating its layout necessarily wants another frame; setting
        // `needs_frame` too means one call suffices per animating-layout frame.
        // A layout animation is user-visible motion, so the implied frame is
        // Transition-class (unpaced) — mark the aggregate accordingly.
        self.request_frame_class(TickClass::Transition);
    }

    /// Whether a layout re-run was requested during this (sub)paint.
    pub fn needs_layout(&self) -> bool {
        self.needs_layout
    }

    /// Publish the focused editable's current IME surface during paint.
    ///
    /// The event pass ([`EventCtx::publish_ime_state`]) refreshes the shell's
    /// IME view on every edit, but an *app-driven* controlled change — a
    /// submit clearing the field, applied by the next rebuild rather than by
    /// an event — never crosses the event pass, so the event-published value
    /// goes stale. A focused editable therefore also republishes here, in the
    /// paint that runs after every rebuild, so [`crate::app::RenderRoot::ime_state`]
    /// tracks the field's current text/caret regardless of what drove the
    /// change. Bubbles up through [`ChildPod::paint_child`], mirroring
    /// [`Self::request_frame`].
    pub fn publish_ime_state(&mut self, state: ImeState) {
        self.ime_state = Some(state);
    }

    /// Take the IME surface published during this (sub)paint, if any.
    pub fn take_ime_state(&mut self) -> Option<ImeState> {
        self.ime_state.take()
    }

    /// Publish a platform-view child's paint-time frame (a
    /// `PlatformViewSlot`) for this paint pass.
    ///
    /// Pushes onto a `Vec` rather than setting an `Option` — deliberately NOT
    /// the same shape as [`PaintCtx::publish_ime_state`]. IME state has a
    /// single focused surface at most, so an overwrite is correct there; a
    /// platform view has no such "the" instance, so two slots publishing in
    /// one pass must both survive. [`ChildPod::paint_child`] bubbles this by
    /// `extend`, never overwrite, for exactly that reason.
    pub fn publish_platform_view(&mut self, frame: PlatformViewFrame) {
        self.platform_views.push(frame);
    }

    /// Take (and clear) every platform-view frame published during this
    /// (sub)paint, in paint order.
    pub fn take_platform_views(&mut self) -> Vec<PlatformViewFrame> {
        std::mem::take(&mut self.platform_views)
    }

    /// Report an absolute-coordinate region where frust content painted OVER a
    /// platform-view slot must keep winning pointer input (the "z-shield").
    ///
    /// The auto-collection half of the Mode B input contract: an interactive
    /// slot hands a touch-DOWN inside its rect to the
    /// native sibling, EXCEPT inside a shield. `frust-widgets`' `shield(child)`
    /// wrapper is the reporter — it paints its child unchanged and reports its
    /// own painted rect here — so an app marks chrome that overlaps a slot
    /// rather than hand-listing rects on the slot itself.
    ///
    /// Core stays dumb, exactly as it does for [`PlatformViewFrame`]: this is a
    /// flat, pass-scoped rect list with no slot association at all. The
    /// shell-side differ (`frust-shell-common::platform_view`) owns the
    /// intersection rule that decides which shields belong to which slot.
    /// Pushes (never overwrites) — see the `input_shields` field doc.
    pub fn report_input_shield(&mut self, rect: Rect) {
        self.input_shields.push(rect);
    }

    /// Take (and clear) every z-shield rect reported during this (sub)paint, in
    /// paint order. The [`PaintCtx::take_platform_views`] sibling for the shield
    /// channel (see [`PaintCtx::report_input_shield`]).
    pub fn take_input_shields(&mut self) -> Vec<Rect> {
        std::mem::take(&mut self.input_shields)
    }

    /// Float `entry`'s pod above the whole app for this frame, and register its
    /// rect for the next frame's input routing.
    ///
    /// # The owner must not paint the pod
    ///
    /// A registered pod is painted by [`crate::app::RenderRoot::paint`], **after**
    /// the main tree — that is the only way it escapes its owner's paint order
    /// and every ancestor's clip. An owner that also paints it itself draws the
    /// surface twice: once clipped in place, once floated.
    ///
    /// # Per pass, in registration order
    ///
    /// The registry is cleared when each paint pass begins, so a surface stays
    /// alive only while its owner keeps registering it — there is nothing to
    /// unregister, and an owner that stops (or is unmounted) simply disappears
    /// from the routing table after the next paint. Within a
    /// [band](crate::overlay::OverlayBand), later registration paints and
    /// hit-tests above earlier; the band itself outranks registration order.
    ///
    /// [`OverlayEntry::window_rect`](crate::overlay::OverlayEntry::window_rect)
    /// is absolute logical window space, so an owner computes it from
    /// [`PaintCtx::origin`] — the only absolute anchor a widget has. Recomputing
    /// it every paint is what makes an anchored surface follow its owner with no
    /// subscription of any kind.
    ///
    /// Registering outside a root-driven paint pass (a leaf unit test painting a
    /// bare [`PaintCtx`]) is harmless: the entry is dropped by the next real
    /// pass's clear rather than leaking into it.
    pub fn register_overlay(&mut self, entry: crate::overlay::OverlayEntry) {
        crate::overlay::register(entry);
    }

    /// Publish "this field is focused, these verbs apply, and here is where a
    /// menu would go" for this frame.
    ///
    /// Resolved by [`crate::app::RenderRoot::paint`] into
    /// [`RenderRoot::selection_toolbar`](crate::app::RenderRoot::selection_toolbar)
    /// plus a generation a shell diffs
    /// ([`selection_toolbar_generation`](crate::app::RenderRoot::selection_toolbar_generation)),
    /// for the platform edit-menu route.
    ///
    /// **Publish under either policy.** A field drawing its own toolbar through
    /// the overlay portal ([`crate::selection_toolbar::SelectionToolbarPolicy::Framework`])
    /// publishes this too: it costs one pointer-sized write, and it keeps a single
    /// code path rather than one per route.
    ///
    /// **A focused field publishes whether or not it has a selection, and whether
    /// or not any bar is up.** The verbs are a level a platform responder chain
    /// must be able to read at any moment — a hardware Cmd+C/X/V/A is asked for
    /// with no menu on screen — so gating the publish on a bar being open is what
    /// used to leave those shortcuts unanswerable. Whether a menu should be
    /// *presented* rides in the request's own flag instead.
    ///
    /// Pass-scoped and last-writer-wins, like every other paint-time request: a
    /// pass in which nothing publishes resolves to "no field is focused", which is
    /// what puts the toolbar away on a blur without any widget having to retract
    /// anything.
    pub fn publish_selection_toolbar(
        &mut self,
        request: crate::selection_toolbar::SelectionToolbarRequest,
    ) {
        crate::selection_toolbar::publish(request);
    }

    /// Report a tagged ("hero") element's absolute paint `bounds` and read back
    /// what it should do this frame.
    ///
    /// A no-op returning [`HeroDirective::Normal`] unless a container installed
    /// a reporter via [`PaintCtx::with_hero_registry`] over this subtree
    /// (the normal case — no shared-element transition in flight). When a
    /// reporter is installed, `bounds` is recorded (page-local, i.e. relative
    /// to the reporter's reference origin, so it stays stable under a page's
    /// per-frame animated transition offset), and the directive the installer
    /// set for `tag` is returned — [`HeroDirective::Suppress`] (skip painting,
    /// this endpoint is morphed by its counterpart) or
    /// [`HeroDirective::Morph`] (repaint under a rect→rect transform to the
    /// morph destination).
    pub fn report_hero(&mut self, tag: &str, bounds: Rect) -> HeroDirective {
        match self.hero {
            Some(cell) => {
                let mut frames = cell.borrow_mut();
                let local = Rect::from_origin_size(
                    bounds.origin() - frames.reference.to_vec2(),
                    bounds.size(),
                );
                frames.captured.insert(tag.to_string(), local);
                frames
                    .directives
                    .get(tag)
                    .copied()
                    .unwrap_or(HeroDirective::Normal)
            }
            None => HeroDirective::Normal,
        }
    }

    /// Whether a shared-element ("hero") transition is currently in flight over
    /// this subtree — i.e. an ancestor installed a hero reporter via
    /// [`PaintCtx::with_hero_registry`], the same condition that makes
    /// [`PaintCtx::report_hero`] record rather than no-op.
    ///
    /// The public, boolean sibling of the crate-private
    /// [`PaintCtx::hero_ref`], exposed so a container that culls far-offscreen
    /// children (a `Flex` under a `ScrollView`) can *stop* culling while a hero
    /// is morphing: a tagged descendant scrolled beyond the warm margin would
    /// otherwise never paint, and so never report its bounds
    /// ([`PaintCtx::report_hero`]) for the morph. `false` in the normal case
    /// (no transition), so culling is unaffected off the transition path.
    pub fn hero_active(&self) -> bool {
        self.hero.is_some()
    }

    /// Run `f` with a paint context that has `registry` installed as the
    /// tagged-rect ("hero") reporter, threading this context's clock/theme/
    /// focus/geometry down unchanged. A container paints a subtree inside the
    /// closure; descendants report through [`PaintCtx::report_hero`], and the
    /// container reads the captured rects back from `registry` afterward. Any
    /// continuation-frame request or IME publish made inside bubbles back onto
    /// `self`, mirroring [`ChildPod::paint_child`]'s absorb.
    pub fn with_hero_registry(
        &mut self,
        registry: &RefCell<HeroFrames>,
        f: impl FnOnce(&mut PaintCtx),
    ) {
        let mut child = PaintCtx {
            origin: self.origin,
            size: self.size,
            needs_frame: false,
            needs_layout: false,
            frame_unpaced: false,
            paced_interval: None,
            ime_state: None,
            has_focus: self.has_focus,
            hovered: self.hovered,
            hover_epoch: self.hover_epoch,
            focus_epoch: self.focus_epoch,
            frame_time: self.frame_time,
            theme: self.theme,
            window_insets: self.window_insets,
            presented_frames: self.presented_frames,
            hero: Some(registry),
            visible_rect: self.visible_rect,
            platform_views: Vec::new(),
            input_shields: Vec::new(),
            translucent: self.translucent,
        };
        f(&mut child);
        if child.needs_frame {
            self.needs_frame = true;
        }
        if child.needs_layout {
            self.needs_layout = true;
        }
        // Max-lattice OR: any Transition request inside dominates, keeping the
        // aggregate unpaced (mirrors `ChildPod::paint_child`'s absorb).
        if child.frame_unpaced {
            self.frame_unpaced = true;
        }
        // MIN-lattice fold of the paced interval, the orthogonal half of the
        // same absorb: a slower interval inside never loosens the outer
        // aggregate, and a tighter one tightens it. `absorb_paced_interval`
        // is the shared rule with `ChildPod::paint_child`'s own bubble below —
        // skip on `None` rather than folding in `Duration::ZERO`.
        self.absorb_paced_interval(child.paced_interval);
        if let Some(ime) = child.ime_state.take() {
            self.ime_state = Some(ime);
        }
        // EXTEND, never overwrite — mirrors `ChildPod::paint_child`'s absorb;
        // see `PaintCtx::publish_platform_view`'s doc comment for why this
        // channel is a `Vec` merge rather than the `ime_state` `Option` merge
        // above.
        self.platform_views.extend(child.platform_views);
        // The z-shield channel merges the same way, for the same reason (see
        // `PaintCtx::report_input_shield`).
        self.input_shields.extend(child.input_shields);
    }

    /// Seed the hero reporter lent by an ancestor. Called by
    /// [`ChildPod::paint_child`] for each child, mirroring how `theme` is
    /// threaded, so a nested hero wrapper observes the same reporter.
    pub(crate) fn set_hero(&mut self, hero: Option<&'a RefCell<HeroFrames>>) {
        self.hero = hero;
    }

    /// The hero reporter this context carries, for re-lending to a child
    /// context (copied, so it does not hold a borrow of `self`).
    pub(crate) fn hero_ref(&self) -> Option<&'a RefCell<HeroFrames>> {
        self.hero
    }

    /// The absolute-coordinate visible rectangle a scroll ancestor has threaded
    /// down, or `None` when no viewport constraint is in effect (paint
    /// everything). A container that culls offscreen children (`Flex` under a
    /// `ScrollView`) tests each child's absolute bounds against this; a widget
    /// with no interest in culling ignores it entirely. See
    /// [`PaintCtx::constrain_visible_rect`] for how a scroll surface sets it.
    pub fn visible_rect(&self) -> Option<Rect> {
        self.visible_rect
    }

    /// Constrain the threaded visible rectangle to `rect` (in absolute paint
    /// coordinates), the seam a [`ScrollView`](crate::app) uses to publish its
    /// viewport to descendants.
    ///
    /// When no rect is threaded yet this installs `rect`; when one already is
    /// (a nested scroll surface), the two are **intersected** — the visible
    /// region can only ever narrow, never widen, as scroll surfaces nest, so an
    /// inner viewport never re-reveals content an outer one clipped away. The
    /// value flows to children unchanged via [`ChildPod::paint_child`], mirroring
    /// how `window_insets`/`theme` are threaded.
    pub fn constrain_visible_rect(&mut self, rect: Rect) {
        self.visible_rect = Some(match self.visible_rect {
            Some(existing) => existing.intersect(rect),
            None => rect,
        });
    }

    /// Seed the visible rectangle lent by an ancestor. Called by
    /// [`ChildPod::paint_child`] for each child, mirroring how `theme` is
    /// threaded (copied down unchanged), so a descendant container observes the
    /// same viewport constraint the scroll ancestor established.
    pub(crate) fn set_visible_rect(&mut self, rect: Option<Rect>) {
        self.visible_rect = rect;
    }

    /// The visible rectangle this context carries, for re-lending to a child
    /// context (copied, so it holds no borrow of `self`).
    pub(crate) fn visible_rect_ref(&self) -> Option<Rect> {
        self.visible_rect
    }

    /// Whether the shell created a translucent (alpha-channel, "Mode B") GPU
    /// surface for this frame — threaded from the render root and copied down to
    /// every descendant like the theme/insets.
    ///
    /// `false` in the normal opaque ("Mode A") case, bare-core tests, and every
    /// desktop app. The platform-view hole-punch reads it: a slot only clears
    /// its rect ([`PaintScene::clear_rect`]) when this is `true`, so punching
    /// never erases app content on an opaque surface (see `frust-widgets`'
    /// `PlatformViewWidget::paint`).
    pub fn is_translucent(&self) -> bool {
        self.translucent
    }

    /// Seed the shell's surface-translucency flag. Called by
    /// [`crate::app::RenderRoot::paint`] at the root and by
    /// [`ChildPod::paint_child`] for each child, mirroring how `theme` is
    /// threaded (copied down unchanged).
    pub(crate) fn set_translucent(&mut self, translucent: bool) {
        self.translucent = translucent;
    }
}

/// A tagged-rect reporter threaded through the paint pass, letting a container
/// discover where tagged ("hero") descendants painted and drive a
/// shared-element morph between two of them across a navigation transition.
///
/// Generic vocabulary — `frust-core` carries no navigation knowledge here,
/// the same way its [`semantics`](crate::semantics) node collector carries no
/// widget-catalog knowledge. A container installs one over a subtree with
/// [`PaintCtx::with_hero_registry`]; descendants report through
/// [`PaintCtx::report_hero`].
#[derive(Debug, Default)]
pub struct HeroFrames {
    /// The absolute top-left of the enclosing surface this paint, subtracted
    /// from each reported rect so captures are stored surface-local (stable
    /// across a page's per-frame animated transition offset).
    reference: Point,
    /// Surface-local rects reported by tagged descendants this paint.
    captured: HashMap<String, Rect>,
    /// Per-tag paint directive the installer set for this paint.
    directives: HashMap<String, HeroDirective>,
}

impl HeroFrames {
    /// A reporter with `reference` as the enclosing surface's absolute top-left
    /// and per-tag paint `directives` (empty for a pure discovery pass).
    pub fn new(reference: Point, directives: HashMap<String, HeroDirective>) -> Self {
        Self {
            reference,
            captured: HashMap::new(),
            directives,
        }
    }

    /// The surface-local rects captured this paint, keyed by tag.
    pub fn captured(&self) -> &HashMap<String, Rect> {
        &self.captured
    }

    /// Consume the reporter, returning the captured surface-local rects.
    pub fn into_captured(self) -> HashMap<String, Rect> {
        self.captured
    }
}

/// What a reported hero should do this paint — the reply
/// [`PaintCtx::report_hero`] hands back to a tagged ("hero") wrapper.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HeroDirective {
    /// Paint normally (no active flight involves this tag) — the default.
    Normal,
    /// Skip painting the child: this endpoint is being morphed by the other
    /// surface's matching hero, so it must not also paint at its rest position.
    Suppress,
    /// Paint the child under a transform mapping the hero's own absolute paint
    /// bounds onto `dest` (absolute) — the morph overlay for this frame.
    Morph {
        /// The absolute destination rect the hero's bounds morph onto.
        dest: Rect,
    },
}

/// A process-wide monotonic counter backing [`next_slot_id`].
static NEXT_SLOT_ID: AtomicU64 = AtomicU64::new(1);

/// Allocate a fresh, stable platform-view slot id.
///
/// Called once per widget instance at construction (a
/// `PlatformViewSlot`) — the same stability class as [`ChildPod`]'s
/// semantics base id: identity that must survive a tree reorder, so it is
/// never derived from tree position. A flat process-wide counter rather than
/// a per-[`crate::app::RenderRoot`] allocator, since a widget has no
/// `RenderRoot` handle to draw one from at construction time.
pub fn next_slot_id() -> u64 {
    NEXT_SLOT_ID.fetch_add(1, Ordering::Relaxed)
}

/// Upper bound on the undrained retire list (see [`report_retired_slot`]).
///
/// Only reachable when nothing drains — a desktop app (no native compositor,
/// so no drain) that churns platform-view slots, or a mobile shell whose frame
/// loop has stopped. Past the cap the OLDEST id is dropped: the shell-side
/// differ's missing-streak backstop still disposes that slot, so a dropped id
/// costs a slower teardown, never a leak. Sized far above any realistic
/// per-frame teardown burst.
const MAX_PENDING_RETIRED_SLOTS: usize = 256;

/// The process-wide pending-retire list backing [`report_retired_slot`] /
/// [`take_retired_slots`].
///
/// A `Mutex<Vec<_>>` rather than a `RenderRoot` field for the same reason
/// [`NEXT_SLOT_ID`] is a process-wide counter: a widget being torn down has no
/// `RenderRoot` handle to reach — and unlike `build`/`rebuild`, the id-space is
/// already process-global, so a global drain is coherent. Same single-root
/// caveat as `next_slot_id`, revisited together with it if multi-root ever
/// lands. Panics are impossible while the lock is held (a `Vec` push/take), but
/// the poison-tolerant `unwrap_or_else(into_inner)` idiom is used anyway,
/// matching `frust-shell-common`'s process-global slots.
static RETIRED_SLOTS: Mutex<Vec<u64>> = Mutex::new(Vec::new());

/// Record that the widget owning `slot_id` was torn down (its `View::teardown`
/// ran), so the shell can dispose the native view promptly instead of waiting
/// out the differ's missing-streak heuristic.
///
/// The teardown half of the platform-view frame channel: `paint` says "this
/// slot exists here", this says "this slot is gone for good". Kept a flat
/// process-wide list (not a per-pass channel) because teardown does NOT run in
/// the paint pass — it runs mid-rebuild, arbitrarily deep inside a
/// `Component`'s own nested build context, so there is no threaded per-frame
/// sink every teardown can reach.
///
/// Drained by [`crate::app::RenderRoot::take_retired_platform_views`]; a shell
/// with no native compositor simply never drains, which is why the list is
/// capped (see [`MAX_PENDING_RETIRED_SLOTS`]).
pub fn report_retired_slot(slot_id: u64) {
    let mut pending = RETIRED_SLOTS.lock().unwrap_or_else(|e| e.into_inner());
    if pending.len() >= MAX_PENDING_RETIRED_SLOTS {
        // Drop-oldest: the differ's missing-streak backstop still catches the
        // dropped id (see the constant's doc).
        pending.remove(0);
    }
    pending.push(slot_id);
}

/// Take (and clear) every slot id reported to [`report_retired_slot`] since the
/// last call, in teardown order. Drained once per frame by a shell through
/// [`crate::app::RenderRoot::take_retired_platform_views`].
pub fn take_retired_slots() -> Vec<u64> {
    let mut pending = RETIRED_SLOTS.lock().unwrap_or_else(|e| e.into_inner());
    std::mem::take(&mut *pending)
}

/// A platform-view child's paint-time frame — everything a shell's native
/// compositor needs to place, size, clip, and dispose a native
/// sibling view for one paint pass.
///
/// All rects are logical px, **absolute window coordinates** — the same
/// space [`PaintCtx::report_hero`] callers use, built from the painting
/// pod's [`PaintCtx::origin`]/[`PaintCtx::size`]. Frames are
/// paint-pass-scoped: [`crate::app::RenderRoot::paint`] replaces the whole
/// collection every pass, so a slot that didn't paint this pass (a culled
/// subtree) simply has no frame in
/// [`crate::app::RenderRoot::platform_view_frames`] — the shell's differ owns
/// absent-means-hide/dispose semantics, not this crate.
#[derive(Clone, Debug, PartialEq)]
pub struct PlatformViewFrame {
    /// Stable per-widget-instance id, allocated once via [`next_slot_id`] at
    /// construction — never derived from tree position, so a reorder keeps
    /// identity.
    pub slot_id: u64,
    /// `"dev.frust.<Factory>"` convention naming which native view factory
    /// creates this slot's platform view.
    pub view_type: String,
    /// Opaque creation params for the native factory (may be empty).
    pub params_json: String,
    /// Bumped by the widget whenever `params_json` changes; this
    /// crate only ever carries the number through.
    pub params_generation: u64,
    /// Absolute paint bounds.
    pub rect: Rect,
    /// `visible_rect` (see [`PaintCtx::visible_rect`]) intersected with
    /// `rect`, or `None` when fully visible — no scroll ancestor is clipping
    /// it.
    pub clip: Option<Rect>,
    /// `false` ⇒ hidden (offscreen/culled by the widget itself, distinct from
    /// simply being absent from the collection this pass).
    pub visible: bool,
    /// Mode B input forwarding: whether
    /// the hosted native view should receive pointer input — a touch-DOWN
    /// inside `rect` (and outside every `shields` rect) hands the whole
    /// gesture to the native sibling in the embedding. `false` (the default)
    /// keeps the v1 no-input contract: the frust surface consumes everything.
    pub interactive: bool,
    /// The z-shield list: absolute-coordinate regions where frust content
    /// drawn OVER this slot must keep winning input. Only consulted when
    /// `interactive`. Same coordinate space as `rect`.
    ///
    /// Carries only the slot's own **manually declared** shields
    /// (`PlatformViewView::shield_local`, the escape hatch). The ordinary
    /// source is auto-collection: a `shield(child)` wrapper reports its painted
    /// rect through [`PaintCtx::report_input_shield`], and the shell-side differ
    /// merges whichever of those intersect this `rect` into the command it
    /// emits — so the shipped wire shape is the union of both, assembled one
    /// layer up.
    pub shields: Vec<Rect>,
}

/// The result of a whole [`crate::app::RenderRoot::paint`] pass.
///
/// `needs_frame` is whether any widget advanced animation state during paint and
/// asked (via [`PaintCtx::request_frame`]) to be re-invoked to continue. The
/// shell turns it into another scheduled frame — the desktop shell via
/// `window.request_redraw()`, the mobile shells implicitly through their
/// continuous loop. Mirrors [`crate::event::EventOutcome`]'s `needs_redraw`.
///
/// `needs_layout` is whether any widget asked (via [`PaintCtx::request_layout`])
/// to have layout re-run next frame because its animation changed its layout, not
/// just its paint. [`crate::app::RenderRoot::paint`] folds it into the render
/// root's pending [`crate::view::ChangeFlags`] (`LAYOUT`) so the next frame's
/// `take_change_flags().needs_layout()` reports it — driving the mobile
/// intra-frame layout skip to relayout while the animation is in flight.
///
/// `needs_frame_paced_only` is the aggregated [`TickClass`] verdict: `true` only
/// when a frame was requested and *every* request this frame was
/// [`TickClass::CosmeticLoop`] (a pacable decorative loop), `false` the instant
/// any [`TickClass::Transition`] request (including any `request_layout`) joined
/// in. The mobile frame gate may throttle such a purely-cosmetic frame
/// to a lower cadence; a `false` here means the frame runs every vsync as today.
/// Only meaningful when `needs_frame` is `true`.
///
/// `paced_interval` is *how fast* that paced frame asked to be re-run: the MIN
/// over every paced request this pass (see [`PaintCtx::request_frame_paced_at`]).
/// Only meaningful alongside `needs_frame_paced_only`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PaintOutcome {
    /// Whether the shell should schedule another frame to continue an animation.
    pub needs_frame: bool,
    /// Whether the render root folded a layout-continuation request into its
    /// pending change flags (a widget called [`PaintCtx::request_layout`]).
    pub needs_layout: bool,
    /// Whether a frame was requested and every request this frame was
    /// [`TickClass::CosmeticLoop`] — the paced-only state the mobile frame gate
    /// may throttle (see [`PaintCtx::needs_frame_paced_only`]). Meaningful only
    /// when `needs_frame` is set.
    pub needs_frame_paced_only: bool,
    /// The tightest (MIN) interval any paced request this frame named — see
    /// [`PaintCtx::paced_interval`]. `None` (no paced request) and
    /// `Some(Duration::ZERO)` (a bare [`PaintCtx::request_frame_paced`]) both
    /// mean "the theme's own `cosmetic_loop_rate`"; a longer value asks the gate
    /// to pace this loop slower than that cap. Meaningful only alongside
    /// `needs_frame_paced_only`; a shell latches it beside that flag and hands it
    /// to the frame gate, which resolves it against the live theme's cap.
    pub paced_interval: Option<Duration>,
}

/// A retained UI element living in the widget tree.
///
/// `Widget: Any` so the render root can downcast a boxed widget back to the
/// concrete element type its originating view produced (needed during rebuild).
/// Implementing types get [`Widget::downcast_mut`] for free — no boilerplate
/// method to write.
pub trait Widget: Any {
    /// Choose a size within `bc` and return it. The chosen size must satisfy
    /// `bc` (callers may additionally clamp via [`BoxConstraints::constrain`]).
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size;

    /// Emit draw commands for this widget into `scene`.
    ///
    /// Paint **may** advance a widget's own animation state (e.g. a scroll
    /// fling integrated from a monotonic clock) as a v1 seam. A widget that does
    /// so must call [`PaintCtx::request_frame`] while the animation is still
    /// running so the shell re-invokes paint absent any external event —
    /// otherwise the desktop `ControlFlow::Wait` loop idles and the animation
    /// stalls. It must stop signalling once the animation reaches rest.
    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene);

    /// Handle an input event, optionally mutating application state through
    /// `ctx` and reporting whether it was consumed.
    ///
    /// Defaulted to [`EventResult::Ignored`] so non-interactive widgets are
    /// unaffected. Interactive widgets
    /// (Button/Checkbox/Slider) override this; containers forward to
    /// their [`ChildPod`] children via [`ChildPod::event_child`].
    fn event(&mut self, _ctx: &mut EventCtx, _event: &InputEvent) -> EventResult {
        EventResult::Ignored
    }

    /// Contribute this widget's accessibility node(s) into `ctx`.
    ///
    /// Defaulted to a no-op so non-semantic widgets (and every widget written
    /// before this seam) are unaffected — exactly like [`Widget::event`]. A leaf
    /// widget overrides it to call [`SemanticsCtx::push_node`] with its role and
    /// state; a container overrides it to forward to each child via
    /// [`ChildPod::semantics_child`] (a transparent container contributes no node
    /// of its own, only recursion). The pass runs *after* layout, so
    /// [`SemanticsCtx::origin`]/[`SemanticsCtx::size`] carry valid absolute
    /// geometry.
    fn semantics(&self, _ctx: &mut SemanticsCtx) {}

    /// This widget's concrete type name, for read-only tooling.
    ///
    /// Defaulted to [`core::any::type_name`] of the implementing type, so every
    /// widget reports its own name through the vtable — including one reached
    /// as a `dyn Widget`, where the concrete type is otherwise unrecoverable.
    /// Asking the live widget beats recording a name when it was built: a
    /// rebuild that swaps a child's concrete type cannot leave a stale name
    /// behind, not even through the doubly-erased pods no reconciler can
    /// observe (`docs/LIMITATIONS.md`'s `focus-double-erasure-swap-blind`).
    ///
    /// Diagnostic only: `type_name`'s output is not a stable contract across
    /// compiler versions, so never parse or match on it. Overriding it is
    /// sanctioned only for a transparent wrapper reporting what it wraps (the
    /// `Box<dyn Widget>` blanket impl is the one in-crate case).
    fn type_name(&self) -> &'static str {
        core::any::type_name::<Self>()
    }

    /// Visit this widget's owned [`ChildPod`]s, in declaration (paint) order —
    /// the read-only seam that makes the retained hierarchy enumerable.
    ///
    /// Containers own their children as `ChildPod` fields rather than as arena
    /// nodes (see [`ChildPod`]), so nothing outside a container could walk into
    /// its subtree; this is that walk, and
    /// [`WidgetTree::inspect`](crate::tree::WidgetTree::inspect) is its one
    /// in-crate consumer.
    ///
    /// **Defaulted to visiting nothing**, exactly like [`Widget::event`] and
    /// [`Widget::semantics`]: a leaf widget needs no impl and pays nothing, and
    /// a container that never overrides it simply reads as a leaf to tooling. It
    /// runs behind `&self` and must not mutate anything a pass depends on — no
    /// build/layout/paint/event behavior may be routed through it.
    ///
    /// **No cycles by construction.** A `ChildPod` owns its widget (`Box<dyn
    /// Widget>`); ownership is a tree, so a descent through `visit_children`
    /// terminates without any runtime cycle check. A widget that handed the
    /// visitor a pod it does not own would break that, which is why the visitor
    /// takes `&ChildPod` — there is no way to publish a shared one.
    fn visit_children(&self, _visitor: &mut dyn FnMut(&ChildPod)) {}
}

impl dyn Widget {
    /// Attempt to downcast this trait object to a concrete widget type.
    ///
    /// Uses trait upcasting (`Widget: Any`, stable since Rust 1.86; the
    /// workspace MSRV is 1.88) — no `unsafe`.
    pub fn downcast_mut<W: Widget>(&mut self) -> Option<&mut W> {
        let any: &mut dyn Any = self;
        any.downcast_mut::<W>()
    }
}

/// A boxed widget is itself a [`Widget`], delegating every pass to its contents.
///
/// This blanket impl is what makes type-erased children work: a
/// [`crate::view::AnyView`]'s element is a `Box<dyn Widget>`, and
/// `View::Element` must implement `Widget` — so the box has to be a widget too.
/// It also lets a `Box<dyn Widget>` be stored inside a [`ChildPod`] like any
/// concrete widget. `Box<dyn Widget>` is `'static` (hence `Any`), so it satisfies
/// the `Widget: Any` bound and can be recovered by
/// [`downcast_mut`](dyn Widget::downcast_mut) during rebuild.
impl Widget for Box<dyn Widget> {
    fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        (**self).layout(ctx, bc)
    }

    fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        (**self).paint(ctx, scene);
    }

    fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
        (**self).event(ctx, event)
    }

    fn semantics(&self, ctx: &mut SemanticsCtx) {
        (**self).semantics(ctx);
    }

    fn visit_children(&self, visitor: &mut dyn FnMut(&ChildPod)) {
        (**self).visit_children(visitor);
    }

    /// Report the *boxed* widget's name, not `Box<dyn Widget>` — the box is a
    /// storage detail of type erasure, never a tree element in its own right,
    /// and it nests (a doubly-boxed pod resolves through both layers).
    fn type_name(&self) -> &'static str {
        (**self).type_name()
    }
}

/// A container's owned child: a boxed widget plus the layout geometry and
/// capture bookkeeping the container maintains for it.
///
/// Containers own their children directly as `ChildPod`s (a `Vec` for
/// Flex/Stack, named fields for Padding/Align) rather than as arena nodes — the
/// [`WidgetTree`](crate::tree::WidgetTree) arena stays single-root. This is a
/// deliberate divergence from the masonry "everything in the arena" model:
/// it needs zero global-id plumbing and no
/// disjoint-borrow gymnastics for the container features this crate ships. Arena-backed children
/// (for damage tracking / a11y global access) are deferred to a later phase.
///
/// `origin`/`size` are in the **container's** local coordinate space;
/// [`ChildPod::event_child`] translates events into the child's local space and
/// [`ChildPod::paint_child`] offsets the child's paint origin accordingly.
///
/// Because the arena cannot see into a container, the pod also carries what
/// read-only tooling needs to describe the element it wraps —
/// [`type_name`](ChildPod::type_name), [`debug_label`](ChildPod::debug_label),
/// [`inspect_id`](ChildPod::inspect_id), plus the geometry above — and
/// [`Widget::visit_children`] is how a walk reaches it.
pub struct ChildPod {
    widget: Box<dyn Widget>,
    origin: Point,
    size: Size,
    /// An optional transform placing the child under an arbitrary
    /// [`Affine`] relative to its `origin` — `None` (the default) for every pod
    /// that never calls [`ChildPod::set_transform`], which then takes exactly the
    /// untransformed paint/event/hit-test/semantics path. See
    /// [`ChildPod::set_transform`] for the mapping contract.
    transform: Option<Affine>,
    /// Set when the child captured the pointer, so the container can route
    /// subsequent moves/releases straight to it (capture-by-recorded-path).
    /// Cleared by the container on `Up`/`Cancel` via [`ChildPod::set_active`].
    active: bool,
    /// Whether the child widget itself called
    /// [`EventCtx::capture_contacts`] on the capture that set `active` — the
    /// pod a non-claimant contact's forward-only walk ends at (see
    /// [`ChildPod::event_child`]). Meaningful only while `active`; reset when a
    /// fresh capture is recorded and whenever the link is cleared.
    contacts_captor: bool,
    /// Whether the child or a widget below it called
    /// [`EventCtx::capture_contacts`] on the capture that set `active` — what
    /// [`EventCtx::release_captured_child`] asks to decide whether releasing
    /// this pod ends the gesture's contact opt-in. Same lifetime as
    /// `contacts_captor`.
    contacts_path: bool,
    /// Set when the child holds the focus path, so the container can route
    /// keyboard/IME events straight to it with no hit test (focus is the
    /// second recorded path, a mirror of `active`). Maintained by
    /// [`ChildPod::event_child`] on a `focus_requested`/`focus_released` bubble.
    ///
    /// **A set flag on its own says nothing about the live session.** It records
    /// that a claim once passed through this pod, and the only routes that clear
    /// it are a container's own blur sweep and a reconciler severing the link —
    /// neither of which can reach a pod held off-tree (a floated overlay
    /// surface). `focus_epoch` below is what makes the record falsifiable; read
    /// [`ChildPod::holds_live_focus`], not this flag, to decide anything.
    focused: bool,
    /// The focus epoch this pod's recorded link belongs to — stamped by
    /// [`ChildPod::set_focused`]`(true)` from the session standing on this
    /// thread ([`set_live_focus_session`]) and never cleared.
    ///
    /// The focus analog of `hover_epoch` below, and for the same reason: a
    /// session that moves has no way to visit the branch it left. The root
    /// advances its epoch around every dispatch that could record a new chain,
    /// so a claim recorded in that dispatch carries the new value and every link
    /// recorded by an older claim is stranded by arithmetic — including one
    /// belonging to a pod no container owns. `0` until a claim first passes
    /// through.
    focus_epoch: u64,
    /// The identity of the [`RenderRoot`](crate::app::RenderRoot) whose session
    /// `focus_epoch` names, recorded with it and never cleared either. `0` until
    /// a claim first passes through.
    ///
    /// Exactly `hover_root`'s job below: epoch counters are per-root and collide
    /// by construction, so the identity is what keeps one root's pod from
    /// reading as a holder of another root's identically-numbered session — and
    /// what keeps a dying pod from ending a session it was never part of.
    focus_root: u64,
    /// The hover epoch this pod's recorded hover link belongs to — stamped by
    /// [`ChildPod::event_child`] when a [`EventCtx::claim_hover`] bubbles through
    /// it, and never explicitly cleared. `0` until a claim first passes through —
    /// a [`RenderRoot`](crate::app::RenderRoot)'s live epoch starts past `0`, so a
    /// never-claimed pod reads unhovered.
    ///
    /// The hover analog of `active`/`focused`, but a stamp rather than a flag,
    /// because hover has no leave event to clear it with: the pointer moving
    /// elsewhere advances the live epoch, which strands every stale stamp at once
    /// without the container that owns it having to hear about the move. See the
    /// [`crate::event`] module docs.
    ///
    /// The one move the epoch cannot strand is the pod's own removal, which is
    /// why this field is also what `Drop` reports on (see the `Drop` impl and
    /// `mark_hover_orphaned`).
    hover_epoch: u64,
    /// The identity of the [`RenderRoot`](crate::app::RenderRoot) whose pass
    /// stamped `hover_epoch`, recorded with it and never cleared either. `0` until
    /// a claim first passes through.
    ///
    /// Epoch counters are per-root and all start at `1`, so two roots on one
    /// thread produce colliding integers by construction. Only `Drop` reads this:
    /// it is what tells this pod's own root's live link from another root's
    /// identically-numbered epoch, so a dying pod can never end a hover it was
    /// never part of. The event/paint comparisons need no such qualifier — a pod
    /// is only ever visited by the root that owns its tree.
    hover_root: u64,
    /// This pod's persistent semantics base id, lazily assigned on
    /// the pod's first [`ChildPod::semantics_child`] visit from the
    /// [`RenderRoot`](crate::app::RenderRoot) allocator and reused for the whole
    /// pod lifetime — so the node id a widget contributes is stable across frames
    /// (and survives a keyed reorder, which relocates the whole pod). Interior
    /// mutability because `semantics_child` runs behind `&self` (mirroring
    /// `Widget::semantics`); `NonZeroU64` niche-packs the `Option` and encodes
    /// "id 0 is not a valid base". `None` until the first semantics pass reaches
    /// this pod.
    semantics_id: Cell<Option<NonZeroU64>>,
    /// An optional human name for tooling, `None` unless something calls
    /// [`ChildPod::set_debug_label`]. Mirrors
    /// [`WidgetPod::debug_label`](crate::tree::WidgetPod::debug_label).
    debug_label: Option<Cow<'static, str>>,
    /// This pod's persistent tooling id, lazily assigned on its first
    /// [`ChildPod::inspect_id`] call and reused for the whole pod lifetime —
    /// the same shape (and the same reason) as `semantics_id` above: an id a
    /// devtools client selected must survive the next frame's rebuild, and must
    /// survive a keyed reorder, which relocates the whole pod. `None` until a
    /// walk first reaches this pod, so a process that never inspects allocates
    /// nothing.
    inspect_id: Cell<Option<NonZeroU64>>,
}

thread_local! {
    /// The next tooling id [`ChildPod::inspect_id`] hands out.
    ///
    /// Thread-local and UI-thread-affine, mirroring `mark_focus_orphaned`'s
    /// shape: the widget tree is single-threaded, and an inspect walk runs
    /// behind `&self` with no allocator in scope to thread down.
    static NEXT_INSPECT_ID: Cell<u64> = const { Cell::new(ChildPod::INSPECT_ID_BASE) };

    /// The focus session standing on this thread right now, as `(root identity,
    /// live epoch, claim epoch)` — published by [`crate::app::RenderRoot`] and
    /// compared against by every [`ChildPod`] that records, reads or drops a
    /// focus link.
    ///
    /// The two epochs are the same value except during a dispatch, where the
    /// root opens a *candidate* session the claim recorded in that dispatch is
    /// stamped with (see [`focus_claim_stamp`]) while reads still answer against
    /// the session standing when the dispatch began. That is hover's
    /// `hover_epoch`/`hover_claim_epoch` split, in a channel rather than on the
    /// context — and the reason both are visible at once is that a claim
    /// recorded on the way back up must be observable to the container that is
    /// still unwinding: a blur sweep deciding which child *kept* focus, and a
    /// portal noticing that its surface just took the session, both ask after
    /// the claim they are reacting to.
    ///
    /// `(0, 0, 0)` until a root publishes, which is also what a dispatch driven
    /// without any root at all (a widget unit test) sees: a pod claiming focus
    /// there stamps `0` too, so its link reads live and routing behaves exactly
    /// as it did before this channel existed. A real root's identity starts at
    /// `1` and its epoch at `1`, so it can never publish that triple.
    static LIVE_FOCUS_SESSION: Cell<(u64, u64, u64)> = const { Cell::new((0, 0, 0)) };
}

/// Publish the focus session standing on this thread: `live` is the session a
/// recorded link must name to count, `claim` the one a link recorded *now* takes
/// (equal to `live` outside a dispatch).
///
/// # Why a thread-local, and not the running context
///
/// The hover epoch rides [`EventCtx`]/[`PaintCtx`] because every reader of it is
/// inside a pass the root itself seeded. A focus link has two readers that are
/// not: a container deciding where a focus-routed event goes runs its own
/// dispatch (a component boundary and an overlay slot both substitute a context
/// of their own on the way down, so a value threaded from the root does not
/// survive the trip), and a pod's destructor runs with no context at all. The
/// triple is therefore published where both can reach it, exactly as the hover
/// link's own `(root, epoch)` pair already is for the destructor's sake
/// (`crate::event::set_live_hover_link`).
///
/// It mirrors **one** root: a second [`crate::app::RenderRoot`] driving passes on
/// the same thread republishes before each of its own passes, which is why the
/// identity rides along — a pod of the other root can then never match by an
/// epoch integer the two happen to share.
pub(crate) fn set_live_focus_session(root: u64, live: u64, claim: u64) {
    LIVE_FOCUS_SESSION.with(|slot| slot.set((root, live, claim)));
}

/// The `(root identity, epoch)` a link recorded right now is stamped with — the
/// candidate session while a dispatch is open, the live one otherwise.
fn focus_claim_stamp() -> (u64, u64) {
    let (root, _live, claim) = LIVE_FOCUS_SESSION.with(|slot| slot.get());
    (root, claim)
}

/// Whether `(root, epoch)` names the session standing on this thread — either
/// the live one, or the candidate a dispatch currently open is recording claims
/// against.
fn names_live_focus_session(root: u64, epoch: u64) -> bool {
    let (live_root, live, claim) = LIVE_FOCUS_SESSION.with(|slot| slot.get());
    root == live_root && (epoch == live || epoch == claim)
}

impl Drop for ChildPod {
    /// Report a **live** hover link severed by the pod's own removal, so
    /// [`RenderRoot::rebuild`](crate::app::RenderRoot::rebuild) ends the hover
    /// before the frame ends.
    ///
    /// The epoch mechanism strands a stale stamp on every hover pass, but a pass
    /// is exactly what a removed widget no longer gets: a rebuild that drops the
    /// claimant leaves the root's mirror standing (`is_hover_active()` keeps
    /// reporting a link nothing holds) and leaves every surviving ancestor of the
    /// dead claimant reading hovered off its own still-matching stamp, until some
    /// later `Move` happens to re-derive — which never arrives on a pointer the
    /// user has stopped moving. This destructor is the hover analog of the
    /// focus-orphan mark, and lives here rather than in the reconcilers because
    /// the stamp has no setter for a container to cooperate through; see
    /// `crate::event::mark_hover_orphaned` for the full rationale and the
    /// "only when the link was live" invariant this comparison enforces.
    ///
    /// The comparison is against the published `(root, epoch)` pair, not the epoch
    /// alone: per-root counters collide, so an unqualified match would let a pod
    /// of one root end another root's live hover (see `hover_root`).
    ///
    /// Costs one predictable branch on a `u64` field per pod dropped; the
    /// thread-local read happens only for the pod chain that has actually held a
    /// claim at some point.
    fn drop(&mut self) {
        if crate::event::live_hover_link_is(self.hover_root, self.hover_epoch) {
            crate::event::mark_hover_orphaned(self.hover_root);
        }
        // The focus half of the same report. The reconcilers raise this mark for
        // every pod they sever themselves (`teardown_child` and friends), which
        // covers the whole main tree; a pod floated by the overlay portal is
        // reached by none of them — its owner holds it behind an `Rc` and can
        // drop it with no view to tear it down through — so the pod reports its
        // own severance here, with nothing for an owner to remember to call.
        //
        // Gated on the stamp exactly as the hover half is, and additionally on a
        // non-zero epoch: a pod that never held a link carries `(0, 0)`, which is
        // precisely what a dispatch driven without a root publishes, and a
        // rootless test dropping pods owes no release.
        if self.focused
            && self.focus_epoch != 0
            && names_live_focus_session(self.focus_root, self.focus_epoch)
        {
            crate::event::mark_focus_orphaned();
        }
    }
}

impl ChildPod {
    /// Where [`ChildPod::inspect_id`]'s allocator starts.
    ///
    /// Pod ids and arena [`WidgetId`](crate::view::WidgetId)s share one
    /// namespace in an inspect snapshot, and the arena's are allocated from zero
    /// upward by `BuildCtx::alloc_id`. Starting the pod allocator at 2^48 keeps
    /// the two apart for any tree an app could plausibly build (the arena would
    /// have to allocate 281 trillion ids to reach it) without threading a shared
    /// counter through a read-only walk.
    pub const INSPECT_ID_BASE: u64 = 1 << 48;

    /// Wrap a freshly built child widget at the origin, with zero size until its
    /// first layout.
    pub fn new(widget: Box<dyn Widget>) -> Self {
        Self {
            widget,
            origin: Point::ZERO,
            size: Size::ZERO,
            transform: None,
            active: false,
            contacts_captor: false,
            contacts_path: false,
            focused: false,
            focus_epoch: 0,
            focus_root: 0,
            hover_epoch: 0,
            hover_root: 0,
            semantics_id: Cell::new(None),
            debug_label: None,
            inspect_id: Cell::new(None),
        }
    }

    /// The wrapped widget's concrete type name, asked of the live widget
    /// ([`Widget::type_name`]) rather than recorded at build time — so a
    /// rebuild that swapped the child's type can never leave a stale name here,
    /// and the double box `build_child` stores resolves through both layers.
    ///
    /// Diagnostic only: `type_name`'s output is not a stable contract across
    /// compiler versions, so never parse or match on it.
    pub fn type_name(&self) -> &'static str {
        self.widget.type_name()
    }

    /// The human name attached for tooling, if any. `None` by default.
    pub fn debug_label(&self) -> Option<&str> {
        self.debug_label.as_deref()
    }

    /// Attach a human name for tooling (an inspector shows it beside the type
    /// name). Purely descriptive — nothing in the build/layout/paint/event path
    /// reads it.
    pub fn set_debug_label(&mut self, label: impl Into<Cow<'static, str>>) {
        self.debug_label = Some(label.into());
    }

    /// Drop any attached debug label.
    pub fn clear_debug_label(&mut self) {
        self.debug_label = None;
    }

    /// The attached label as an owned [`Cow`] for a snapshot, cloning the
    /// borrowed case for free — what [`crate::tree::WidgetTree::inspect`] needs
    /// and [`ChildPod::debug_label`]'s `&str` cannot give.
    pub(crate) fn debug_label_cow(&self) -> Option<Cow<'static, str>> {
        self.debug_label.clone()
    }

    /// This pod's tooling id, assigning one on the first call and reusing it
    /// thereafter — so the id a devtools client holds keeps naming the same pod
    /// across frames, and across a keyed reorder that relocates the pod.
    ///
    /// Behind `&self` (interior mutability) because the whole introspection
    /// seam is read-only; ids come from [`INSPECT_ID_BASE`](ChildPod::INSPECT_ID_BASE)
    /// upward and never collide with an arena `WidgetId`.
    pub fn inspect_id(&self) -> crate::view::WidgetId {
        let id = match self.inspect_id.get() {
            Some(id) => id,
            None => {
                let id = NEXT_INSPECT_ID.with(|next| {
                    let id = next.get();
                    next.set(id + 1);
                    NonZeroU64::new(id).expect("the allocator starts at 2^48, never zero")
                });
                self.inspect_id.set(Some(id));
                id
            }
        };
        crate::view::WidgetId(id.get())
    }

    /// Shared access to the boxed child widget.
    pub fn widget(&self) -> &dyn Widget {
        &*self.widget
    }

    /// Mutable access to the boxed child widget (e.g. to downcast during a
    /// container's own rebuild).
    pub fn widget_mut(&mut self) -> &mut dyn Widget {
        &mut *self.widget
    }

    /// Replace the boxed child widget (used when a type-changing rebuild swaps
    /// the underlying widget).
    pub fn set_widget(&mut self, widget: Box<dyn Widget>) {
        self.widget = widget;
    }

    /// The child's origin in the container's coordinate space.
    pub fn origin(&self) -> Point {
        self.origin
    }

    /// The child's resolved size (valid after [`ChildPod::layout_child`]).
    pub fn size(&self) -> Size {
        self.size
    }

    /// Place the child at `origin` within the container's coordinate space.
    pub fn set_origin(&mut self, origin: Point) {
        self.origin = origin;
    }

    /// The child's transform, if any (see [`ChildPod::set_transform`]).
    pub fn transform(&self) -> Option<Affine> {
        self.transform
    }

    /// Place the child under an arbitrary `transform`, or clear it with `None`.
    ///
    /// The transform is applied in the child's own local space, **before** the
    /// `origin` offset: a child-local point `p` lands at
    /// `origin + transform * p` in the container's space. So
    /// `Affine::scale_about(2.0, center)` zooms the child about its own local
    /// `center`, and a pan/zoom container can leave `origin` at zero and drive
    /// the whole placement through the transform.
    ///
    /// While one is set:
    ///
    /// * [`ChildPod::paint_child`] wraps the child's paint in
    ///   [`PaintScene::push_transform`]/[`PaintScene::pop_transform`], and maps
    ///   an ancestor's visible rect back into the child's frame (the bounding box
    ///   of its inverse image), so a culling descendant still culls against what
    ///   is really on screen;
    /// * [`ChildPod::contains`] maps the point through the inverse before the
    ///   bounds test, so it hits exactly what paint drew — a rotated child hits
    ///   along its rotated edges, not its axis-aligned bounding box (the same
    ///   test as [`crate::hit::point_in_transformed_rect`]);
    /// * [`ChildPod::event_child`] maps pointer, scroll and scale positions
    ///   through the inverse ([`InputEvent::transformed`]), so the child sees
    ///   local coordinates exactly as an untransformed child does;
    /// * [`ChildPod::semantics_child`] reports the subtree at the
    ///   **axis-aligned bounding box** of the transformed child rect. This is an
    ///   approximation (v1): the pod's frame becomes that box, and descendants
    ///   are offset from its corner unscaled and unrotated.
    ///
    /// A transform with no inverse (a zero scale, a collapsed axis, a non-finite
    /// coefficient — see [`crate::hit::checked_inverse`]) draws nothing and hits
    /// nothing: `contains` is `false` and paint skips the subtree. An event that
    /// still reaches the child through a recorded capture or focus path is
    /// delivered translated by `-origin` only, so a capture can always release.
    ///
    /// Out of v1's reach: rects a descendant reports in window space from
    /// `paint` (platform-view frames, input shields, hero rects, overlay anchors)
    /// are not mapped through the transform.
    pub fn set_transform(&mut self, transform: Option<Affine>) {
        self.transform = transform;
    }

    /// The child's local→container mapping for a set `transform`:
    /// `translate(origin) * transform`.
    fn local_to_container(&self, transform: Affine) -> Affine {
        Affine::translate(self.origin.to_vec2()) * transform
    }

    /// Whether this child currently holds the recorded active (captured) path.
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Set (or clear) the recorded active path — the container clears this on
    /// `Up`/`Cancel` when capture auto-releases.
    ///
    /// **The link is keyed on the gesture's claimant.** While the root is
    /// delivering a *non-claimant* contact down a live capture's path (rule (c)
    /// of [`InputEvent::PointerContact`](crate::event::InputEvent::PointerContact)'s
    /// multi-contact contract), a clear is refused: that contact's `Up`/`Cancel`
    /// reaches every container on the path, and a container clearing its link on
    /// it would strand the claimant's own follow-ups. Outside such a pass — every
    /// single-pointer dispatch, a rebuild, a container's own teardown — a clear
    /// takes effect as always.
    ///
    /// A container that clears the link to take the gesture over from its
    /// child (rather than because the gesture ended) should release it through
    /// [`EventCtx::release_captured_child`] instead, which also ends the
    /// gesture's contact opt-in when the released subtree held it.
    pub fn set_active(&mut self, active: bool) {
        if !active && crate::event::in_secondary_contact_pass() {
            return;
        }
        self.active = active;
        if !active {
            self.contacts_captor = false;
            self.contacts_path = false;
        }
    }

    /// Whether this pod's recorded active path leads to the widget that opted
    /// into the gesture's other contacts ([`EventCtx::capture_contacts`]) —
    /// the child itself, or a widget below it.
    pub(crate) fn holds_contact_opt_in(&self) -> bool {
        self.active && self.contacts_path
    }

    /// Whether this child has a recorded focus path at all — **not** whether
    /// that record belongs to the session the root currently holds.
    ///
    /// The raw flag, kept for the things that legitimately want it: a paint-time
    /// culling exemption, a blur sweep clearing whatever it finds, a container
    /// asking "did I ever record a link here". Deciding *where a focus-routed
    /// event goes*, or whether a widget may speak for the focus session, needs
    /// [`ChildPod::holds_live_focus`] instead — a link this flag reports can be
    /// one a moved session left behind, and there is no pass that visits an
    /// abandoned branch to clear it.
    pub fn is_focused(&self) -> bool {
        self.focused
    }

    /// Record (or drop) this child's focus path **against the live session**.
    ///
    /// Setting it stamps the session standing on this thread
    /// (`set_live_focus_session`) beside the flag, so the link says which session
    /// it belongs to rather than merely that one existed; clearing it leaves the
    /// stamp alone, which costs nothing because the flag gates every read.
    /// Containers clear it on blur-on-outside-tap and set it when a child
    /// requests focus; the flag is maintained automatically by
    /// [`ChildPod::event_child`] on a `focus_requested`/`focus_released` bubble.
    pub fn set_focused(&mut self, focused: bool) {
        self.focused = focused;
        if focused {
            let (root, epoch) = focus_claim_stamp();
            self.focus_root = root;
            self.focus_epoch = epoch;
        }
    }

    /// The focus epoch this pod's recorded link was stamped with — the focus
    /// counterpart of [`ChildPod::hover_epoch`], and just as much an identity
    /// rather than an ordering or a boolean.
    ///
    /// Diagnostic only, for the same reason the hover stamp's accessor is: a
    /// stamp is never cleared, only stranded by the next session, so a non-zero
    /// value means "a claim passed through here once", never "focused". Ask
    /// [`ChildPod::holds_live_focus`], which is the comparison this exists for.
    pub fn focus_epoch(&self) -> u64 {
        self.focus_epoch
    }

    /// Whether this child holds a focus link **on the session the root currently
    /// has** — the read every routing and provenance decision wants.
    ///
    /// `true` only while the flag is set *and* the stamp names the live session
    /// (`set_live_focus_session`). Two branches can both carry a set flag — an
    /// overlay pod's claim reaches no container's blur sweep, so the branch it
    /// superseded keeps its own record — and this is what tells them apart
    /// without either branch having to be visited.
    ///
    /// A dispatch driven with no root at all reads `(0, 0)` on both sides, so a
    /// pod that claimed focus during such a dispatch answers `true`: with no
    /// session to be stale relative to, the flag is all there is.
    pub fn holds_live_focus(&self) -> bool {
        self.focused && names_live_focus_session(self.focus_root, self.focus_epoch)
    }

    /// Drop a recorded focus link that the live session has already stranded,
    /// reporting whether one was dropped.
    ///
    /// The retirement seam a [`RenderRoot`](crate::app::RenderRoot) needs and
    /// cannot otherwise have. A pod floated by the overlay portal lives off the
    /// tree, behind its owner's `Rc`, and the root borrows it for exactly the
    /// length of the paint pass that floats it — so the one moment the root can
    /// act on such a link is that pass, and the one thing it can honestly say
    /// about it is what the stamp already decides. Calling this keeps the raw
    /// flag and the stamp telling the same story, which is what the consumers of
    /// [`ChildPod::is_focused`] that cannot consult an epoch depend on.
    ///
    /// Deliberately *not* a bare `set_focused(false)` at the call site: the
    /// condition is the whole contract, and a pod whose link is live must never
    /// be retired by a pass that merely walked past it.
    pub fn retire_stale_focus_link(&mut self) -> bool {
        if self.focused && !self.holds_live_focus() {
            self.focused = false;
            true
        } else {
            false
        }
    }

    /// The hover epoch this pod's recorded hover link belongs to — the hover
    /// counterpart of [`ChildPod::is_focused`], reported as a stamp rather than a
    /// flag because "is it hovered?" is only answerable against the live epoch
    /// (`0` means no claim has ever passed through this pod).
    ///
    /// There is no setter: the stamp is maintained solely by
    /// [`ChildPod::event_child`] from a claim bubble, so a container cannot record
    /// or clear a hover link by hand — which is what keeps at most one path
    /// hovered. See the [`crate::event`] module docs.
    ///
    /// # A bare stamp answers nothing
    ///
    /// The returned `u64` is an identity, not an ordering and not a boolean. It
    /// means something only compared **for equality against the live epoch**, and
    /// that comparison is the pipeline's own: the live epoch rides the running
    /// context (`PaintCtx::hover_epoch`/`EventCtx::hover_epoch`), both
    /// crate-private, and the comparison is already ANDed with the ancestor chain
    /// by `paint_child`/`event_child` before any widget sees it. Treating a
    /// non-zero stamp as "hovered", or ordering two pods' stamps, reads reasonable
    /// and is wrong: a stamp is never cleared, only stranded by the next epoch
    /// advance, so a pod the pointer left an hour ago still carries a non-zero
    /// one, and the counter wraps.
    ///
    /// **Read [`PaintCtx::is_hovered`] instead** (authoritative), or
    /// [`EventCtx::is_hovered`] for the state as of the previous pass; between
    /// them they answer "is this widget or its subtree hovered" — which is the
    /// question a widget actually has. A container asking the narrower "*which* of
    /// my children" answers it with the same hit test its own claim rides, not
    /// from here. This accessor is diagnostic — tooling, tests, and the debug
    /// dump — the way [`ChildPod::type_name`] is.
    pub fn hover_epoch(&self) -> u64 {
        self.hover_epoch
    }

    /// Lay the child out under `bc`, recording and returning its chosen size.
    pub fn layout_child(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
        let size = self.widget.layout(ctx, bc);
        self.size = size;
        size
    }

    /// Paint the child, offsetting its paint origin by the container's origin
    /// (`ctx.origin()`) so the child draws at its absolute position.
    ///
    /// Bubbles the child's animation-continuation request ([`PaintCtx::needs_frame`])
    /// back into the parent `ctx`, mirroring [`ChildPod::event_child`]'s absorb of
    /// the child's redraw/capture flags — so a nested flinging widget keeps the
    /// whole tree's frames coming.
    ///
    /// A pod with a [`transform`](ChildPod::set_transform) additionally wraps
    /// that paint in [`PaintScene::push_transform`]/[`PaintScene::pop_transform`]
    /// (and skips it entirely when the transform has no inverse); an
    /// untransformed pod pushes nothing.
    pub fn paint_child(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
        // Fast path first: an untransformed pod is the pre-transform code path,
        // threading the ancestor's visible rect down unchanged.
        let Some(transform) = self.transform else {
            let visible_rect = ctx.visible_rect_ref();
            self.paint_child_in(ctx, scene, visible_rect);
            return;
        };
        // A singular transform collapses the child to a line or a point: there is
        // nothing to draw, and no inverse to map the visible rect through.
        if crate::hit::checked_inverse(&transform).is_none() {
            return;
        }
        // The scene speaks absolute coordinates, and the child paints at its
        // absolute origin, so conjugate the child-local transform by that
        // origin: a local point `p` drawn at `abs + p` lands at
        // `abs + transform * p`.
        let abs = (ctx.origin() + self.origin.to_vec2()).to_vec2();
        let around = Affine::translate(abs) * transform * Affine::translate(-abs);
        // Culling descendants compare their own (untransformed) absolute rects
        // against the visible rect, so hand them its preimage: the bounding box
        // of the visible rect mapped back through the inverse — conservative,
        // never culling anything actually on screen.
        let visible_rect = match (ctx.visible_rect_ref(), crate::hit::checked_inverse(&around)) {
            (Some(rect), Some(inverse)) => Some(inverse.transform_rect_bbox(rect)),
            _ => None,
        };
        scene.push_transform(around);
        self.paint_child_in(ctx, scene, visible_rect);
        scene.pop_transform();
    }

    /// [`ChildPod::paint_child`]'s body: paint the child at its absolute origin
    /// with `visible_rect` as the child's culling rect.
    fn paint_child_in(
        &mut self,
        ctx: &mut PaintCtx,
        scene: &mut dyn PaintScene,
        visible_rect: Option<Rect>,
    ) {
        let child_origin = ctx.origin() + self.origin.to_vec2();
        let mut child_ctx = PaintCtx::new(child_origin, self.size);
        // Thread the shared shell clock down unchanged so every widget in the
        // frame advances animations against one consistent timestamp.
        child_ctx.set_frame_time(ctx.frame_time());
        // Thread the app's active theme down unchanged (copied ref, so the child
        // context holds no borrow of the parent), mirroring the clock.
        child_ctx.set_theme(ctx.theme_ref());
        // Thread the window insets down unchanged (copied — global and
        // origin-independent), mirroring the theme.
        child_ctx.set_window_insets(ctx.window_insets_ref());
        // Thread the shell's presented-frame count down unchanged (copied
        // `Option<u64>`), mirroring the clock/insets — global, origin-independent.
        child_ctx.set_presented_frames(ctx.presented_frames());
        // Thread the tagged-rect ("hero") reporter down the same way, so a hero
        // wrapper nested arbitrarily deep under an installer sees it. `None` in
        // the normal case (no shared-element transition in flight).
        child_ctx.set_hero(ctx.hero_ref());
        // Thread the scroll ancestor's visible rect down unchanged (absolute
        // coords, so a nested container tests its children directly against it),
        // mirroring the theme/insets. `None` in the normal case (no scroll
        // ancestor culling), so paint descends into every child as before. A
        // transformed pod passes the rect's preimage instead (see `paint_child`).
        child_ctx.set_visible_rect(visible_rect);
        // Thread the shell's surface-translucency flag down unchanged (copied
        // bool, global and origin-independent), mirroring the theme/insets — the
        // platform-view hole-punch reads it (see `PaintCtx::is_translucent`).
        child_ctx.set_translucent(ctx.is_translucent());
        // Thread the live focus epoch down unchanged (global, like the clock),
        // and seed this child's focus from its own recorded link against it —
        // the mirror of how `event_child` seeds the child `EventCtx`, so a
        // focus-dependent widget observes a blur that never reached its
        // `event()`. Three conjuncts, each load-bearing:
        //
        // * `self.focused` — a link was recorded here at all;
        // * the stamp — that link belongs to the session the root has *now*, not
        //   to one it has since left. Paint descends into every branch
        //   unconditionally and a branch the session left is reached by no pass
        //   that could clear its flag, so without this a field the user has
        //   walked away from goes on painting a caret and republishing the
        //   surface it described while it still had the session;
        // * `ctx.has_focus()` — the ancestor chain, since a blur clears the link
        //   at the nearest common ancestor only and flags deeper in the blurred
        //   subtree legitimately go stale.
        //
        // Exactly the composition the hover seed below uses, for exactly the
        // same reason.
        child_ctx.set_focus_epoch(ctx.focus_epoch());
        child_ctx.set_has_focus(
            self.focused && self.focus_epoch == ctx.focus_epoch() && ctx.has_focus(),
        );
        // Thread the live hover epoch down unchanged (global, like the clock), and
        // seed this child's hover link from its own recorded stamp against it —
        // ANDed with the ancestor's hover, exactly like `focused` above. Both halves
        // are load-bearing: the stamp is what distinguishes the current claim path
        // from a stale one no container ever cleared, and the chain is what keeps a
        // context carrying no live epoch at all (a bare `PaintCtx::new`, whose `0`
        // would match a never-claimed pod's `0`) from reading as hovered.
        child_ctx.set_hover_epoch(ctx.hover_epoch());
        child_ctx.set_hovered(self.hover_epoch == ctx.hover_epoch() && ctx.is_hovered());
        self.widget.paint(&mut child_ctx, scene);
        // Bubble the child's continuation-frame request AND its tick class up
        // unchanged: forwarding the aggregate class (rather than always calling
        // `request_frame`, which is Transition) is what lets a purely-cosmetic
        // subtree stay paceable through nested containers. `frame_class()` is
        // `None` when the child asked for nothing, so a still child bubbles
        // nothing (the max-lattice identity).
        match child_ctx.frame_class() {
            Some(TickClass::Transition) => ctx.request_frame_class(TickClass::Transition),
            // Deliberately NOT `request_frame_class(CosmeticLoop)`: that folds
            // `Duration::ZERO` (the theme cap) into the parent's MIN-lattice and
            // would silently re-tighten a child that asked for a *slower*
            // cadence. Forward the child's own aggregate interval instead — the
            // MIN-lattice's bubbling identity — via `absorb_paced_interval`,
            // the same rule `with_hero_registry` uses.
            Some(TickClass::CosmeticLoop) => {
                // Bubble `needs_frame` unconditionally: a CosmeticLoop
                // `frame_class` means the child genuinely requested a frame,
                // independent of whether an interval merges below (mirrors
                // `with_hero_registry`'s unconditional `needs_frame` bubble,
                // which is likewise separate from its interval fold).
                ctx.needs_frame = true;
                // Invariant: `frame_class() == Some(CosmeticLoop)` requires
                // `needs_frame && !frame_unpaced`, and the only paths that can
                // produce that pair — `request_frame_paced_at` directly, or a
                // nested `paint_child`/`with_hero_registry` bubble grounded in
                // the same call by this identical induction — always merge a
                // paced interval in the same step. So `paced_interval()` is
                // never actually `None` here through the public
                // `request_frame_paced*` API; this documents that belief
                // rather than silently trusting it. `absorb_paced_interval`
                // (below) is what actually implements the fallback, so
                // behavior stays correct even if a future caller manages to
                // trip this.
                debug_assert!(
                    child_ctx.paced_interval().is_some(),
                    "CosmeticLoop frame_class with no merged paced_interval — \
                     a new caller must be bypassing request_frame_paced_at"
                );
                ctx.absorb_paced_interval(child_ctx.paced_interval());
            }
            None => {}
        }
        // Bubble the child's layout-continuation request the same way as
        // `needs_frame`, so a nested widget animating its layout keeps layout
        // re-running up the whole tree. (`request_layout` also re-forces the
        // Transition class via `request_frame_class` above's contract.)
        if child_ctx.needs_layout() {
            ctx.request_layout();
        }
        // Bubble a focused editable's republished IME surface up the paint path,
        // so `RenderRoot::paint` can refresh the shell-facing state after a
        // rebuild-driven controlled change (see `PaintCtx::publish_ime_state`).
        if let Some(ime) = child_ctx.take_ime_state() {
            ctx.publish_ime_state(ime);
        }
        // Bubble any platform-view frames published this paint by EXTENDING
        // the parent's Vec — deliberately NOT the `ime_state` overwrite shape
        // above. Two sibling slots publishing in the same pass must both
        // survive; an Option-based merge here would silently drop every slot
        // but the last child painted (see `PaintCtx::publish_platform_view`).
        ctx.platform_views.extend(child_ctx.take_platform_views());
        // Bubble any z-shield rects reported this paint the same way, and for
        // the same reason — two sibling shields must both survive (see
        // `PaintCtx::report_input_shield`).
        ctx.input_shields.extend(child_ctx.take_input_shields());
    }

    /// Collect the child's semantics, translating the current absolute origin
    /// into the child's space exactly like [`ChildPod::paint_child`] offsets its
    /// paint origin (`child_origin = ctx.origin() + self.origin`).
    ///
    /// A container's [`Widget::semantics`] calls this for each of its
    /// [`ChildPod`]s so their nodes attach under the container's node (or, for a
    /// transparent container, under whatever encloses it — see
    /// [`crate::semantics`]).
    ///
    /// A pod with a [`transform`](ChildPod::set_transform) reports its subtree at
    /// the axis-aligned bounding box of the transformed child rect — an
    /// approximation: descendants are offset from that box's corner, unscaled
    /// and unrotated.
    pub fn semantics_child(&self, ctx: &mut SemanticsCtx) {
        let base = self.semantics_base(ctx);
        let (offset, size) = match self.transform {
            None => (self.origin.to_vec2(), self.size),
            Some(transform) => {
                let bounds = self
                    .local_to_container(transform)
                    .transform_rect_bbox(self.size.to_rect());
                if bounds.is_finite() {
                    (bounds.origin().to_vec2(), bounds.size())
                } else {
                    // A non-finite transform has no meaningful box: report an
                    // empty frame at the origin rather than NaN bounds.
                    (self.origin.to_vec2(), Size::ZERO)
                }
            }
        };
        ctx.descend_into_pod(base, offset, size, |ctx| {
            self.widget.semantics(ctx);
        });
    }

    /// This pod's stable semantics base id, assigning one from the allocator on
    /// the first visit and reusing the cached value thereafter —
    /// the mechanism that keeps a widget's node id stable across frames and keyed
    /// reorders. See [`ChildPod::semantics_id`].
    fn semantics_base(&self, ctx: &mut SemanticsCtx) -> NonZeroU64 {
        match self.semantics_id.get() {
            Some(id) => id,
            None => {
                let id = ctx.alloc_base();
                self.semantics_id.set(Some(id));
                id
            }
        }
    }

    /// Route an event into the child, translating its position into the child's
    /// local space and folding the child's redraw/capture flags back into `ctx`.
    ///
    /// If the child captured the pointer, this records the active path
    /// ([`ChildPod::is_active`]); the container clears it on `Up`/`Cancel`.
    ///
    /// Containers should not call this directly gated on an ad-hoc
    /// `contains()` check — that drops a captured gesture the instant it moves
    /// outside the child's bounds. Route through `frust-widgets`'
    /// `route_event`/`route_event_single` helpers instead, which check
    /// [`ChildPod::is_active`] first and forward unconditionally to a captured
    /// child.
    ///
    /// A pod with a [`transform`](ChildPod::set_transform) maps positions
    /// through the inverse of its local→container mapping instead
    /// ([`InputEvent::transformed`]); everything else about the dispatch —
    /// capture, contact and focus bookkeeping, hover — is identical.
    ///
    /// # Another contact walks the active path forward-only
    ///
    /// A non-claimant contact the root delivers down a live capture (rule (c) of
    /// [`InputEvent::PointerContact`]'s contract) is meant for the widget that
    /// opted in with [`EventCtx::capture_contacts`] — **the captor** — and for
    /// nothing above it. The containers between the root and the captor must
    /// not run their own pointer handling on it: a scroll view that saw a second
    /// finger's `Down` as its own would re-arm its drag from the wrong finger and
    /// take the gesture away from the captor on the claimant's next move.
    ///
    /// A pod cannot reach into its child widget's own pods, so the walk travels
    /// on the one route every container already provides without running its
    /// pointer machinery: the broadcast-first rule. While the root walks such a
    /// contact, each container on the path is handed an inert carrier (an
    /// [`InputEvent::Overlay`] addressed to a key no overlay owner holds, which
    /// every widget ignores and every container forwards to its children before
    /// anything else), and the real event rides beside it, re-based into each
    /// pod's space on the way down. This method then decides, per pod:
    ///
    /// * **Off the recorded active path:** nothing — the child widget is not
    ///   called at all.
    /// * **The captor** (the child itself opted in on the capture that made
    ///   this pod active): the child receives the real event, translated as
    ///   usual, with the walk closed, so it — and whatever it routes below
    ///   itself — handles the contact the ordinary way. The walk ends here: a
    ///   widget below the captor that also opted in hears the contact only if
    ///   the captor forwards it.
    /// * **On the path, above the captor:** the child receives the carrier, so
    ///   its own handler runs but none of its gesture, capture, focus, blur or
    ///   hit-test logic does; the walk continues into its children. The result
    ///   reported upward is the captor's, not the carrier's `Ignored`. If the
    ///   carrier never reaches a pod on the path (a container whose captured
    ///   child is not one of its broadcast targets — an overlay owner whose
    ///   captured pod is a floated surface), this child alone is handed the
    ///   real event the ordinary way instead.
    ///
    /// Everything this method folds back into `ctx` — redraw, capture, focus,
    /// IME — still bubbles from the captor through every pod on the way back
    /// up. No hover, cursor or blur bookkeeping moves: the root opens no hover
    /// pass for a non-claimant contact, and no container above the captor runs
    /// the blur sweep it would run on a `Down`. Every other dispatch, including
    /// the claimant's own events, takes exactly the path described above this
    /// section.
    pub fn event_child(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
        if let Some(real) = crate::event::secondary_walk_event(event) {
            return self.walk_secondary(ctx, &real);
        }
        let local = self.localize(event);
        self.dispatch_local(ctx, &local)
    }

    /// `event` (in the container's space) mapped into the child's local space —
    /// translated by `-origin`, or through the inverse of a set transform.
    fn localize(&self, event: &InputEvent) -> InputEvent {
        match self.transform {
            None => event.translated(-self.origin.to_vec2()),
            Some(transform) => {
                match crate::hit::checked_inverse(&self.local_to_container(transform)) {
                    Some(inverse) => event.transformed(&inverse),
                    // No inverse: `contains` never hits such a pod, so only a
                    // recorded capture/focus path reaches here. Deliver the event
                    // translated as if untransformed so that path can still end.
                    None => event.translated(-self.origin.to_vec2()),
                }
            }
        }
    }

    /// One step of a non-claimant contact's forward-only walk (see
    /// [`ChildPod::event_child`]); `real` is the contact's event in the
    /// container's space.
    fn walk_secondary(&mut self, ctx: &mut EventCtx, real: &InputEvent) -> EventResult {
        if !self.active {
            return EventResult::Ignored;
        }
        let local = self.localize(real);
        let result = if self.contacts_captor {
            crate::event::without_secondary_walk(|| self.dispatch_local(ctx, &local))
        } else {
            let carrier = crate::event::secondary_walk_carrier();
            let (_, delivered) = crate::event::run_secondary_walk(local.clone(), || {
                self.dispatch_local(ctx, &carrier)
            });
            match delivered {
                Some(result) => result,
                None => crate::event::without_secondary_walk(|| self.dispatch_local(ctx, &local)),
            }
        };
        crate::event::note_secondary_delivered(result);
        result
    }

    /// Dispatch `local` (already in the child's space) to the child widget and
    /// fold everything it bubbled back into `ctx`.
    fn dispatch_local(&mut self, ctx: &mut EventCtx, local: &InputEvent) -> EventResult {
        // The child's hover link, composed with the ancestor chain exactly like
        // `focused` (see `paint_child`).
        let hovered = self.hover_epoch == ctx.hover_epoch() && ctx.is_hovered();
        // Two narrowings on top of whatever the root allowed, both structural:
        // a pod holding the capture path can never let a claim through (a drag
        // must not paint hover under the pointer, whatever the root's own capture
        // mirror says), and a pass that already recorded a claim is closed to
        // further ones, so the first claim recorded wins. With topmost-first hit
        // testing and containers claiming only *after* they route (see
        // `EventCtx::claim_hover`'s contract), that first claim is the topmost
        // claimant's; a container that claims before it forwards is recorded first
        // instead and closes the pass to its own subtree.
        let hover_eligible = ctx.is_hover_eligible() && !ctx.is_hover_claimed() && !self.active;
        let claim_epoch = ctx.hover_claim_epoch();
        // The child context inherits `ctx.pointer_id()` unchanged (see
        // `EventCtx::child_ctx`), so every widget on the routed path reports the
        // same contact.
        let (
            (opted_in, opted_in_at_or_below),
            captured,
            contacts,
            released,
            hover_claimed,
            focus_req,
            focus_rel,
            redraw,
            ime,
            result,
        ) = {
            let mut child_ctx = ctx.child_ctx(
                self.origin,
                self.size,
                self.focused,
                hovered,
                hover_eligible,
            );
            // The frame attributes a `capture_contacts` call to this child (or
            // to a widget below it) across a component boundary, and marks the
            // dispatch as running under the live opt-in's holder.
            let frame = crate::event::ContactFrame::enter(self.active && self.contacts_captor);
            let result = self.widget.event(&mut child_ctx, local);
            let (opted_in, opted_in_at_or_below) = frame.close();
            (
                (opted_in, opted_in_at_or_below),
                child_ctx.is_pointer_captured(),
                child_ctx.is_contact_capture_requested(),
                child_ctx.is_capture_released(),
                child_ctx.is_hover_claimed(),
                child_ctx.is_focus_requested(),
                child_ctx.is_focus_released(),
                child_ctx.needs_redraw(),
                child_ctx.take_ime_state(),
                result,
            )
        };
        if captured {
            if !self.active {
                // A fresh capture: whatever opt-in the last gesture recorded
                // here is gone.
                self.contacts_captor = false;
                self.contacts_path = false;
            }
            self.active = true;
            self.contacts_captor |= opted_in;
            self.contacts_path |= opted_in_at_or_below;
        }
        // Stamp the claim onto this pod so the whole path from the claimant up to
        // the root carries the epoch the next paint compares against. Never
        // cleared: a stale stamp is stranded by the next epoch advance instead.
        // The running root's identity rides along, so this pod's destructor can
        // tell its own root's live link from another root's identical epoch
        // integer (see `hover_root`).
        if hover_claimed {
            self.hover_epoch = claim_epoch;
            self.hover_root = ctx.hover_root();
        }
        // Focus is the second recorded path, maintained exactly like `active`: a
        // `focus_requested` bubble records this child as the focused one; a
        // `focus_released` bubble drops it. A request wins over a release in the
        // rare case both fire in one dispatch (a re-focus supersedes a blur).
        //
        // The record goes through `set_focused`, which stamps the session the
        // claim belongs to beside the flag: the whole chain from the claimant up
        // to the root is on one bubble and therefore takes one stamp, which is
        // what lets a container later ask which of two flagged children is on the
        // live chain.
        if focus_rel {
            self.set_focused(false);
        }
        if focus_req {
            self.set_focused(true);
        }
        // The contact opt-in bubbles exactly like the capture it accompanies; the
        // `active` link above stays keyed on the claimant (see `set_active`).
        ctx.absorb_child(
            redraw,
            captured,
            contacts,
            released,
            hover_claimed,
            focus_req,
            focus_rel,
            ime,
        );
        result
    }

    /// Whether `point` (in the container's coordinate space) lies within this
    /// child's bounds — the container's hit test.
    ///
    /// This is only the *initial* hit test (deciding which child a fresh
    /// `Down`/first contact goes to). Once a child has captured the pointer
    /// ([`ChildPod::is_active`]), subsequent events must bypass this check and
    /// go straight to the captured child regardless of where the point now
    /// falls — see `frust-widgets`' `route_event`/`route_event_single`.
    ///
    /// A pod with a [`transform`](ChildPod::set_transform) maps `point` back
    /// through the transform first, so the test agrees with what paint drew; a
    /// transform with no inverse hits nothing.
    pub fn contains(&self, point: Point) -> bool {
        if let Some(transform) = self.transform {
            return crate::hit::point_in_transformed_rect(
                point,
                self.size.to_rect(),
                &self.local_to_container(transform),
            );
        }
        point.x >= self.origin.x
            && point.x < self.origin.x + self.size.width
            && point.y >= self.origin.y
            && point.y < self.origin.y + self.size.height
    }
}

#[cfg(test)]
mod focus_link_tests {
    use super::*;

    /// A guard restoring the focus channel this thread started with, so a test
    /// that publishes a session of its own cannot leak it into a neighbour.
    struct Session(u64, u64, u64);

    impl Session {
        fn enter(root: u64, live: u64, claim: u64) -> Self {
            let previous = LIVE_FOCUS_SESSION.with(|slot| slot.get());
            set_live_focus_session(root, live, claim);
            Session(previous.0, previous.1, previous.2)
        }
    }

    impl Drop for Session {
        fn drop(&mut self) {
            set_live_focus_session(self.0, self.1, self.2);
        }
    }

    /// A do-nothing leaf: these tests exercise the pod's own bookkeeping, so
    /// the widget inside it never runs.
    struct Inert;

    impl Widget for Inert {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(Size::new(10.0, 10.0))
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
    }

    fn pod() -> ChildPod {
        ChildPod::new(Box::new(Inert))
    }

    #[test]
    fn a_recorded_link_counts_only_while_its_stamp_names_the_live_session() {
        let _session = Session::enter(7, 3, 3);
        let mut pod = pod();
        pod.set_focused(true);
        assert!(pod.holds_live_focus(), "recorded against the live session");
        assert_eq!(pod.focus_epoch(), 3);

        // The session moves on. Nothing visits this pod; its flag is untouched.
        set_live_focus_session(7, 4, 4);
        assert!(
            pod.is_focused(),
            "the raw record survives, as it always did"
        );
        assert!(
            !pod.holds_live_focus(),
            "but it no longer names the session the root has"
        );
    }

    #[test]
    fn a_link_of_another_root_never_counts_however_the_epochs_line_up() {
        let _session = Session::enter(7, 3, 3);
        let mut pod = pod();
        pod.set_focused(true);

        // A second root on the same thread, with the identical epoch integer —
        // which two roots hold as a rule, not as a fluke.
        set_live_focus_session(8, 3, 3);
        assert!(!pod.holds_live_focus());
    }

    #[test]
    fn a_claim_recorded_during_a_dispatch_counts_before_the_dispatch_commits_it() {
        // The root opened a candidate session: reads still answer against the
        // live one, and a link recorded now takes the candidate.
        let _session = Session::enter(7, 3, 4);
        let mut claimed = pod();
        claimed.set_focused(true);
        assert_eq!(claimed.focus_epoch(), 4, "stamped with the candidate");
        assert!(
            claimed.holds_live_focus(),
            "and observable to the container still unwinding around the claim"
        );

        let mut standing = pod();
        standing.focused = true;
        standing.focus_root = 7;
        standing.focus_epoch = 3;
        assert!(
            standing.holds_live_focus(),
            "while a link recorded before this dispatch still reads live"
        );

        // The dispatch commits the claim: the older link is stranded.
        set_live_focus_session(7, 4, 4);
        assert!(claimed.holds_live_focus());
        assert!(!standing.holds_live_focus());
    }

    #[test]
    fn retiring_a_link_drops_only_one_the_live_session_has_already_stranded() {
        let _session = Session::enter(7, 3, 3);
        let mut pod = pod();
        pod.set_focused(true);
        assert!(
            !pod.retire_stale_focus_link(),
            "a live link is never retired by a pass that merely walked past it"
        );
        assert!(pod.is_focused());

        set_live_focus_session(7, 4, 4);
        assert!(pod.retire_stale_focus_link(), "a stranded link is dropped");
        assert!(
            !pod.is_focused(),
            "so the raw flag and the stamp tell one story"
        );
        assert!(
            !pod.retire_stale_focus_link(),
            "and retiring is idempotent — there is nothing left to drop"
        );
    }

    #[test]
    fn a_pod_that_never_held_a_link_reports_nothing_to_retire() {
        let _session = Session::enter(7, 3, 3);
        let mut pod = pod();
        assert!(!pod.holds_live_focus());
        assert!(!pod.retire_stale_focus_link());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::{PointerButton, PointerEvent, PointerPhase};

    /// A leaf widget that paints a filled box of a fixed intrinsic size.
    struct FixedBox {
        intrinsic: Size,
    }

    impl Widget for FixedBox {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(self.intrinsic)
        }

        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            scene.fill_rect(ctx.origin(), ctx.size(), Color::BLACK);
        }
    }

    /// A leaf widget that advances no state but signals it wants another frame
    /// on every paint — stands in for an animating widget (e.g. a fling).
    struct Animator;

    impl Widget for Animator {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }

        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            ctx.request_frame();
        }
    }

    /// A leaf widget whose animation changes its layout: it signals
    /// [`PaintCtx::request_layout`] on every paint — stands in for an animating
    /// widget that resizes/repositions (e.g. an expanding accordion).
    struct LayoutAnimator;

    impl Widget for LayoutAnimator {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }

        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            ctx.request_layout();
        }
    }

    /// A leaf widget whose animation is a *pacable* decorative loop: it signals
    /// [`PaintCtx::request_frame_paced`] on every paint — stands in for a
    /// shimmer/idle-pulse whose cadence the frame gate may throttle.
    struct PacedAnimator;

    impl Widget for PacedAnimator {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }

        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            ctx.request_frame_paced();
        }
    }

    /// The interval a [`SlowPacedAnimator`] asks for — a ~2Hz caret blink,
    /// deliberately far slower than any theme's cosmetic-loop cap.
    const SLOW_PACE: Duration = Duration::from_millis(500);

    /// A leaf widget whose decorative loop names its own (slow) cadence via
    /// [`PaintCtx::request_frame_paced_at`] — stands in for a blinking caret.
    struct SlowPacedAnimator;

    impl Widget for SlowPacedAnimator {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }

        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            ctx.request_frame_paced_at(SLOW_PACE);
        }
    }

    /// A scene recorder used to assert paint output without any GPU dependency.
    #[derive(Default)]
    struct RecordingScene {
        rects: Vec<(Point, Size)>,
        texts: Vec<(Point, String)>,
        shaders: Vec<(u64, Rect, f32)>,
        scene_textures: Vec<(u64, Rect)>,
    }

    impl PaintScene for RecordingScene {
        fn fill_rect(&mut self, origin: Point, size: Size, _color: Color) {
            self.rects.push((origin, size));
        }
        fn draw_text(&mut self, origin: Point, text: &str) {
            self.texts.push((origin, text.to_string()));
        }
        fn draw_shader(&mut self, program: &ShaderProgram, dest: Rect, time: f32) {
            self.shaders.push((program.id(), dest, time));
        }
        fn draw_scene_texture(&mut self, id: u64, dest: Rect) {
            self.scene_textures.push((id, dest));
        }
    }

    /// A leaf widget that records the local position of the last event it saw,
    /// mutates a `u32` app state, and optionally captures the pointer on `Down`.
    struct Probe {
        last_pos: Option<Point>,
        capture_on_down: bool,
    }

    impl Widget for Probe {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            self.last_pos = Some(event.position());
            *ctx.state_mut::<u32>() += 1;
            ctx.request_redraw();
            if self.capture_on_down
                && matches!(
                    event,
                    InputEvent::Pointer(PointerEvent {
                        phase: PointerPhase::Down,
                        ..
                    })
                )
            {
                ctx.capture_pointer();
            }
            EventResult::Handled
        }
    }

    fn down(x: f64, y: f64) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase: PointerPhase::Down,
            position: Point::new(x, y),
            button: PointerButton::Primary,
        })
    }

    /// A leaf that requests focus on `Down`, releases it on Escape, records
    /// whether it saw a `Key`/`Ime` event, and reports whether it had focus when
    /// the last event arrived.
    #[derive(Default)]
    struct FocusProbe {
        saw_key: bool,
        had_focus_on_key: bool,
    }

    impl Widget for FocusProbe {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, ctx: &mut EventCtx, event: &crate::event::InputEvent) -> EventResult {
            match event {
                InputEvent::Pointer(PointerEvent {
                    phase: PointerPhase::Down,
                    ..
                }) => {
                    ctx.request_focus();
                    EventResult::Handled
                }
                InputEvent::Key(_) | InputEvent::Ime(_) => {
                    self.saw_key = true;
                    self.had_focus_on_key = ctx.has_focus();
                    EventResult::Handled
                }
                _ => EventResult::Ignored,
            }
        }
    }

    fn key_enter() -> InputEvent {
        InputEvent::Key(crate::event::KeyEvent {
            key: crate::event::Key::Named(crate::event::NamedKey::Enter),
            modifiers: crate::event::Modifiers::default(),
            repeat: false,
        })
    }

    #[test]
    fn event_child_records_focus_on_request() {
        let mut pod = ChildPod::new(Box::new(FocusProbe::default()));
        pod.set_origin(Point::new(5.0, 5.0));
        assert!(!pod.is_focused());

        let mut count = 0u32;
        let mut ctx = EventCtx::new(&mut count, Point::ZERO, Size::new(50.0, 50.0));
        pod.event_child(&mut ctx, &down(6.0, 6.0));

        // The child requested focus → the pod records the focus path and it
        // bubbles up into the parent context.
        assert!(pod.is_focused());
        assert!(ctx.is_focus_requested());
    }

    #[test]
    fn event_child_threads_has_focus_into_child() {
        // A focused pod seeds `has_focus` on the child dispatch; a Key event
        // reaching a focused child sees `has_focus() == true`.
        let mut pod = ChildPod::new(Box::new(FocusProbe::default()));
        pod.set_focused(true);

        let mut count = 0u32;
        let mut ctx = EventCtx::new(&mut count, Point::ZERO, Size::new(10.0, 10.0));
        pod.event_child(&mut ctx, &key_enter());

        let probe = pod.widget_mut().downcast_mut::<FocusProbe>().unwrap();
        assert!(probe.saw_key);
        assert!(probe.had_focus_on_key);
    }

    #[test]
    fn widget_layout_respects_constraints() {
        let mut w = FixedBox {
            intrinsic: Size::new(1000.0, 1000.0),
        };
        let mut ctx = LayoutCtx::new();
        let bc = BoxConstraints::loose(Size::new(200.0, 100.0));
        assert_eq!(w.layout(&mut ctx, &bc), Size::new(200.0, 100.0));
    }

    #[test]
    fn with_window_insets_scopes_and_restores_on_both_contexts() {
        use crate::insets::EdgeInsets;
        let root = WindowInsets::new(EdgeInsets::new(1.0, 2.0, 3.0, 4.0), EdgeInsets::ZERO);
        let scoped = root.consuming(true, true, true, true);

        let mut lctx = LayoutCtx::new();
        lctx.set_window_insets(root);
        let inside = lctx.with_window_insets(scoped, |ctx| ctx.window_insets());
        assert_eq!(inside, scoped);
        assert_eq!(lctx.window_insets(), root, "layout override restored");

        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        pctx.set_window_insets(root);
        let inside = pctx.with_window_insets(scoped, |ctx| ctx.window_insets());
        assert_eq!(inside, scoped);
        assert_eq!(pctx.window_insets(), root, "paint override restored");
    }

    #[test]
    fn widget_paint_emits_into_scene() {
        let mut w = FixedBox {
            intrinsic: Size::new(50.0, 20.0),
        };
        let mut scene = RecordingScene::default();
        let mut ctx = PaintCtx::new(Point::new(5.0, 7.0), Size::new(50.0, 20.0));
        w.paint(&mut ctx, &mut scene);
        assert_eq!(
            scene.rects,
            vec![(Point::new(5.0, 7.0), Size::new(50.0, 20.0))]
        );
    }

    #[test]
    fn widget_paint_emits_shader_into_scene() {
        /// A leaf widget that paints a shader quad.
        struct ShaderWidget {
            program: ShaderProgram,
            dest: Rect,
            time: f32,
        }

        impl Widget for ShaderWidget {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.max()
            }

            fn paint(&mut self, _ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
                scene.draw_shader(&self.program, self.dest, self.time);
            }
        }

        let program = ShaderProgram::new("fn main() {}");
        let dest = Rect::new(10.0, 20.0, 100.0, 150.0);
        let time = 1.5;
        let mut w = ShaderWidget {
            program: program.clone(),
            dest,
            time,
        };
        let mut scene = RecordingScene::default();
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(200.0, 200.0));
        w.paint(&mut ctx, &mut scene);
        assert_eq!(scene.shaders.len(), 1);
        assert_eq!(scene.shaders[0].0, program.id());
        assert_eq!(scene.shaders[0].1, dest);
        assert_eq!(scene.shaders[0].2, time);
    }

    #[test]
    fn widget_paint_emits_scene_texture_into_scene() {
        /// A leaf widget that paints a scene texture.
        struct SceneTextureWidget {
            id: u64,
            dest: Rect,
        }

        impl Widget for SceneTextureWidget {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.max()
            }

            fn paint(&mut self, _ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
                scene.draw_scene_texture(self.id, self.dest);
            }
        }

        let id = 42u64;
        let dest = Rect::new(10.0, 20.0, 100.0, 150.0);
        let mut w = SceneTextureWidget { id, dest };
        let mut scene = RecordingScene::default();
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(200.0, 200.0));
        w.paint(&mut ctx, &mut scene);
        assert_eq!(scene.scene_textures.len(), 1);
        assert_eq!(scene.scene_textures[0].0, id);
        assert_eq!(scene.scene_textures[0].1, dest);
    }

    #[test]
    fn downcast_recovers_concrete_widget() {
        let mut boxed: Box<dyn Widget> = Box::new(FixedBox {
            intrinsic: Size::new(3.0, 4.0),
        });
        let concrete = boxed.downcast_mut::<FixedBox>().expect("downcast");
        assert_eq!(concrete.intrinsic, Size::new(3.0, 4.0));
    }

    #[test]
    fn boxed_widget_delegates_every_pass() {
        // The `Box<dyn Widget>: Widget` blanket impl must forward layout/paint/event.
        let mut boxed: Box<dyn Widget> = Box::new(Probe {
            last_pos: None,
            capture_on_down: false,
        });
        let mut ctx = LayoutCtx::new();
        assert_eq!(
            boxed.layout(&mut ctx, &BoxConstraints::tight(Size::new(4.0, 5.0))),
            Size::new(4.0, 5.0)
        );
        let mut count = 0u32;
        let mut ectx = EventCtx::new(&mut count, Point::ZERO, Size::new(4.0, 5.0));
        assert_eq!(
            boxed.event(&mut ectx, &down(1.0, 1.0)),
            EventResult::Handled
        );
        assert_eq!(count, 1);
    }

    #[test]
    fn child_pod_layout_and_paint_offset_by_origin() {
        let mut pod = ChildPod::new(Box::new(FixedBox {
            intrinsic: Size::new(30.0, 10.0),
        }));
        pod.set_origin(Point::new(12.0, 8.0));

        let mut lctx = LayoutCtx::new();
        let size = pod.layout_child(&mut lctx, &BoxConstraints::loose(Size::new(100.0, 100.0)));
        assert_eq!(size, Size::new(30.0, 10.0));
        assert_eq!(pod.size(), Size::new(30.0, 10.0));

        // Paint under a container placed at (100, 200): child draws at the sum.
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::new(100.0, 200.0), Size::new(300.0, 300.0));
        pod.paint_child(&mut pctx, &mut scene);
        assert_eq!(
            scene.rects,
            vec![(Point::new(112.0, 208.0), Size::new(30.0, 10.0))]
        );
    }

    #[test]
    fn child_pod_translates_event_into_child_space() {
        let mut pod = ChildPod::new(Box::new(Probe {
            last_pos: None,
            capture_on_down: false,
        }));
        pod.set_origin(Point::new(10.0, 20.0));

        let mut count = 0u32;
        let mut ctx = EventCtx::new(&mut count, Point::ZERO, Size::new(200.0, 200.0));
        // Event at container-space (25, 35) lands at child-local (15, 15).
        let result = pod.event_child(&mut ctx, &down(25.0, 35.0));
        assert_eq!(result, EventResult::Handled);
        assert_eq!(count, 1); // state mutated through the reborrowed context
        let probe = pod.widget_mut().downcast_mut::<Probe>().unwrap();
        assert_eq!(probe.last_pos, Some(Point::new(15.0, 15.0)));
    }

    #[test]
    fn child_pod_propagates_capture_flag() {
        let mut pod = ChildPod::new(Box::new(Probe {
            last_pos: None,
            capture_on_down: true,
        }));
        pod.set_origin(Point::new(5.0, 5.0));
        assert!(!pod.is_active());

        let mut count = 0u32;
        let mut ctx = EventCtx::new(&mut count, Point::ZERO, Size::new(50.0, 50.0));
        pod.event_child(&mut ctx, &down(6.0, 6.0));

        // The child captured → the pod records the active path and the flag
        // bubbles up to the parent context.
        assert!(pod.is_active());
        assert!(ctx.is_pointer_captured());
        assert!(ctx.needs_redraw());
    }

    #[test]
    fn child_pod_bubbles_needs_frame_from_child_paint() {
        // A non-animating child leaves the parent's frame flag clear.
        let mut still = ChildPod::new(Box::new(FixedBox {
            intrinsic: Size::new(10.0, 10.0),
        }));
        let mut lctx = LayoutCtx::new();
        still.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        still.paint_child(&mut pctx, &mut scene);
        assert!(!pctx.needs_frame());

        // An animating child bubbles its request into the parent context.
        let mut anim = ChildPod::new(Box::new(Animator));
        anim.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut pctx2 = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        assert!(!pctx2.needs_frame());
        anim.paint_child(&mut pctx2, &mut scene);
        assert!(pctx2.needs_frame());
    }

    /// A leaf widget that publishes a fixed [`PlatformViewFrame`] on every
    /// paint, unless `should_publish` is false — the `false` arm stands in for
    /// a slot that didn't paint this pass (culled subtree), exercising the
    /// "no publishers this pass" behavior at the `RenderRoot`
    /// level (see `app.rs`'s tests).
    struct PlatformViewProbe {
        slot_id: u64,
        should_publish: bool,
    }

    impl Widget for PlatformViewProbe {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }

        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            if self.should_publish {
                ctx.publish_platform_view(PlatformViewFrame {
                    slot_id: self.slot_id,
                    view_type: "dev.frust.Probe".to_string(),
                    params_json: String::new(),
                    params_generation: 0,
                    rect: Rect::from_origin_size(ctx.origin(), ctx.size()),
                    clip: None,
                    visible: true,
                    interactive: false,
                    shields: Vec::new(),
                });
            }
        }
    }

    #[test]
    fn child_pod_extends_platform_views_never_overwrites() {
        // Two slots publishing across two `paint_child` calls in one pass must
        // BOTH survive, in paint order — the regression test for the
        // Option-overwrite hazard: an ime_state-shaped merge here would leave
        // only the second slot's frame (see `PaintCtx::publish_platform_view`'s
        // doc comment).
        let mut lctx = LayoutCtx::new();

        let mut first = ChildPod::new(Box::new(PlatformViewProbe {
            slot_id: 1,
            should_publish: true,
        }));
        first.set_origin(Point::new(0.0, 0.0));
        first.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));

        let mut second = ChildPod::new(Box::new(PlatformViewProbe {
            slot_id: 2,
            should_publish: true,
        }));
        second.set_origin(Point::new(20.0, 0.0));
        second.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));

        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(100.0, 100.0));
        first.paint_child(&mut pctx, &mut scene);
        second.paint_child(&mut pctx, &mut scene);

        let frames = pctx.take_platform_views();
        assert_eq!(
            frames.len(),
            2,
            "both slots' frames must survive, not just the last-painted one"
        );
        assert_eq!(frames[0].slot_id, 1);
        assert_eq!(frames[1].slot_id, 2);
    }

    /// A container widget wrapping a single child pod at a fixed offset —
    /// stands in for `frust-widgets::Padding` to test that a published frame's
    /// rect compounds correctly under nesting rather than staying local to the
    /// innermost pod.
    struct TranslatingWrapper {
        child: ChildPod,
    }

    impl Widget for TranslatingWrapper {
        fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            self.child.layout_child(ctx, bc)
        }

        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            self.child.paint_child(ctx, scene);
        }
    }

    #[test]
    fn platform_view_frame_rect_is_absolute_under_nested_translation() {
        // Wrap a publishing probe under two levels of translation — an inner
        // pod at (5, 7) inside a wrapper placed at (100, 200) — the published
        // rect must land in ABSOLUTE window coordinates (the same space
        // `PaintCtx::report_hero` callers use), not local to either level.
        let mut lctx = LayoutCtx::new();

        let inner = ChildPod::new(Box::new(PlatformViewProbe {
            slot_id: 9,
            should_publish: true,
        }));
        let mut wrapper = TranslatingWrapper { child: inner };
        wrapper.child.set_origin(Point::new(5.0, 7.0));
        wrapper
            .child
            .layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));

        let mut outer = ChildPod::new(Box::new(wrapper));
        outer.set_origin(Point::new(100.0, 200.0));
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));

        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(400.0, 400.0));
        outer.paint_child(&mut pctx, &mut scene);

        let frames = pctx.take_platform_views();
        assert_eq!(frames.len(), 1);
        assert_eq!(
            frames[0].rect,
            Rect::from_origin_size(Point::new(105.0, 207.0), Size::new(10.0, 10.0))
        );
    }

    #[test]
    fn paint_ctx_origin_is_absolute_through_nested_offsets() {
        // Nest a leaf widget under two levels of offset containers: the leaf
        // must observe the summed absolute window-space origin, not a
        // parent-relative one. This pins the accumulation contract that external
        // design systems (anchored overlays) depend on.
        use std::cell::Cell;

        struct OriginRecorder {
            recorded_origin: Cell<Option<Point>>,
        }

        impl Widget for OriginRecorder {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.max()
            }

            fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
                self.recorded_origin.set(Some(ctx.origin()));
            }
        }

        let mut lctx = LayoutCtx::new();

        // Inner recorder at (20, 30) relative to middle container.
        let recorder = OriginRecorder {
            recorded_origin: Cell::new(None),
        };
        let inner = ChildPod::new(Box::new(recorder));
        let mut middle = TranslatingWrapper { child: inner };
        middle.child.set_origin(Point::new(20.0, 30.0));
        middle
            .child
            .layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));

        // Middle container at (50, 70) relative to outer.
        let mut outer = ChildPod::new(Box::new(middle));
        outer.set_origin(Point::new(50.0, 70.0));
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));

        // Paint from root at (0, 0).
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(400.0, 400.0));
        outer.paint_child(&mut pctx, &mut scene);

        // Verify: leaf's origin must be sum of all offsets:
        // root(0,0) + outer(50,70) + middle(20,30) = (70, 100).
        let leaf = outer
            .widget_mut()
            .downcast_mut::<TranslatingWrapper>()
            .unwrap()
            .child
            .widget_mut()
            .downcast_mut::<OriginRecorder>()
            .unwrap();
        assert_eq!(
            leaf.recorded_origin.get(),
            Some(Point::new(70.0, 100.0)),
            "leaf must observe summed absolute origin"
        );
    }

    #[test]
    fn request_frame_alone_does_not_set_needs_layout() {
        // A paint-only animation (request_frame, no request_layout) must leave
        // `needs_layout` clear — the mobile intra-frame layout-skip depends on this.
        let mut anim = ChildPod::new(Box::new(Animator));
        let mut lctx = LayoutCtx::new();
        anim.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        anim.paint_child(&mut pctx, &mut scene);
        assert!(pctx.needs_frame(), "request_frame sets needs_frame");
        assert!(
            !pctx.needs_layout(),
            "request_frame alone must NOT set needs_layout"
        );
    }

    #[test]
    fn request_layout_implies_needs_frame() {
        // `request_layout` also sets `needs_frame` so one call per
        // animating-layout frame suffices.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        assert!(!ctx.needs_frame());
        assert!(!ctx.needs_layout());
        ctx.request_layout();
        assert!(ctx.needs_layout());
        assert!(ctx.needs_frame());
    }

    #[test]
    fn child_pod_bubbles_needs_layout_from_child_paint() {
        // A non-layout-animating child leaves the parent's layout flag clear.
        let mut still = ChildPod::new(Box::new(FixedBox {
            intrinsic: Size::new(10.0, 10.0),
        }));
        let mut lctx = LayoutCtx::new();
        still.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        still.paint_child(&mut pctx, &mut scene);
        assert!(!pctx.needs_layout());

        // A layout-animating child bubbles its request into the parent context.
        let mut anim = ChildPod::new(Box::new(LayoutAnimator));
        anim.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut pctx2 = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        assert!(!pctx2.needs_layout());
        anim.paint_child(&mut pctx2, &mut scene);
        assert!(pctx2.needs_layout());
        // Bubbling `request_layout` also carries the implied `needs_frame`.
        assert!(pctx2.needs_frame());
    }

    #[test]
    fn needs_layout_bubbles_through_nested_containers() {
        // A container holding a single `ChildPod` forwards paint via
        // `paint_child`; a layout-animating leaf two levels deep must still
        // surface `needs_layout` at the outermost paint context.
        struct SingleChildContainer {
            child: ChildPod,
        }
        impl Widget for SingleChildContainer {
            fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                self.child.layout_child(ctx, bc)
            }
            fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
                self.child.paint_child(ctx, scene);
            }
        }

        let inner = SingleChildContainer {
            child: ChildPod::new(Box::new(LayoutAnimator)),
        };
        let mut outer = ChildPod::new(Box::new(SingleChildContainer {
            child: ChildPod::new(Box::new(inner)),
        }));
        let mut lctx = LayoutCtx::new();
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        outer.paint_child(&mut pctx, &mut scene);
        assert!(
            pctx.needs_layout(),
            "needs_layout bubbles up nested containers"
        );
        assert!(pctx.needs_frame());
    }

    /// A single-`ChildPod` container that forwards paint via `paint_child`,
    /// reused by the tick-class bubbling tests below.
    struct SingleChildContainer {
        child: ChildPod,
    }
    impl Widget for SingleChildContainer {
        fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            self.child.layout_child(ctx, bc)
        }
        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            self.child.paint_child(ctx, scene);
        }
    }

    #[test]
    fn no_request_yields_no_frame_class() {
        // No frame requested at all → `frame_class()` is `None` and the frame is
        // not paced-only (as today: nothing to schedule).
        let ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        assert!(ctx.frame_class().is_none());
        assert!(!ctx.needs_frame());
        assert!(!ctx.needs_frame_paced_only());
    }

    #[test]
    fn request_frame_is_transition_unpaced() {
        // The unchanged `request_frame` is a Transition request: it must NOT be
        // paced-only, preserving today's every-vsync behavior for existing callers.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame();
        assert!(ctx.needs_frame());
        assert_eq!(ctx.frame_class(), Some(TickClass::Transition));
        assert!(
            !ctx.needs_frame_paced_only(),
            "request_frame stays unpaced (Transition), unchanged behavior"
        );
    }

    #[test]
    fn request_frame_paced_is_cosmetic_loop() {
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_paced();
        assert!(ctx.needs_frame());
        assert_eq!(ctx.frame_class(), Some(TickClass::CosmeticLoop));
        assert!(ctx.needs_frame_paced_only());
        // The bare form names no interval: `Duration::ZERO` is "at the theme's
        // own cosmetic rate" — unchanged behavior for all six shimmer widgets.
        assert_eq!(ctx.paced_interval(), Some(Duration::ZERO));
    }

    #[test]
    fn request_frame_paced_at_carries_its_interval() {
        // The explicit form is the same class, only slower: a ~500ms caret.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_paced_at(Duration::from_millis(500));
        assert!(ctx.needs_frame());
        assert_eq!(ctx.frame_class(), Some(TickClass::CosmeticLoop));
        assert!(ctx.needs_frame_paced_only());
        assert_eq!(ctx.paced_interval(), Some(Duration::from_millis(500)));
    }

    #[test]
    fn request_frame_paced_at_clamps_past_the_ten_second_ceiling() {
        // Past the ceiling: clamps DOWN to it rather than carrying the raw
        // caller value out to the shell's pacing arithmetic unbounded.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_paced_at(Duration::from_secs(10) + Duration::from_secs(1));
        assert_eq!(ctx.paced_interval(), Some(PaintCtx::MAX_PACED_INTERVAL));
    }

    #[test]
    fn request_frame_paced_at_leaves_a_real_cadence_untouched() {
        // Every shipped cadence (the ~500ms caret above, muxr's ~550ms blink)
        // sits nowhere near the ceiling and must pass through byte-for-byte —
        // the clamp must never change behavior for any existing caller.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_paced_at(Duration::from_millis(550));
        assert_eq!(ctx.paced_interval(), Some(Duration::from_millis(550)));
    }

    #[test]
    fn paced_intervals_aggregate_on_the_min_lattice() {
        // Two paced requests at different rates in one pass: the TIGHTEST wins,
        // so both are honored (the slower one is merely repainted more often
        // than it asked — see `request_frame_paced_at`'s contract).
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_paced_at(Duration::from_millis(500));
        ctx.request_frame_paced_at(Duration::from_millis(33));
        assert_eq!(ctx.paced_interval(), Some(Duration::from_millis(33)));
        assert!(ctx.needs_frame_paced_only());

        // Order-independent (a lattice fold, not a last-writer-wins slot).
        let mut reversed = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        reversed.request_frame_paced_at(Duration::from_millis(33));
        reversed.request_frame_paced_at(Duration::from_millis(500));
        assert_eq!(reversed.paced_interval(), Some(Duration::from_millis(33)));

        // A bare `request_frame_paced` (the theme cap, `Duration::ZERO`) is the
        // absorbing element: a 30Hz shimmer beside a 2Hz caret paces at 30Hz.
        let mut shimmer_and_caret = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        shimmer_and_caret.request_frame_paced_at(Duration::from_millis(500));
        shimmer_and_caret.request_frame_paced();
        assert_eq!(shimmer_and_caret.paced_interval(), Some(Duration::ZERO));
    }

    #[test]
    fn request_frame_class_cosmetic_matches_the_bare_paced_request() {
        // The general form must stay interchangeable with `request_frame_paced`
        // (the widgets' `cull_pacing`/`pacing_integration` suites drive it).
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_class(TickClass::CosmeticLoop);
        assert_eq!(ctx.frame_class(), Some(TickClass::CosmeticLoop));
        assert_eq!(ctx.paced_interval(), Some(Duration::ZERO));
    }

    #[test]
    fn no_paced_request_names_no_interval() {
        // Nothing requested, and a Transition-only request, both leave the
        // interval unset — there is no paced loop to pace.
        let ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        assert_eq!(ctx.paced_interval(), None);
        let mut transition = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        transition.request_frame();
        assert_eq!(transition.paced_interval(), None);
    }

    #[test]
    fn transition_dominates_cosmetic_regardless_of_order() {
        // Paced then Transition → unpaced.
        let mut a = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        a.request_frame_paced();
        a.request_frame();
        assert_eq!(a.frame_class(), Some(TickClass::Transition));
        assert!(!a.needs_frame_paced_only());

        // Transition then paced → still unpaced (a CosmeticLoop never clears it).
        let mut b = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        b.request_frame();
        b.request_frame_paced();
        assert_eq!(b.frame_class(), Some(TickClass::Transition));
        assert!(!b.needs_frame_paced_only());
    }

    #[test]
    fn request_layout_implies_transition_class() {
        // `request_layout` is user-visible motion, so it re-forces the unpaced
        // Transition class even if a paced request preceded it.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.request_frame_paced();
        assert!(ctx.needs_frame_paced_only());
        ctx.request_layout();
        assert_eq!(ctx.frame_class(), Some(TickClass::Transition));
        assert!(
            !ctx.needs_frame_paced_only(),
            "request_layout implies Transition, leaving the frame unpaced"
        );
    }

    #[test]
    fn child_pod_bubbles_paced_class_from_child_paint() {
        // A purely-cosmetic child bubbles a paced request into the parent — the
        // parent's aggregate stays paced-only.
        let mut anim = ChildPod::new(Box::new(PacedAnimator));
        let mut lctx = LayoutCtx::new();
        anim.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        anim.paint_child(&mut pctx, &mut scene);
        assert!(pctx.needs_frame());
        assert_eq!(pctx.frame_class(), Some(TickClass::CosmeticLoop));
        assert!(pctx.needs_frame_paced_only());
    }

    #[test]
    fn paced_class_bubbles_through_nested_containers() {
        // A cosmetic-loop leaf two levels deep must still surface as paced-only
        // at the outermost paint context (the bubbling identity of the lattice).
        let inner = SingleChildContainer {
            child: ChildPod::new(Box::new(PacedAnimator)),
        };
        let mut outer = ChildPod::new(Box::new(SingleChildContainer {
            child: ChildPod::new(Box::new(inner)),
        }));
        let mut lctx = LayoutCtx::new();
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        outer.paint_child(&mut pctx, &mut scene);
        assert!(pctx.needs_frame());
        assert!(
            pctx.needs_frame_paced_only(),
            "a nested cosmetic-loop leaf stays paced-only up the tree"
        );
    }

    #[test]
    fn child_pod_bubbles_a_named_interval_unchanged() {
        // A slow caret nested under a container must reach the root with its own
        // interval intact — bubbling must never re-tighten it to the theme cap
        // (which a blanket `request_frame_class(CosmeticLoop)` forward would).
        let mut outer = ChildPod::new(Box::new(SingleChildContainer {
            child: ChildPod::new(Box::new(SlowPacedAnimator)),
        }));
        let mut lctx = LayoutCtx::new();
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        outer.paint_child(&mut pctx, &mut scene);
        assert!(pctx.needs_frame_paced_only());
        assert_eq!(
            pctx.paced_interval(),
            Some(SLOW_PACE),
            "a nested slow paced loop keeps its own cadence up the tree"
        );
    }

    #[test]
    fn absorb_paced_interval_skips_on_none_without_tightening_to_zero() {
        // The one rule shared by both paced-interval absorb sites
        // (`ChildPod::paint_child`'s CosmeticLoop arm, `with_hero_registry`):
        // a `None` interval must leave the aggregate untouched rather than
        // defaulting to `Duration::ZERO` (the MIN-lattice's own tightest,
        // most-tightening value) — the exact defect class `unwrap_or_default`
        // used to risk in `paint_child`.
        //
        // Exercised directly against the shared fold rather than through
        // `paint_child`'s real bubble: that call site's `debug_assert!`
        // documents `frame_class() == Some(CosmeticLoop)` with no merged
        // interval as unreachable through the public `request_frame_paced*`
        // API (a provable invariant — see its doc comment), so forcing that
        // exact state through the full `ChildPod::paint_child` path would
        // trip the tripwire instead of exercising the fallback it guards.
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.absorb_paced_interval(None);
        assert_eq!(
            ctx.paced_interval(),
            None,
            "a None interval must not tighten the aggregate to Duration::ZERO"
        );

        // A pre-existing aggregate is likewise untouched by a `None` fold.
        let mut ctx2 = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx2.request_frame_paced_at(Duration::from_millis(500));
        ctx2.absorb_paced_interval(None);
        assert_eq!(
            ctx2.paced_interval(),
            Some(Duration::from_millis(500)),
            "a None fold must not override an already-merged interval either"
        );
    }

    #[test]
    fn sibling_paced_intervals_fold_to_the_tightest() {
        // A shimmer (theme cap) beside a slow caret under one container: the
        // container's aggregate paces at the shimmer's rate. The caret is then
        // repainted more often than it asked — no visual harm, by design.
        struct TwoChildContainer {
            a: ChildPod,
            b: ChildPod,
        }
        impl Widget for TwoChildContainer {
            fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                self.a.layout_child(ctx, bc);
                self.b.layout_child(ctx, bc)
            }
            fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
                self.a.paint_child(ctx, scene);
                self.b.paint_child(ctx, scene);
            }
        }

        let mut outer = ChildPod::new(Box::new(TwoChildContainer {
            a: ChildPod::new(Box::new(SlowPacedAnimator)),
            b: ChildPod::new(Box::new(PacedAnimator)),
        }));
        let mut lctx = LayoutCtx::new();
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        outer.paint_child(&mut pctx, &mut scene);
        assert!(pctx.needs_frame_paced_only());
        assert_eq!(
            pctx.paced_interval(),
            Some(Duration::ZERO),
            "the tightest sibling request (the theme cap) wins the fold"
        );
    }

    #[test]
    fn mixed_sibling_requests_aggregate_to_unpaced() {
        // Two sibling children under one container: one paced, one Transition.
        // The container's aggregate must be unpaced (any Transition dominates).
        struct TwoChildContainer {
            a: ChildPod,
            b: ChildPod,
        }
        impl Widget for TwoChildContainer {
            fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                self.a.layout_child(ctx, bc);
                self.b.layout_child(ctx, bc)
            }
            fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
                self.a.paint_child(ctx, scene);
                self.b.paint_child(ctx, scene);
            }
        }

        let mut outer = ChildPod::new(Box::new(TwoChildContainer {
            a: ChildPod::new(Box::new(PacedAnimator)),
            b: ChildPod::new(Box::new(Animator)),
        }));
        let mut lctx = LayoutCtx::new();
        outer.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut pctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        outer.paint_child(&mut pctx, &mut scene);
        assert!(pctx.needs_frame());
        assert_eq!(pctx.frame_class(), Some(TickClass::Transition));
        assert!(
            !pctx.needs_frame_paced_only(),
            "a mixed paced+transition sibling set aggregates to unpaced"
        );
    }

    #[test]
    fn with_hero_registry_bubbles_paced_class() {
        // The hero-reporter sub-context absorbs a paced request the same way it
        // absorbs `needs_frame`/`needs_layout`.
        let registry = RefCell::new(HeroFrames::default());
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx.with_hero_registry(&registry, |child| {
            child.request_frame_paced();
        });
        assert!(ctx.needs_frame());
        assert!(
            ctx.needs_frame_paced_only(),
            "with_hero_registry bubbles the paced class up"
        );

        // A Transition inside the closure dominates the outer aggregate too.
        let mut ctx2 = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx2.request_frame_paced();
        ctx2.with_hero_registry(&registry, |child| {
            child.request_frame();
        });
        assert_eq!(ctx2.frame_class(), Some(TickClass::Transition));
        assert!(!ctx2.needs_frame_paced_only());

        // The interval half of the absorb: a named interval inside surfaces
        // outside, and folds on the MIN-lattice with an outer request.
        let mut ctx3 = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        ctx3.with_hero_registry(&registry, |child| {
            child.request_frame_paced_at(SLOW_PACE);
        });
        assert_eq!(ctx3.paced_interval(), Some(SLOW_PACE));
        ctx3.request_frame_paced();
        assert_eq!(
            ctx3.paced_interval(),
            Some(Duration::ZERO),
            "the outer theme-cap request tightens the folded aggregate"
        );
    }

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

        // A probe recording what `ctx.has_focus()` it observed during paint.
        struct FocusProbe(Rc<Cell<Option<bool>>>);
        impl Widget for FocusProbe {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.constrain(Size::new(10.0, 10.0))
            }
            fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
                self.0.set(Some(ctx.has_focus()));
            }
        }

        let seen = Rc::new(Cell::new(None));
        let mut pod = ChildPod::new(Box::new(FocusProbe(seen.clone())));
        let mut lctx = LayoutCtx::new();
        pod.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();

        // Focused pod under a focused ancestor: the child observes focus.
        pod.set_focused(true);
        let mut focused_parent = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        focused_parent.set_has_focus(true);
        pod.paint_child(&mut focused_parent, &mut scene);
        assert_eq!(seen.get(), Some(true));

        // Focused pod under a BLURRED ancestor (the stale-deep-flag case): the
        // cleared ancestor link must force `has_focus == false` below it.
        let mut blurred_parent = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        blurred_parent.set_has_focus(false);
        pod.paint_child(&mut blurred_parent, &mut scene);
        assert_eq!(seen.get(), Some(false));

        // Unfocused pod under a focused ancestor stays unfocused.
        pod.set_focused(false);
        let mut focused_parent2 = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        focused_parent2.set_has_focus(true);
        pod.paint_child(&mut focused_parent2, &mut scene);
        assert_eq!(seen.get(), Some(false));
    }

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

        /// A probe that claims hover on every event it receives and records what
        /// `is_hovered()` each pass reported.
        struct HoverProbe {
            event_seen: Rc<Cell<Option<bool>>>,
            paint_seen: Rc<Cell<Option<bool>>>,
        }
        impl Widget for HoverProbe {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.constrain(Size::new(10.0, 10.0))
            }
            fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
                self.paint_seen.set(Some(ctx.is_hovered()));
            }
            fn event(&mut self, ctx: &mut EventCtx, _event: &InputEvent) -> EventResult {
                self.event_seen.set(Some(ctx.is_hovered()));
                ctx.claim_hover();
                EventResult::Ignored
            }
        }

        let event_seen = Rc::new(Cell::new(None));
        let paint_seen = Rc::new(Cell::new(None));
        let mut pod = ChildPod::new(Box::new(HoverProbe {
            event_seen: event_seen.clone(),
            paint_seen: paint_seen.clone(),
        }));
        let mut lctx = LayoutCtx::new();
        pod.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();
        let mut state = ();
        let event = InputEvent::Pointer(PointerEvent {
            phase: PointerPhase::Move,
            position: Point::new(5.0, 5.0),
            button: PointerButton::Primary,
        });

        // A never-claimed pod carries no stamp, and reads unhovered against any
        // live epoch (the root's starts past `0` for exactly this reason).
        assert_eq!(pod.hover_epoch(), 0);

        // Dispatch on an INELIGIBLE pass (the default): the claim records nothing.
        {
            let mut ctx = EventCtx::new(&mut state as &mut dyn Any, Point::ZERO, pod.size());
            ctx.set_hover_epoch(4);
            pod.event_child(&mut ctx, &event);
            assert!(!ctx.is_hover_claimed(), "nothing bubbled up");
        }
        assert_eq!(pod.hover_epoch(), 0, "no stamp from an ineligible pass");

        // Dispatch on an eligible pass: the pod is stamped with the *next* epoch
        // (the root advances its own when the pass ends) and the claim bubbles.
        {
            let mut ctx = EventCtx::new(&mut state as &mut dyn Any, Point::ZERO, pod.size());
            ctx.set_hover_epoch(4);
            ctx.set_hovered(true);
            ctx.set_hover_eligible(true);
            pod.event_child(&mut ctx, &event);
            assert!(ctx.is_hover_claimed());
            assert_eq!(
                event_seen.get(),
                Some(false),
                "the pod held no link going into this pass"
            );
        }
        assert_eq!(pod.hover_epoch(), 5);

        // Paint against the epoch the claim recorded: hovered, and the ancestor
        // chain is ANDed in exactly like focus.
        let mut live = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        live.set_hover_epoch(5);
        live.set_hovered(true);
        pod.paint_child(&mut live, &mut scene);
        assert_eq!(paint_seen.get(), Some(true));

        // Same stamp under an UNHOVERED ancestor: the chain wins.
        let mut unhovered_parent = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        unhovered_parent.set_hover_epoch(5);
        unhovered_parent.set_hovered(false);
        pod.paint_child(&mut unhovered_parent, &mut scene);
        assert_eq!(paint_seen.get(), Some(false));

        // The epoch moves on (the pointer went elsewhere): the stamp is stranded
        // with nobody clearing it — the whole point of stamping rather than
        // flagging.
        let mut later = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        later.set_hover_epoch(6);
        later.set_hovered(true);
        pod.paint_child(&mut later, &mut scene);
        assert_eq!(paint_seen.get(), Some(false));

        // A pod holding the capture path refuses a claim outright, whatever the
        // pass says — a drag never paints hover under the pointer.
        pod.set_active(true);
        {
            let mut ctx = EventCtx::new(&mut state as &mut dyn Any, Point::ZERO, pod.size());
            ctx.set_hover_epoch(6);
            ctx.set_hover_eligible(true);
            pod.event_child(&mut ctx, &event);
            assert!(!ctx.is_hover_claimed());
        }
        assert_eq!(pod.hover_epoch(), 5, "the captured pod kept its old stamp");
    }

    /// Two overlapping children can both hit-test a point (a Stack, or any
    /// container whose topmost child ignores the move). Only the first claim in
    /// **dispatch order** is recorded, which is the primitive; "the topmost
    /// claimant wins" is the consequence of dispatching topmost-first *and* of
    /// every container claiming after it routes (see `EventCtx::claim_hover`),
    /// not a rule this level enforces. Either way, no pass can leave two widgets
    /// hovered.
    #[test]
    fn only_the_first_hover_claim_in_a_pass_is_recorded() {
        struct Claimer;
        impl Widget for Claimer {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.constrain(Size::new(10.0, 10.0))
            }
            fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
            fn event(&mut self, ctx: &mut EventCtx, _event: &InputEvent) -> EventResult {
                ctx.claim_hover();
                EventResult::Ignored
            }
        }

        let mut first = ChildPod::new(Box::new(Claimer));
        let mut second = ChildPod::new(Box::new(Claimer));
        let mut state = ();
        let event = InputEvent::Pointer(PointerEvent {
            phase: PointerPhase::Move,
            position: Point::new(5.0, 5.0),
            button: PointerButton::Primary,
        });
        let mut ctx = EventCtx::new(&mut state as &mut dyn Any, Point::ZERO, Size::ZERO);
        ctx.set_hover_epoch(2);
        ctx.set_hover_eligible(true);

        first.event_child(&mut ctx, &event);
        second.event_child(&mut ctx, &event);
        assert_eq!(first.hover_epoch(), 3, "the first claim is recorded");
        assert_eq!(
            second.hover_epoch(),
            0,
            "the pass was closed to further claims"
        );
    }

    #[test]
    fn child_pod_contains_uses_container_space_bounds() {
        let mut pod = ChildPod::new(Box::new(FixedBox {
            intrinsic: Size::ZERO,
        }));
        pod.set_origin(Point::new(10.0, 10.0));
        let mut lctx = LayoutCtx::new();
        pod.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(20.0, 20.0)));

        assert!(pod.contains(Point::new(10.0, 10.0))); // top-left inclusive
        assert!(pod.contains(Point::new(29.9, 29.9)));
        assert!(!pod.contains(Point::new(30.0, 30.0))); // bottom-right exclusive
        assert!(!pod.contains(Point::new(9.9, 15.0)));
    }

    /// A scene recorder that overrides the shadow/layer `PaintScene` additions, to
    /// prove they reach an implementing scene that opts in.
    #[derive(Default)]
    struct ShadowLayerRecordingScene {
        shadows: Vec<(Point, Size, f64, f64, Color)>,
        layers: Vec<(Point, Size, f32)>,
        pops: u32,
    }

    impl PaintScene for ShadowLayerRecordingScene {
        fn fill_rect(&mut self, _origin: Point, _size: Size, _color: Color) {}
        fn draw_text(&mut self, _origin: Point, _text: &str) {}

        fn draw_shadow(
            &mut self,
            origin: Point,
            size: Size,
            radius: f64,
            std_dev: f64,
            color: Color,
        ) {
            self.shadows.push((origin, size, radius, std_dev, color));
        }

        fn push_layer(&mut self, origin: Point, size: Size, alpha: f32) {
            self.layers.push((origin, size, alpha));
        }

        fn pop_layer(&mut self) {
            self.pops += 1;
        }
    }

    #[test]
    fn draw_shadow_and_push_layer_are_no_ops_when_not_overridden() {
        // `RecordingScene` (defined above) does not override the shadow/layer
        // additions — the trait's default no-op bodies must compile
        // unchanged and simply do nothing.
        let mut scene = RecordingScene::default();
        scene.draw_shadow(Point::ZERO, Size::new(10.0, 10.0), 4.0, 2.0, Color::BLACK);
        scene.push_layer(Point::ZERO, Size::new(10.0, 10.0), 0.5);
        scene.pop_layer();
        assert!(scene.rects.is_empty());
        assert!(scene.texts.is_empty());
    }

    #[test]
    fn fill_path_and_stroke_path_are_no_ops_when_not_overridden() {
        // `RecordingScene` does not override the path additions
        // either — the trait's default no-op bodies must compile unchanged.
        let mut scene = RecordingScene::default();
        let mut path = BezPath::new();
        path.move_to((0.0, 0.0));
        path.line_to((1.0, 0.0));
        scene.fill_path(Point::ZERO, &path, &Brush::Solid(Color::BLACK));
        scene.stroke_path(Point::ZERO, &path, 2.0, &Brush::Solid(Color::BLACK));
        assert!(scene.rects.is_empty());
        assert!(scene.texts.is_empty());
    }

    /// A scene recorder overriding the path additions, proving they
    /// reach an implementing scene that opts in.
    #[derive(Default)]
    struct PathRecordingScene {
        fills: Vec<(Point, BezPath)>,
        strokes: Vec<(Point, BezPath, f64)>,
    }

    impl PaintScene for PathRecordingScene {
        fn fill_rect(&mut self, _origin: Point, _size: Size, _color: Color) {}
        fn draw_text(&mut self, _origin: Point, _text: &str) {}

        fn fill_path(&mut self, origin: Point, path: &BezPath, _brush: &Brush) {
            self.fills.push((origin, path.clone()));
        }

        fn stroke_path(&mut self, origin: Point, path: &BezPath, width: f64, _brush: &Brush) {
            self.strokes.push((origin, path.clone(), width));
        }
    }

    #[test]
    fn fill_path_and_stroke_path_reach_an_overriding_implementor() {
        let mut scene = PathRecordingScene::default();
        let mut path = BezPath::new();
        path.move_to((0.0, 0.0));
        path.line_to((5.0, 0.0));

        scene.fill_path(Point::new(1.0, 2.0), &path, &Brush::Solid(Color::BLACK));
        scene.stroke_path(
            Point::new(3.0, 4.0),
            &path,
            1.5,
            &Brush::Solid(Color::BLACK),
        );

        assert_eq!(scene.fills.len(), 1);
        assert_eq!(scene.fills[0].0, Point::new(1.0, 2.0));
        assert_eq!(scene.fills[0].1, path);

        assert_eq!(scene.strokes.len(), 1);
        assert_eq!(scene.strokes[0].0, Point::new(3.0, 4.0));
        assert_eq!(scene.strokes[0].1, path);
        assert_eq!(scene.strokes[0].2, 1.5);
    }

    #[test]
    fn path_at_translates_path_points_by_origin() {
        let mut path = BezPath::new();
        path.move_to((0.0, 0.0));
        path.line_to((5.0, 0.0));

        let translated = path_at(Point::new(10.0, 20.0), &path);
        let mut expected = BezPath::new();
        expected.move_to((10.0, 20.0));
        expected.line_to((15.0, 20.0));
        assert_eq!(translated, expected);
    }

    /// A dummy theme type, standing in for `frust_theme::Theme` — proving the
    /// type-erased theme slot works for *any* `'static` type, not just the real
    /// theme (`frust-core` never names it).
    #[derive(Debug, PartialEq)]
    struct TestTheme {
        accent: u32,
    }

    #[test]
    fn layout_ctx_theme_as_recovers_threaded_theme() {
        let theme = TestTheme { accent: 7 };
        let ctx = LayoutCtx::new().with_theme(&theme);
        assert_eq!(ctx.theme_as::<TestTheme>(), Some(&TestTheme { accent: 7 }));
    }

    #[test]
    fn layout_ctx_theme_as_is_none_without_a_theme() {
        let ctx = LayoutCtx::new();
        assert!(ctx.theme_as::<TestTheme>().is_none());
    }

    #[test]
    fn layout_ctx_theme_as_is_none_on_type_mismatch() {
        let theme = TestTheme { accent: 1 };
        let ctx = LayoutCtx::new().with_theme(&theme);
        // A downcast to the wrong type yields `None`, never a panic.
        assert!(ctx.theme_as::<u32>().is_none());
    }

    #[test]
    fn paint_ctx_theme_as_recovers_threaded_theme() {
        let theme = TestTheme { accent: 9 };
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(1.0, 1.0));
        ctx.set_theme(Some(&theme));
        assert_eq!(ctx.theme_as::<TestTheme>(), Some(&TestTheme { accent: 9 }));
    }

    #[test]
    fn paint_ctx_theme_as_is_none_without_a_theme() {
        let ctx = PaintCtx::new(Point::ZERO, Size::new(1.0, 1.0));
        assert!(ctx.theme_as::<TestTheme>().is_none());
    }

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

        // A probe recording the accent it recovered from the paint context's
        // threaded theme (or `None` if no theme reached it).
        struct ThemeProbe(Rc<Cell<Option<u32>>>);
        impl Widget for ThemeProbe {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.constrain(Size::new(10.0, 10.0))
            }
            fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
                self.0.set(ctx.theme_as::<TestTheme>().map(|t| t.accent));
            }
        }

        let seen = Rc::new(Cell::new(None));
        let mut pod = ChildPod::new(Box::new(ThemeProbe(seen.clone())));
        let mut lctx = LayoutCtx::new();
        pod.layout_child(&mut lctx, &BoxConstraints::tight(Size::new(10.0, 10.0)));
        let mut scene = RecordingScene::default();

        // A parent carrying a theme threads it into the child paint.
        let theme = TestTheme { accent: 42 };
        let mut parent = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        parent.set_theme(Some(&theme));
        pod.paint_child(&mut parent, &mut scene);
        assert_eq!(seen.get(), Some(42));

        // A parent with no theme leaves the child's accessor empty.
        let mut bare = PaintCtx::new(Point::ZERO, Size::new(10.0, 10.0));
        pod.paint_child(&mut bare, &mut scene);
        assert_eq!(seen.get(), None);
    }

    /// A leaf widget whose visible appearance is driven purely by
    /// [`PaintCtx::frame_time`] — stands in for a caret-blink widget: it fills
    /// a rect only during the "on" half of a 1-second blink cycle, with no
    /// internal state of its own.
    struct BlinkBox;

    impl Widget for BlinkBox {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(Size::new(4.0, 4.0))
        }
        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            let millis = ctx.frame_time().as_nanos() / 1_000_000;
            if (millis / 500).is_multiple_of(2) {
                scene.fill_rect(ctx.origin(), ctx.size(), Color::BLACK);
            }
        }
    }

    #[test]
    fn for_test_seeds_the_requested_frame_time() {
        let ctx = PaintCtx::for_test(Point::ZERO, Size::new(1.0, 1.0), FrameTime::from_nanos(42));
        assert_eq!(ctx.frame_time(), FrameTime::from_nanos(42));
    }

    /// End-to-end proof the seam actually drives a clock-dependent widget:
    /// the same [`BlinkBox`] paints differently at two [`FrameTime`]s built
    /// via [`PaintCtx::for_test`] alone — no [`crate::app::RenderRoot`]
    /// involved, exactly how an app crate outside this workspace would use
    /// the seam.
    #[test]
    fn for_test_drives_a_clock_dependent_widget_to_two_appearances() {
        let mut widget = BlinkBox;
        let size = Size::new(4.0, 4.0);

        let mut on_ctx = PaintCtx::for_test(Point::ZERO, size, FrameTime::from_nanos(0));
        let mut on_scene = RecordingScene::default();
        widget.paint(&mut on_ctx, &mut on_scene);
        assert_eq!(on_scene.rects.len(), 1, "expected the caret painted on");

        let mut off_ctx = PaintCtx::for_test(Point::ZERO, size, FrameTime::from_nanos(500_000_000));
        let mut off_scene = RecordingScene::default();
        widget.paint(&mut off_ctx, &mut off_scene);
        assert!(
            off_scene.rects.is_empty(),
            "expected the caret painted off half a blink cycle later"
        );
    }

    #[test]
    fn draw_shadow_and_push_layer_reach_an_overriding_implementor() {
        let mut scene = ShadowLayerRecordingScene::default();
        let origin = Point::new(3.0, 4.0);
        let size = Size::new(20.0, 12.0);
        scene.draw_shadow(origin, size, 6.0, 3.0, Color::BLACK);
        scene.push_layer(origin, size, 0.25);
        scene.pop_layer();

        assert_eq!(scene.shadows, vec![(origin, size, 6.0, 3.0, Color::BLACK)]);
        assert_eq!(scene.layers, vec![(origin, size, 0.25)]);
        assert_eq!(scene.pops, 1);
    }

    #[test]
    fn a_pods_type_name_resolves_through_every_box() {
        // A pod's widget is always erased, and the container plumbing stores it
        // double-boxed — the name must still be the widget's own, at any depth.
        let single = ChildPod::new(Box::new(Animator));
        assert!(
            single.type_name().ends_with("Animator"),
            "{}",
            single.type_name()
        );

        let boxed: Box<dyn Widget> = Box::new(Animator);
        let double = ChildPod::new(Box::new(boxed));
        assert!(
            double.type_name().ends_with("Animator"),
            "{}",
            double.type_name()
        );
    }

    #[test]
    fn a_pods_tooling_id_is_assigned_once_and_never_shared() {
        let a = ChildPod::new(Box::new(Animator));
        let b = ChildPod::new(Box::new(Animator));
        let first = a.inspect_id();
        assert_eq!(a.inspect_id(), first, "a pod keeps the id it was given");
        assert_ne!(b.inspect_id(), first, "two pods never share an id");
        assert!(
            first.0 >= ChildPod::INSPECT_ID_BASE,
            "pod ids stay in the range reserved against arena WidgetIds"
        );
    }

    #[test]
    fn a_leaf_visits_no_children_and_a_container_visits_all_of_its_own() {
        struct Two {
            children: Vec<ChildPod>,
        }
        impl Widget for Two {
            fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
                bc.max()
            }
            fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
            fn visit_children(&self, visitor: &mut dyn FnMut(&ChildPod)) {
                for child in &self.children {
                    visitor(child);
                }
            }
        }

        // The trait default: a widget that says nothing publishes nothing.
        let mut seen = 0;
        Animator.visit_children(&mut |_| seen += 1);
        assert_eq!(seen, 0);

        let container = Two {
            children: vec![
                ChildPod::new(Box::new(Animator)),
                ChildPod::new(Box::new(Animator)),
            ],
        };
        let mut ids = Vec::new();
        container.visit_children(&mut |child| ids.push(child.inspect_id()));
        assert_eq!(ids.len(), 2);
        assert_ne!(ids[0], ids[1]);
    }

    /// A recorder that implements only the *uniform* rounded methods and the
    /// solid stroke — i.e. every pre-per-corner recorder scene in the wild —
    /// so the per-corner/dashed trait defaults can be observed falling back.
    #[derive(Default)]
    struct UniformOnlyScene {
        fills: Vec<(Point, Size, f64)>,
        clips: Vec<(Point, Size, f64)>,
        strokes: Vec<(Point, f64)>,
        pops: usize,
    }

    impl PaintScene for UniformOnlyScene {
        fn fill_rect(&mut self, _origin: Point, _size: Size, _color: Color) {}
        fn draw_text(&mut self, _origin: Point, _text: &str) {}
        fn fill_rounded_rect(&mut self, origin: Point, size: Size, radius: f64, _color: Color) {
            self.fills.push((origin, size, radius));
        }
        fn push_clip_rounded(&mut self, origin: Point, size: Size, radius: f64) {
            self.clips.push((origin, size, radius));
        }
        fn pop_clip(&mut self) {
            self.pops += 1;
        }
        fn stroke_path(&mut self, origin: Point, _path: &BezPath, width: f64, _brush: &Brush) {
            self.strokes.push((origin, width));
        }
    }

    fn corner_probe_path() -> BezPath {
        let mut path = BezPath::new();
        path.move_to((0.0, 0.0));
        path.line_to((10.0, 0.0));
        path
    }

    #[test]
    fn per_corner_paint_defaults_fall_back_to_the_uniform_methods() {
        // A scene that predates per-corner radii still paints something, at the
        // largest corner — and its clip stack stays balanced, which is why the
        // push delegates rather than no-op'ing against a real `pop_clip`.
        let mut scene = UniformOnlyScene::default();
        let origin = Point::new(2.0, 3.0);
        let size = Size::new(20.0, 10.0);
        let radii = CornerRadii::new(4.0, 12.0, 0.0, 1.0);

        scene.fill_rounded_rect_radii(origin, size, radii, Color::BLACK);
        scene.push_clip_rounded_radii(origin, size, radii);
        scene.pop_clip();

        assert_eq!(scene.fills, vec![(origin, size, 12.0)]);
        assert_eq!(scene.clips, vec![(origin, size, 12.0)]);
        assert_eq!(scene.pops, 1);
    }

    #[test]
    fn dashed_stroke_default_falls_back_to_the_solid_stroke() {
        let mut scene = UniformOnlyScene::default();
        let origin = Point::new(5.0, 6.0);
        scene.stroke_path_dashed(
            origin,
            &corner_probe_path(),
            2.0,
            DashPattern::new(4.0, 2.0),
            &Brush::Solid(Color::BLACK),
        );

        assert_eq!(scene.strokes, vec![(origin, 2.0)]);
    }

    #[test]
    fn scene_builder_records_per_corner_radii_translated_by_origin() {
        // The `SceneBuilder` impl overrides the defaults above: every corner
        // reaches the command intact, under the same origin→rect convention the
        // uniform methods use.
        let mut scene = frust_scene::Scene::new();
        let radii = CornerRadii::new(4.0, 12.0, 0.0, 1.0);
        {
            let mut builder = frust_scene::SceneBuilder::new(&mut scene);
            let paint: &mut dyn PaintScene = &mut builder;
            paint.fill_rounded_rect_radii(
                Point::new(2.0, 3.0),
                Size::new(20.0, 10.0),
                radii,
                Color::BLACK,
            );
            paint.push_clip_rounded_radii(Point::new(0.0, 0.0), Size::new(5.0, 5.0), radii);
            paint.pop_clip();
        }

        match &scene.commands()[0] {
            frust_scene::Command::RoundedRect {
                rect, radii: got, ..
            } => {
                assert_eq!(*rect, Rect::new(2.0, 3.0, 22.0, 13.0));
                assert_eq!(*got, radii);
            }
            other => panic!("expected RoundedRect, got {other:?}"),
        }
        match &scene.commands()[1] {
            frust_scene::Command::PushClipRounded { radii: got, .. } => assert_eq!(*got, radii),
            other => panic!("expected PushClipRounded, got {other:?}"),
        }
        assert!(matches!(scene.commands()[2], frust_scene::Command::PopClip));
    }

    #[test]
    fn scene_builder_records_a_dashed_stroke_translated_by_origin() {
        let mut scene = frust_scene::Scene::new();
        let dash = DashPattern::new(4.0, 2.0).with_phase(1.0);
        {
            let mut builder = frust_scene::SceneBuilder::new(&mut scene);
            let paint: &mut dyn PaintScene = &mut builder;
            paint.stroke_path_dashed(
                Point::new(5.0, 0.0),
                &corner_probe_path(),
                2.0,
                dash,
                &Brush::Solid(Color::BLACK),
            );
        }

        match &scene.commands()[0] {
            frust_scene::Command::Path { path, style, .. } => {
                assert_eq!(
                    *style,
                    frust_scene::PathStyle::Stroke {
                        width: 2.0,
                        dash: Some(dash)
                    }
                );
                // Same origin translation `stroke_path` applies.
                assert_eq!(path.elements().len(), 2);
                assert!(matches!(
                    path.elements()[0],
                    kurbo::PathEl::MoveTo(p) if p == Point::new(5.0, 0.0)
                ));
            }
            other => panic!("expected Path, got {other:?}"),
        }
    }

    #[test]
    fn uniform_paint_calls_still_encode_the_commands_they_always_did() {
        // The additive contract: the uniform methods every existing call site
        // uses keep producing the same commands, now spelled as four equal
        // corners / an undashed stroke.
        let mut scene = frust_scene::Scene::new();
        {
            let mut builder = frust_scene::SceneBuilder::new(&mut scene);
            let paint: &mut dyn PaintScene = &mut builder;
            paint.fill_rounded_rect(
                Point::new(0.0, 0.0),
                Size::new(10.0, 10.0),
                4.0,
                Color::BLACK,
            );
            paint.push_clip_rounded(Point::new(0.0, 0.0), Size::new(10.0, 10.0), 4.0);
            paint.pop_clip();
            paint.draw_shadow(
                Point::new(0.0, 0.0),
                Size::new(10.0, 10.0),
                4.0,
                2.0,
                Color::BLACK,
            );
            paint.stroke_path(
                Point::new(0.0, 0.0),
                &corner_probe_path(),
                1.0,
                &Brush::Solid(Color::BLACK),
            );
        }

        let uniform = CornerRadii::uniform(4.0);
        match &scene.commands()[0] {
            frust_scene::Command::RoundedRect { radii, .. } => assert_eq!(*radii, uniform),
            other => panic!("expected RoundedRect, got {other:?}"),
        }
        match &scene.commands()[1] {
            frust_scene::Command::PushClipRounded { radii, .. } => assert_eq!(*radii, uniform),
            other => panic!("expected PushClipRounded, got {other:?}"),
        }
        match &scene.commands()[3] {
            frust_scene::Command::BlurredRoundedRect { radii, .. } => assert_eq!(*radii, uniform),
            other => panic!("expected BlurredRoundedRect, got {other:?}"),
        }
        match &scene.commands()[4] {
            frust_scene::Command::Path { style, .. } => assert_eq!(
                *style,
                frust_scene::PathStyle::Stroke {
                    width: 1.0,
                    dash: None
                }
            ),
            other => panic!("expected Path, got {other:?}"),
        }
    }

    #[test]
    fn every_paint_scene_method_terminates_on_discard_scene() {
        // Every `PaintScene` method — including the delegating defaults
        // (per-corner/dashed variants, the additive image/shader/shadow
        // surface) — is reachable and terminates on `DiscardScene` without
        // panicking; a future `todo!()` or an infinitely-recursive default
        // would fail here. The records-nothing guarantee itself is asserted
        // where a scene actually exists, at the navigator/switcher call
        // sites, not here.
        use frust_scene::{FontHandle, Glyph};

        let mut scene = DiscardScene;
        let origin = Point::new(2.0, 3.0);
        let size = Size::new(20.0, 10.0);
        let color = Color::BLACK;
        let brush = Brush::Solid(color);
        let radii = CornerRadii::new(4.0, 12.0, 0.0, 1.0);
        let path = corner_probe_path();

        scene.fill_rect(origin, size, color);
        scene.fill_rounded_rect(origin, size, 4.0, color);
        scene.fill_rounded_rect_radii(origin, size, radii, color);
        scene.stroke_line(origin, Point::new(10.0, 10.0), 1.0, color);
        scene.push_clip(origin, size);
        scene.push_clip_rounded(origin, size, 4.0);
        scene.push_clip_rounded_radii(origin, size, radii);
        scene.pop_clip();
        scene.draw_text(origin, "discarded");

        let font = FontHandle::new(peniko::FontData::new(
            peniko::Blob::from(Vec::<u8>::new()),
            0,
        ));
        let run = GlyphRun {
            font,
            font_size: 16.0,
            brush: brush.clone(),
            transform: Affine::IDENTITY,
            glyphs: vec![Glyph {
                id: 1,
                x: 0.0,
                y: 0.0,
            }],
        };
        scene.draw_glyph_run(run);

        let image = peniko::ImageData {
            data: peniko::Blob::from(vec![0u8; 2 * 2 * 4]),
            format: peniko::ImageFormat::Rgba8,
            alpha_type: peniko::ImageAlphaType::Alpha,
            width: 2,
            height: 2,
        };
        scene.draw_image(&image, Rect::new(0.0, 0.0, 20.0, 20.0));

        let program = ShaderProgram::new("fn main() {}");
        scene.draw_shader(&program, Rect::new(0.0, 0.0, 10.0, 10.0), 1.5);

        scene.draw_shadow(origin, size, 4.0, 2.0, color);
        scene.fill_rect_brush(origin, size, &brush);
        scene.fill_rounded_rect_brush(origin, size, 4.0, &brush);
        scene.push_layer(origin, size, 0.5);
        scene.pop_layer();
        scene.clear_rect(origin, size);
        scene.fill_path(origin, &path, &brush);
        scene.stroke_path(origin, &path, 1.0, &brush);
        scene.stroke_path_dashed(origin, &path, 1.0, DashPattern::new(4.0, 2.0), &brush);
        scene.push_transform(Affine::translate((1.0, 2.0)));
        scene.pop_transform();
    }

    /// A minimal recorder that tracks only transform and layer stack operations
    /// to verify the default [`PaintScene::push_snapshot`]/[`PaintScene::pop_snapshot`]
    /// implementation emulates the presentation correctly.
    #[derive(Default)]
    struct MinimalSnapshotRecorder {
        operations: Vec<String>,
    }

    impl PaintScene for MinimalSnapshotRecorder {
        fn fill_rect(&mut self, _origin: Point, _size: Size, _color: Color) {}
        fn draw_text(&mut self, _origin: Point, _text: &str) {}
        fn push_transform(&mut self, _transform: Affine) {
            self.operations.push("push_transform".to_string());
        }
        fn pop_transform(&mut self) {
            self.operations.push("pop_transform".to_string());
        }
        fn push_layer(&mut self, _origin: Point, _size: Size, _alpha: f32) {
            self.operations.push("push_layer".to_string());
        }
        fn pop_layer(&mut self) {
            self.operations.push("pop_layer".to_string());
        }
    }

    #[test]
    fn default_push_snapshot_pop_snapshot_emulates_presentation_for_recorders() {
        // The default `push_snapshot` and `pop_snapshot` implementation
        // ensures recorders that override only the transform/layer methods
        // see a consistent sequence: push_transform, push_layer, paint body,
        // pop_layer, pop_transform — the reverse order matching the push ops.
        let mut recorder = MinimalSnapshotRecorder::default();
        let origin = Point::new(10.0, 20.0);
        let size = Size::new(100.0, 50.0);
        let alpha = 0.8;
        let scale = 0.9;

        // Emulate a body that doesn't call any paint methods (just has side effects).
        recorder.push_snapshot(1, origin, size, alpha, scale);
        // Body paint code would go here
        recorder.pop_snapshot();

        // Verify the sequence: transform, layer, pop_layer, pop_transform.
        assert_eq!(
            recorder.operations,
            vec![
                "push_transform".to_string(),
                "push_layer".to_string(),
                "pop_layer".to_string(),
                "pop_transform".to_string(),
            ]
        );
    }

    #[test]
    fn scene_builder_records_push_pop_snapshot_commands_directly_without_extra_transforms() {
        // The `SceneBuilder` impl overrides `push_snapshot`/`pop_snapshot` to
        // record the snapshot commands directly, without the emulating
        // transform/layer pairs. It records Command::PushSnapshot with the
        // key, rect (converted from origin/size), alpha, scale, and the current
        // transform, and Command::PopSnapshot with no extra layer/transform commands.
        let mut scene = frust_scene::Scene::new();
        {
            let mut builder = frust_scene::SceneBuilder::new(&mut scene);
            let paint: &mut dyn PaintScene = &mut builder;

            paint.push_snapshot(7, Point::new(5.0, 10.0), Size::new(80.0, 40.0), 0.5, 1.2);
            // Paint some content inside the snapshot.
            paint.fill_rect(Point::new(10.0, 15.0), Size::new(20.0, 25.0), Color::BLACK);
            paint.pop_snapshot();
        }

        // Verify the command sequence: PushSnapshot, FillRect, PopSnapshot.
        // No PushLayer, PopLayer, PushTransform, or PopTransform commands.
        let commands = scene.commands();
        assert_eq!(commands.len(), 3);

        match &commands[0] {
            frust_scene::Command::PushSnapshot {
                key,
                rect,
                alpha,
                scale,
                ..
            } => {
                assert_eq!(*key, 7);
                assert_eq!(*rect, Rect::new(5.0, 10.0, 85.0, 50.0));
                assert_eq!(*alpha, 0.5);
                assert_eq!(*scale, 1.2);
            }
            other => panic!("expected PushSnapshot, got {other:?}"),
        }

        match &commands[1] {
            frust_scene::Command::FillRect { rect, .. } => {
                assert_eq!(*rect, Rect::new(10.0, 15.0, 30.0, 40.0));
            }
            other => panic!("expected FillRect, got {other:?}"),
        }

        assert!(
            matches!(commands[2], frust_scene::Command::PopSnapshot),
            "expected PopSnapshot, got {:?}",
            commands[2]
        );
    }
}

#[cfg(test)]
mod transform_tests {
    use std::f64::consts::FRAC_PI_4;

    use kurbo::Vec2;

    use super::*;
    use crate::event::{
        PointerButton, PointerEvent, PointerId, PointerPhase, ScaleEvent, ScalePhase, ScrollDelta,
    };

    /// One recorded paint operation, in order.
    #[derive(Clone, Debug, PartialEq)]
    enum Op {
        Rect(Point, Size),
        Push(Affine),
        Pop,
    }

    /// A scene recorder that keeps the transform stack interleaved with draws,
    /// so a test can see exactly what a pod pushed around its child.
    #[derive(Default)]
    struct OpLog(Vec<Op>);

    impl PaintScene for OpLog {
        fn fill_rect(&mut self, origin: Point, size: Size, _color: Color) {
            self.0.push(Op::Rect(origin, size));
        }
        fn draw_text(&mut self, _origin: Point, _text: &str) {}
        fn push_transform(&mut self, transform: Affine) {
            self.0.push(Op::Push(transform));
        }
        fn pop_transform(&mut self) {
            self.0.push(Op::Pop);
        }
    }

    /// A leaf that fills its whole box, records every event it receives (in
    /// local space), captures on `Down`, and contributes one semantics node.
    #[derive(Default)]
    struct Recorder {
        events: Vec<InputEvent>,
    }

    impl Widget for Recorder {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }
        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            scene.fill_rect(ctx.origin(), ctx.size(), Color::BLACK);
        }
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            self.events.push(event.clone());
            if matches!(
                event,
                InputEvent::Pointer(PointerEvent {
                    phase: PointerPhase::Down,
                    ..
                })
            ) {
                ctx.capture_pointer();
            }
            EventResult::Handled
        }
        fn semantics(&self, ctx: &mut SemanticsCtx) {
            ctx.push_node(accesskit::Role::Label, |_| {});
        }
    }

    /// A leaf that records the visible rect its paint context carries.
    struct VisibleProbe(std::rc::Rc<Cell<Option<Rect>>>);

    impl Widget for VisibleProbe {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.max()
        }
        fn paint(&mut self, ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {
            self.0.set(ctx.visible_rect());
        }
    }

    fn pointer(phase: PointerPhase, x: f64, y: f64) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase,
            position: Point::new(x, y),
            button: PointerButton::Primary,
        })
    }

    /// A laid-out `Recorder` pod of `size` at `origin`.
    fn recorder_pod(origin: Point, size: Size) -> ChildPod {
        let mut pod = ChildPod::new(Box::new(Recorder::default()));
        pod.layout_child(&mut LayoutCtx::new(), &BoxConstraints::tight(size));
        pod.set_origin(origin);
        pod
    }

    fn recorded(pod: &mut ChildPod) -> Vec<InputEvent> {
        pod.widget_mut()
            .downcast_mut::<Recorder>()
            .expect("recorder pod")
            .events
            .clone()
    }

    fn paint(pod: &mut ChildPod, visible: Option<Rect>) -> (Vec<Op>, Option<Rect>) {
        let mut ctx = PaintCtx::new(Point::ZERO, Size::new(400.0, 400.0));
        ctx.set_visible_rect(visible);
        let mut scene = OpLog::default();
        pod.paint_child(&mut ctx, &mut scene);
        (scene.0, ctx.visible_rect_ref())
    }

    fn dispatch(pod: &mut ChildPod, event: &InputEvent) -> EventResult {
        let mut state = 0u32;
        let mut ctx = EventCtx::new(&mut state, Point::ZERO, Size::new(400.0, 400.0));
        pod.event_child(&mut ctx, event)
    }

    #[test]
    fn a_child_under_scale_and_translate_receives_down_at_its_local_point() {
        let mut pod = recorder_pod(Point::new(10.0, 20.0), Size::new(50.0, 50.0));
        // Local p lands at origin + translate(5, 5) * scale(2) * p.
        pod.set_transform(Some(
            Affine::translate(Vec2::new(5.0, 5.0)) * Affine::scale(2.0),
        ));
        // Local (7, 9) is drawn at (10 + 5 + 14, 20 + 5 + 18) = (29, 43).
        let at = Point::new(29.0, 43.0);
        assert!(pod.contains(at));
        assert_eq!(
            dispatch(&mut pod, &pointer(PointerPhase::Down, at.x, at.y)),
            EventResult::Handled
        );
        assert!(pod.is_active(), "capture bookkeeping is unchanged");
        // Scroll positions and scale focal points take the same mapping; their
        // magnitudes do not.
        dispatch(
            &mut pod,
            &InputEvent::Scroll {
                position: at,
                delta: ScrollDelta::Pixels(0.0, 12.0),
            },
        );
        dispatch(
            &mut pod,
            &InputEvent::Scale(ScaleEvent {
                phase: ScalePhase::Update,
                scale_delta: 1.1,
                focal: at,
                velocity: 0.0,
            }),
        );
        let local = Point::new(7.0, 9.0);
        assert_eq!(
            recorded(&mut pod),
            vec![
                pointer(PointerPhase::Down, local.x, local.y),
                InputEvent::Scroll {
                    position: local,
                    delta: ScrollDelta::Pixels(0.0, 12.0),
                },
                InputEvent::Scale(ScaleEvent {
                    phase: ScalePhase::Update,
                    scale_delta: 1.1,
                    focal: local,
                    velocity: 0.0,
                }),
            ]
        );
        // The child now covers (15..115, 25..125): the untransformed box's
        // corner misses, and a point past its untransformed extent hits.
        assert!(!pod.contains(Point::new(12.0, 22.0)));
        assert!(pod.contains(Point::new(100.0, 100.0)));
        assert!(!pod.contains(Point::new(116.0, 60.0)));
        // A contact's inner event is mapped the same way.
        let contact = InputEvent::PointerContact {
            pointer_id: PointerId::touch(1),
            event: PointerEvent {
                phase: PointerPhase::Move,
                position: at,
                button: PointerButton::Primary,
            },
        };
        dispatch(&mut pod, &contact);
        assert_eq!(
            recorded(&mut pod).last(),
            Some(&InputEvent::PointerContact {
                pointer_id: PointerId::touch(1),
                event: PointerEvent {
                    phase: PointerPhase::Move,
                    position: local,
                    button: PointerButton::Primary,
                },
            })
        );
    }

    #[test]
    fn contains_agrees_with_paint_for_rotated_content_at_the_corners() {
        let size = Size::new(100.0, 100.0);
        let mut pod = recorder_pod(Point::new(40.0, 40.0), size);
        pod.set_transform(Some(Affine::rotate_about(
            FRAC_PI_4,
            Point::new(50.0, 50.0),
        )));
        let (ops, _) = paint(&mut pod, None);
        let [Op::Push(drawn), Op::Rect(rect_origin, rect_size), Op::Pop] = ops.as_slice() else {
            panic!("expected push/rect/pop, got {ops:?}");
        };
        assert_eq!((*rect_origin, *rect_size), (Point::new(40.0, 40.0), size));
        let rect = Rect::from_origin_size(*rect_origin, *rect_size);
        let center = *drawn * rect.center();
        for corner in [
            Point::new(rect.x0, rect.y0),
            Point::new(rect.x1, rect.y0),
            Point::new(rect.x1, rect.y1),
            Point::new(rect.x0, rect.y1),
        ] {
            // Where paint actually put this corner (the parent paints at the
            // absolute origin zero, so absolute space is the container's space).
            let painted = *drawn * corner;
            let inward = (center - painted).normalize();
            assert!(
                pod.contains(painted + inward),
                "just inside painted corner {painted:?}"
            );
            assert!(
                !pod.contains(painted - inward),
                "just outside painted corner {painted:?}"
            );
            // The untransformed box's own corner is outside the painted
            // diamond: the hit test is not an AABB test.
            let unrotated = corner + (rect.center() - corner) * 0.02;
            assert!(!pod.contains(unrotated), "AABB corner {unrotated:?}");
        }
    }

    #[test]
    fn an_untransformed_pod_paints_and_routes_exactly_as_before() {
        let origin = Point::new(12.0, 34.0);
        let size = Size::new(60.0, 40.0);
        let events = [
            pointer(PointerPhase::Down, 20.0, 40.0),
            pointer(PointerPhase::Move, 90.0, 10.0),
            pointer(PointerPhase::Up, 30.0, 50.0),
            InputEvent::Scroll {
                position: Point::new(25.0, 45.0),
                delta: ScrollDelta::Lines(0.0, 1.0),
            },
            InputEvent::Scale(ScaleEvent {
                phase: ScalePhase::Begin,
                scale_delta: 1.0,
                focal: Point::new(15.0, 35.0),
                velocity: 0.0,
            }),
            InputEvent::Housekeeping,
        ];
        let visible = Some(Rect::new(0.0, 0.0, 50.0, 50.0));

        // Baseline: a pod that never had a transform.
        let mut baseline = recorder_pod(origin, size);
        let baseline_paint = paint(&mut baseline, visible);
        for event in &events {
            dispatch(&mut baseline, event);
        }
        let baseline_events = recorded(&mut baseline);
        // The baseline is the pre-transform contract: no transform pushed, the
        // child drawn at its origin, the visible rect threaded unchanged, and
        // every event translated by `-origin` and nothing else.
        assert_eq!(baseline_paint.0, vec![Op::Rect(origin, size)]);
        assert_eq!(baseline_paint.1, visible);
        let translated: Vec<_> = events
            .iter()
            .map(|e| e.translated(-origin.to_vec2()))
            .collect();
        assert_eq!(baseline_events, translated);

        // A pod whose transform was set and then cleared is indistinguishable.
        let mut cleared = recorder_pod(origin, size);
        cleared.set_transform(Some(Affine::rotate(1.0) * Affine::scale(3.0)));
        cleared.set_transform(None);
        assert_eq!(cleared.transform(), None);
        assert_eq!(paint(&mut cleared, visible), baseline_paint);
        for event in &events {
            dispatch(&mut cleared, event);
        }
        assert_eq!(recorded(&mut cleared), baseline_events);
        for point in [
            Point::new(12.0, 34.0),
            Point::new(71.9, 73.9),
            Point::new(72.0, 50.0),
            Point::new(11.9, 50.0),
        ] {
            assert_eq!(cleared.contains(point), baseline.contains(point));
        }
    }

    #[test]
    fn a_singular_transform_hits_nothing_and_never_panics() {
        let origin = Point::new(10.0, 10.0);
        for singular in [
            Affine::scale(0.0),
            Affine::scale_non_uniform(2.0, 0.0),
            Affine::new([1.0, 2.0, 2.0, 4.0, 0.0, 0.0]),
            Affine::new([f64::NAN, 0.0, 0.0, 1.0, 0.0, 0.0]),
        ] {
            let mut pod = recorder_pod(origin, Size::new(50.0, 50.0));
            pod.set_transform(Some(singular));
            for point in [origin, Point::new(20.0, 20.0), Point::new(10.0, 30.0)] {
                assert!(!pod.contains(point), "{singular:?} hit {point:?}");
            }
            // Paint skips the collapsed subtree entirely.
            assert_eq!(
                paint(&mut pod, Some(Rect::new(0.0, 0.0, 99.0, 99.0))).0,
                vec![]
            );
            // An event reaching it through a recorded path still arrives,
            // translated as if untransformed, so a capture can end.
            dispatch(&mut pod, &pointer(PointerPhase::Up, 20.0, 25.0));
            assert_eq!(
                recorded(&mut pod),
                vec![pointer(PointerPhase::Up, 10.0, 15.0)]
            );
            // Semantics never reports NaN bounds.
            let mut sem = SemanticsCtx::new(Size::new(200.0, 200.0), 2);
            pod.semantics_child(&mut sem);
            let update = sem.finish(accesskit::NodeId(1));
            let bounds = update.nodes[0].1.bounds().expect("bounds");
            assert!(
                [bounds.x0, bounds.y0, bounds.x1, bounds.y1]
                    .iter()
                    .all(|v| v.is_finite()),
                "{singular:?} gave {bounds:?}"
            );
        }
    }

    #[test]
    fn a_transformed_pod_maps_the_visible_rect_and_reports_its_bounding_box() {
        let mut pod = recorder_pod(Point::new(10.0, 20.0), Size::new(50.0, 50.0));
        pod.set_transform(Some(Affine::scale(2.0)));
        // Paint: the transform is conjugated by the absolute origin, and the
        // visible rect reaches the child as its preimage. The parent's own
        // visible rect is untouched.
        let visible = Some(Rect::new(10.0, 20.0, 110.0, 120.0));
        let (ops, parent_visible) = paint(&mut pod, visible);
        assert_eq!(parent_visible, visible);
        assert_eq!(
            ops,
            vec![
                Op::Push(
                    Affine::translate(Vec2::new(10.0, 20.0))
                        * Affine::scale(2.0)
                        * Affine::translate(Vec2::new(-10.0, -20.0))
                ),
                Op::Rect(Point::new(10.0, 20.0), Size::new(50.0, 50.0)),
                Op::Pop,
            ]
        );
        // What the child itself culls against: the visible rect mapped back
        // through the inverse — (10, 20) .. (60, 70) in its own absolute frame.
        let seen = std::rc::Rc::new(Cell::new(None));
        let mut probe = ChildPod::new(Box::new(VisibleProbe(seen.clone())));
        probe.layout_child(
            &mut LayoutCtx::new(),
            &BoxConstraints::tight(Size::new(50.0, 50.0)),
        );
        probe.set_origin(Point::new(10.0, 20.0));
        probe.set_transform(Some(Affine::scale(2.0)));
        paint(&mut probe, visible);
        assert_eq!(seen.get(), Some(Rect::new(10.0, 20.0, 60.0, 70.0)));
        // Semantics: the transformed box, (10, 20) .. (110, 120).
        let mut sem = SemanticsCtx::new(Size::new(400.0, 400.0), 2);
        pod.semantics_child(&mut sem);
        let update = sem.finish(accesskit::NodeId(1));
        let bounds = update.nodes[0].1.bounds().expect("bounds");
        assert_eq!(
            (bounds.x0, bounds.y0, bounds.x1, bounds.y1),
            (10.0, 20.0, 110.0, 120.0)
        );
    }
}

#[cfg(test)]
mod contact_release_tests {
    use super::*;
    use crate::event::{ContactPass, PointerButton, PointerEvent, PointerId, PointerPhase};

    /// A leaf that captures on `Down`, opting into the gesture's other contacts
    /// when `opt_in` is set.
    struct Grab {
        opt_in: bool,
    }
    impl Widget for Grab {
        fn layout(&mut self, _ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            bc.constrain(Size::new(20.0, 20.0))
        }
        fn paint(&mut self, _ctx: &mut PaintCtx, _scene: &mut dyn PaintScene) {}
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            if let InputEvent::Pointer(p) = event
                && p.phase == PointerPhase::Down
            {
                ctx.capture_pointer();
                if self.opt_in {
                    ctx.capture_contacts();
                }
            }
            EventResult::Handled
        }
    }

    /// A single-child container that takes the gesture over from its captured
    /// child on any `Move`.
    struct Taker {
        inner: ChildPod,
    }
    impl Widget for Taker {
        fn layout(&mut self, ctx: &mut LayoutCtx, bc: &BoxConstraints) -> Size {
            self.inner.layout_child(ctx, bc);
            bc.constrain(Size::new(20.0, 20.0))
        }
        fn paint(&mut self, ctx: &mut PaintCtx, scene: &mut dyn PaintScene) {
            self.inner.paint_child(ctx, scene);
        }
        fn event(&mut self, ctx: &mut EventCtx, event: &InputEvent) -> EventResult {
            match event {
                InputEvent::Pointer(p)
                    if p.phase == PointerPhase::Move && self.inner.is_active() =>
                {
                    ctx.release_captured_child(&mut self.inner);
                    EventResult::Handled
                }
                _ => self.inner.event_child(ctx, event),
            }
        }
    }

    /// An outer pod around a [`Taker`] around a [`Grab`].
    fn nested(opt_in: bool) -> ChildPod {
        let mut pod = ChildPod::new(Box::new(Taker {
            inner: ChildPod::new(Box::new(Grab { opt_in })),
        }));
        pod.layout_child(
            &mut LayoutCtx::new(),
            &BoxConstraints::tight(Size::new(20.0, 20.0)),
        );
        pod
    }

    fn pointer(phase: PointerPhase) -> InputEvent {
        InputEvent::Pointer(PointerEvent {
            phase,
            position: Point::new(5.0, 5.0),
            button: PointerButton::Primary,
        })
    }

    /// Dispatch into `pod` from a fresh context; whether a capture release
    /// bubbled out of it.
    fn released(pod: &mut ChildPod, phase: PointerPhase) -> bool {
        let mut unit = ();
        let mut ctx = EventCtx::new(&mut unit, Point::ZERO, Size::new(20.0, 20.0));
        pod.event_child(&mut ctx, &pointer(phase));
        ctx.is_capture_released()
    }

    fn inner_active(pod: &mut ChildPod) -> bool {
        pod.widget_mut()
            .downcast_mut::<Taker>()
            .expect("a Taker")
            .inner
            .is_active()
    }

    #[test]
    fn releasing_the_opted_in_child_signals_and_bubbles() {
        let mut pod = nested(true);
        assert!(!released(&mut pod, PointerPhase::Down));
        assert!(pod.holds_contact_opt_in(), "the opt-in below is recorded");
        assert!(
            released(&mut pod, PointerPhase::Move),
            "and its release bubbles"
        );
        assert!(!inner_active(&mut pod), "the child left the active path");
        assert!(pod.is_active(), "the container that took over keeps it");
    }

    #[test]
    fn releasing_a_child_without_the_opt_in_clears_the_link_silently() {
        let mut pod = nested(false);
        released(&mut pod, PointerPhase::Down);
        assert!(!pod.holds_contact_opt_in());
        assert!(!released(&mut pod, PointerPhase::Move));
        assert!(!inner_active(&mut pod));
    }

    #[test]
    fn a_non_claimant_contact_cannot_release_anything() {
        let mut pod = nested(true);
        released(&mut pod, PointerPhase::Down);
        let _pass = ContactPass::enter(PointerId::touch(1), true);
        assert!(!released(&mut pod, PointerPhase::Move));
        assert!(inner_active(&mut pod), "the claimant's link stands");
    }
}