day-spec 0.6.2

Declarative app development API using native UI toolkits
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
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! day-spec: the toolkit specification (DESIGN.md §8).
//!
//! Backends depend only on this crate (never on day-core). One backend is linked per binary;
//! `day-core` is monomorphized over the concrete [`Toolkit`].

use std::any::Any;
use std::collections::HashMap;

pub use day_geometry::*;

pub mod controls;
pub use controls::datetime::{DayDate, DayTime};

pub mod applications;
pub mod capture;
/// Inline markdown → styled runs (docs/markdown.md). Lives here rather than in day-pieces
/// because it produces `TextRun`s, and every format codec beside it reads the same model.
pub mod markdown;
/// Bundled-resource random-access API + the per-backend `ResourceOpener` hook (§18.3).
pub mod resource;
/// Styled text: the document model `label().runs(…)` renders and `day-piece-text-editor` edits,
/// with the Markdown / HTML / RTF codecs over it (docs/texteditor.md).
pub mod styled;
/// Import and export for [`StyledText`]: Markdown, HTML and RTF (docs/texteditor.md).
pub mod styled_codec;
pub mod transfer;

pub use resource::{
    AssetDir, AssetName, FontFamily, ImageName, Resource, ResourceOpener, VectorName,
    resolve_asset_dir, resolve_image_file, resource, set_resource_opener,
};
pub use styled::{
    ListStyle, ParagraphAlign, ParagraphRun, ParagraphStyle, RunStyle, StyledText, Underline,
    coalesce_runs, paragraph_bounds, paragraphs_are_valid,
};
pub use styled_codec::{
    DocStyle, html_to_styled, markdown_to_styled, rtf_to_styled, styled_to_html,
    styled_to_markdown, styled_to_rtf,
};

/// Bundled custom fonts: name-table parsing, runtime font directory, family → file resolution
/// (§18.4). Shared by the CLI stagers and the backends' startup registration. Lives in the leaf
/// `day-fonts` crate (pure std, no `day-geometry`), re-exported here so `day_spec::fonts::…` is
/// unchanged for the backends while the CLI can depend on `day-fonts` alone.
pub use day_fonts as fonts;

/// The route inside a deep-link URL (docs/deep-links.md): everything after `scheme://`,
/// query included (`notes://mail/inbox?hint=x` ⇒ `mail/inbox?hint=x`). A string with no
/// scheme passes through unchanged (it is already a route). One definition, shared by every
/// platform's intake and the dayscript `deep_link` step, so a URL maps to the same route
/// bytes everywhere; percent-decoding stays with the route parser (docs/navigation.md).
pub fn route_of_url(url: &str) -> String {
    match url.split_once("://") {
        Some((_, rest)) => rest.to_string(),
        None => url.to_string(),
    }
}

// ---------------------------------------------------------------------------
// Identity
// ---------------------------------------------------------------------------

/// Interned piece-kind key, e.g. `"day.label"` or `"acme.combobox"`.
pub type PieceKind = &'static str;

/// Declare the built-in piece vocabulary once: the [`Builtin`] enum, its string keys, and the
/// `kinds::*` constants are all generated from this list, so they can never drift apart.
///
/// Adding a variant here is a breaking change for backends: every `Toolkit` must decide how
/// to realize the new kind, and the exhaustive `match Builtin` in each backend's `realize`
/// turns that decision into a compile error rather than a runtime placeholder.
macro_rules! builtin_kinds {
    ($( $(#[$meta:meta])* $variant:ident = $konst:ident => $key:literal ),+ $(,)?) => {
        /// Every piece kind Day itself defines (§5.3). Backends match on this exhaustively in
        /// `realize`; anything outside it is an extension piece resolved through the
        /// [`Registry`] by its string [`PieceKind`].
        #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
        pub enum Builtin {
            $( $(#[$meta])* $variant, )+
        }

        impl Builtin {
            /// This kind's wire key: the same string as the matching `kinds::*` constant.
            pub const fn key(self) -> PieceKind {
                match self { $( Builtin::$variant => $key, )+ }
            }

            /// The built-in this key names, or `None` for an extension piece's kind.
            pub fn from_key(kind: PieceKind) -> Option<Builtin> {
                match kind {
                    $( $key => Some(Builtin::$variant), )+
                    _ => None,
                }
            }

            /// Every built-in, in declaration order (conformance tests iterate it).
            pub const ALL: &'static [Builtin] = &[ $( Builtin::$variant, )+ ];
        }

        /// The built-in piece keys as plain strings, for the registry and the `PieceKind` API.
        pub mod kinds {
            $( $(#[$meta])* pub const $konst: super::PieceKind = super::Builtin::$variant.key(); )+
        }
    };
}

builtin_kinds! {
    /// A dumb native panel (the column/row/stack backing).
    Container = CONTAINER => "day.container",
    Label = LABEL => "day.label",
    Button = BUTTON => "day.button",
    Toggle = TOGGLE => "day.toggle",
    Slider = SLIDER => "day.slider",
    TextField = TEXT_FIELD => "day.text_field",
    /// A native multi-line text editor (docs/textarea.md). Built-in since 2026-07 (previously
    /// the satellite `day-piece-textarea`).
    TextArea = TEXT_AREA => "day.text_area",
    /// A native option picker with menu/segmented/inline stylings (docs/picker.md). Built-in
    /// since 2026-07 (previously the satellite `day-piece-picker`).
    Picker = PICKER => "day.picker",
    Divider = DIVIDER => "day.divider",
    Scroll = SCROLL => "day.scroll",
    Image = IMAGE => "day.image",
    /// Progress indicator: determinate bar (fraction) or indeterminate spinner.
    Progress = PROGRESS => "day.progress",
    Canvas = CANVAS => "day.canvas",
    /// Navigation host (docs/navigation.md): stack on mobile, split panes on desktop.
    Nav = NAV => "day.nav",
    /// One destination's native container inside a NAV host.
    NavPage = NAV_PAGE => "day.nav_page",
    /// Native navigation item list (docs/navigation.md): NSOutlineView source list /
    /// GtkListBox navigation-sidebar / QListWidget / UITableView rows with chevrons.
    NavMenu = NAV_MENU => "day.nav_menu",
    /// Native recycling list (docs/list.md): NSTableView / UITableView / RecyclerView /
    /// GtkListView / QListView. Owns scrolling + cell reuse; Day binds row content on demand.
    List = LIST => "day.list",
    /// A recycled row's content anchor inside a `LIST`; Day adopts the native cell as its handle.
    /// Adopted, never realized: `Toolkit::adopt` wraps the native cell, so backends' `realize`
    /// never sees this kind.
    ListCell = LIST_CELL => "day.list_cell",
    /// Native hierarchical tree (docs/tree.md): NSOutlineView / sidebar collection list /
    /// GtkListView+TreeListModel / WinUI TreeView / ArkTS TreeView. Rows nest, disclose, and
    /// drag-to-reparent; Day binds row content on demand through `Toolkit::attach_tree`.
    /// Row cells are adopted (the same `LIST_CELL` anchor path as `List`).
    Tree = TREE => "day.tree",
    /// A fullscreen cover (docs/cover.md): a modal surface presented over the whole window,
    /// edge-to-edge, driven by `CoverPatch::{Present,Dismiss}`. The handle is the cover's
    /// content container; its frame is native-owned while presented (the backend sizes it to
    /// the safe area and reports it via `Event::FrameChanged`).
    Cover = COVER => "day.cover",
    /// Content beside a trailing inspector pane (docs/inspector.md): the native split whose
    /// second pane is a show/hidable properties panel. Exactly two `INSPECTOR_PANE` children:
    /// the content, then the panel (`InspectorPaneProps::panel`). Only realized where
    /// `Cap::Inspector` answers `Native`; everywhere else the `inspector` piece composes the
    /// pane from plain containers and this kind never reaches the backend.
    Inspector = INSPECTOR => "day.inspector",
    /// One pane's container inside an `INSPECTOR` host: the `NAV_PAGE` of the inspector split.
    /// Its frame is native-owned (the splitter/dock sizes it), reported via
    /// `Event::FrameChanged` on this node; Day lays the pane's content out inside it.
    InspectorPane = INSPECTOR_PANE => "day.inspector_pane",
    /// Two panes with a divider the user drags (docs/split.md): the toolkit's own splitter,
    /// side by side or stacked (`SplitProps::axis`), the first pane's share bound to the app
    /// (`SplitProps::fraction`, reported back as `Event::ValueChanged`). Exactly two
    /// `SPLIT_PANE` children, first then second. Only realized where `Cap::Split` answers
    /// `Native`; everywhere else the `split` piece composes the panes and draws the divider
    /// itself, and this kind never reaches the backend.
    Split = SPLIT => "day.split",
    /// One pane's container inside a `SPLIT` host: native-owned frame (the splitter sizes it),
    /// reported via `Event::FrameChanged` on this node, like an `INSPECTOR_PANE`.
    SplitPane = SPLIT_PANE => "day.split_pane",
    /// A list row's standard content (docs/list.md "List items"): a leading icon, a title, an
    /// optional subtitle and trailing detail, and a check mark, drawn the way the platform
    /// draws its own list rows: a `UIListContentView` with the cell's default content
    /// configuration, a Material list item, an `NSTableCellView`'s image and text, a GTK row
    /// box. Only realized where `Cap::ListItem` answers `Native`; everywhere else the
    /// `list_item` piece composes the same content and this kind never reaches the backend.
    ListItem = LIST_ITEM => "day.list_item",
}

/// Whether a kind is worth asking [`Toolkit::first_baseline`] about (docs/baseline.md).
///
/// A blocklist, not an allowlist: the structural and graphic kinds below have no text of their
/// own, and everything else (including extension pieces like the date/time pickers, whose kinds
/// day-spec has never heard of) is assumed to be worth asking. An extension piece that turns
/// out to have no baseline answers `None`, which costs one query; an allowlist would instead
/// silently leave every extension piece centered, which is the bug this shape avoids.
pub fn kind_has_baseline(kind: PieceKind) -> bool {
    !matches!(
        Builtin::from_key(kind),
        Some(
            Builtin::Container
                | Builtin::Scroll
                | Builtin::Divider
                | Builtin::Image
                | Builtin::Canvas
                | Builtin::Slider
                | Builtin::Toggle
                | Builtin::Progress
                | Builtin::Nav
                | Builtin::NavPage
                | Builtin::NavMenu
                | Builtin::Split
                | Builtin::SplitPane
                | Builtin::List
                | Builtin::ListCell
                | Builtin::Cover
                | Builtin::Inspector
                | Builtin::InspectorPane
        )
    )
}

/// Placeholder leaves: the one hole in Day's rendering that is invisible to a screenshot.
///
/// When a backend has no renderer for a kind it realizes a visible `⟨kind⟩` label rather than
/// failing. That is the right runtime behavior, but it means a missing renderer looks like a
/// rendered app: the walkthrough passes, and the gallery's validator (which counts distinct
/// colors) sees nothing wrong. That is how a stale `skip_on:` survived in the showcase
/// walkthrough after the renderer it skipped had landed.
///
/// So every backend reports here instead of keeping its own warn-once set. The table is process-
/// wide and append-only, which gives dayscript's `assert_no_placeholders` something to assert on
/// (`crates/day-script`): a placeholder becomes a test failure instead of a silent gap.
pub mod placeholder {
    use super::PieceKind;
    use std::collections::BTreeSet;
    use std::sync::{Mutex, OnceLock};

    fn table() -> &'static Mutex<BTreeSet<PieceKind>> {
        static TABLE: OnceLock<Mutex<BTreeSet<PieceKind>>> = OnceLock::new();
        TABLE.get_or_init(|| Mutex::new(BTreeSet::new()))
    }

    /// Record that `toolkit` had no renderer for `kind` and warn, once per kind, however many
    /// nodes of it are realized. Call from a backend's `realize` fallback arm.
    pub fn report(kind: PieceKind, toolkit: &str) {
        let Ok(mut seen) = table().lock() else { return };
        if seen.insert(kind) {
            log::warn!(
                "no renderer for piece kind \"{kind}\" on {toolkit} — is the piece's \
                 {toolkit} feature enabled? (rendering a placeholder)"
            );
        }
    }

    /// Every kind that has rendered a placeholder in this process, sorted. Empty is the goal.
    pub fn seen() -> Vec<PieceKind> {
        table()
            .lock()
            .map(|s| s.iter().copied().collect())
            .unwrap_or_default()
    }
}

/// Downcast a realize/update payload to the props/patch type a backend arm expects,
/// warning (once per kind, via [`placeholder::report`]) instead of panicking on a
/// mismatch. A mismatch means a piece registered under a builtin key or a day-core
/// regression; degrade to the placeholder path, never abort: most backend arms run
/// inside native up-calls, where a panic is a process kill.
pub fn props_of<'a, T: 'static>(
    kind: PieceKind,
    toolkit: &str,
    any: &'a dyn std::any::Any,
) -> Option<&'a T> {
    let p = any.downcast_ref::<T>();
    if p.is_none() {
        placeholder::report(kind, toolkit);
    }
    p
}

/// Pointer-keyed per-view side tables with an automatic release sweep.
///
/// Backends keep auxiliary per-view state in thread-local maps keyed by the native
/// handle's address. Historically each map needed its own line in `release()`, a
/// checklist that drifted repeatedly (missed entries have produced both leaks and
/// stale-pointer CI segfaults, since a freed address gets recycled). A [`crate::sidetable::SideTable`]
/// registers itself with a per-thread sweeper list at construction, so a backend's
/// `release()` calls [`crate::sidetable::sweep`] once and every table, present and future, drops its
/// entry for that handle, running its teardown hook if one was given.
pub mod sidetable {
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::rc::Rc;

    /// One table's "remove this key" hook, registered at construction.
    type Sweeper = Rc<dyn Fn(usize)>;

    thread_local! {
        static SWEEPERS: RefCell<Vec<Sweeper>> = const { RefCell::new(Vec::new()) };
    }

    /// A pointer-keyed map swept automatically by [`crate::sidetable::sweep`]. Construct inside a
    /// `thread_local!` initializer; the optional teardown hook runs for each removed
    /// value (release a retained native object, dispose an owned child, …), both on sweep
    /// and on plain [`SideTable::remove`], so teardown cannot be bypassed by accident.
    pub struct SideTable<V: 'static> {
        map: Rc<RefCell<HashMap<usize, V>>>,
        teardown: Option<Rc<dyn Fn(V)>>,
    }

    impl<V> Default for SideTable<V> {
        fn default() -> Self {
            Self::new()
        }
    }

    impl<V> SideTable<V> {
        pub fn new() -> Self {
            Self::build(None)
        }

        /// A table whose values need active teardown when their view goes away.
        pub fn with_teardown(teardown: impl Fn(V) + 'static) -> Self {
            Self::build(Some(Rc::new(teardown)))
        }

        fn build(teardown: Option<Rc<dyn Fn(V)>>) -> Self {
            let map: Rc<RefCell<HashMap<usize, V>>> = Rc::default();
            let (m, t) = (map.clone(), teardown.clone());
            SWEEPERS.with(|s| {
                s.borrow_mut().push(Rc::new(move |key| {
                    // Remove under the borrow, tear down outside it: hooks may re-enter
                    // toolkit code that reads other tables.
                    let v = m.borrow_mut().remove(&key);
                    if let (Some(v), Some(t)) = (v, &t) {
                        t(v);
                    }
                }));
            });
            SideTable { map, teardown }
        }

        pub fn insert(&self, key: usize, value: V) -> Option<V> {
            self.map.borrow_mut().insert(key, value)
        }

        /// Remove and tear down the entry (returns `None` always when a teardown hook
        /// exists, because the value is consumed by it; use [`SideTable::take`] to skip it).
        pub fn remove(&self, key: usize) -> Option<V> {
            let v = self.map.borrow_mut().remove(&key)?;
            match &self.teardown {
                Some(t) => {
                    t(v);
                    None
                }
                None => Some(v),
            }
        }

        /// Remove without running the teardown hook (the caller takes ownership).
        pub fn take(&self, key: usize) -> Option<V> {
            self.map.borrow_mut().remove(&key)
        }

        pub fn contains(&self, key: usize) -> bool {
            self.map.borrow().contains_key(&key)
        }

        pub fn get(&self, key: usize) -> Option<V>
        where
            V: Clone,
        {
            self.map.borrow().get(&key).cloned()
        }

        /// Run `f` on the value in place (returns `None` if absent).
        pub fn with<R>(&self, key: usize, f: impl FnOnce(&mut V) -> R) -> Option<R> {
            self.map.borrow_mut().get_mut(&key).map(f)
        }

        /// Run `f` over every `(key, value)` (immutable; do not re-enter this table).
        pub fn for_each(&self, mut f: impl FnMut(usize, &V)) {
            for (k, v) in self.map.borrow().iter() {
                f(*k, v);
            }
        }
    }

    /// Remove `key` from every table registered on this thread, running teardowns.
    /// Call once from a backend's `release()` (and once per auxiliary native object a
    /// release frees, e.g. an owned content container).
    pub fn sweep(key: usize) {
        // Clone the sweeper list first: a teardown may construct a new SideTable
        // (registering a sweeper) without deadlocking on the borrow.
        let sweepers: Vec<Sweeper> = SWEEPERS.with(|s| s.borrow().clone());
        for f in sweepers {
            f(key);
        }
    }
}

/// Containment for FFI entry points: native callbacks, JNI up-calls, posted-closure
/// trampolines. A Rust panic unwinding out of an `extern "C"` frame is undefined
/// behavior (an abort), so every backend trampoline runs its body through
/// [`ffi_guard::contain`]: a caught panic is reported, the installed recovery hook
/// restores runtime coherence (day-core installs the reactive runtime's
/// `recover_from_panic` at boot), and the given default is returned.
pub mod ffi_guard {
    use std::sync::OnceLock;

    static RECOVERY: OnceLock<fn()> = OnceLock::new();

    /// Install the post-panic recovery hook (idempotent; first install wins). day-core
    /// registers `day_reactive::recover_from_panic` here so a contained panic cannot
    /// leave the reactive observer stack stranded.
    pub fn set_recovery(f: fn()) {
        let _ = RECOVERY.set(f);
    }

    /// Run `f`, containing any panic; on panic, report, run the recovery hook, and
    /// return `default`.
    pub fn contain<R>(default: R, f: impl FnOnce() -> R) -> R {
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {
            Ok(r) => r,
            Err(payload) => {
                let msg = payload
                    .downcast_ref::<&str>()
                    .map(|s| s.to_string())
                    .or_else(|| payload.downcast_ref::<String>().cloned())
                    .unwrap_or_else(|| "<non-string panic>".into());
                log::error!("panic contained at an FFI boundary: {msg}");
                if let Some(recover) = RECOVERY.get() {
                    recover();
                }
                default
            }
        }
    }
}

/// Realized-node identity as seen by backends (day-core's slotmap key, FFI-encoded).
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct NodeId(pub u64);

/// Default navigation sidebar width (split presentation) until the pane reports its size.
/// Semantic container surfaces (see `ContainerProps::role`): each backend maps a role to its
/// own theme-adaptive material so the fill tracks light/dark mode without app code.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SurfaceRole {
    /// A form `section` card, the platform's grouped-content background: AppKit quaternary
    /// system fill, libadwaita `.card`, Qt `palette(alternate-base)`, UIKit tertiary system
    /// fill, Material surface-container, XAML card background brush.
    SectionCard,
    /// The window's own background, the surface a page sits on: what an opaque cover paints
    /// by default, and the card of a composed modal sheet (docs/cover.md "Modal sheet").
    Window,
    /// The layer between a composed modal sheet and the page under it, which says the page is
    /// out of reach until the sheet goes. The container's `background` is the plain dimming a
    /// backend draws when it has no material of its own; the web frosts the page instead.
    Scrim,
}

pub const NAV_SIDEBAR_WIDTH: f64 = 240.0;

/// Drag limits for a navigation host's sidebar pane, around [`NAV_SIDEBAR_WIDTH`]. Shared by the
/// desktops whose divider the user can drag (docs/navigation.md): AppKit enforces both through
/// its `NSSplitViewItem`; Qt honors the minimum through the pane's own minimum size and leaves
/// the maximum to the user.
pub const NAV_SIDEBAR_MIN_W: f64 = 160.0;
pub const NAV_SIDEBAR_MAX_W: f64 = 400.0;

/// Default preferred width of a navigation host's content-list pane
/// (`props::NavProps::list_width`, docs/navigation.md), Mail's message-list proportion.
pub const NAV_LIST_WIDTH: f64 = 300.0;

/// Drag limits for the content-list pane, around the app's preferred width; the same split of
/// duties as the sidebar's.
pub const NAV_LIST_MIN_W: f64 = 220.0;
pub const NAV_LIST_MAX_W: f64 = 560.0;

/// Reserved id for window-level events (resize, lifecycle): day-core routes it to the root.
pub const WINDOW_NODE: NodeId = NodeId(u64::MAX);

/// Which nodes handle the non-text keys (docs/menus.md). Keys follow focus (the focused piece
/// hears them and nobody else), so a backend whose focused view would have to claim a key from
/// the platform's own dispatch (AppKit's responder chain, the DOM's default action) has to know
/// whether the app wants it before swallowing it. An unclaimed arrow has to keep traveling, or
/// a canvas inside a scroll view would silently eat the keys that scroll it.
///
/// It lives here, in day-spec, rather than in day-core: `day-toolkit-dom` depends on day-spec alone,
/// and this is a fact about a node that both sides need.
pub mod keys {
    use super::NodeId;
    use std::cell::RefCell;
    use std::collections::HashSet;

    thread_local! {
        static HANDLED: RefCell<HashSet<NodeId>> = RefCell::new(HashSet::new());
    }

    /// Declare that `node` has a key handler (what `Decorate::on_key` records at build).
    pub fn mark(node: NodeId) {
        HANDLED.with(|h| h.borrow_mut().insert(node));
    }

    /// Whether `node` has one.
    pub fn handled(node: NodeId) -> bool {
        HANDLED.with(|h| h.borrow().contains(&node))
    }
}

/// Raw foreign native handle for polyglot adoption (§15.3).
pub type RawHandle = *mut std::ffi::c_void;

// ---------------------------------------------------------------------------
// Events (§8.3)
// ---------------------------------------------------------------------------

/// The wire table for backends whose native side reaches Rust through one numeric-kind
/// trampoline (Android's JNI `nativeOnEvent`, ArkUI's `day_arkui_on_event`). This enum
/// defines those kind numbers; the Java and C++ sides carry mirrored constants that parity
/// tests check against these discriminants (so a collision or drift fails `cargo test` on the
/// host instead of silently mis-decoding events on a device). AppKit/UIKit/GTK/Qt emit `Event`
/// values directly and never use these numbers; XAML uses per-event callbacks with its own
/// small local codes.
///
/// Payload conventions ride `(num: f64, text: String)` per kind, documented on each variant.
pub mod bridge {
    /// One numeric event kind. `as i32` is the wire value.
    #[repr(i32)]
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub enum BridgeKind {
        /// Click/press. No payload.
        Pressed = 0,
        /// `text` = the field's full new text.
        TextChanged = 1,
        /// `num` != 0 ⇒ on.
        ToggleChanged = 2,
        /// `num` = the new value.
        ValueChanged = 3,
        /// `num` = the selected index.
        SelectionChanged = 4,
        /// `num` == 1 ⇒ the native side already popped (predictive back / up arrow).
        NavBack = 5,
        /// Nav/tab page size report; `text` = `"w,h"` in px (Rust divides by density).
        FrameChanged = 6,
        /// Warm deep link; `text` = the route.
        Deeplink = 7,
        /// Modal answered with a button; `num` = the button index.
        PresentButton = 8,
        /// Modal answered with text; `text` = the entry.
        PresentText = 9,
        /// Modal dismissed.
        PresentDismissed = 10,
        /// Gesture; `num` = phase (0 tap, 1 began, 2 changed, 3 ended), `text` = `"x,y,tx,ty"` px.
        Gesture = 11,
        /// Piece-defined open channel (`Event::Custom` with an empty tag): the piece reads the
        /// raw `num`/`text` payload.
        Custom = 12,
        /// Menu selection; the event's node id is the chosen action's dispatch id.
        MenuAction = 13,
        /// App lifecycle; `num` = the phase code (`day_spec::Lifecycle` order).
        Lifecycle = 14,
        /// File-picker answer; `text` = chosen locators joined by the unit separator.
        PresentFile = 15,
        /// `num` != 0 ⇒ gained keyboard focus.
        FocusChanged = 16,
        /// IME action / Return.
        Submitted = 17,
        /// Root size change; `text` = `"w,h"` in px. Routed to `WINDOW_NODE` as a window
        /// resize (the rail rotation, late inset passes, and the soft keyboard ride).
        WindowResized = 18,
        /// Safe-area report from an edge-to-edge backend; `text` =
        /// `"top,bottom,leading,trailing"` in px (Rust divides by density and feeds
        /// `day_core::set_safe_area`). Node id ignored; no `Event` is emitted.
        SafeArea = 19,
        /// A secondary window closed (docs/windows.md); the node id is the window's root.
        WindowClosed = 20,
        /// A secondary window's key/active state changed; `num` != 0 ⇒ focused.
        WindowFocused = 21,
        /// `num` = the settled value: the drag ended (see `Event::ValueCommitted`). A backend
        /// that cannot tell a settled value from a moving one sends only `ValueChanged`.
        ValueCommitted = 22,
        /// Inline search on a `.searchable()` navigation surface (docs/search.md): the field's
        /// new text, against the nav host's node. `num` = 1 ⇒ the text was submitted (Return or
        /// the keyboard's Search key), decoding to [`crate::Event::SearchSubmitted`].
        SearchChanged = 23,
        /// The toolkit's own adaptive nav container changed presentation and is reporting it
        /// (docs/size-classes.md). `num` = 1.0 for split, 0.0 for stacked.
        NavPresentation = 24,
        /// The system switched between light and dark appearance. No payload; node id ignored
        /// and no `Event` is emitted; Rust calls `day_core::note_appearance_changed`, the same
        /// thing AppKit's and GTK's own scheme observers do.
        AppearanceChanged = 25,
        /// A fullscreen cover's hide transition finished (docs/cover.md); no payload, and the
        /// node id is the cover's. Decodes to [`crate::Event::CoverHidden`].
        CoverHidden = 26,
        /// A styled text run's link was tapped (docs/text-runs.md); `text` = the run's target.
        /// Decodes to [`crate::Event::LinkActivated`].
        LinkActivated = 27,
        /// The platform's own undo affordance fired (⌘Z, a three-finger swipe, the Edit menu
        /// through a native front); `num` != 0 ⇒ redo.
        UndoInvoked = 28,
        /// A toolbar item produced a value (docs/toolbars.md): the node id is the item's
        /// dispatch action; `text` = `"on"` with `num` != 0 ⇒ a toggle turned on, `"on"` with
        /// 0 ⇒ off, `"sel"` with `num` = the chosen segment, `"text:<query>"` ⇒ a search
        /// item's new text, `"submit:<query>"` ⇒ that text submitted. Decodes to
        /// [`crate::Event::ToolbarChanged`]. A plain toolbar button sends `MenuAction`.
        ToolbarChanged = 30,
        /// An activated list row; `num` is its current index.
        ListActivated = 31,
        /// External document copied into app storage; `text` = its local locator.
        DocumentOpened = 32,
        /// The user's reduce-motion setting flipped (docs/accessibility.md). No payload; node
        /// id ignored and no `Event` is emitted; Rust calls `day_core::note_motion_changed`, as
        /// the desktop backends' own observers do.
        ReduceMotionChanged = 33,
        /// A non-text key reached the focused node (docs/menus.md); `text` = the day key name
        /// (`"ArrowLeft"`, `"5"`, …), `num` = the [`crate::KeyEvent`] modifier mask. Decodes to
        /// [`crate::Event::Key`].
        Key = 29,
        /// A window's display state changed (docs/windows.md): `num` = the
        /// [`crate::WindowState`] code (0 normal, 1 minimized, 2 maximized, 3 fullscreen), against
        /// the window's root node, or [`crate::WINDOW_NODE`] for the primary. Decodes to
        /// [`crate::Event::WindowStateChanged`] through [`crate::WindowState::from_code`].
        WindowStateChanged = 34,
        /// Native pull-to-refresh request; no payload.
        RefreshRequested = 35,
    }

    impl BridgeKind {
        /// Every variant, for uniqueness/parity tests and exhaustive dispatch.
        pub const ALL: [BridgeKind; 36] = [
            BridgeKind::Pressed,
            BridgeKind::TextChanged,
            BridgeKind::ToggleChanged,
            BridgeKind::ValueChanged,
            BridgeKind::SelectionChanged,
            BridgeKind::NavBack,
            BridgeKind::FrameChanged,
            BridgeKind::Deeplink,
            BridgeKind::PresentButton,
            BridgeKind::PresentText,
            BridgeKind::PresentDismissed,
            BridgeKind::Gesture,
            BridgeKind::Custom,
            BridgeKind::MenuAction,
            BridgeKind::Lifecycle,
            BridgeKind::PresentFile,
            BridgeKind::FocusChanged,
            BridgeKind::Submitted,
            BridgeKind::WindowResized,
            BridgeKind::SafeArea,
            BridgeKind::WindowClosed,
            BridgeKind::WindowFocused,
            BridgeKind::ValueCommitted,
            BridgeKind::SearchChanged,
            BridgeKind::NavPresentation,
            BridgeKind::AppearanceChanged,
            BridgeKind::CoverHidden,
            BridgeKind::LinkActivated,
            BridgeKind::UndoInvoked,
            BridgeKind::Key,
            BridgeKind::ToolbarChanged,
            BridgeKind::ListActivated,
            BridgeKind::DocumentOpened,
            BridgeKind::ReduceMotionChanged,
            BridgeKind::WindowStateChanged,
            BridgeKind::RefreshRequested,
        ];
    }

    #[cfg(test)]
    mod tests {
        use super::BridgeKind;

        /// The kind-15 lesson: two meanings on one number decode silently as the first. Every
        /// discriminant must be unique, and the table must stay dense enough to spot gaps.
        #[test]
        fn discriminants_are_unique() {
            let mut seen = std::collections::BTreeSet::new();
            for k in BridgeKind::ALL {
                assert!(
                    seen.insert(k as i32),
                    "duplicate bridge kind number {} ({k:?})",
                    k as i32
                );
            }
            assert_eq!(seen.len(), BridgeKind::ALL.len());
        }

        /// `ALL` is what the uniqueness check above sees, so a variant left out of it is a variant
        /// nothing checks, which is how `SearchChanged` and `NavPresentation` sat outside the
        /// table. The wire numbers are assigned densely from 0, so demanding the set be exactly
        /// `0..len` catches both a gap and an omission.
        #[test]
        fn table_covers_every_wire_number() {
            let mut nums: Vec<i32> = BridgeKind::ALL.iter().map(|k| *k as i32).collect();
            nums.sort_unstable();
            let dense: Vec<i32> = (0..BridgeKind::ALL.len() as i32).collect();
            assert_eq!(
                nums, dense,
                "bridge kinds must be dense from 0 — a missing entry means a variant no test sees"
            );
        }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    Pressed,
    TextChanged(String),
    Submitted,
    ToggleChanged(bool),
    ValueChanged(f64),
    /// A continuous control's value settled: the drag ended (mouse/touch up), or the value moved
    /// by a discrete action (a keyboard arrow, a click on the track). Always preceded by the
    /// `ValueChanged` carrying the same value.
    ///
    /// The pair exists because one gesture produces two different facts. `ValueChanged` is the
    /// live one (bindings follow it so the UI tracks the thumb) and it fires continuously, which
    /// is why nothing durable should key off it: a drag from 1 to 100 and back to 50 emits every
    /// value in between. `ValueCommitted` fires once, with the value the user chose, and is what
    /// a recording, a log, or a refetch should use.
    ///
    /// A backend that cannot tell the two apart emits only `ValueChanged`; its sliders then do not
    /// record (docs/coverage-matrix.md).
    ValueCommitted(f64),
    SelectionChanged(i64),
    /// A list row was activated: desktop double-click/Enter, or a touch tap.
    /// Separate from selection so keyboard browsing need not open or play the row.
    ListActivated(usize),
    /// The platform's own undo affordance fired through a native front (⌘Z on the Edit menu,
    /// a three-finger swipe, shake-to-undo); `redo` distinguishes the pair. Only backends
    /// with a native undo system emit it; everywhere else the app's own controls call the
    /// stack directly and this event never exists (docs/model.md).
    Undo {
        redo: bool,
    },
    /// The platform's own standard edit command fired through its native route (Edit ▸
    /// Cut/Copy/Paste, ⌘X/⌘C/⌘V, the browser's `copy`/`paste` DOM events) with no text
    /// widget claiming it first; the app's edit bridge answers (docs/menus.md). Transport
    /// is the system clipboard (day-part-clipboard), not the event.
    Edit(EditOp),
    /// A multi-select list's selection changed: the full set of selected row indices,
    /// ascending (empty = nothing selected). Emitted instead of `SelectionChanged` where
    /// `ListProps::multi_select` is honored (docs/list.md).
    SelectionSet(Vec<i64>),
    FocusChanged(bool),
    Tap(Point),
    /// A link run inside a label was activated; the payload is [`TextRun::link`] verbatim.
    LinkActivated(String),
    LongPress(Point),
    /// A context-menu summon reported by a toolkit that presents no native menu of its own
    /// (web-dom): the pieces layer shows the composed menu (docs/menus.md). `local` is the
    /// point in the node's own coordinates (what the app's provider receives); `window` the
    /// same point in window coordinates (where the composed panel goes). Toolkits that serve
    /// context menus natively never emit this.
    ContextMenu {
        local: Point,
        window: Point,
    },
    /// A drag/pan gesture (docs/shapes.md). `location` is in the node's local coordinates;
    /// `translation` is the cumulative movement since `Began`.
    Drag {
        phase: DragPhase,
        location: Point,
        translation: Point,
    },
    /// A pinch/magnify gesture over the node (docs/shapes.md): `scale` is cumulative since
    /// `Began` (1.0 = unchanged), `location` the gesture's centroid in local coordinates,
    /// the anchor a zoom keeps stationary. Only nodes that enabled
    /// [`GestureKind::Pinch`] receive it; a backend with no recognizer emits nothing.
    Pinch {
        phase: DragPhase,
        scale: f64,
        location: Point,
    },
    /// A viewport pan over the node (docs/shapes.md): `delta` is the movement since the
    /// previous event; incremental, not cumulative, because desktop wheels have no gesture
    /// session to accumulate over (a discrete wheel tick arrives as a lone `Changed`).
    /// Two-finger touch pans bracket theirs with `Began`/`Ended`. Distinct from
    /// [`Event::Drag`], the primary pointer's press-drag.
    Pan {
        phase: DragPhase,
        delta: Point,
        location: Point,
    },
    /// The pointer moved over the node, or left it (docs/canvas.md "Interaction"). `location` is
    /// in the node's local coordinates. Phases follow the drag vocabulary: `Began` on entry,
    /// `Changed` for each move, `Ended` on exit, where `location` is the last point seen inside,
    /// so a handler always knows where the pointer went out.
    ///
    /// Only nodes that enabled [`GestureKind::Hover`] receive it, and only on a device with a
    /// pointer at all.
    Hover {
        phase: DragPhase,
        location: Point,
    },
    ScrollChanged(Point),
    /// A canvas node was re-framed by layout; re-record (§11). Nav pane/page containers
    /// also report their allocated size with this (docs/navigation.md).
    FrameChanged(Size),
    /// Native back navigation (iOS back button/swipe, Android system back or toolbar up).
    /// `already_popped` = the toolkit already performed the pop natively (iOS); the nav
    /// host then syncs its stack without re-issuing `NavPatch::Popped`.
    NavBack {
        already_popped: bool,
    },
    /// A nav host's own adaptive container changed presentation, and Day is being told about it
    /// after the fact (docs/size-classes.md).
    ///
    /// The counterpart to [`props::NavPatch::Presentation`], for the toolkits that answer
    /// `Cap::NavRepresent = Emulated`: `UISplitViewController` collapsing as a Pro Max iPhone
    /// rotates into portrait, `SlidingPaneLayout` deciding at measure time that two panes no
    /// longer fit. Day did not ask for it and must not fight it; the pieces layer only
    /// reconciles what follows, which is the selection rule (a split presentation cannot draw an
    /// empty detail pane, so expanding with nothing selected picks the first item).
    ///
    /// Emitted on the NAV host node, and only when the presentation actually changed.
    NavPresentationChanged(props::NavPresentation),
    Key(KeyEvent),
    Pointer(PointerEvent),
    WindowResized(Size),
    /// The platform asks the app to show a route (docs/navigation.md), a runtime deep link:
    /// on web-dom, the URL hash changing under the app (hand-edited, or browser back/forward);
    /// on mobile, a warm scheme link (iOS `application:openURL:`, Android `onNewIntent` via
    /// `BridgeKind::Deeplink`). Emitted on [`WINDOW_NODE`] (day-core answers with `navigate()`
    /// when the route differs from the current one) or on the active nav host's node (the nav
    /// piece answers with `navigate()` itself, docs/deep-links.md). Launch-time deep links use
    /// `DAY_DEEPLINK`/`set_launch_deeplink` instead; this variant is for changes while the
    /// app runs.
    RouteRequested(String),
    /// A native modal answered request `req` (docs/dialogs.md).
    PresentResult {
        req: u64,
        result: present::PresentResult,
    },
    /// A decode started by [`Toolkit::decode_image`] finished (docs/images.md).
    ///
    /// Keyed by request id like [`Event::PresentResult`], and for the same reason: the answer
    /// belongs to a waiting caller, not to a tree node. It never crosses a native boundary
    /// (every backend raises it from its own Rust arm once the platform decoder answers), so it
    /// has no [`bridge::BridgeKind`], exactly like the completion events dialogs use in-process.
    ///
    /// No bitmap id rides here: day-core minted it and handed it to the backend with the bytes,
    /// so it already knows which image a request answers for. A backend that stored the image
    /// under that id has nothing more to say than the facts it read.
    ImageDecoded {
        req: u64,
        result: Result<BitmapInfo, ImageError>,
    },
    /// An encode started by [`Toolkit::encode_image`] finished (docs/images.md): the encoded
    /// bytes, or why they could not be produced.
    ImageEncoded {
        req: u64,
        result: Result<Vec<u8>, ImageError>,
    },
    /// A canvas drawing started by [`Toolkit::render_bitmap`] finished rendering
    /// (docs/canvas.md "Exporting"). Keyed by request id like [`Event::ImageDecoded`], and like
    /// it carries no bitmap id: day-core minted the id and handed it over with the ops, so the
    /// answer is only the facts of the image the backend stored under it.
    BitmapRendered {
        req: u64,
        result: Result<BitmapInfo, ExportError>,
    },
    /// A PDF started by [`Toolkit::render_pdf`] finished (docs/canvas.md "Exporting"): the
    /// document's bytes, or why they could not be produced.
    PdfRendered {
        req: u64,
        result: Result<Vec<u8>, ExportError>,
    },
    /// An open, piece-defined event (§8.2). `tag` names the event for in-process emitters (a static
    /// literal); it is empty for events that cross a native boundary (JNI/C-ABI), which carry only the
    /// primitive `num`/`text` payload. A piece's `cx.on` reads whichever fields it needs. This is the
    /// escape hatch for events the fixed variants above don't cover (a web view's URL, a picked date, …).
    Custom {
        tag: &'static str,
        num: f64,
        text: String,
    },
    /// A menu item (app menu or context menu) with this action id was activated (§ menus). day-core
    /// routes it to the app closure registered for the id. Standard-role items don't carry an id
    /// (`role` items are handled natively) so they never emit this.
    MenuAction(u64),
    /// A toolbar item produced a value: a search field's text, a toggle's new state
    /// (docs/toolbars.md). `action` is the item's dispatch id, from the same registry
    /// [`Event::MenuAction`] uses, and day-core routes it to the closure registered for it.
    /// A plain toolbar button has no value and emits `MenuAction` instead.
    ToolbarChanged {
        action: u64,
        value: ToolbarValue,
    },
    /// A searchable navigation surface's field changed (docs/search.md). Emitted against the nav
    /// host's node, not through the toolbar's dispatch registry: search belongs to the surface,
    /// so the field can move between the toolbar and the navigation list without the app
    /// re-registering anything.
    SearchChanged(String),
    /// The user picked a different scope. Carries the index into `SearchProps::scopes`.
    SearchScopeChanged(usize),
    /// The user chose one of `SearchProps::suggestions`, by index. The toolkit has already put
    /// that completion in the field and emitted [`Event::SearchChanged`] for it; this says which
    /// one, for an app that wants to act on the choice itself.
    SearchSuggestionChosen(usize),
    /// The user submitted the inline field's text with its Return or Search key. Emitted
    /// after the last [`Event::SearchChanged`], with the text as submitted, for a search that
    /// runs on demand (a server query) rather than narrowing as the text changes.
    SearchSubmitted(String),
    /// The app moved through a lifecycle phase (docs/lifecycle.md). Backends emit this from the
    /// native app/activity delegate; day-core routes it to the app's `on_lifecycle` handlers.
    Lifecycle(Lifecycle),
    /// A secondary native window closed (the title-bar close, a platform gesture such as an
    /// app-switcher swipe or an activity finish, or `Toolkit::close_window`); emitted on the
    /// window's root node after the platform committed the close. day-core disposes the
    /// window's subtree on receipt, so native and programmatic closes share one teardown
    /// path (docs/windows.md). Never emitted for the primary window (its close terminates
    /// the app).
    WindowClosed,
    /// A secondary window's key/active state changed; emitted on the window's root node.
    /// day-core tracks the focused window with it (dialog parenting, dayscript targeting).
    WindowFocused(bool),
    /// A window's display state changed (docs/windows.md): the user minimized, zoomed or took it
    /// fullscreen, or a [`WindowChange::State`] request landed. Emitted on the window's root node
    /// (the primary's may arrive on [`WINDOW_NODE`]); day-core feeds the window's `state()`
    /// signal with it, so the app reads what the platform did rather than what it asked for.
    WindowStateChanged(WindowState),
    /// A native list committed a drag-reorder (docs/list.md): row `from` landed at row `to`.
    /// Emitted on the `LIST` node by the list piece's commit hook: the reorder driver
    /// rotates its snapshot synchronously inside the platform's drop callback, then reports
    /// through the event queue so the app's `on_reorder` never runs inside a native animation
    /// callstack.
    ListReorder {
        from: usize,
        to: usize,
    },
    /// A regrouping sidebar committed a drop (`props::NavMenuProps::regroup`, docs/navigation.md
    /// "Moving rows between sections"), in item indices into the rows as they were before the
    /// move: row `from` now sits in the section whose first row is item `section` (item 0 for
    /// rows above the first header), before item `before`, or at that section's end for
    /// `None`. `before` is never `from`. Emitted on the `NAV_MENU` node by a toolkit whose
    /// `Cap::NavReorder` is `Native`, deferred through the event queue exactly as
    /// [`Event::ListReorder`] is; the nav validates it against the app's rules before reporting.
    NavRegroup {
        from: usize,
        section: usize,
        before: Option<usize>,
    },
    /// A native list committed a swipe-delete (docs/list.md): the row at this index is gone.
    /// Deferred through the event queue exactly as [`Event::ListReorder`] is.
    ListDelete(usize),
    /// The native pull-to-refresh control requested an update. The app owns its busy state.
    RefreshRequested,
    /// A native list activated a swipe action (docs/list.md): the user pressed button `action`
    /// (an index into the row's [`ListSwipe::actions_at`] offer for `edge`) on row `index`, or
    /// swiped clear across for the edge's first action. Emitted on the `LIST` node by the list
    /// piece's commit hook and deferred through the event queue exactly as
    /// [`Event::ListReorder`] is, so the app's handler never runs inside a native animation
    /// callstack.
    ListSwipe {
        index: usize,
        edge: SwipeEdge,
        action: usize,
    },
    /// A fullscreen cover's hide transition finished (docs/cover.md): the content can now be
    /// disposed. Answers [`props::CoverPatch::Dismiss`]; delivery is a hard guarantee, and
    /// backends over-report rather than under-report; consumers gate on their own closing
    /// flag, so duplicates and belated reports are no-ops.
    CoverHidden,
    /// The user showed or hid an inspector pane through a native affordance (a dock widget's
    /// close button, a divider dragged shut) rather than through Day (docs/inspector.md).
    /// Emitted on the `kinds::INSPECTOR` node, and only when the visibility actually changed;
    /// the piece writes it back to the bound signal. Applying
    /// [`props::InspectorPatch::Visible`] must never re-emit it (the from-native echo rule).
    InspectorChanged(bool),
    /// The user disclosed or collapsed a tree row through the native affordance (docs/tree.md).
    /// Emitted on the `kinds::TREE` node; the piece writes it back to the app's expansion
    /// signal. Applying [`props::TreePatch::Expand`] must never re-emit it (the from-native
    /// echo rule).
    TreeExpanded {
        token: u64,
        expanded: bool,
    },
    /// A native tree committed a drag move (docs/tree.md): `token` now sits under `parent`
    /// (`None` = the root) at `index` (`None` = dropped onto the parent, an append). Deferred
    /// through the event queue exactly as [`Event::ListReorder`] is; the app's `on_move`
    /// writes its own data, whose refresh reloads the tree.
    TreeMove {
        token: u64,
        parent: Option<u64>,
        index: Option<usize>,
    },
    /// A tree's selection changed: the full set of selected row tokens (empty = cleared).
    /// Token-addressed, since a tree cannot speak row indices: expanding a row renumbers
    /// everything below it (docs/tree.md).
    TreeSelection(Vec<u64>),
}

impl Event {
    /// Build a text-carrying [`Event::Custom`] (with `num` defaulted to 0), the common case for an
    /// in-process piece reporting a value back: `emit(node, Event::custom("webview:url", url))`.
    pub fn custom(tag: &'static str, text: impl Into<String>) -> Event {
        Event::Custom {
            tag,
            num: 0.0,
            text: text.into(),
        }
    }
}

/// An app-lifecycle phase (docs/lifecycle.md). Each backend maps these onto its OS's native app /
/// activity delegate. Some phases only exist on some platforms (a mobile app enters the
/// background and can be low on memory, a desktop app cannot), so [`Lifecycle::is_universal`]
/// marks the ones every backend delivers, and [`Toolkit::supports_lifecycle`] reports per-backend
/// truth.
///
/// Rough native mapping:
///
/// | phase | AppKit | UIKit | GTK | Qt | Android | XAML |
/// |---|---|---|---|---|---|---|
/// | `WillLaunch` / `DidLaunch` | `applicationWill/DidFinishLaunching` | same | `startup`/mount | mount | `onCreate` | window create |
/// | `DidBecomeActive` | `didBecomeActive` | `didBecomeActive` | `notify::is-active` | `ApplicationActive` | `onResume` | `Activated` |
/// | `WillResignActive` | `willResignActive` | `willResignActive` | `notify::is-active` | `ApplicationInactive` | `onPause` | `Deactivated` |
/// | `WillEnterForeground` | — | `willEnterForeground` | — | — | `onStart` | — |
/// | `DidEnterBackground` | — | `didEnterBackground` | — | — | `onStop` | — |
/// | `DidReceiveMemoryWarning` | — | `didReceiveMemoryWarning` | — | — | `onTrimMemory` | — |
/// | `WillTerminate` | `willTerminate` | `willTerminate` | `shutdown` | `aboutToQuit` | `onDestroy` | window close |
/// | `DidExit` | after `willTerminate` | after `willTerminate` | `run` returned | `exec` returned | after `onDestroy` | loop returned |
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Lifecycle {
    /// Before the window and UI are built: the first thing to run. Set up global state here.
    WillLaunch,
    /// The UI is mounted and the app is about to start running. Kick off startup work here.
    DidLaunch,
    /// The app came to the foreground and is the active, focused app receiving input.
    DidBecomeActive,
    /// The app is about to stop being active (an interruption, app switch, or losing focus).
    WillResignActive,
    /// The app is about to return to the foreground (mobile). Refresh what background invalidated.
    WillEnterForeground,
    /// The app left the foreground and is no longer visible (mobile). Persist state, release UI work.
    DidEnterBackground,
    /// The system is low on memory (mobile). Drop caches and non-essential memory now.
    DidReceiveMemoryWarning,
    /// The app is about to terminate: the last chance to save. Triggered by the Quit command,
    /// the platform's quit shortcut, or the OS reclaiming the app.
    WillTerminate,
    /// The run loop is over and nothing of the app will run after this: the last phase, after
    /// every `WillTerminate` handler. Day logs its exit line ("Clean exit for …") once the
    /// handlers have run, so a handler here is the app's last word before it.
    DidExit,
}

impl Lifecycle {
    /// Every phase, in delivery order (launch → run → quit). Handy for logging/registration sweeps.
    pub const ALL: [Lifecycle; 9] = [
        Lifecycle::WillLaunch,
        Lifecycle::DidLaunch,
        Lifecycle::DidBecomeActive,
        Lifecycle::WillResignActive,
        Lifecycle::WillEnterForeground,
        Lifecycle::DidEnterBackground,
        Lifecycle::DidReceiveMemoryWarning,
        Lifecycle::WillTerminate,
        Lifecycle::DidExit,
    ];

    /// True for phases every backend delivers (launch, activation, termination). The remaining
    /// phases (`WillEnterForeground`, `DidEnterBackground`, `DidReceiveMemoryWarning`) are mobile
    /// concepts and are only delivered by the mobile backends. `const` so it composes into a
    /// backend's `const fn lifecycle_supported` and thus into compile-time guards.
    pub const fn is_universal(self) -> bool {
        matches!(
            self,
            Lifecycle::WillLaunch
                | Lifecycle::DidLaunch
                | Lifecycle::DidBecomeActive
                | Lifecycle::WillResignActive
                | Lifecycle::WillTerminate
                | Lifecycle::DidExit
        )
    }

    /// A stable, human-readable name (for logs/warnings).
    pub const fn name(self) -> &'static str {
        match self {
            Lifecycle::WillLaunch => "WillLaunch",
            Lifecycle::DidLaunch => "DidLaunch",
            Lifecycle::DidBecomeActive => "DidBecomeActive",
            Lifecycle::WillResignActive => "WillResignActive",
            Lifecycle::WillEnterForeground => "WillEnterForeground",
            Lifecycle::DidEnterBackground => "DidEnterBackground",
            Lifecycle::DidReceiveMemoryWarning => "DidReceiveMemoryWarning",
            Lifecycle::WillTerminate => "WillTerminate",
            Lifecycle::DidExit => "DidExit",
        }
    }
}

/// The phase of a drag gesture (docs/shapes.md).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DragPhase {
    Began,
    Changed,
    Ended,
}

/// A gesture a node wants delivered. Backends attach the matching native recognizer when day-core
/// calls [`Toolkit::enable_gesture`]; the default is no gesture (recognizers cost, so opt-in).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum GestureKind {
    Tap,
    LongPress,
    Drag,
    /// The pointer moving over the node without pressing (docs/canvas.md "Interaction"), and
    /// leaving it. Delivered only where a pointer exists: every desktop, an iPad with a trackpad
    /// or pencil, an Android device with a mouse or stylus. A touch-only device reports none,
    /// which is the right answer, not a gap, so anything reachable by hover must also be
    /// reachable by a tap.
    Hover,
    /// Pinch/magnify (docs/shapes.md): trackpad magnification, two-finger touch pinch.
    Pinch,
    /// Viewport pan (docs/shapes.md): trackpad two-finger scroll, two-finger touch pan.
    /// Distinct from [`GestureKind::Drag`], the primary pointer's press-drag.
    Pan,
}

// ---------------------------------------------------------------------------
// Menus (app menu bar + context menus). The model is a toolkit-neutral tree; each backend renders
// it with its native affordance (NSMenu / GMenu+GtkPopoverMenu / QMenu / UIMenu / Android
// PopupMenu / XAML MenuFlyout) and its own conventions, so day imposes no menu manager of its own.
// ---------------------------------------------------------------------------

/// A keyboard shortcut for a menu item. `primary` is the platform's command modifier (⌘ on Apple,
/// Ctrl on GTK/Qt/XAML) so one declaration reads correctly everywhere. `key` is a single character
/// (`"s"`, `"."`) or a named key (`"Return"`, `"Delete"`, `"Left"`, `"F1"`).
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct Shortcut {
    pub key: String,
    /// ⌘ (Apple) / Ctrl (elsewhere). The conventional command modifier.
    pub primary: bool,
    pub shift: bool,
    /// ⌥ / Alt.
    pub alt: bool,
    /// Literal Control (⌃ on Apple). Rare; prefer `primary` for the command modifier.
    pub control: bool,
}

impl Shortcut {
    /// `primary`+`key` (⌘S / Ctrl+S), the common case: `Shortcut::primary("s").shift()`.
    pub fn primary(key: impl Into<String>) -> Shortcut {
        Shortcut {
            key: key.into(),
            primary: true,
            ..Default::default()
        }
    }
    /// `key` with no modifiers (e.g. `F1`, plain `Delete`).
    pub fn plain(key: impl Into<String>) -> Shortcut {
        Shortcut {
            key: key.into(),
            ..Default::default()
        }
    }
    pub fn shift(mut self) -> Shortcut {
        self.shift = true;
        self
    }
    pub fn alt(mut self) -> Shortcut {
        self.alt = true;
        self
    }
    pub fn control(mut self) -> Shortcut {
        self.control = true;
        self
    }
}

/// A standard/system command. The backend supplies the native item, a selector on AppKit/UIKit
/// (`cut:`/`copy:`/`paste:`…) or a stock action on GTK/Qt/XAML, so it targets the focused
/// control, gets the platform's default label + shortcut, and enables/disables itself
/// automatically. This is how default items (Edit ▸ Cut/Copy/Paste, the app's Quit/About) are
/// accommodated without the app re-implementing them.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MenuRole {
    Cut,
    Copy,
    Paste,
    SelectAll,
    Undo,
    Redo,
    Delete,
    /// The app's About command (docs/settings.md). With an About registered through
    /// `day::register_about` the item lowers to that dispatch action (a Day-rendered About
    /// window, or the toolkit's own About dialog where one exists); without one AppKit shows
    /// its stock Info.plist panel and the other desktops show the label alone.
    About,
    Quit,
    Preferences,
    Minimize,
    CloseWindow,
    Fullscreen,
    /// File ▸ New Window (docs/windows.md): opens another window through the builder the
    /// app registered with `day::register_new_window`. No platform has a native selector
    /// for it, so the item lowers to the registered dispatch action (disabled when none).
    NewWindow,
    /// Check for Updates… (docs/settings.md): placed directly under About in the macOS App
    /// menu (the Sparkle convention) and in Help elsewhere. Lowers to the action an updater
    /// registered with `day::register_check_for_updates`; absent from the bar when none did.
    CheckForUpdates,
}

/// The keyboard modifiers held at an interaction, queryable ambiently
/// ([`Toolkit::modifiers`]): `primary` is the platform's command key (⌘ on Apple platforms,
/// Ctrl elsewhere, the same convention [`Shortcut::primary`] uses). Touch-only backends
/// answer all-false.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Modifiers {
    pub shift: bool,
    pub primary: bool,
    pub alt: bool,
}

/// A standard edit command a platform route delivered ([`Event::Edit`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EditOp {
    Cut,
    Copy,
    Paste,
    SelectAll,
}

/// What the app's edit bridge can currently do, mirrored into the toolkit
/// ([`Toolkit::set_edit_state`]) so native menu validation enables the stock items.
/// `can_paste` is the app's half ("a paste handler is installed"); the toolkit combines it
/// with its own clipboard-has-text check where one exists.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct EditState {
    pub can_cut: bool,
    pub can_copy: bool,
    pub can_paste: bool,
    pub can_select_all: bool,
}

/// The undo stack's face, as a native front mirrors it ([`Toolkit::set_undo_state`]): what is
/// possible and what the menu titles should say. Labels arrive already localized: a toolkit
/// cannot invent translated text, the same rule as every other label in this file.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct UndoState {
    pub can_undo: bool,
    pub can_redo: bool,
    /// The next undo unit's display label ("Rename"), empty when nothing is undoable. Fronts
    /// interpolate it into the platform's own title form ("Undo Rename").
    pub undo_label: String,
    pub redo_label: String,
}

/// One entry in a menu (recursive: a `Submenu` nests).
#[derive(Clone, Debug, PartialEq)]
pub enum MenuItem {
    /// A command. `action` (nonzero) dispatches [`Event::MenuAction`] to the app; a `role`-only item
    /// uses the native standard command instead (action 0). `label`/`shortcut` override the role's
    /// defaults. `icon` is the platform's own glyph beside the title where menus carry one (macOS,
    /// Windows, GNOME, KDE, Android); a backend whose menus are text-only ignores it.
    ///
    /// The `id`/`action` split is [`ToolbarItem`]'s: `id` names the item and `action` is what it
    /// runs. They are separate because a label cannot serve as a name (it is localized, and an
    /// item that shows its own state changes it), so anything addressing an item from outside
    /// (dayscript's `menu: { id: … }`) needs something that does not move.
    Action {
        /// The app's own name for this item, where it gave one. Stable across locales and across
        /// a change of `checked`, and unique within the menu it is installed in.
        id: Option<String>,
        /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
        /// (0 = no command), so a toolbar button and its menu twin can share one closure.
        action: u64,
        label: String,
        shortcut: Option<Shortcut>,
        enabled: bool,
        /// On/off state where the item stands for a setting or one of several choices, drawn with
        /// the platform's own check mark. `None` is a plain command and reserves no mark; `Some`
        /// makes the item checkable and says which way it currently sits.
        ///
        /// The item still runs its `action` when chosen; a backend never flips this on its own.
        /// The app owns the state, and re-installing the menu (`app_menu`, which re-lowers on change) is what moves
        /// the mark, so what the menu shows can never disagree with what the app thinks.
        checked: Option<bool>,
        role: Option<MenuRole>,
        icon: Option<Icon>,
    },
    /// A nested submenu. At the top level of an app menu a `role` claims one of the platform's
    /// standard menu-bar slots: the backend then uses this menu instead of its stock one, and
    /// places it where the platform expects that menu to sit.
    Submenu {
        label: String,
        items: Vec<MenuItem>,
        role: Option<MenuBarRole>,
    },
    /// A visual separator.
    Separator,
}

/// A standard menu-bar slot (macOS's File/Edit/View/Window/Help, and their counterparts
/// elsewhere). A backend that has a house style for the menu bar fills every slot an app did
/// not claim with its own stock menu, so an app never has to restate the platform's furniture,
/// and can still replace any of it by tagging its own submenu with the matching role.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MenuBarRole {
    File,
    Edit,
    View,
    /// KDE/Plasma's Settings menu (`Configure <App>`, Configure Shortcuts). No counterpart on
    /// macOS, where preferences live in the app menu, or on GNOME/Windows.
    Settings,
    /// macOS's Window menu. Windows and Linux desktops do not have one.
    Window,
    Help,
}

// ---------------------------------------------------------------------------
// Window toolbars (docs/toolbars.md)
// ---------------------------------------------------------------------------

/// A standard icon, named by what it means rather than by how it looks, so each backend can
/// draw the platform's own glyph for it: an SF Symbol on macOS, a freedesktop icon name on
/// GTK and Qt, a Fluent glyph on Windows. This is the only way an icon looks native on every
/// desktop at once; a bundled PNG cannot, because it is one artist's take on all four.
///
/// The set is kept small: the commands that recur across toolbars. Anything
/// app-specific is an [`Icon::Image`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Symbol {
    Add,
    Remove,
    Delete,
    Edit,
    New,
    Open,
    Save,
    Print,
    Refresh,
    Search,
    Share,
    Settings,
    Info,
    Star,
    Bookmark,
    Back,
    Forward,
    Up,
    Down,
    Home,
    /// Show/hide the sidebar, the leading item of most desktop toolbars.
    Sidebar,
    Filter,
    Sort,
    /// An overflow affordance (macOS `ellipsis`, GNOME's hamburger, Fluent `More`).
    More,
    Play,
    Pause,
    Stop,
    /// A photo capture: a screenshot command, a camera control.
    Camera,
    /// Source code.
    Code,
    /// Light appearance (a sun). The three below are the vocabulary of a theme chooser, which
    /// every platform draws with the same three ideas.
    Light,
    /// Dark appearance (a moon).
    Dark,
    /// Follow the system: the half-filled circle every platform uses for "automatic".
    Auto,
    ZoomIn,
    ZoomOut,
    /// Back to actual size: the 100% zoom command between [`Symbol::ZoomIn`] and
    /// [`Symbol::ZoomOut`].
    ZoomReset,
    Undo,
    Redo,
    Copy,
    Cut,
    Paste,
    Mail,
    Folder,
    Document,
    Check,
    Close,
    Warning,
    /// A rectangle: the shape vocabulary a drawing surface needs (docs/shapes.md), and the
    /// glyphs every drawing, diagram and annotation tool puts in the same place.
    Rectangle,
    /// An ellipse.
    Oval,
    /// An outlined circle: the read/unread vocabulary (a read row, its dot removed), and the
    /// generic ring glyph.
    Circle,
    /// A filled circle: the unread dot itself.
    CircleFilled,
    /// A straight line segment.
    Line,
    /// Combine the selection into a group: the drawing-tool command (two stacked squares).
    Group,
    /// Dissolve a group back into its members (two separated squares).
    Ungroup,
    /// Text: a line of type as a drawing element (the drawing-tool "T").
    Text,
}

/// The SF Symbol each standard symbol draws as. The system's own glyphs match the user's
/// device: weight, optical size, accent color and all. Shared by both Apple backends
/// (toolbars on macOS, menus on both).
///
/// The match is exhaustive so that a new [`Symbol`] must name its glyph here rather than
/// silently drawing nothing on Apple. A name this OS release does not know still resolves to
/// no image, and the item falls back to its label.
pub fn sf_symbol_name(s: Symbol) -> &'static str {
    match s {
        Symbol::Add => "plus",
        Symbol::Remove => "minus",
        Symbol::Delete => "trash",
        Symbol::Edit => "pencil",
        Symbol::New => "square.and.pencil",
        Symbol::Open => "folder",
        Symbol::Save => "square.and.arrow.down",
        Symbol::Print => "printer",
        Symbol::Refresh => "arrow.clockwise",
        Symbol::Search => "magnifyingglass",
        Symbol::Share => "square.and.arrow.up",
        Symbol::Settings => "gearshape",
        Symbol::Info => "info.circle",
        Symbol::Star => "star",
        Symbol::Bookmark => "bookmark",
        Symbol::Back => "chevron.backward",
        Symbol::Forward => "chevron.forward",
        Symbol::Up => "chevron.up",
        Symbol::Down => "chevron.down",
        Symbol::Home => "house",
        Symbol::Sidebar => "sidebar.leading",
        Symbol::Filter => "line.3.horizontal.decrease",
        Symbol::Sort => "arrow.up.arrow.down",
        Symbol::More => "ellipsis",
        Symbol::Play => "play.fill",
        Symbol::Pause => "pause.fill",
        Symbol::Stop => "stop.fill",
        Symbol::Camera => "camera",
        Symbol::Code => "chevron.left.forwardslash.chevron.right",
        Symbol::Light => "sun.max",
        Symbol::Dark => "moon",
        Symbol::Auto => "circle.lefthalf.filled",
        Symbol::ZoomIn => "plus.magnifyingglass",
        Symbol::ZoomReset => "1.magnifyingglass",
        Symbol::ZoomOut => "minus.magnifyingglass",
        Symbol::Undo => "arrow.uturn.backward",
        Symbol::Redo => "arrow.uturn.forward",
        Symbol::Copy => "doc.on.doc",
        Symbol::Cut => "scissors",
        Symbol::Paste => "doc.on.clipboard",
        Symbol::Mail => "envelope",
        Symbol::Folder => "folder",
        Symbol::Document => "doc",
        Symbol::Check => "checkmark",
        Symbol::Close => "xmark",
        Symbol::Warning => "exclamationmark.triangle",
        Symbol::Rectangle => "rectangle",
        Symbol::Oval => "oval",
        Symbol::Circle => "circle",
        Symbol::CircleFilled => "circle.fill",
        Symbol::Line => "line.diagonal",
        Symbol::Group => "square.on.square",
        Symbol::Ungroup => "square.on.square.dashed",
        Symbol::Text => "textformat",
    }
}

/// A button or toolbar item's picture: a standard [`Symbol`] (drawn with the platform's own icon set) or
/// a bundled image from `resource/images` for something only this app has.
#[derive(Clone, Debug, PartialEq)]
pub enum Icon {
    Symbol(Symbol),
    /// A bundled image name, resolved the same way [`ImageName`] is elsewhere.
    Image(String),
}

/// What a toolbar item is. The variants are the vocabulary every desktop toolbar shares; each
/// backend realizes one with its native control, never with a drawn imitation.
#[derive(Clone, Debug, PartialEq)]
pub enum ToolbarItemKind {
    /// A push button running the item's `action`.
    Button,
    /// A two-state button. `on` seeds it; the user flipping it emits
    /// [`ToolbarValue::On`], and the app's own writes arrive as [`ToolbarPatch::On`].
    Toggle { on: bool },
    /// A button that drops a menu: the same [`MenuItem`] model the menu bar uses, so a
    /// toolbar menu and its menu-bar twin are one list of commands.
    Menu { items: Vec<MenuItem> },
    /// A search field. Edits emit [`ToolbarValue::Text`]; the app's own writes arrive as
    /// [`ToolbarPatch::Text`].
    ///
    /// Day creates this item itself, from a `.searchable()` surface whose placement resolved to
    /// the toolbar (docs/search.md); apps declare search on the surface, never here.
    Search {
        text: String,
        placeholder: String,
        /// Completions for the current text, drawn by the field's own completion affordance
        /// where it has one (`AutoSuggestBox`, `QCompleter`, `<datalist>`). Empty = none.
        suggestions: Vec<String>,
    },
    /// A row of mutually exclusive choices drawn as one control: the native segmented control
    /// (`NSSegmentedControl`, a linked GTK/Qt button box, a XAML toggle strip, `.day-segmented`
    /// on the web).
    ///
    /// This is what a set of related toolbar toggles should be when exactly one of them is on at
    /// a time: three separate toggles say "three independent switches" to the eye and to a screen
    /// reader, and leave the app to keep them exclusive. Choosing a segment emits
    /// [`ToolbarValue::Selected`]; the app's own writes arrive as [`ToolbarPatch::Selected`].
    Segmented {
        /// One entry per segment. A segment with an icon draws it in place of its title where
        /// the platform does that, and keeps the title as its accessible name.
        segments: Vec<ToolbarSegment>,
        selected: usize,
    },
    /// Static text, for a status or a caption.
    Label,
    /// A divider between neighbors in the same placement bucket, where the platform draws one
    /// (macOS toolbars have no separator, so AppKit renders it as a fixed space,
    /// docs/toolbars.md). Grouping is all it does: alignment is [`ToolbarPlacement`]'s job.
    Separator,
}

/// One choice inside a [`ToolbarItemKind::Segmented`] control.
#[derive(Clone, Debug, PartialEq)]
pub struct ToolbarSegment {
    /// The segment's name: its label where the platform shows text, its accessible name always.
    pub title: String,
    pub icon: Option<Icon>,
}

/// The reserved id of the sidebar affordance a `nav(Sidebar)` supplies for itself
/// (docs/toolbars.md). Backends with a system item for the job (AppKit's
/// `NSToolbarToggleSidebarItem`) recognize it by this id and draw theirs instead; dayscript
/// recognizes it to drive the toolkit's own duty rather than an app closure.
pub const SIDEBAR_TOGGLE_ID: &str = "day::sidebar_toggle";

/// The reserved id of a `.searchable()` surface's field (docs/search.md): the `ToolbarItem` a
/// desktop bar draws for it, and the name dayscript's `toolbar:` step drives it by wherever the
/// platform put it — on the bar, or inline on the navigation surface where the bar holds no
/// field, in which case day-core resolves the id to that host instead.
pub const SEARCH_ITEM_ID: &str = "day::search";

/// One item in a window's toolbar (docs/toolbars.md).
#[derive(Clone, Debug, PartialEq)]
pub struct ToolbarItem {
    /// Stable identity: the native item identifier, the dayscript target, and the key a
    /// [`ToolbarPatch`] addresses. Unique within a toolbar.
    pub id: String,
    pub kind: ToolbarItemKind,
    /// The item's name. Shown beside or below the icon where the platform does that, and used
    /// verbatim in the overflow and customization menus, so it is never optional, even on a
    /// toolbar that only shows icons. It is also the item's accessible name.
    pub label: String,
    /// Hover help. Defaults to `label` where the platform expects a tooltip and none is given.
    pub tooltip: Option<String>,
    pub icon: Option<Icon>,
    pub enabled: bool,
    /// The item's command, as a dispatch id from the same registry [`Event::MenuAction`] uses
    /// (0 = no command), so a toolbar button and its menu twin can share one closure.
    pub action: u64,
    /// This item's role on the chrome carrying it (docs/toolbars.md). It never names a surface:
    /// Which chrome an item rides is decided by where the app declared it, so this says only
    /// where on that chrome it belongs.
    pub placement: ToolbarPlacement,
    /// Whether the item draws its title, its icon, or both, where the platform can do more than
    /// one. An item folded into an overflow menu shows its title whatever this asks for; a menu
    /// row with no words is not a menu row.
    pub label_style: LabelStyle,
    /// Draw this item in the platform's emphasized style (a tinted/filled bar button, a
    /// prominent `NSToolbarItem`). For the one action a chrome is really offering.
    pub prominent: bool,
    /// Which column of a multi-pane window this item came from (docs/toolbars.md), set by Day
    /// from the piece that declared it, never by an app.
    ///
    /// A desktop toolbar spans every column at once, and a three-pane app expects each column's
    /// commands to sit over that column: the sidebar's against the first divider, the list's over
    /// the list, the rest over the detail. That is what Mail, Notes and Finder do, and it is only
    /// expressible because the declaration site already said which pane the command belongs to.
    /// Backends that draw one undivided bar ignore it.
    pub column: ToolbarColumn,
}

/// Which pane of a window's navigation a toolbar item was declared in (docs/toolbars.md).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ToolbarColumn {
    /// The window itself, over no particular column. Draws with the detail's items, which is
    /// where a command that acts on the whole window belongs when the panes are side by side.
    #[default]
    Window,
    /// The sidebar / master column.
    Sidebar,
    /// The content-list column between the sidebar and the detail.
    List,
    /// The detail column.
    Detail,
}

/// Where an item sits on the chrome that carries it (docs/toolbars.md).
///
/// A placement is a role, never a surface. Which toolbar, navigation bar or column an item
/// rides follows from the piece that declared it, so an app never spells that out twice.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ToolbarPlacement {
    /// The natural spot on this chrome: after the leading group on a desktop toolbar, the
    /// trailing item group on a navigation bar, an `IF_ROOM` menu action on Android.
    #[default]
    Automatic,
    /// The leading edge: a pane toggle, a control that reveals what is to its left.
    Navigation,
    /// Centered: a title accessory, a transport, a status readout.
    Principal,
    /// Trailing, and the last thing a crowded chrome gives up.
    Primary,
    /// Trailing, and the first thing a crowded chrome folds into its overflow.
    Secondary,
    /// A bottom bar where the platform has one (iOS `toolbarItems`, an Android bottom app bar);
    /// [`ToolbarPlacement::Secondary`] everywhere else.
    Bottom,
}

/// Which halves of an item's label a platform draws, where it can draw more than one.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum LabelStyle {
    /// The platform's own convention for this chrome.
    #[default]
    Automatic,
    /// The icon alone (the title stays as the accessible name and the tooltip).
    IconOnly,
    /// The title alone, even where an icon was given.
    TitleOnly,
    /// Both, where the chrome has room for both.
    TitleAndIcon,
}

/// A value a toolbar item produced.
#[derive(Clone, Debug, PartialEq)]
pub enum ToolbarValue {
    /// A search item's full new text.
    Text(String),
    /// A search item's text, submitted with the field's Return or Search key. Sent after the
    /// last [`ToolbarValue::Text`]; it changes no state of its own.
    Submit(String),
    /// A toggle item's new state.
    On(bool),
    /// A segmented item's newly chosen index.
    Selected(usize),
}

/// A targeted update to one live toolbar item: the path that keeps a bound signal in sync
/// without rebuilding the bar (which would drop the search field's focus mid-keystroke).
#[derive(Clone, Debug, PartialEq)]
pub enum ToolbarPatch {
    /// Focus a search control and select its text without changing its value.
    Focus { item: String },
    /// Replace a search item's text.
    Text { item: String, text: String },
    /// Set a toggle item's state.
    On { item: String, on: bool },
    /// Select a segmented item's index.
    Selected { item: String, index: usize },
    /// Enable or disable any item.
    Enabled { item: String, on: bool },
    /// Replace a search item's completions (docs/search.md). Targeted rather than a rebuild,
    /// because these change on every keystroke and rebuilding the bar would take the field's
    /// focus with it.
    Suggestions { item: String, list: Vec<String> },
    /// Replace an item's words (a language change): its label, which an icon-only item still
    /// carries for the overflow menu and assistive technology, and its tooltip. The item keeps
    /// its native widget, its action and its place.
    Label {
        item: String,
        label: String,
        tooltip: Option<String>,
    },
    /// Replace a search item's empty-state prompt (docs/search.md), in the live field.
    Placeholder { item: String, text: String },
}

impl ToolbarPatch {
    /// The id of the item this patch addresses.
    pub fn item(&self) -> &str {
        match self {
            ToolbarPatch::Focus { item }
            | ToolbarPatch::Text { item, .. }
            | ToolbarPatch::On { item, .. }
            | ToolbarPatch::Selected { item, .. }
            | ToolbarPatch::Enabled { item, .. }
            | ToolbarPatch::Suggestions { item, .. }
            | ToolbarPatch::Label { item, .. }
            | ToolbarPatch::Placeholder { item, .. } => item,
        }
    }

    /// Write this patch's value into `items`, the model of a bar. `false` when no item there
    /// takes it (an unknown id, or a kind the value does not apply to).
    pub fn apply_to(&self, items: &mut [ToolbarItem]) -> bool {
        let Some(it) = items.iter_mut().find(|i| i.id == self.item()) else {
            return false;
        };
        match (self, &mut it.kind) {
            (ToolbarPatch::Focus { .. }, ToolbarItemKind::Search { .. }) => (),
            (ToolbarPatch::Text { text, .. }, ToolbarItemKind::Search { text: t, .. }) => {
                *t = text.clone()
            }
            (
                ToolbarPatch::Suggestions { list, .. },
                ToolbarItemKind::Search { suggestions, .. },
            ) => *suggestions = list.clone(),
            (ToolbarPatch::On { on, .. }, ToolbarItemKind::Toggle { on: o }) => *o = *on,
            (
                ToolbarPatch::Selected { index, .. },
                ToolbarItemKind::Segmented { segments, selected },
            ) if *index < segments.len() => *selected = *index,
            (ToolbarPatch::Enabled { on, .. }, _) => it.enabled = *on,
            (ToolbarPatch::Label { label, tooltip, .. }, _) => {
                it.label = label.clone();
                it.tooltip = tooltip.clone();
            }
            (
                ToolbarPatch::Placeholder { text, .. },
                ToolbarItemKind::Search { placeholder, .. },
            ) => *placeholder = text.clone(),
            _ => return false,
        }
        true
    }
}

/// One step of an edit to a window's toolbar (docs/toolbars.md).
///
/// Day hands a backend its bar as edits, never as a whole new model to rebuild, for the same
/// reason the view tree arrives as `insert`/`remove` rather than as a fresh tree: an item the
/// edit does not name keeps its native widget, and with it the keyboard focus, the caret, a
/// menu that is open. A value (search text, a toggle) never travels as an edit; it is a
/// [`ToolbarPatch`] on the live item.
///
/// An edit lists every [`ToolbarOp::Remove`] first, then every [`ToolbarOp::Insert`] in
/// ascending `index`, so applying them in order to the bar's current items (a
/// [`ToolbarMirror`] does exactly that) produces the new bar. Items keep their relative order
/// across an edit: an item that moves arrives as a remove and an insert, like one whose
/// presentation changed.
#[derive(Clone, Debug, PartialEq)]
pub enum ToolbarOp {
    /// The item with this id leaves the bar.
    Remove { id: String },
    /// `item` joins the bar at `index`, its position once this edit is complete.
    Insert { index: usize, item: ToolbarItem },
}

impl ToolbarOp {
    /// Apply this op to `items`, a bar's model in order.
    pub fn apply_to(&self, items: &mut Vec<ToolbarItem>) {
        match self {
            ToolbarOp::Remove { id } => items.retain(|i| i.id != *id),
            ToolbarOp::Insert { index, item } => {
                items.insert((*index).min(items.len()), item.clone())
            }
        }
    }
}

/// A backend's copy of one window's toolbar, kept in step with the [`ToolbarOp`]s and
/// [`ToolbarPatch`]es that reach it, and the one place a backend works out where a new item
/// goes (docs/toolbars.md).
///
/// Every backend lays its bar out as a few groups (the leading and trailing ends of a header
/// bar, the columns of a split window, the primary and overflow commands of a command bar) and
/// keeps model order within each. So an inserted item always goes right after
/// [`ToolbarMirror::prev_where`] its own group, or first in the group when that is `None`, and
/// nothing already on the bar moves.
#[derive(Clone, Debug, Default)]
pub struct ToolbarMirror {
    items: Vec<ToolbarItem>,
}

impl ToolbarMirror {
    /// The bar's items, in model order.
    pub fn items(&self) -> &[ToolbarItem] {
        &self.items
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// The item with this id.
    pub fn get(&self, id: &str) -> Option<&ToolbarItem> {
        self.items.iter().find(|i| i.id == id)
    }

    /// The item dispatching `action`: how a backend whose native bar reports only an action
    /// id (a menu tap) finds what was tapped.
    pub fn by_action(&self, action: u64) -> Option<&ToolbarItem> {
        self.items
            .iter()
            .find(|i| i.action == action && action != 0)
    }

    /// Take the item with `id` out, returning it.
    pub fn remove(&mut self, id: &str) -> Option<ToolbarItem> {
        let at = self.items.iter().position(|i| i.id == id)?;
        Some(self.items.remove(at))
    }

    /// Put `item` at `index` (clamped to the end).
    pub fn insert(&mut self, index: usize, item: ToolbarItem) {
        let at = index.min(self.items.len());
        self.items.insert(at, item);
    }

    /// Apply one op to the model: what a backend that repaints its whole native bar from the
    /// model (a menu of actions) does with each.
    pub fn apply(&mut self, op: &ToolbarOp) {
        op.apply_to(&mut self.items);
    }

    /// Write a value patch into the model. `false` when no item takes it.
    pub fn patch(&mut self, patch: &ToolbarPatch) -> bool {
        patch.apply_to(&mut self.items)
    }

    /// The nearest item before `index` that `same_group` accepts: the native item a new one at
    /// `index` goes right after, in that group. `None` = it goes first in the group.
    pub fn prev_where(
        &self,
        index: usize,
        same_group: impl Fn(&ToolbarItem) -> bool,
    ) -> Option<&ToolbarItem> {
        self.items[..index.min(self.items.len())]
            .iter()
            .rev()
            .find(|i| same_group(i))
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct KeyEvent {
    /// The key's name, in the web `KeyboardEvent.key` vocabulary every platform can map onto:
    /// the four arrows ("ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown") and the ten digits
    /// ("0" through "9", from the main row or the numeric keypad) everywhere, plus
    /// "Delete" and "Backspace" on backends with no menu bar ([`Cap::AppMenu`] unsupported),
    /// where no accelerator can own those keys. A focused piece claims every key the route
    /// carries, so offering them on a menu-bar platform would let a canvas swallow the Delete
    /// its own Edit menu was about to act on (docs/menus.md). The two delete keys keep the
    /// names the platform gives the physical keys (a Mac's ⌫ is "Backspace" and its ⌦ is
    /// "Delete"), so a handler that means "remove this" takes both. A digit arrives only while
    /// neither [`KeyEvent::PRIMARY`] nor [`KeyEvent::ALT`] (nor a Mac's Control) is held: ⌘1
    /// and Ctrl+1 are accelerators, and a canvas claiming them would starve the menu. Most
    /// backends name the digit the keypress types, so a layout whose number row needs Shift for
    /// digits reports "1" with [`KeyEvent::SHIFT`] set; XAML and ArkUI read the physical key.
    /// Backends emit `Event::Key` only while no text widget has focus; a field's own editing
    /// keys never surface here.
    pub key: String,
    /// A [`KeyEvent::SHIFT`]/[`KeyEvent::PRIMARY`]/[`KeyEvent::ALT`] mask.
    pub modifiers: u8,
}

impl KeyEvent {
    pub const SHIFT: u8 = 1;
    /// The platform's command key: ⌘ on Apple platforms, Ctrl elsewhere (the
    /// [`Shortcut::primary`] convention).
    pub const PRIMARY: u8 = 2;
    pub const ALT: u8 = 4;

    /// The ten digit key names, indexed by value.
    pub const DIGITS: [&'static str; 10] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];

    /// The key name for a typed character when it is one of the ten digits: what a backend
    /// reports for a keypress that types `0`–`9`.
    pub fn digit_name(c: char) -> Option<&'static str> {
        c.to_digit(10).map(|d| Self::DIGITS[d as usize])
    }

    /// The value of a digit key, or `None` for every other key.
    pub fn digit(&self) -> Option<u8> {
        match self.key.as_bytes() {
            [d @ b'0'..=b'9'] => Some(d - b'0'),
            _ => None,
        }
    }

    pub fn shift(&self) -> bool {
        self.modifiers & Self::SHIFT != 0
    }
    pub fn primary(&self) -> bool {
        self.modifiers & Self::PRIMARY != 0
    }
    pub fn alt(&self) -> bool {
        self.modifiers & Self::ALT != 0
    }
}

#[cfg(test)]
mod key_event_tests {
    use super::KeyEvent;

    #[test]
    fn digit_names_read_back_as_values() {
        for (value, c) in ('0'..='9').enumerate() {
            let name = KeyEvent::digit_name(c).expect("an ASCII digit names itself");
            let key = KeyEvent {
                key: name.to_string(),
                modifiers: 0,
            };
            assert_eq!(key.digit(), Some(value as u8));
        }
        // Only the ASCII digits: a letter, an Arabic-Indic three, and a named key are not.
        assert_eq!(KeyEvent::digit_name('a'), None);
        assert_eq!(KeyEvent::digit_name('٣'), None);
        let arrow = KeyEvent {
            key: "ArrowUp".to_string(),
            modifiers: 0,
        };
        assert_eq!(arrow.digit(), None);
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PointerEvent {
    pub position: Point,
    pub down: bool,
}

/// The event sink: enqueue-only. It may be invoked re-entrantly from inside any Toolkit method;
/// day-core drains queued events at safe points, each as a fresh batch (§3.3).
pub type EventSink = Box<dyn Fn(NodeId, Event)>;

/// The synchronous row-pull closures for recycling lists (docs/list.md, §10). day-core injects one
/// per `LIST` host via [`Toolkit::attach_list`]; a recycling backend stores it and calls it from
/// its native data-source (on the UI thread, outside any day-core borrow). Each closure re-enters
/// day-core, so, unlike [`EventSink`], these run to completion synchronously (`bind_row` even
/// flushes + lays out the row before returning, so the host can measure the cell immediately).
#[derive(Clone)]
pub struct ListSource {
    /// Report the first actually visible row (exclude overscan). Enqueue-only; optional,
    /// so hosts without a viewport binding incur no app event work.
    pub first_visible: Option<std::rc::Rc<dyn Fn(usize)>>,
    /// Current row count.
    pub len: std::rc::Rc<dyn Fn() -> usize>,
    /// Present on a sectioned list (`ListProps::sections`, docs/list.md "Sections"): whether
    /// row `index` is a section header. Every row index the host sees counts headers, and
    /// day-core translates to the app's items. A header row is not selectable, activatable or
    /// swipeable; the host draws it in its platform's group-header style, sized to its content
    /// even in a `Uniform` list, and floats it where the platform does (macOS group rows,
    /// UIKit plain-table section headers).
    pub is_header: Option<std::rc::Rc<dyn Fn(usize) -> bool>>,
    /// Stable identity token for the row at `index` (for native diffing / animation).
    pub token_at: std::rc::Rc<dyn Fn(usize) -> u64>,
    /// Build (first use of this cell) or rebind (recycled cell) row `index` into the native cell.
    pub bind_row: std::rc::Rc<dyn Fn(usize, RawHandle)>,
    /// A host that emulates `Cap::ListSections` binds the header it pins over the top of the
    /// list with this instead of `bind_row` (docs/list.md "Sections"): the same build or
    /// rebind, but the copy carries no element ids, so a dayscript or accessibility lookup of a
    /// header finds the header row in the list, never its pinned copy.
    pub bind_pinned: std::rc::Rc<dyn Fn(usize, RawHandle)>,
    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
    /// The native host is done with this cell for good (a `GtkListItemFactory::teardown`, a
    /// `UITableViewCell` deallocating): Day disposes the row it built there, its scope, nodes
    /// and element ids. Without this a host that discards cells, as every pool does on a far
    /// jump, leaves one dead row behind in day-core per discarded cell. Safe inside a day-core
    /// borrow (the work is held for the borrow's end) and for a cell Day never saw.
    pub release: std::rc::Rc<dyn Fn(RawHandle)>,
    /// Re-lay the row bound to this cell at `width`, called from the cell's own native layout
    /// pass, the hook [`TreeSource::layout_cell`] already gives trees. day-core lays a row at the
    /// `LIST`'s width first, which is right wherever the cell is the row itself; a backend
    /// whose native row wraps the cell in chrome (GtkListView's themed `row` node pads it)
    /// corrects it here, so the row fits the cell the platform gave it instead of holding the
    /// whole list wider than its frame. Skips quietly when called inside a day-core borrow (a
    /// snapshot pass).
    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
    /// The height day-core last laid the row bound to this cell at: the row's own height,
    /// padding included, as `RowHeight` resolves it. A backend whose cell measures itself
    /// (GtkListView's `DayCell`) reports it as the cell's height, so a padded row keeps its
    /// bottom padding rather than the height of its last child's frame. `0.0` before the row's
    /// first layout, or inside a day-core borrow.
    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
    /// Drag-to-reorder closures, present when `ListProps::reorderable` (docs/list.md). `None` on
    /// non-reorderable lists; backends must not enable their drag machinery without it.
    pub reorder: Option<ListReorder>,
    /// Swipe-to-delete closures, present when `ListProps::deletable` (docs/list.md). `None` on
    /// non-deletable lists; backends must not offer their delete affordance without it.
    pub delete: Option<ListDelete>,
    /// Swipe-actions closures, present when `ListProps::swipe_actions` (docs/list.md). `None` on
    /// lists that declared none; backends must not install their row-action machinery
    /// without it.
    pub swipe: Option<ListSwipe>,
}

/// The synchronous drag-to-reorder half of [`ListSource`] (docs/list.md). Both closures follow
/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks, outside
/// any day-core borrow, and they run to completion synchronously.
#[derive(Clone)]
pub struct ListReorder {
    /// May row `from` drop at row `to`? Called from the native validate/hover hook so the
    /// affordance (gap, insertion mark, forbidden cursor) reflects the app's answer live.
    /// Returns the accepted target index: `to` itself to allow, another index to retarget the
    /// drop, or `-1` to deny.
    pub can_move: std::rc::Rc<dyn Fn(usize, usize) -> i64>,
    /// Commit: row `from` dropped at row `to` (an index `can_move` accepted). Rotates Day's row
    /// snapshot before returning (so `len`/`token_at`/`bind_row` reflect the new order while the
    /// native move animates) and defers the app's own callback to the next event drain.
    pub move_row: std::rc::Rc<dyn Fn(usize, usize)>,
}

/// The synchronous swipe-to-delete half of [`ListSource`] (docs/list.md), shaped exactly like
/// [`ListReorder`]: both closures are called on the UI thread from inside native swipe callbacks,
/// outside any day-core borrow, and run to completion synchronously.
///
/// Each platform spells the gesture its own way (a trailing swipe action on iOS, an
/// `ItemTouchHelper` swipe on Android, a `ListItem` swipe action on ArkUI), but all three ask the
/// same two questions, so this struct is one pair of closures rather than three shapes.
#[derive(Clone)]
pub struct ListDelete {
    /// May row `index` be deleted? Called before the affordance is offered, so a row the app
    /// protects shows no delete action at all rather than one that fails on use.
    pub can_delete: std::rc::Rc<dyn Fn(usize) -> bool>,
    /// Commit: delete row `index`. Removes it from Day's row snapshot before returning (so
    /// `len`/`token_at`/`bind_row` already reflect the shorter list while the native row-removal
    /// animates) and defers the app's own callback to the next event drain.
    pub delete_row: std::rc::Rc<dyn Fn(usize)>,
}

/// Which edge of a row a swipe action rides (docs/list.md). Semantic, not geometric:
/// `Leading` follows the reading direction (the left edge in LTR, the right in RTL), the
/// mapping every platform's swipe API already makes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SwipeEdge {
    Leading,
    Trailing,
}

/// One offered swipe action (docs/list.md): pure data. The pieces layer keeps the handlers;
/// the backend answers a tap through [`ListSwipe::perform`] by index into the offer.
#[derive(Clone, Debug, PartialEq)]
pub struct ListSwipeAction {
    /// The word on the button, already localized (a toolkit cannot translate).
    pub label: String,
    /// Destructive styling: the platform's red.
    pub destructive: bool,
    /// Explicit button color; `None` = the platform's default for the style.
    pub tint: Option<Color>,
    /// A glyph for the button where the platform draws one: above the label on macOS, in
    /// place of it on iOS (docs/list.md).
    pub symbol: Option<Symbol>,
}

/// The synchronous swipe-actions half of [`ListSource`] (docs/list.md), the generalized
/// sibling of [`ListDelete`]: reveal-as-you-swipe buttons on either row edge. The offer is
/// pulled per row at gesture time, so labels follow row state ("Mark Read" on an unread row,
/// "Mark Unread" on a read one); the commit defers to the event drain like every closure here.
#[derive(Clone)]
pub struct ListSwipe {
    /// The offer: the actions for row `index` on `edge`, called inside the platform's swipe
    /// callback, so keep it pure. Empty = no affordance for that row and edge. The first action
    /// is the full-swipe action where the platform activates one at the far edge.
    pub actions_at: std::rc::Rc<dyn Fn(usize, SwipeEdge) -> Vec<ListSwipeAction>>,
    /// The commit: the user activated action `action` (an index into the offer) on row
    /// `index`, `edge`. Unlike a delete this never reshapes the row snapshot; the app's
    /// handler is deferred to the next event drain, never run inside the native callback.
    pub perform: std::rc::Rc<dyn Fn(usize, SwipeEdge, usize)>,
}

/// The synchronous row-pull closures for hierarchical trees (docs/tree.md): [`ListSource`]'s
/// shape, addressed by token instead of row index, because expanding a row renumbers every
/// index below it while tokens hold still. day-core injects one per `TREE` host via
/// [`Toolkit::attach_tree`]; the backend answers its native data-source from it. The same
/// synchronous discipline as [`ListSource`]: UI thread, outside any day-core borrow;
/// `bind_row` flushes and lays the row out before returning.
#[derive(Clone)]
pub struct TreeSource {
    /// How many children `parent` has (`None` = the root level).
    pub children_len: std::rc::Rc<dyn Fn(Option<u64>) -> usize>,
    /// The i-th child of `parent`: the stable token every backend keys its rows by.
    pub child_token: std::rc::Rc<dyn Fn(Option<u64>, usize) -> u64>,
    /// Whether this token can hold children at all: what draws (or omits) the disclosure.
    pub expandable: std::rc::Rc<dyn Fn(u64) -> bool>,
    /// Non-selectable section heading, separate from a navigation destination.
    pub section_header: std::rc::Rc<dyn Fn(u64) -> bool>,
    /// Current desired expansion, including restoration before the first native reload.
    pub expanded: std::rc::Rc<dyn Fn(u64) -> bool>,
    /// Build (first use of this cell) or rebind (recycled cell) the row for `token` into the
    /// native cell.
    pub bind_row: std::rc::Rc<dyn Fn(u64, RawHandle)>,
    /// The native cell left the viewport; Day may drop per-cell bookkeeping (optional).
    pub recycle: std::rc::Rc<dyn Fn(RawHandle)>,
    /// Re-lay the row bound to this cell at `width`, called from the cell's own native
    /// layout pass. Trees need this where lists don't: indentation makes every cell's
    /// content width per-row, so the host-width layout `bind_row` did is only a first
    /// approximation. Skips quietly when called inside a day-core borrow (a snapshot pass).
    pub layout_cell: std::rc::Rc<dyn Fn(RawHandle, f64)>,
    /// Native bounds for controls whose group headers have a different height from leaves.
    /// Overrides the initial row-height estimate and preserves the native height on rebind.
    pub layout_cell_size: std::rc::Rc<dyn Fn(RawHandle, Size)>,
    /// The height day-core last laid this cell's row at (see [`ListSource::cell_height`]).
    pub cell_height: std::rc::Rc<dyn Fn(RawHandle) -> f64>,
    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
    pub type_select_text: std::rc::Rc<dyn Fn(u64) -> String>,
    /// The row's context menu, built when the menu is summoned (docs/menus.md "Dynamic context
    /// menus"), called on the UI thread from the platform's own menu callback, outside any
    /// day-core borrow, like every closure here. `None` = rows carry no menu; an empty
    /// result suppresses the menu for that row.
    pub row_menu: Option<std::rc::Rc<dyn Fn(u64) -> Vec<MenuItem>>>,
    /// Drag-to-move closures, present when `TreeProps::movable` (docs/tree.md). `None` on
    /// immovable trees; backends must not enable their drag machinery without it.
    pub moves: Option<TreeMoves>,
}

/// The synchronous drag half of [`TreeSource`] (docs/tree.md). Both closures follow
/// `bind_row`'s discipline: called on the UI thread from inside native drag callbacks.
#[derive(Clone)]
pub struct TreeMoves {
    /// The live verdict, consulted while the drag is over a target: may `token` land under
    /// `parent` at `index`? `index: None` means "dropped onto the parent" (append). Pure, since
    /// it runs inside the platform's drag-validate callback.
    #[allow(clippy::type_complexity)]
    pub can_move: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>) -> MoveVerdict>,
    /// Commit an accepted drop. Defers the app's `on_move` through the event queue
    /// ([`Event::TreeMove`]); the app's own data write drives the reload.
    #[allow(clippy::type_complexity)]
    pub move_node: std::rc::Rc<dyn Fn(u64, Option<u64>, Option<usize>)>,
}

/// A summon-time context-menu provider (docs/menus.md): local-point in, menu out.
pub type ContextMenuFn = std::rc::Rc<dyn Fn(Point) -> Vec<MenuItem>>;

/// A tree move guard's verdict (docs/tree.md). No `Retarget` yet: the drop vocabulary is
/// already positional, so a guard that wants a different target denies and the user drops
/// where it is allowed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MoveVerdict {
    Allow,
    Deny,
}

/// One addressable widget within a composite native backing (docs/tree.md,
/// docs/tweaks.md), Qt's name for the concept (`QStyle::SubControl`). A `list`'s or
/// `tree`'s node handle is its scroller; `Subcontrol::Content` is the widget inside it.
/// Backends resolve an unknown subcontrol to `None`, never to the host.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Subcontrol {
    /// The node's own handle: what every tweak accessor reached before subcontrols existed.
    Host,
    /// The content widget inside the scroller (`NSOutlineView`, `NSTableView`, …).
    Content,
    /// The header view, where the widget has one. Day's lists and trees ship headerless, so
    /// this answers `None` until a kind grows a header.
    Header,
}

// ---------------------------------------------------------------------------
// Capabilities, animation, a11y
// ---------------------------------------------------------------------------

/// What to show on the app's icon in the Dock, launcher, home screen, or taskbar (docs/badge.md).
///
/// Distinct from `NavItem::badge`, which annotates a sidebar row inside the window. This one
/// decorates the application itself and is drawn by the shell, not by Day.
///
/// What each payload needs is asked separately (`Cap::AppBadgeCount`, `AppBadgeText`,
/// `AppBadgeDot`) because the platforms differ in what they accept more than in whether they have
/// a badge at all: macOS takes arbitrary text, iOS and the web take a number, Android takes nothing.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub enum AppBadge {
    /// Clear the badge.
    #[default]
    None,
    /// A count. Zero clears it, matching every platform's own convention.
    Count(u32),
    /// Short arbitrary text (`"99+"`, `"beta"`). Only macOS renders it; probe `Cap::AppBadgeText`.
    Text(String),
    /// An indicator with no value.
    Dot,
}

/// How wide a window is, in coarse buckets (docs/size-classes.md).
///
/// The breakpoints are Android's window size classes, in density-independent points, and they are
/// used verbatim on every backend rather than per-platform. One table means one answer: a 700pt
/// window is [`WidthClass::Medium`] on a Mac, in a browser, and on a tablet, so an app that lays
/// out from the class gets the same layout at the same size everywhere. Apple publishes only two
/// buckets (compact/regular); those map onto this table rather than replacing it, with
/// [`WidthClass::Compact`] the compact one and everything above it regular.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
pub enum WidthClass {
    /// `< 600dp`: a phone in portrait. One pane at a time.
    #[default]
    Compact,
    /// `600–839dp`: a tablet in portrait, a narrow desktop window.
    Medium,
    /// `840–1199dp`: a tablet in landscape, a typical desktop window.
    Expanded,
    /// `1200–1599dp`: a large desktop window.
    Large,
    /// `≥ 1600dp`: a maximized window on a big display.
    ExtraLarge,
}

/// How tall a window is (docs/size-classes.md). Consulted far less than [`WidthClass`]: it is
/// what tells a phone in landscape (wide enough for two panes, too short for a tall list) that
/// it should not grow vertical chrome.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default)]
pub enum HeightClass {
    /// `< 480dp`: a phone in landscape.
    #[default]
    Compact,
    /// `480–899dp`: a phone in portrait, a tablet in landscape.
    Medium,
    /// `≥ 900dp`: a tablet in portrait, most desktop windows.
    Expanded,
}

/// A window's size class (docs/size-classes.md), reported by the backend and read by apps
/// through `day::size_class()`.
///
/// Per-window, not per-app: two windows of one process can sit in different classes at the same
/// time (a narrow and a wide window side by side, iPadOS Stage Manager, Android split-screen), and
/// an app that keyed off a single global would lay the second window out for the first one's size.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct SizeClass {
    pub width: WidthClass,
    pub height: HeightClass,
}

impl SizeClass {
    /// The `Compact`/`Medium` width boundary in dp: the narrowest window where a second
    /// pane starts to fit. Backends that hand an adaptive container its pane widths derive
    /// them from this (Android's list + minimum-detail widths sum to it), so the platform's
    /// measure-time decision and this table agree by construction (docs/size-classes.md).
    pub const SPLIT_MIN_WIDTH: f64 = 600.0;

    /// Bucket a window's size in points. The one place the breakpoint numbers appear.
    pub fn from_size(width: f64, height: f64) -> Self {
        SizeClass {
            width: match width {
                w if w >= 1600.0 => WidthClass::ExtraLarge,
                w if w >= 1200.0 => WidthClass::Large,
                w if w >= 840.0 => WidthClass::Expanded,
                w if w >= Self::SPLIT_MIN_WIDTH => WidthClass::Medium,
                _ => WidthClass::Compact,
            },
            height: match height {
                h if h >= 900.0 => HeightClass::Expanded,
                h if h >= 480.0 => HeightClass::Medium,
                _ => HeightClass::Compact,
            },
        }
    }

    /// Whether a two-pane presentation fits. The rule behind an automatic
    /// [`props::NavPresentation`]: anything wider than compact gets both panes.
    pub fn prefers_split(self) -> bool {
        self.width > WidthClass::Compact
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Cap {
    /// Standard searchfield control.
    SearchField,
    /// Standard combobox control.
    ComboBox,
    /// Standard stepper control.
    Stepper,
    /// Standard datetime control.
    DateTimePicker,
    /// Standard colorpicker control.
    ColorPicker,
    /// Standard pullrefresh control.
    PullRefresh,
    /// Standard pager control.
    Pager,
    /// User-driven pull recognition, separate from a refresh indicator.
    PullRefreshGesture,

    /// Native data-transfer source and destination callbacks.
    DragDrop,
    /// Transfers between independent native applications (inbound).
    DragExternalImport,
    /// Transfers to independent native applications, including arbitrary binary MIME data.
    DragExternalExport,
    /// Lossless ordered items and alternatives between Day applications.
    DragMultipleItems,
    /// Existing native file references, distinct from promised/generated files.
    DragFileReferences,
    /// Native result can wait for asynchronous data receipt.
    DragDeferredReceipt,
    /// Generated files supplied to a destination after dropping.
    DragFilePromises,
    /// External move acknowledgment safe for source deletion.
    DragExternalMove,
    ListRecycling,
    /// The toolkit fronts the app's undo stack with the platform's own undo system
    /// ([`Toolkit::set_undo_state`] + `Event::Undo`): `Native` where one exists
    /// (`NSUndoManager` on macOS/iOS, `QUndoStack`), `Unsupported` everywhere else, where
    /// Day's menu items and accelerators drive the stack directly and nothing platform-owned
    /// needs mirroring (docs/model.md).
    UndoBridge,
    /// The toolkit routes the platform's standard Cut/Copy/Paste to the app's edit bridge
    /// ([`Toolkit::set_edit_state`] + `Event::Edit`): the same menu items, shortcuts, and
    /// responder precedence the platform's text editing uses; a focused text widget keeps
    /// its own clipboard behavior, everything else reaches the app (docs/menus.md).
    /// `Native` where a system route exists (the responder chain, the browser's clipboard
    /// events), `Emulated` where Day's own menu items dispatch it, `Unsupported` elsewhere.
    EditBridge,
    /// The toolkit realizes `ListProps::reorderable` as drag-to-reorder rows: `Native` when the
    /// platform's own mechanism drives it (NSTableView drag/drop, UITableView drag delegates,
    /// ItemTouchHelper, …), `Emulated` for a pointer-tracked fake (web-dom). `Unsupported` ⇒ the
    /// list renders normally but rows cannot be dragged (docs/list.md).
    ListReorder,
    /// Sidebar destinations can be dragged to reorder (`NavBuilder::reorder_items`) and between
    /// sections (`NavBuilder::regroup_items`). `Native` when the toolkit's own sidebar drags them
    /// (`NavMenuProps::movable`, and across headers under `NavMenuProps::regroup`); `Emulated`
    /// when Day stands a reorderable list in for the sidebar. Independent of `ListReorder`: UIKit
    /// supports draggable content lists but retains its native navigation collection for
    /// sidebars.
    NavReorder,
    /// The toolkit realizes `ListProps::deletable` as the platform's delete gesture:
    /// `Native` where the platform ships one (UIKit's trailing swipe actions, Android's
    /// `ItemTouchHelper`, ArkUI's `ListItem.swipeAction`), `Unsupported` on the desktop toolkits,
    /// whose lists have no swipe idiom and where deletion belongs to a menu or a button
    /// (docs/list.md).
    ListDelete,
    /// The toolkit realizes `ListProps::swipe_actions` as edge swipe actions: buttons
    /// that reveal as the row tracks the swipe, with the far edge activating the first one
    /// (docs/list.md). `Native` where the platform ships the affordance: macos-appkit
    /// (`NSTableView` row actions, Mail's own machinery) and ios-uikit
    /// (`UISwipeActionsConfiguration`). `Unsupported` everywhere else: the affordance is
    /// absent, and the app's command lives in its explicit controls.
    ListSwipeActions,
    /// The toolkit realizes `ListProps::editing` as the platform's list editing mode: rows
    /// show their delete controls and reorder grips while the list is editing (docs/list.md).
    /// `Native` on ios-uikit (`UITableView` editing). `Unsupported` everywhere else, where a
    /// list has no separate editing mode: its rows already drag, swipe and open menus as they
    /// are, and the list renders as if `editing` were off.
    ListEditing,
    /// The toolkit realizes `kinds::LIST_ITEM` as its own list row content (docs/list.md "List
    /// items"): `Native` where the platform has a standard row it draws itself (UIKit's
    /// `UIListContentConfiguration`, a Material list item, AppKit's image-and-text table cell,
    /// a GTK row box), so the row takes the platform's fonts, icon size, spacing, secondary
    /// colors and check mark. `Unsupported` ⇒ the `list_item` piece composes the same content
    /// from plain pieces. Apps have no reason to probe this; the piece does.
    ListItem,
    /// The toolkit realizes `kinds::TREE` as a hierarchical tree view (docs/tree.md):
    /// `Native` where a platform tree widget hosts Day-built rows (NSOutlineView, the UIKit
    /// sidebar list, GtkListView+TreeListModel, WinUI TreeView, ArkTS TreeView), `Emulated`
    /// where Day flattens the tree onto its list machinery, `Unsupported` where neither
    /// exists yet. An app gates its tree UI on this answer rather than showing a placeholder.
    Tree,
    /// The toolkit realizes `TreeProps::movable` as drag-to-reparent/restack rows
    /// (docs/tree.md). A strictly smaller set than [`Cap::Tree`]: a backend can render a
    /// tree it cannot yet drag within.
    TreeMove,
    /// Native two-level section headers; general trees may still be composed.
    TreeSections,
    /// The toolkit answers [`Toolkit::first_baseline`], so rows can align text on its baseline
    /// rather than on the middle of its box (docs/baseline.md). `Native` where the platform
    /// reports the baseline itself (`NSView.firstBaselineOffsetFromTop`, `View.getBaseline`,
    /// `gtk_widget_measure`), `Emulated` where Day derives it from the widget's font metrics,
    /// `Unsupported` ⇒ baseline-aligned rows fall back to centering and look exactly as they do
    /// today.
    BaselineAlignment,
    /// The toolkit draws a label's [`TextRun`]s: bold, italic, color or a monospace face within
    /// one wrapping paragraph (docs/text-runs.md). `Unsupported` ⇒ the label renders its text
    /// uniformly, which reads correctly and loses only the emphasis.
    TextRuns,
    /// The toolkit makes a run carrying [`TextRun::link`] activatable, emitting
    /// [`Event::LinkActivated`]. A strictly smaller set than [`Cap::TextRuns`]: several toolkits
    /// draw a link run in link colors but have no way to hit-test it, and one (Android) can do
    /// links or selection but not both (docs/text-runs.md).
    TextLinks,
    Lottie,
    NativeSymbols,
    /// The toolkit can rasterize its window and hand back the pixels
    /// (`Toolkit::snapshot_window`): what the dayscript `screenshot` step captures in-process
    /// and what `day::window_image()` offers the app (docs/window-image.md). `Unsupported` where
    /// a backend cannot draw itself into a bitmap: web-dom, which would need a rasterizer
    /// shipped with it. Probe it before offering a "save a screenshot" affordance, rather than
    /// offering one that fails when pressed.
    Snapshot,
    /// The toolkit can present `nav()` as sidebar+detail split panes, a statement about the
    /// toolkit, not about the window it is currently drawing. Whether a given host is split right
    /// now follows from its [`SizeClass`]: the pieces layer resolves an automatic
    /// [`props::NavPresentation`] against both, and re-resolves on every class change. A backend
    /// with no split container answers `Unsupported` and stays stacked at every size.
    NavSplit,
    /// The toolkit can draw a navigation host's rows as its own chrome: a tab bar
    /// ([`props::NavPresentation::Tabs`]) and, where it has one, a rail
    /// ([`props::NavPresentation::Rail`]). Like [`Self::NavSplit`] this is a statement about the
    /// toolkit, not about the window it is drawing right now.
    ///
    /// This is what `NavStyle::Automatic` resolves against (docs/navigation.md): a backend
    /// answering `Unsupported` gets the sidebar resolver instead (`Split` ↔ `Stack`), which is
    /// what every backend did before adaptive navigation existed. So an unimplemented backend
    /// degrades to its previous behavior rather than to a hole.
    ///
    /// `Emulated` means the rows are composed from other widgets rather than drawn by a native
    /// tab container (Qt, web-dom). `Native` means a real one (`UITabBarController`, a Material
    /// `NavigationBarView`, `NavigationView`).
    NavTabs,
    /// A narrow window should become a tab bar here, a separate question from [`Self::NavTabs`],
    /// which only says the toolkit *can* draw one.
    ///
    /// The two differ on every desktop. macOS, GNOME, Qt and Windows can all draw a tab bar, and
    /// must, because an app is free to pin `NavStyle::Tabs`; but none of them grows one when
    /// its window is dragged narrow. A narrow Mail.app hides its sidebar and pushes; it does not
    /// sprout a bottom tab bar, and an app that did would look like a port. The phones and the web
    /// are the opposite: those are the surfaces whose window size ranges from a phone to a
    /// desktop, and a tab bar is what their users expect at the narrow end.
    ///
    /// So this is a statement about the platform's idiom, not about its widget set:
    ///
    /// - `Native`/`Emulated`: `NavStyle::Automatic` may resolve to
    ///   [`props::NavPresentation::Tabs`] on a compact window (ios-uikit, android-material,
    ///   harmony-arkui, web-dom).
    /// - `Unsupported`: it may not; a compact window collapses to
    ///   [`props::NavPresentation::Stack`] instead, exactly as `NavStyle::Sidebar` has always
    ///   done (macos-appkit, linux-gtk, linux-qt, windows-winui).
    ///
    /// [`props::NavPresentation::Rail`] is not gated by this. A narrow sidebar is an ordinary
    /// desktop shape (on Windows it is what `NavigationView` does at that width on its own), so
    /// the rail rung stays available everywhere `Cap::NavSplit` is.
    NavTabsAdaptive,
    /// How a navigation host's presentation follows the window (docs/size-classes.md). All three
    /// answers mean something different here, and the difference is who decides:
    ///
    /// - `Native`: **Day tells the toolkit.** The pieces layer resolves the presentation from
    ///   the [`SizeClass`], re-resolves on every change, and sends
    ///   [`props::NavPatch::Presentation`]; the toolkit rebuilds its chrome and re-homes the
    ///   pages it already has. The desktops and web-dom.
    /// - `Emulated`: **the toolkit tells Day.** Its own adaptive container owns the decision
    ///   (`UISplitViewController` collapsing as a Pro Max iPhone rotates, `SlidingPaneLayout`
    ///   measuring whether both panes fit), so Day must not push a presentation into it: that
    ///   would be a second decision racing the platform's own animation. The toolkit
    ///   reports what it did with [`Event::NavPresentationChanged`] and Day reconciles.
    /// - `Unsupported`: nobody re-presents. The presentation is resolved once, from
    ///   [`Cap::NavSplit`] alone, and the window's size never enters into it. A toolkit that
    ///   cannot change presentation must not have it decided by something that can, or a window
    ///   launched narrow would be stuck stacked with no way back.
    NavRepresent,
    /// The toolkit places a navigation host's content-list page ([`props::Pane::List`]) in its
    /// own pane between the sidebar and the detail, the Mail shape: mailboxes, message list,
    /// message (docs/navigation.md). The three answers differ on what happens when the host
    /// leaves the split:
    ///
    /// - `Native`: the pane exists at every presentation. A narrow window collapses the
    ///   sidebar but keeps the list beside the detail, exactly as a narrow Mail.app does
    ///   (macos-appkit: a `contentList` `NSSplitViewItem`).
    /// - `Emulated`: the pane exists while split and merges into the navigation stack when
    ///   the host collapses (ios-uikit: `UISplitViewController` triple-column). The pieces
    ///   layer then interposes the list between the sidebar root and the detail
    ///   ([`props::NavPatch::ListInStack`]) and gates the detail push on the app's
    ///   `detail_visible` binding.
    /// - `Unsupported`: the backend never sees [`props::Pane::List`] or
    ///   [`props::NavProps::list_width`]; the nav piece composes the pane beside (split)
    ///   or in place of (stacked) the destination content itself.
    NavContentList,
    /// The toolkit shows the current destination's title in a native header/bar, so a page
    /// needn't repeat it in its own content. `Native` on XAML (the NavigationView header),
    /// UIKit (`UINavigationBar`), Android (`MaterialToolbar`), and ArkUI (`NavDestination`
    /// title bars). The desktop custom back-headers (AppKit/Qt/web) show a title only in
    /// stack mode, so those backends stay `Unsupported` (docs/navigation.md).
    NavHeader,
    /// The toolkit applies a runtime appearance override (`set_appearance`): native widgets
    /// restyle in place and `dark_mode` answers the override. Probe before showing a theme
    /// picker; on `Unsupported` backends the call is ignored.
    Appearance,
    /// The toolkit renders an application menu bar (docs/menus.md), so `app_menu` is visible to
    /// the user, and `register_preferences` gets its automatic Settings… item.
    ///
    /// The question an app asks before deciding where a command lives. Settings is the usual
    /// case: on a platform with a menu bar it belongs in the App menu and putting it in the
    /// navigation as well is clutter; on one without, the menu is a no-op and a Settings row is
    /// the only way in. Distinct from `Cap::Toolbar`: web-dom draws a window toolbar and has no
    /// menu bar at all, so keying off the toolbar strands Settings there.
    AppMenu,
    /// The toolkit can present native alert/confirm/sheet/prompt modals (docs/dialogs.md).
    Dialogs,
    /// The toolkit can present native open/save file pickers (docs/files.md).
    FileDialogs,
    /// The toolkit can present a native folder chooser (`PresentSpec::OpenFolder`,
    /// docs/files.md). `Native` on the four desktop toolkits (AppKit, GTK, Qt, WinUI); the
    /// phone and web backends answer `Unsupported` and resolve the request as `Dismissed`, so
    /// an app hides its "Add Folder…" command where this is not `Native`.
    FolderDialog,
    /// The toolkit runs backend-executed animation for `AnimSpec` intents on
    /// `update`/`set_frame`/`set_opacity`/`set_transform` (§8.4). `Unsupported` ⇒ animated calls
    /// apply instantly (still correct, just not animated).
    Animation,
    /// The toolkit presents a `kinds::COVER` node as a native fullscreen modal surface
    /// (docs/cover.md). `Unsupported` ⇒ the `cover` piece's content never shows.
    Cover,
    /// The toolkit presents a `.sheet()` cover as a native modal sheet (AppKit's window sheet,
    /// UIKit's page sheet) over the page it covers (docs/cover.md "Modal sheet"). `Unsupported`
    /// ⇒ the `cover` piece composes the sheet itself: on a window wider than compact, a card
    /// centered over the dimmed page; on a compact one, the full window.
    CoverSheet,
    /// The toolkit can hide the system status bar while a `status_bar_hidden` subtree is
    /// mounted (`Toolkit::set_status_bar_hidden`, docs/cover.md). `Native` on the phone and
    /// tablet backends; desktop and web have no status bar, so a setting that offers to hide
    /// it should be offered only where this is not `Unsupported`.
    StatusBarHidden,
    /// The toolkit's `text_area` can be made read-only (`TextAreaProps::editable = false`).
    TextEditable,
    /// The toolkit's `text_area` selectability can be toggled (`TextAreaProps::selectable`).
    /// `Unsupported` where selection is always on (GTK); `Emulated` where the backend
    /// collapses native selections itself (XAML, ArkUI).
    TextSelectable,
    /// The toolkit's `text_area` has built-in spell-check/autocorrect (`TextAreaProps::spellcheck`).
    /// `Unsupported` where the toolkit ships none (GTK, Qt, ArkUI).
    TextSpellCheck,
    /// The toolkit can open additional native OS windows (`Toolkit::open_window`,
    /// docs/windows.md). `Native` on the desktop backends and on mobile backends whose
    /// platform has a real secondary-window surface (iPad scenes, Android document
    /// activities, OHOS multiton abilities). On `Unsupported` backends
    /// `day_core::open_window` still works; the content presents as a fullscreen cover in
    /// the primary window instead. Probe it to adapt chrome: an `Unsupported` tier has no
    /// native title bar or close button, so window content should carry its own close
    /// affordance.
    MultiWindow,
    /// The toolkit can put a count on the app icon (`Toolkit::set_app_badge`, docs/badge.md).
    /// `Emulated` where the call is made but the shell may ignore it: desktop Linux, where the
    /// Unity launcher protocol is honored by Plasma and Dash-to-Dock but not by stock GNOME.
    AppBadgeCount,
    /// The toolkit renders `AppBadge::Text` as written. macOS only: `NSDockTile.badgeLabel` is an
    /// arbitrary string, while every other platform's badge is a number or nothing.
    AppBadgeText,
    /// The toolkit can show a valueless indicator (`AppBadge::Dot`).
    AppBadgeDot,
    /// The toolkit gives a window chrome that persists across pages
    /// (`Toolkit::edit_toolbar`, docs/toolbars.md): `Native` on the desktop backends and the
    /// phones, `Emulated` on web-dom, `Unsupported` where the only chrome belongs to a page.
    ///
    /// It no longer decides whether a command can be shown at all: a toolbar item declared on a
    /// piece rides that piece's own chrome everywhere. Probe it only for a layout decision that
    /// turns on a persistent bar existing.
    Toolbar,
    /// The window toolbar can hold a search field (docs/search.md): `Native` on the desktop
    /// backends, `Emulated` on web-dom. `Unsupported` on the phones, whose bar is a row of actions
    /// (an Android app-bar menu, iOS bar buttons, ArkUI title-bar menus): their field goes on the
    /// navigation surface instead, so `SearchPlacement::Toolbar` resolves to `Inline` there.
    ToolbarSearch,
    /// The toolkit realizes `kinds::INSPECTOR` as its own trailing-pane container
    /// (docs/inspector.md): an `NSSplitView` inspector pane, a `GtkPaned` with the panel as
    /// its end child, a `QDockWidget`, a XAML `SplitView` right pane. `Unsupported` ⇒ the
    /// `inspector` piece composes the pane from plain containers instead (same panel, same
    /// signal, no native divider), so an unimplemented backend degrades to a drawn pane, not
    /// to a hole. Apps normally have no reason to probe this; the piece does.
    Inspector,
    /// The toolkit realizes `kinds::SPLIT` as its own splitter (docs/split.md): an
    /// `NSSplitView`, a `GtkPaned`, a `QSplitter`, each side by side or stacked and with the
    /// divider the user drags. `Unsupported` ⇒ the `split` piece composes the two panes and
    /// draws and drags the divider itself (the web, the mobile toolkits, XAML), so the piece
    /// behaves the same everywhere and only the divider's look is the toolkit's. Apps have no
    /// reason to probe this; the piece does.
    Split,
    /// The toolkit shapes the pointer over a node from the `.cursor()` decorator
    /// ([`Toolkit::set_cursor`], docs/cursor.md). `Native` where the platform draws the requested
    /// shape from its own set (AppKit, GTK, the DOM, Android's `PointerIcon`), `Emulated` where
    /// some shapes map to a nearest neighbor (Qt, XAML) or the platform draws pointer effects
    /// rather than shapes (iPadOS), `Unsupported` where nothing changes: a touch-only toolkit,
    /// or one whose pointer API Day does not reach yet. Apps ask before offering an affordance
    /// that only a cursor reveals, such as a resize handle with no other visual.
    Cursor,
    /// The toolkit can enumerate the platform's font families with the faces each ships
    /// ([`Toolkit::font_families`], docs/fonts.md). `Native` where an OS font database answers
    /// (NSFontManager, UIFont, Pango, QFontDatabase, Android's `fonts.xml`,
    /// `OH_Drawing_FontMgr`, DirectWrite); `Emulated` where the list is composed rather than
    /// read: web-dom answers the CSS generic families plus the bundled `document.fonts`, since
    /// a browser exposes no local font list without a permission prompt; `Unsupported` means
    /// the list is empty and an app should offer only the default face. Measurement
    /// ([`Toolkit::measure_text`]) has no probe: a `None` answer degrades to
    /// [`TextMetrics::approximate`]. Probe this before offering a font menu, not before
    /// drawing; a [`CanvasFont`] draws everywhere.
    FontList,
    /// The toolkit reads the user's reduce-motion setting ([`Toolkit::reduce_motion`],
    /// docs/accessibility.md) and reports when it changes. `Native` where the platform has the
    /// switch and Day reaches it; `Unsupported` where Day reaches none (the app then animates as
    /// it would with the setting off, and `DAY_REDUCE_MOTION=1` still forces it on).
    ReduceMotion,
    /// The toolkit can speak a sentence through the screen reader without moving its focus
    /// ([`Toolkit::announce`], docs/accessibility.md): "Saved", "3 results", "Upload failed".
    /// `Native` where the platform has an announcement request (`NSAccessibility`'s
    /// announcement notification, `UIAccessibility`'s, Android's accessibility event, GTK
    /// 4.14's `gtk_accessible_announce`, a WinUI notification event); `Emulated` on the web,
    /// where an ARIA live region carries it; `Unsupported` where Day reaches no announcement
    /// API yet. An app with a visible status label needs no announcement: screen readers read
    /// what changes on screen only when told to, so this is for the change the user cannot
    /// otherwise learn about.
    Announce,
    /// The toolkit can turn encoded image bytes into a native image
    /// ([`Toolkit::decode_image`], docs/images.md): what `image(bytes)`, a pasted screenshot and
    /// a canvas image all rest on. `Native` wherever the platform decoder takes a buffer;
    /// `Unsupported` means only staged asset names draw, so an app should not offer "open an
    /// image" at all. Every backend that decodes also answers [`Toolkit::image_info`], so pixel
    /// size needs no probe of its own.
    ImageDecode,
    /// The toolkit can encode a decoded image back to bytes ([`Toolkit::encode_image`]).
    /// Which formats it encodes is [`Toolkit::encode_formats`], the same shape as
    /// [`Cap::FontList`]/[`Toolkit::font_families`], because "can encode" and "can encode WebP"
    /// are different questions and only the second one needs a list.
    ImageEncode,
    /// The toolkit can read an image's metadata beyond its pixels: EXIF orientation, DPI,
    /// capture time ([`Toolkit::image_properties`]). `Native` where a platform metadata reader
    /// is already linked (WinRT's `BitmapPropertiesView`, Android's `ExifInterface`);
    /// `Unsupported` where reading it would mean shipping a parser or a new framework, which is
    /// most places. An app that wants orientation must handle `None`.
    ImageProperties,
    /// The toolkit can replay a canvas drawing into an offscreen bitmap
    /// ([`Toolkit::render_bitmap`], docs/canvas.md "Exporting"): what `Drawing::to_bitmap` and
    /// `Drawing::to_png` rest on. `Native` where the toolkit's own canvas painter can target an
    /// image surface (a `CGBitmapContext`, a cairo image surface, a `QImage`, an android
    /// `Bitmap`, an `OH_Drawing_Bitmap`, a detached `<canvas>`); `Unsupported` where the
    /// on-screen canvas has no painter to retarget (WinUI builds XAML shapes instead).
    CanvasBitmap,
    /// The toolkit can replay canvas drawings into a PDF document ([`Toolkit::render_pdf`],
    /// docs/canvas.md "Exporting"), with vector shapes and the platform's own font embedding.
    /// `Native` only where the platform ships a PDF writer the canvas painter can draw into
    /// (Core Graphics on AppKit and UIKit, cairo on GTK, `QPdfWriter` on Qt, `PdfDocument` on
    /// Android); `Unsupported` on ArkUI, the web and WinUI, which have none.
    CanvasPdf,
    /// The toolkit minimizes, zooms, hides and restores a window on request
    /// ([`WindowChange::State`], [`WindowChange::Visible`], docs/windows.md) and reports what the
    /// user does through [`Event::WindowStateChanged`]. `Native` on the desktop backends;
    /// `Unsupported` on the phones and the web, whose windows the OS sizes.
    WindowStates,
    /// The toolkit takes a window fullscreen on request and reports when it enters and leaves
    /// ([`WindowState::Fullscreen`]). `Native` on the desktops, on Android (system bars hidden
    /// through `WindowInsetsController`), on HarmonyOS and on the web (the Fullscreen API, which
    /// browsers allow only during a user gesture); `Emulated` on iOS, which hides the status bar
    /// and lets the home indicator fade but always keeps the app full-screen anyway.
    WindowFullscreen,
    /// The toolkit keeps a window out of screenshots, recordings and screen sharing
    /// ([`WindowChange::ContentProtected`]). `Native` on macOS (`NSWindowSharingNone`), Windows
    /// (`WDA_EXCLUDEFROMCAPTURE`), Android (`FLAG_SECURE`) and HarmonyOS (privacy mode);
    /// `Emulated` on iOS, which has no switch for it: Day covers the content while the screen is
    /// being recorded or mirrored, but a screenshot still captures it. `Unsupported` on Linux
    /// and the web.
    ContentProtection,
    /// The toolkit honors [`WindowOptions::tabbing`]: macOS window tabs. `Unsupported` everywhere
    /// else, where no system window tabs exist.
    WindowTabbing,
    /// The toolkit shows a Dock menu ([`Toolkit::set_dock_menu`], docs/menus.md): the app's
    /// shortcuts and `dock_menu(..)` entries above the system's own items. macOS only.
    DockMenu,
    /// The toolkit resizes a window and bounds its size on request ([`WindowChange::Frame`]'s
    /// size, [`WindowChange::Limits`], [`WindowChange::Resizable`]).
    WindowGeometry,
    /// The toolkit moves a window to a requested position ([`WindowChange::Frame`]'s origin).
    /// `Unsupported` on GTK 4, which removed window positioning, and wherever the compositor owns
    /// placement (Wayland).
    WindowPosition,
    /// The toolkit changes how a window stacks ([`WindowChange::Level`],
    /// [`WindowChange::OnAllWorkspaces`], [`WindowChange::SkipTaskbar`]).
    WindowLevel,
    /// The toolkit gives one window its own light/dark appearance ([`WindowChange::Appearance`]).
    /// Where it cannot, the app-wide [`Toolkit::set_appearance`] still applies to every window.
    WindowAppearance,
    /// The toolkit asks for the user's attention on request ([`WindowChange::RequestAttention`]):
    /// a Dock bounce, a flashing taskbar button.
    RequestAttention,
    /// The toolkit opens a window with no title bar or frame ([`WindowChrome::Frameless`],
    /// docs/window-chrome.md). Desktop backends only.
    FramelessWindow,
    /// The toolkit runs a window's content under its title bar with the window controls kept
    /// ([`WindowChrome::Overlay`]) and reports the bar's height as the safe-area top inset.
    OverlayTitleBar,
    /// The toolkit opens a window whose unpainted pixels show the desktop
    /// ([`WindowBackground::Transparent`]).
    TransparentWindow,
    /// The toolkit puts a translucent system material behind a window
    /// ([`WindowBackground::Material`]): macOS's visual-effect materials, Windows 11's Mica and
    /// Acrylic. `Emulated` where an approximation stands in.
    WindowMaterial,
    /// The toolkit lets a piece move its window like a title bar does
    /// ([`Toolkit::set_drag_region`], `.window_drag_region()`). `Emulated` on the web, where
    /// only an installed app with a window-controls overlay honors it.
    DragRegion,
    /// The toolkit shows status items ([`Toolkit::set_status_items`], docs/status-item.md): the
    /// macOS menu bar, the Windows notification area, a Linux tray. On Linux the answer depends
    /// on the desktop: `Native` while a StatusNotifierItem host is running (KDE Plasma, most
    /// panels, GNOME with the AppIndicator extension), `Unsupported` without one (stock GNOME),
    /// so an app can keep a window instead of vanishing into a tray nobody shows.
    StatusItem,
    /// The toolkit shows progress on the app's Dock or taskbar icon
    /// ([`Toolkit::set_app_progress`]). `Emulated` on Linux, where the Unity launcher protocol is
    /// honored by KDE Plasma and Dash to Dock but not by every dock.
    AppProgress,
    /// The toolkit can hide the app's Dock icon while it runs ([`Toolkit::set_dock_visible`]).
    /// macOS only.
    DockVisibility,
    /// The toolkit lists the displays and their work areas ([`Toolkit::monitors`]). `Emulated`
    /// where the one screen the app runs on is reported (a phone, the web).
    Monitors,
    /// The toolkit shows launcher shortcuts the app sets while it runs
    /// ([`Toolkit::set_launcher_shortcuts`]).
    DynamicShortcuts,
    /// How the toolkit draws a sectioned list's headers (`ListProps::sections`, docs/list.md
    /// "Sections"). `Native` where the platform's list has group headers that pin to the top
    /// while their section scrolls under them: macos-appkit (`NSTableView` group rows with
    /// `floatsGroupRows`) and ios-uikit (plain-style `UITableView` section headers).
    /// `Emulated` where the host pins a copy of the current header over the top of the list
    /// itself. Headers are unselectable rows on every toolkit, so an app needs this only to
    /// describe the difference, never to decide whether to call `.sections`.
    ListSections,
}

impl Cap {
    /// Every capability, in declaration order: what a conformance run asks the toolkit about,
    /// so the evidence can be held against the declared coverage matrix (docs/testing.md).
    pub const ALL: [Cap; 90] = [
        Cap::DragDrop,
        Cap::DragExternalImport,
        Cap::DragExternalExport,
        Cap::DragMultipleItems,
        Cap::DragFileReferences,
        Cap::DragDeferredReceipt,
        Cap::DragFilePromises,
        Cap::DragExternalMove,
        Cap::ListRecycling,
        Cap::UndoBridge,
        Cap::EditBridge,
        Cap::ListReorder,
        Cap::NavReorder,
        Cap::ListDelete,
        Cap::ListSwipeActions,
        Cap::Tree,
        Cap::TreeMove,
        Cap::BaselineAlignment,
        Cap::TextRuns,
        Cap::TextLinks,
        Cap::Lottie,
        Cap::NativeSymbols,
        Cap::Snapshot,
        Cap::NavSplit,
        Cap::NavTabs,
        Cap::NavTabsAdaptive,
        Cap::NavRepresent,
        Cap::NavContentList,
        Cap::NavHeader,
        Cap::Appearance,
        Cap::AppMenu,
        Cap::Dialogs,
        Cap::FileDialogs,
        Cap::Animation,
        Cap::Cover,
        Cap::StatusBarHidden,
        Cap::TextEditable,
        Cap::TextSelectable,
        Cap::TextSpellCheck,
        Cap::MultiWindow,
        Cap::AppBadgeCount,
        Cap::AppBadgeText,
        Cap::AppBadgeDot,
        Cap::Toolbar,
        Cap::ToolbarSearch,
        Cap::Inspector,
        Cap::Cursor,
        Cap::FontList,
        Cap::ReduceMotion,
        Cap::Announce,
        Cap::ImageDecode,
        Cap::ImageEncode,
        Cap::ImageProperties,
        Cap::WindowStates,
        Cap::WindowFullscreen,
        Cap::ContentProtection,
        Cap::WindowTabbing,
        Cap::DockMenu,
        Cap::WindowGeometry,
        Cap::WindowPosition,
        Cap::WindowLevel,
        Cap::WindowAppearance,
        Cap::RequestAttention,
        Cap::FramelessWindow,
        Cap::OverlayTitleBar,
        Cap::TransparentWindow,
        Cap::WindowMaterial,
        Cap::DragRegion,
        Cap::StatusItem,
        Cap::AppProgress,
        Cap::DockVisibility,
        Cap::Monitors,
        Cap::DynamicShortcuts,
        Cap::Split,
        Cap::TreeSections,
        Cap::CoverSheet,
        Cap::ListEditing,
        Cap::ListItem,
        Cap::CanvasBitmap,
        Cap::CanvasPdf,
        Cap::SearchField,
        Cap::ComboBox,
        Cap::Stepper,
        Cap::DateTimePicker,
        Cap::ColorPicker,
        Cap::PullRefresh,
        Cap::Pager,
        Cap::PullRefreshGesture,
        Cap::FolderDialog,
        Cap::ListSections,
    ];

    /// The capability's place in [`Cap::ALL`]. Exhaustive, so a new variant fails to compile
    /// here until it is given one, and the unit test below then holds `ALL` to it.
    pub const fn ordinal(self) -> usize {
        match self {
            Cap::DragDrop => 0,
            Cap::DragExternalImport => 1,
            Cap::DragExternalExport => 2,
            Cap::DragMultipleItems => 3,
            Cap::DragFileReferences => 4,
            Cap::DragDeferredReceipt => 5,
            Cap::DragFilePromises => 6,
            Cap::DragExternalMove => 7,
            Cap::ListRecycling => 8,
            Cap::UndoBridge => 9,
            Cap::EditBridge => 10,
            Cap::ListReorder => 11,
            Cap::NavReorder => 12,
            Cap::ListDelete => 13,
            Cap::ListSwipeActions => 14,
            Cap::Tree => 15,
            Cap::TreeMove => 16,
            Cap::BaselineAlignment => 17,
            Cap::TextRuns => 18,
            Cap::TextLinks => 19,
            Cap::Lottie => 20,
            Cap::NativeSymbols => 21,
            Cap::Snapshot => 22,
            Cap::NavSplit => 23,
            Cap::NavTabs => 24,
            Cap::NavTabsAdaptive => 25,
            Cap::NavRepresent => 26,
            Cap::NavContentList => 27,
            Cap::NavHeader => 28,
            Cap::Appearance => 29,
            Cap::AppMenu => 30,
            Cap::Dialogs => 31,
            Cap::FileDialogs => 32,
            Cap::Animation => 33,
            Cap::Cover => 34,
            Cap::StatusBarHidden => 35,
            Cap::TextEditable => 36,
            Cap::TextSelectable => 37,
            Cap::TextSpellCheck => 38,
            Cap::MultiWindow => 39,
            Cap::AppBadgeCount => 40,
            Cap::AppBadgeText => 41,
            Cap::AppBadgeDot => 42,
            Cap::Toolbar => 43,
            Cap::ToolbarSearch => 44,
            Cap::Inspector => 45,
            Cap::Cursor => 46,
            Cap::FontList => 47,
            Cap::ReduceMotion => 48,
            Cap::Announce => 49,
            Cap::ImageDecode => 50,
            Cap::ImageEncode => 51,
            Cap::ImageProperties => 52,
            Cap::WindowStates => 53,
            Cap::WindowFullscreen => 54,
            Cap::ContentProtection => 55,
            Cap::WindowTabbing => 56,
            Cap::DockMenu => 57,
            Cap::WindowGeometry => 58,
            Cap::WindowPosition => 59,
            Cap::WindowLevel => 60,
            Cap::WindowAppearance => 61,
            Cap::RequestAttention => 62,
            Cap::FramelessWindow => 63,
            Cap::OverlayTitleBar => 64,
            Cap::TransparentWindow => 65,
            Cap::WindowMaterial => 66,
            Cap::DragRegion => 67,
            Cap::StatusItem => 68,
            Cap::AppProgress => 69,
            Cap::DockVisibility => 70,
            Cap::Monitors => 71,
            Cap::DynamicShortcuts => 72,
            Cap::Split => 73,
            Cap::TreeSections => 74,
            Cap::CoverSheet => 75,
            Cap::ListEditing => 76,
            Cap::ListItem => 77,
            Cap::CanvasBitmap => 78,
            Cap::CanvasPdf => 79,
            Cap::SearchField => 80,
            Cap::ComboBox => 81,
            Cap::Stepper => 82,
            Cap::DateTimePicker => 83,
            Cap::ColorPicker => 84,
            Cap::PullRefresh => 85,
            Cap::Pager => 86,
            Cap::PullRefreshGesture => 87,
            Cap::FolderDialog => 88,
            Cap::ListSections => 89,
        }
    }
}

// ---------------------------------------------------------------------------
// Raster images (docs/images.md): the currency shared by the `image` piece, the canvas, and
// the decode/metadata/encode duties below.
// ---------------------------------------------------------------------------

/// A decoded image the toolkit holds, addressed by an id day-core mints.
///
/// Opaque, because what sits behind it is an `NSImage`, a `UIImage`, a `GdkTexture`, a
/// `QPixmap`, a `BitmapImage`, an android `Bitmap` or an `ImageBitmap`, and none of those cross
/// the boundary. The id is released through [`Toolkit::release_image`] when the app's handle
/// drops, so a backend's side table never outlives the app's interest in it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BitmapId(pub u64);

/// An encoded image format: what [`BitmapInfo::format`] reports and [`EncodeSpec::format`] asks
/// for. Not every backend encodes every one: ask [`Toolkit::encode_formats`] (the
/// [`Cap::ImageEncode`] pair of [`Toolkit::font_families`]/[`Cap::FontList`]) rather than
/// assuming.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum ImageFormat {
    #[default]
    Png,
    Jpeg,
    Webp,
    Gif,
    Bmp,
    Tiff,
    /// HEIF/HEIC, Apple's camera format; decodable on the Apple backends and Android, and
    /// encodable almost nowhere.
    Heif,
    /// Decoded from bytes whose magic numbers [`ImageFormat::sniff`] does not know. A backend may
    /// still decode it: the platform decoders read more formats than Day names.
    Unknown,
}

impl ImageFormat {
    /// The IANA media type, which is also the string the ArkUI packer, GDI+ and the browser's
    /// `toBlob` take. `Unknown` answers `application/octet-stream`.
    pub fn mime(self) -> &'static str {
        match self {
            ImageFormat::Png => "image/png",
            ImageFormat::Jpeg => "image/jpeg",
            ImageFormat::Webp => "image/webp",
            ImageFormat::Gif => "image/gif",
            ImageFormat::Bmp => "image/bmp",
            ImageFormat::Tiff => "image/tiff",
            ImageFormat::Heif => "image/heif",
            ImageFormat::Unknown => "application/octet-stream",
        }
    }

    /// The pixel size the encoded bytes declare, read from the container's own header
    /// (docs/images.md).
    ///
    /// Every backend that decodes natively reports its own dimensions; this exists for the one
    /// that cannot. The XAML backend's (`windows-winui`) `BitmapImage` learns its size
    /// asynchronously, only once the element has been shown, so a synchronous `image_info` there
    /// would have nothing to say.
    /// Reading the header instead gives the same answer the decoder would, before any decoding.
    ///
    /// `None` when the header is absent, truncated, or a container this does not parse.
    pub fn dimensions(bytes: &[u8]) -> Option<(u32, u32)> {
        let be16 = |i: usize| -> Option<u32> {
            Some(u32::from(u16::from_be_bytes([
                *bytes.get(i)?,
                *bytes.get(i + 1)?,
            ])))
        };
        let le16 = |i: usize| -> Option<u32> {
            Some(u32::from(u16::from_le_bytes([
                *bytes.get(i)?,
                *bytes.get(i + 1)?,
            ])))
        };
        let be32 = |i: usize| -> Option<u32> {
            Some(u32::from_be_bytes([
                *bytes.get(i)?,
                *bytes.get(i + 1)?,
                *bytes.get(i + 2)?,
                *bytes.get(i + 3)?,
            ]))
        };
        let le32 = |i: usize| -> Option<u32> {
            Some(u32::from_le_bytes([
                *bytes.get(i)?,
                *bytes.get(i + 1)?,
                *bytes.get(i + 2)?,
                *bytes.get(i + 3)?,
            ]))
        };
        match Self::sniff(bytes)? {
            // IHDR is always the first chunk: 8-byte signature, 4-byte length, 4-byte type.
            ImageFormat::Png => Some((be32(16)?, be32(20)?)),
            // The logical screen descriptor follows the 6-byte version stamp, little-endian.
            ImageFormat::Gif => Some((le16(6)?, le16(8)?)),
            // The DIB header's width/height are signed; a negative height is a top-down bitmap.
            ImageFormat::Bmp => Some((
                le32(18)?.cast_signed().unsigned_abs(),
                le32(22)?.cast_signed().unsigned_abs(),
            )),
            // Walk the segment chain to the frame header. Every SOF marker carries the size at
            // the same offsets; the arithmetic-coded and progressive ones are SOFs too, which is
            // why this matches the whole range rather than SOF0 alone. DNL/DHP (0xC4, 0xC8,
            // 0xCC) are not frame headers and are skipped like any other segment.
            ImageFormat::Jpeg => {
                let mut i = 2usize;
                // `<=`, not `<`: a frame header that ends the buffer is still a frame header, and
                // the size sits in its last four bytes.
                while i + 9 <= bytes.len() {
                    if bytes[i] != 0xFF {
                        i += 1;
                        continue;
                    }
                    let marker = bytes[i + 1];
                    // Padding fill bytes and the standalone markers carry no length.
                    if marker == 0xFF || (0xD0..=0xD9).contains(&marker) || marker == 0x01 {
                        i += 1;
                        continue;
                    }
                    let is_sof = (0xC0..=0xCF).contains(&marker)
                        && marker != 0xC4
                        && marker != 0xC8
                        && marker != 0xCC;
                    if is_sof {
                        // [marker][len:2][precision:1][height:2][width:2]
                        return Some((be16(i + 7)?, be16(i + 5)?));
                    }
                    i += 2 + be16(i + 2)? as usize;
                }
                None
            }
            // RIFF: a 12-byte header, then a chunk id. VP8X states the size minus one in 24-bit
            // little-endian; lossy VP8 hides it in the 14 low bits after the start code; lossless
            // VP8L packs width-1 and height-1 into 14 bits each across four bytes.
            ImageFormat::Webp => match bytes.get(12..16)? {
                b"VP8X" => {
                    let w = u32::from(*bytes.get(24)?)
                        | u32::from(*bytes.get(25)?) << 8
                        | u32::from(*bytes.get(26)?) << 16;
                    let h = u32::from(*bytes.get(27)?)
                        | u32::from(*bytes.get(28)?) << 8
                        | u32::from(*bytes.get(29)?) << 16;
                    Some((w + 1, h + 1))
                }
                b"VP8 " => Some((le16(26)? & 0x3FFF, le16(28)? & 0x3FFF)),
                b"VP8L" => {
                    let bits = le32(21)?;
                    Some(((bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1))
                }
                _ => None,
            },
            // TIFF's IFD is a pointer chase and HEIF's is a box tree; neither is worth parsing
            // here, because every backend that reads them decodes natively and answers for itself.
            ImageFormat::Tiff | ImageFormat::Heif | ImageFormat::Unknown => None,
        }
    }

    /// The format `bytes` begins with, by magic number: enough to fill [`BitmapInfo::format`]
    /// on every backend, including the ones whose decoder never says what it decoded.
    ///
    /// Hand-rolled rather than a crate: it is a dozen byte comparisons against fixed prefixes,
    /// and the alternative is an image-decoding dependency in the one crate that must stay
    /// dependency-free.
    pub fn sniff(bytes: &[u8]) -> Option<ImageFormat> {
        let starts = |sig: &[u8]| bytes.len() >= sig.len() && &bytes[..sig.len()] == sig;
        if starts(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]) {
            return Some(ImageFormat::Png);
        }
        if starts(&[0xff, 0xd8, 0xff]) {
            return Some(ImageFormat::Jpeg);
        }
        if starts(b"GIF87a") || starts(b"GIF89a") {
            return Some(ImageFormat::Gif);
        }
        if starts(b"BM") {
            return Some(ImageFormat::Bmp);
        }
        if starts(&[0x49, 0x49, 0x2a, 0x00]) || starts(&[0x4d, 0x4d, 0x00, 0x2a]) {
            return Some(ImageFormat::Tiff);
        }
        // RIFF....WEBP and ....ftypheic/heix/mif1 both carry their tag past a 4-byte prefix.
        if starts(b"RIFF") && bytes.len() >= 12 && &bytes[8..12] == b"WEBP" {
            return Some(ImageFormat::Webp);
        }
        if bytes.len() >= 12 && &bytes[4..8] == b"ftyp" {
            let brand = &bytes[8..12];
            if brand == b"heic" || brand == b"heix" || brand == b"mif1" || brand == b"msf1" {
                return Some(ImageFormat::Heif);
            }
        }
        None
    }
}

/// What a decoded image is, in the terms every backend can answer
/// ([`Toolkit::image_info`], docs/images.md).
///
/// `pixels` is the image's own pixel size, not the points it draws at: an asset that stages at
/// 2× reports twice its point size and a `scale` of 2, so an app sizing a frame divides. Bytes
/// carry no density, so a decoded buffer always answers `scale: 1.0`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct BitmapInfo {
    pub pixels: Size,
    /// Pixels per point (1.0 for decoded bytes; 2 or 3 for a catalog/drawable asset that staged
    /// a density variant).
    pub scale: f64,
    /// The encoded format it came from, where the backend knows or [`ImageFormat::sniff`] said.
    pub format: Option<ImageFormat>,
    pub has_alpha: bool,
}

/// What [`Toolkit::encode_image`] should produce (docs/images.md).
///
/// A struct rather than three positional arguments, per docs/api-style.md: the call site reads
/// `EncodeSpec { format: ImageFormat::Jpeg, quality: Some(0.8), ..Default::default() }`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct EncodeSpec {
    pub format: ImageFormat,
    /// Lossy quality in `0.0..=1.0`. `None` takes the platform's default; a lossless format
    /// ignores it.
    pub quality: Option<f64>,
    /// Scale the longest side down to fit this box first (aspect preserved). `None` encodes at
    /// the image's own size.
    pub fit: Option<Size>,
}

impl Default for EncodeSpec {
    fn default() -> Self {
        EncodeSpec {
            format: ImageFormat::Png,
            quality: None,
            fit: None,
        }
    }
}

/// The metadata an image file carries beyond its pixels ([`Toolkit::image_properties`]).
///
/// Sparse by construction: every field is what the platform's own reader answered, and a
/// backend with no metadata reader at all answers `None` to the whole call rather than an empty
/// struct. Probe [`Cap::ImageProperties`] before offering an affordance that depends on it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ImageProperties {
    /// The EXIF orientation tag (1–8), where one was recorded.
    pub orientation: Option<u16>,
    /// Pixels per inch, where the file records a resolution.
    pub dpi: Option<f64>,
    /// The capture timestamp as the file spells it (no parsing: the formats disagree).
    pub created: Option<String>,
    /// Everything else the platform reader named, in its own vocabulary. Keys are the
    /// platform's, so read them defensively.
    pub extra: Vec<(String, String)>,
}

/// Why an image operation could not answer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageError {
    /// The bytes are not an image this platform decodes.
    Decode,
    /// The image decoded, but this backend cannot encode the format asked for. `encode_formats`
    /// says which it can.
    Encode,
    /// The backend has no path for this at all (probe [`Cap::ImageDecode`] /
    /// [`Cap::ImageEncode`]).
    Unsupported,
    /// The id named no live image: released already, or never decoded.
    Gone,
}

impl std::fmt::Display for ImageError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImageError::Decode => write!(f, "the bytes are not a decodable image"),
            ImageError::Encode => write!(f, "this backend cannot encode that format"),
            ImageError::Unsupported => write!(f, "image support is unavailable on this backend"),
            ImageError::Gone => write!(f, "the image was released"),
        }
    }
}

impl std::error::Error for ImageError {}

// ---------------------------------------------------------------------------
// Canvas export (docs/canvas.md "Exporting"): a recorded drawing replayed into an offscreen
// bitmap or a PDF by the same painter the on-screen canvas uses.
// ---------------------------------------------------------------------------

/// The largest side, in pixels, a rendered bitmap may have (docs/canvas.md "Exporting").
/// day-core answers [`ExportError::TooLarge`] above it before any toolkit allocates.
pub const EXPORT_MAX_SIDE: u32 = 16_384;

/// The most pixels a rendered bitmap may hold in total: 64 megapixels, 256 MB at four bytes a
/// pixel, which is already more than the tightest per-app heap (Android's) comfortably holds.
pub const EXPORT_MAX_PIXELS: u64 = 64 * 1024 * 1024;

/// The pixel size a drawing of `size` points renders to at `scale` pixels per point: each side
/// rounded up, so a drawing never loses its last partial pixel. Shared by day-core's limit
/// check and every backend, so the bitmap a backend allocates is the one day-core approved.
pub fn export_pixels(size: Size, scale: f64) -> (u32, u32) {
    let side = |v: f64| (v * scale).ceil().clamp(0.0, u32::MAX as f64) as u32;
    (side(size.width), side(size.height))
}

/// One page of a PDF [`Toolkit::render_pdf`] writes: the page size in PDF points (1/72 inch,
/// the same unit as canvas points) and the ops to replay onto it, origin top-left.
#[derive(Clone, Debug, PartialEq)]
pub struct PdfPage {
    pub size: Size,
    pub ops: Vec<DrawOp>,
}

/// The document information a PDF carries. A backend whose writer has no metadata API (Android's
/// `PdfDocument`) ignores it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PdfInfo {
    pub title: Option<String>,
    pub author: Option<String>,
}

/// Why a canvas export could not answer (docs/canvas.md "Exporting").
#[derive(Clone, Debug, PartialEq)]
pub enum ExportError {
    /// This toolkit has no path for the export (probe [`Cap::CanvasBitmap`] /
    /// [`Cap::CanvasPdf`]).
    Unsupported,
    /// The bitmap would exceed [`EXPORT_MAX_SIDE`] or [`EXPORT_MAX_PIXELS`]; checked in
    /// day-core before the toolkit runs. The size is the one that was refused, in pixels.
    TooLarge { width: u32, height: u32 },
    /// A zero, negative or non-finite size or scale, or a PDF with no pages.
    Invalid,
    /// The platform refused (out of memory, a writer error); the text is the platform's.
    Failed(String),
}

impl std::fmt::Display for ExportError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ExportError::Unsupported => write!(f, "this export is unavailable on this backend"),
            ExportError::TooLarge { width, height } => {
                write!(
                    f,
                    "a {width} × {height} pixel bitmap is too large to render"
                )
            }
            ExportError::Invalid => write!(f, "the drawing has no size or the PDF has no pages"),
            ExportError::Failed(why) => write!(f, "rendering failed: {why}"),
        }
    }
}

impl std::error::Error for ExportError {}

/// Where a raster image's pixels come from (docs/images.md).
///
/// One currency for both halves of the same question: `Named` is the staged asset every
/// `image(res::images::…)` has always drawn, `Bytes` is an encoded PNG/JPEG the app already
/// holds (a download, a file the user picked, a clipboard paste), and `Decoded` names an image
/// the toolkit decoded once so several nodes (and the canvas) share it.
#[derive(Clone)]
pub enum ImageSource {
    /// A staged asset name, resolved through the backend's own pipeline (§18.2).
    Named(String),
    /// Encoded bytes (PNG/JPEG/…) the app owns, decoded by the platform's own decoder. Shared
    /// rather than copied: handing over a new buffer is a refcount bump.
    Bytes(std::sync::Arc<Vec<u8>>),
    /// An image already decoded through [`Toolkit::decode_image`].
    Decoded(BitmapId),
}

impl Default for ImageSource {
    fn default() -> Self {
        ImageSource::Named(String::new())
    }
}

/// Bytes compare by identity, not content.
///
/// This is the equality a binding gates on (§4.2), so it runs on every evaluation, and
/// comparing two multi-megabyte buffers byte by byte would cost far more than the redundant
/// decode it saves. Handing over a distinct buffer holding the same pixels therefore re-decodes,
/// which is the same trade `Arc::ptr_eq` makes wherever else Day carries shared buffers.
impl PartialEq for ImageSource {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ImageSource::Named(a), ImageSource::Named(b)) => a == b,
            (ImageSource::Bytes(a), ImageSource::Bytes(b)) => std::sync::Arc::ptr_eq(a, b),
            (ImageSource::Decoded(a), ImageSource::Decoded(b)) => a == b,
            _ => false,
        }
    }
}

/// Logs the buffer's length, never its contents: a `Debug` that dumped a megabyte of pixels
/// into a trace line would make the trace useless and slow.
impl std::fmt::Debug for ImageSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ImageSource::Named(n) => f.debug_tuple("Named").field(n).finish(),
            ImageSource::Bytes(b) => f.debug_tuple("Bytes").field(&b.len()).finish(),
            ImageSource::Decoded(id) => f.debug_tuple("Decoded").field(&id.0).finish(),
        }
    }
}

impl From<BitmapId> for ImageSource {
    fn from(id: BitmapId) -> Self {
        ImageSource::Decoded(id)
    }
}

/// A staged asset name is a source, so `image(res::images::cover)` keeps compiling unchanged.
///
/// There is no `From<&str>` here, for the same reason [`resource::ImageName`] has none:
/// `image("typo")` must stay a compile error rather than a blank view at runtime (resource.rs).
/// A path or URL string is not a source either: read the bytes and hand those over.
impl From<resource::ImageName> for ImageSource {
    fn from(name: resource::ImageName) -> Self {
        ImageSource::Named(name.as_str().to_owned())
    }
}

impl From<resource::VectorName> for ImageSource {
    fn from(name: resource::VectorName) -> Self {
        ImageSource::Named(name.as_str().to_owned())
    }
}

impl From<std::sync::Arc<Vec<u8>>> for ImageSource {
    fn from(bytes: std::sync::Arc<Vec<u8>>) -> Self {
        ImageSource::Bytes(bytes)
    }
}

/// An owned string is a name, not bytes: the same conversion [`resource::ImageName`] offers for
/// a name computed at runtime, and the reason `image(some_string)` keeps compiling. A `&str`
/// still converts nowhere, so `image("typo")` stays a compile error (resource.rs).
impl From<String> for ImageSource {
    fn from(name: String) -> Self {
        ImageSource::Named(name)
    }
}

impl From<Vec<u8>> for ImageSource {
    fn from(bytes: Vec<u8>) -> Self {
        ImageSource::Bytes(std::sync::Arc::new(bytes))
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Support {
    Native,
    Emulated,
    /// The default: what an unimplemented capability answers everywhere.
    #[default]
    Unsupported,
}

/// What a text field collects (`text_field(..).input_purpose(_)`, docs/textfield.md).
///
/// One word for everything a platform keys off the kind of text: the on-screen keyboard's
/// layout, capitalization and correction, and the credential or contact the system offers to
/// fill in. A backend applies the parts its toolkit has: a desktop toolkit with no on-screen
/// keyboard still takes the autofill and correction half.
///
/// Purpose is independent of [`InputTraits::secure`]: a numeric PIN is `Number` and secure.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InputPurpose {
    /// Free text: the default keyboard, with the platform's own capitalization and correction.
    #[default]
    Text,
    /// A person's name: words capitalized, never corrected.
    Name,
    /// An email address: the `@` keyboard, never capitalized or corrected.
    Email,
    /// A web address: the URL keyboard, never capitalized or corrected.
    Url,
    /// A telephone number: the phone pad.
    Phone,
    /// A whole number: the digit pad.
    Number,
    /// A number with a fractional part: the digit pad with a decimal separator.
    Decimal,
    /// An account name: never capitalized or corrected, and offered to the password manager.
    Username,
    /// An existing password, offered to the password manager for filling.
    Password,
    /// A password being chosen, so the password manager offers to make and save one.
    NewPassword,
    /// A code sent by message or mail, which the keyboard offers as it arrives. The keyboard
    /// stays the text one, since a code can carry letters.
    OneTimeCode,
}

/// The on-screen keyboard's action key (`text_field(..).submit_label(_)`, docs/textfield.md).
///
/// The key always fires the field's `on_submit`; this names what it promises. A toolkit with
/// no on-screen keyboard ignores it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SubmitLabel {
    /// The platform's own key (Return).
    #[default]
    Return,
    Done,
    Go,
    Next,
    Search,
    Send,
}

/// How a text field takes its text (docs/textfield.md): the whole set travels together through
/// [`Toolkit::set_input_traits`], so a backend that has to rebuild the widget for one member
/// has every other member in hand to dress the replacement.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct InputTraits {
    /// Hide the characters (a password field).
    pub secure: bool,
    /// Show and select the text, take no edits.
    pub read_only: bool,
    pub purpose: InputPurpose,
    pub submit_label: SubmitLabel,
    /// The most characters (Unicode scalar values) the field takes; `None` is unbounded.
    /// day-pieces holds the bound on every backend. A toolkit applies its native limit as well
    /// only where that limit counts the same unit (GTK): one that counts UTF-16 units would
    /// refuse characters the bound allows.
    pub max_length: Option<u32>,
}

/// The pointer's shape over a piece (the `.cursor()` decorator, docs/cursor.md).
///
/// The named variants are the CSS cursor vocabulary: the largest set any toolkit accepts as it
/// is (GTK and the DOM take the names verbatim), and every other toolkit's set is a subset of it
/// or maps onto it. A backend draws its own shape for each name, or the nearest one it has, and
/// answers [`Cap::Cursor`] with how faithful that is. [`Cursor::Native`] reaches a shape only one
/// toolkit names; the `day::cursor::<toolkit>` modules carry those as constants, gated on that
/// toolkit's feature, and every other backend ignores a name it does not know.
///
/// A cursor applies to the node and its descendants until a descendant sets its own.
/// [`Cursor::Default`] hands the shape back to the platform rather than pinning an arrow, so a
/// reactive cursor can release what it took.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Default)]
pub enum Cursor {
    /// The platform default (an arrow), and the value that releases a node's cursor.
    #[default]
    Default,
    /// A pointing hand: links and other tap-to-activate content.
    Pointer,
    /// An I-beam over editable or selectable text.
    Text,
    /// An I-beam for vertical text.
    VerticalText,
    Crosshair,
    /// Four-way move.
    Move,
    /// An open hand: content that can be dragged.
    Grab,
    /// A closed hand: content being dragged.
    Grabbing,
    NotAllowed,
    /// The app is busy and cannot take input.
    Wait,
    /// The app is busy but still takes input.
    Progress,
    Help,
    ContextMenu,
    /// A drop will copy.
    Copy,
    /// A drop will link.
    Alias,
    /// A table cell.
    Cell,
    ZoomIn,
    ZoomOut,
    /// No pointer at all.
    None,
    /// Vertical (north–south) resize.
    NsResize,
    /// Horizontal (east–west) resize.
    EwResize,
    /// Diagonal resize, north-east to south-west.
    NeswResize,
    /// Diagonal resize, north-west to south-east.
    NwseResize,
    ColResize,
    RowResize,
    /// A toolkit's own named cursor, resolved by that backend's lookup and ignored by every
    /// other. Prefer the `day::cursor::<toolkit>` constants, which are gated on the toolkit.
    Native(std::borrow::Cow<'static, str>),
}

impl Cursor {
    /// A toolkit-specific cursor by its native name (see [`Cursor::Native`]).
    pub const fn native(name: &'static str) -> Self {
        Cursor::Native(std::borrow::Cow::Borrowed(name))
    }

    /// The CSS keyword for a named cursor, which GTK and the DOM take as it is. A native cursor
    /// answers its own name, so a backend keyed on CSS names may still recognize it.
    pub fn css_name(&self) -> &str {
        match self {
            Cursor::Default => "default",
            Cursor::Pointer => "pointer",
            Cursor::Text => "text",
            Cursor::VerticalText => "vertical-text",
            Cursor::Crosshair => "crosshair",
            Cursor::Move => "move",
            Cursor::Grab => "grab",
            Cursor::Grabbing => "grabbing",
            Cursor::NotAllowed => "not-allowed",
            Cursor::Wait => "wait",
            Cursor::Progress => "progress",
            Cursor::Help => "help",
            Cursor::ContextMenu => "context-menu",
            Cursor::Copy => "copy",
            Cursor::Alias => "alias",
            Cursor::Cell => "cell",
            Cursor::ZoomIn => "zoom-in",
            Cursor::ZoomOut => "zoom-out",
            Cursor::None => "none",
            Cursor::NsResize => "ns-resize",
            Cursor::EwResize => "ew-resize",
            Cursor::NeswResize => "nesw-resize",
            Cursor::NwseResize => "nwse-resize",
            Cursor::ColResize => "col-resize",
            Cursor::RowResize => "row-resize",
            Cursor::Native(name) => name,
        }
    }

    /// Every named cursor, in declaration order, what a gallery or a test walks.
    pub const NAMED: [Cursor; 25] = [
        Cursor::Default,
        Cursor::Pointer,
        Cursor::Text,
        Cursor::VerticalText,
        Cursor::Crosshair,
        Cursor::Move,
        Cursor::Grab,
        Cursor::Grabbing,
        Cursor::NotAllowed,
        Cursor::Wait,
        Cursor::Progress,
        Cursor::Help,
        Cursor::ContextMenu,
        Cursor::Copy,
        Cursor::Alias,
        Cursor::Cell,
        Cursor::ZoomIn,
        Cursor::ZoomOut,
        Cursor::None,
        Cursor::NsResize,
        Cursor::EwResize,
        Cursor::NeswResize,
        Cursor::NwseResize,
        Cursor::ColResize,
        Cursor::RowResize,
    ];
}

/// A set of screen edges, for the `defers_system_gestures` modifier (docs/cover.md). Mirrors
/// SwiftUI's `Edge.Set`: on iOS these map to `UIRectEdge` for
/// `preferredScreenEdgesDeferringSystemGestures`; on Android any non-empty set enters
/// swipe-to-reveal immersive mode (the closest platform analogue).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Edges(pub u8);

impl Edges {
    pub const NONE: Edges = Edges(0);
    pub const TOP: Edges = Edges(1);
    pub const BOTTOM: Edges = Edges(2);
    pub const LEADING: Edges = Edges(4);
    pub const TRAILING: Edges = Edges(8);
    pub const ALL: Edges = Edges(15);

    pub fn contains(self, other: Edges) -> bool {
        self.0 & other.0 == other.0
    }
    pub fn union(self, other: Edges) -> Edges {
        Edges(self.0 | other.0)
    }
    pub fn is_empty(self) -> bool {
        self.0 == 0
    }
}

impl std::ops::BitOr for Edges {
    type Output = Edges;
    fn bitor(self, rhs: Edges) -> Edges {
        self.union(rhs)
    }
}

/// The timing curve of an animation (§8.4). Native backends map each variant onto their own
/// easing (`CAMediaTimingFunction`, `QEasingCurve`, ArkUI `ARKUI_CURVE_*`, spring animators); the
/// canvas/self-driven path samples it via [`Curve::fraction`]. `Spring` matches SwiftUI's
/// `.spring(response:dampingFraction:)`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Curve {
    Linear,
    EaseIn,
    EaseOut,
    EaseInOut,
    /// `response` = approximate settling period (seconds); `damping` = damping ratio (1.0 =
    /// critically damped, `<1` = bouncy overshoot).
    Spring {
        response: f64,
        damping: f64,
    },
}

impl Curve {
    /// Fraction of the transition complete at `elapsed` seconds (0 at start, reaching 1, or
    /// overshooting it for an under-damped spring). Easing curves clamp to `duration`; springs
    /// evaluate their analytic unit-step response and use `duration` only as a settle cap. Drives
    /// the self-driven/canvas path; native backends interpolate on their own compositor instead.
    pub fn fraction(self, elapsed: f64, duration: f64) -> f64 {
        match self {
            Curve::Spring { response, damping } => spring_step(response, damping, elapsed),
            _ => {
                let t = if duration <= 0.0 {
                    1.0
                } else {
                    (elapsed / duration).clamp(0.0, 1.0)
                };
                self.ease(t)
            }
        }
    }

    /// Eased progress for normalized `t` in `0.0..=1.0` (springs pass through; use [`Self::fraction`]).
    #[inline]
    pub fn ease(self, t: f64) -> f64 {
        match self {
            Curve::Linear | Curve::Spring { .. } => t,
            Curve::EaseIn => t * t,
            Curve::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
            Curve::EaseInOut => t * t * (3.0 - 2.0 * t), // smoothstep
        }
    }

    /// Whether the transition has settled, so the canvas frame clock can stop ticking it.
    pub fn is_settled(self, elapsed: f64, duration: f64) -> bool {
        match self {
            Curve::Spring { response, damping } => {
                let cap = response.max(0.0) * 4.0 + 0.2;
                if elapsed >= cap {
                    return true;
                }
                (spring_step(response, damping, elapsed) - 1.0).abs() < 0.001
                    && elapsed > response * 0.5
            }
            _ => elapsed >= duration.max(0.0),
        }
    }
}

/// Unit-step response of a second-order spring (`response` = period seconds, `damping` = ratio),
/// evaluated at `t` seconds. Under-damped rings and overshoots; critically/over-damped eases in.
fn spring_step(response: f64, damping: f64, t: f64) -> f64 {
    if response <= 0.0 || t <= 0.0 {
        return if t <= 0.0 { 0.0 } else { 1.0 };
    }
    let omega0 = std::f64::consts::TAU / response;
    let zeta = damping.max(0.0);
    if zeta < 1.0 {
        let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
        let e = (-zeta * omega0 * t).exp();
        1.0 - e * ((omega_d * t).cos() + (zeta * omega0 / omega_d) * (omega_d * t).sin())
    } else {
        let e = (-omega0 * t).exp();
        1.0 - e * (1.0 + omega0 * t)
    }
}

/// Animation intent (§8.4). Native-widget backends map it onto their own animator (Core Animation,
/// `ViewPropertyAnimator`, XAML Composition, `OH_ArkUI_AnimateTo`, …); the canvas/self-driven path
/// samples `curve` via [`Curve::fraction`]. Threaded through `Toolkit::update`/`set_frame`/
/// `set_opacity`/`set_transform`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AnimSpec {
    pub duration_ms: u32,
    pub delay_ms: u32,
    pub curve: Curve,
    /// Repeat count beyond the first play (`0` = play once); `u32::MAX` = repeat forever.
    pub repeat: u32,
    pub autoreverse: bool,
}

impl Default for AnimSpec {
    /// The default feel: a smooth spring (SwiftUI's modern default).
    fn default() -> Self {
        AnimSpec {
            duration_ms: 350,
            delay_ms: 0,
            curve: Curve::Spring {
                response: 0.4,
                damping: 0.8,
            },
            repeat: 0,
            autoreverse: false,
        }
    }
}

impl AnimSpec {
    /// A smooth spring: `response` = settling period (s), `damping` = ratio (1.0 = no bounce, `<1`
    /// bouncy). `duration_ms` is a nominal cap for backends that need a duration; spring backends
    /// use `response`/`damping` directly.
    pub fn spring(response: f64, damping: f64) -> Self {
        AnimSpec {
            // `response` is the animation's duration: every backend maps a spring to a
            // fixed-duration overshoot curve over exactly `duration_ms`, so timing is identical
            // across toolkits (a physics spring's settle time would vary per platform).
            duration_ms: (response * 1000.0).max(50.0) as u32,
            delay_ms: 0,
            curve: Curve::Spring { response, damping },
            repeat: 0,
            autoreverse: false,
        }
    }
    pub fn linear(duration_ms: u32) -> Self {
        Self::timed(duration_ms, Curve::Linear)
    }
    pub fn ease_in(duration_ms: u32) -> Self {
        Self::timed(duration_ms, Curve::EaseIn)
    }
    pub fn ease_out(duration_ms: u32) -> Self {
        Self::timed(duration_ms, Curve::EaseOut)
    }
    pub fn ease_in_out(duration_ms: u32) -> Self {
        Self::timed(duration_ms, Curve::EaseInOut)
    }
    fn timed(duration_ms: u32, curve: Curve) -> Self {
        AnimSpec {
            duration_ms,
            delay_ms: 0,
            curve,
            repeat: 0,
            autoreverse: false,
        }
    }
    /// Delay before the animation starts (builder).
    pub fn delay(mut self, ms: u32) -> Self {
        self.delay_ms = ms;
        self
    }
    /// Repeat `count` extra times (builder); `autoreverse` ping-pongs each cycle.
    pub fn repeat(mut self, count: u32, autoreverse: bool) -> Self {
        self.repeat = count;
        self.autoreverse = autoreverse;
        self
    }
    /// Repeat forever (builder), e.g. a pulsing indicator.
    pub fn repeat_forever(mut self, autoreverse: bool) -> Self {
        self.repeat = u32::MAX;
        self.autoreverse = autoreverse;
        self
    }
    #[inline]
    pub fn duration_secs(&self) -> f64 {
        self.duration_ms as f64 / 1000.0
    }
    #[inline]
    pub fn delay_secs(&self) -> f64 {
        self.delay_ms as f64 / 1000.0
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Role {
    #[default]
    None,
    Button,
    Toggle,
    Slider,
    TextInput,
    Heading(u8),
    Image,
    Meter,
    Group,
    /// A hierarchical tree container (docs/tree.md): `role="tree"`, `AXOutline`.
    Tree,
    /// One row of a tree: `role="treeitem"`, with level/expanded state where the platform
    /// carries them (docs/tree.md).
    TreeItem,
    /// One tab in a strip of peers (`role="tab"`, `AXTabButton`): the composed document
    /// strip's title buttons. Pair it with [`A11yProps::selected`] for the current one.
    Tab,
    /// The strip holding tabs (`role="tablist"`, `AXTabGroup`).
    TabList,
}

impl Role {
    /// The a11y role a built-in piece kind reports natively, the audit's *expectation* when the
    /// user hasn't set an explicit `.role()`. Native controls already expose these, so Day records
    /// them for `a11y_audit` (§14.2) rather than overriding the widget; only canvas/custom pieces
    /// need Day to apply a role. Returns `None` for kinds with no inherent control role.
    pub fn for_kind(kind: PieceKind) -> Role {
        match kind {
            kinds::BUTTON => Role::Button,
            kinds::TOGGLE => Role::Toggle,
            kinds::SLIDER => Role::Slider,
            kinds::TEXT_FIELD => Role::TextInput,
            kinds::IMAGE => Role::Image,
            kinds::PROGRESS => Role::Meter,
            kinds::TREE => Role::Tree,
            _ => Role::None,
        }
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct A11yProps {
    pub label: Option<String>,
    pub hint: Option<String>,
    pub value: Option<String>,
    pub role: Role,
    pub identifier: Option<String>,
    pub hidden: bool,
    pub decorative: bool,
    /// Whether the element is the selected one among its peers (a tab, a row): the
    /// platform's selected state, read aloud as such. `None` leaves the widget's own answer.
    pub selected: Option<bool>,
}

impl A11yProps {
    /// Merge another set of annotations onto this one: any field `other` sets (a `Some`, a
    /// non-`None` role, or a `true` flag) overrides ours; unset fields are left intact. Lets a
    /// node accumulate its `.a11y()`, `.id()`, and piece defaults into one stored result, so
    /// each `set_a11y` re-applies the full picture and `a11y_audit` has the complete expectation.
    pub fn merge(&mut self, other: &A11yProps) {
        if other.label.is_some() {
            self.label = other.label.clone();
        }
        if other.hint.is_some() {
            self.hint = other.hint.clone();
        }
        if other.value.is_some() {
            self.value = other.value.clone();
        }
        if other.role != Role::None {
            self.role = other.role;
        }
        if other.identifier.is_some() {
            self.identifier = other.identifier.clone();
        }
        self.hidden |= other.hidden;
        self.decorative |= other.decorative;
        if other.selected.is_some() {
            self.selected = other.selected;
        }
    }

    /// The role to *expect* for a node of `kind` carrying these annotations: an explicit
    /// `.role()` wins, otherwise the kind's native default (`Role::for_kind`).
    pub fn resolved_role(&self, kind: PieceKind) -> Role {
        if self.role != Role::None {
            self.role
        } else {
            Role::for_kind(kind)
        }
    }
}

/// A widget's actual native state, read back from the platform by `Toolkit::read_native`
/// (docs/testing.md): what the widget itself shows and reports, independently of Day's tree,
/// so `a11y_audit` and `assert_native` (§14.2) can diff it against Day's expectation.
///
/// Two groups. The accessibility fields (`role`, `label`, `value`, `identifier`) are read
/// together and `found` says whether they were: `found = false` means the backend cannot read
/// its accessibility tree, and the audit skips the node. Every other field is read on its own,
/// and `None` means "not read": the backend cannot read it, or it does not apply to this kind.
/// A reader never reports a field it did not take from the widget, so a `None` is a recorded
/// gap rather than a pass.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct NativeSnapshot {
    /// The accessibility fields below were read.
    pub found: bool,
    /// The native role mapped back to Day's `Role` (best-effort).
    pub role: Role,
    /// The accessibility label the platform reports.
    pub label: Option<String>,
    /// The accessibility value the platform reports.
    pub value: Option<String>,
    /// The automation identifier, which Day sets from `.id()`.
    pub identifier: Option<String>,
    /// The text the widget displays: a label's string, a button's title, a text field's or
    /// text area's contents, without markup or mnemonic markers. `None` for a secure field
    /// that masks it.
    pub text: Option<String>,
    /// A slider's or progress indicator's value, in the range Day gave it.
    pub number: Option<f64>,
    /// A toggle's state, or a button's selected state (`ButtonProps::selected`).
    pub checked: Option<bool>,
    /// Whether the widget takes input.
    pub enabled: Option<bool>,
    /// Whether the widget is shown: not hidden itself, nor by an ancestor.
    pub visible: Option<bool>,
    /// The widget's frame in points, relative to the window's content area, origin top left.
    pub frame: Option<Rect>,
}

// ---------------------------------------------------------------------------
// Canvas display list (§11): full op set lands with M8a; the types are v1.
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, PartialEq)]
pub enum Shape {
    Rect(Rect),
    RoundedRect(Rect, f64),
    Ellipse(Rect),
    /// Arc within `rect`'s inscribed ellipse; angles in degrees, 0 = +x axis, clockwise.
    Arc {
        rect: Rect,
        start_deg: f64,
        sweep_deg: f64,
    },
    Line(Point, Point),
    Polygon(Vec<Point>),
    /// An arbitrary path: curves, several contours, and a fill rule (docs/canvas.md).
    ///
    /// [`Shape::Polygon`] is the straight-line, single-contour special case, kept because it is
    /// what most drawing code wants and it encodes far more compactly.
    Path(Path),
}

impl Shape {
    /// A rectangle rounded corner by corner (docs/canvas.md "Rounded corners"), as the simplest
    /// shape that draws it: a plain [`Shape::Rect`] when every corner is square, a
    /// [`Shape::RoundedRect`] (each toolkit's own rounded rectangle) when the corners agree, and a
    /// path ([`rounded_rect_segs`]) otherwise. The radii are [fitted](CornerRadii::fitted) first.
    ///
    /// ```
    /// use day_spec::{CornerRadii, Rect, Shape};
    ///
    /// // A bar standing on its axis: rounded on top, square where it meets the baseline.
    /// let bar = Shape::rounded_rect(Rect::new(0.0, 0.0, 20.0, 80.0), CornerRadii::top(6.0));
    /// assert!(matches!(bar, Shape::Path(_)));
    /// ```
    pub fn rounded_rect(rect: Rect, radii: CornerRadii) -> Shape {
        let r = radii.fitted(rect.size);
        if r.is_zero() || rect.size.width <= 0.0 || rect.size.height <= 0.0 {
            Shape::Rect(rect)
        } else if r.is_uniform() {
            Shape::RoundedRect(rect, r.top_left)
        } else {
            Shape::Path(Path {
                segs: rounded_rect_segs(rect, r),
                rule: FillRule::NonZero,
            })
        }
    }

    /// The same shape moved by `(dx, dy)`.
    ///
    /// What a [`Stamp`] means by "the template translated by one point", and the one definition of
    /// it: a backend builds each copy of a batch with this rather than reaching for its own
    /// platform transform, so every toolkit stamps to the same coordinates.
    pub fn translated(&self, dx: f64, dy: f64) -> Shape {
        let r = |r: &Rect| {
            Rect::new(
                r.origin.x + dx,
                r.origin.y + dy,
                r.size.width,
                r.size.height,
            )
        };
        let p = |p: &Point| Point::new(p.x + dx, p.y + dy);
        match self {
            Shape::Rect(rect) => Shape::Rect(r(rect)),
            Shape::RoundedRect(rect, rad) => Shape::RoundedRect(r(rect), *rad),
            Shape::Ellipse(rect) => Shape::Ellipse(r(rect)),
            Shape::Arc {
                rect,
                start_deg,
                sweep_deg,
            } => Shape::Arc {
                rect: r(rect),
                start_deg: *start_deg,
                sweep_deg: *sweep_deg,
            },
            Shape::Line(a, b) => Shape::Line(p(a), p(b)),
            Shape::Polygon(pts) => Shape::Polygon(pts.iter().map(p).collect()),
            Shape::Path(path) => Shape::Path(Path {
                segs: path
                    .segs
                    .iter()
                    .map(|seg| match seg {
                        PathSeg::Move(a) => PathSeg::Move(p(a)),
                        PathSeg::Line(a) => PathSeg::Line(p(a)),
                        PathSeg::Quad(c, a) => PathSeg::Quad(p(c), p(a)),
                        PathSeg::Cubic(c1, c2, a) => PathSeg::Cubic(p(c1), p(c2), p(a)),
                        PathSeg::Close => PathSeg::Close,
                    })
                    .collect(),
                rule: path.rule,
            }),
        }
    }

    /// The shape's bounding rectangle: the box gradient [`UnitPoint`]s resolve against.
    pub fn bounds(&self) -> Rect {
        match self {
            Shape::Rect(r) | Shape::RoundedRect(r, _) | Shape::Ellipse(r) => *r,
            Shape::Arc { rect, .. } => *rect,
            Shape::Line(a, b) => points_bounds(&[*a, *b]),
            Shape::Polygon(pts) => points_bounds(pts),
            Shape::Path(p) => p.bounds(),
        }
    }
}

/// One step of a [`Path`]. Points are absolute, in the canvas's coordinate space.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PathSeg {
    /// Start a new contour at this point.
    Move(Point),
    Line(Point),
    /// Quadratic bezier: one control point, then the end point.
    Quad(Point, Point),
    /// Cubic bezier: two control points, then the end point.
    Cubic(Point, Point, Point),
    /// Close the current contour back to its `Move`.
    Close,
}

/// Which points count as inside when a path's contours overlap (docs/canvas.md).
///
/// This matters the moment a shape has a hole: the counter of an "o", a washer, a ring chart. It
/// is a property of the fill, so stroking ignores it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum FillRule {
    /// Direction-sensitive: a hole needs its contour wound the opposite way. Every 2-D API's
    /// default, and what a font's glyph outlines assume.
    #[default]
    NonZero,
    /// Parity: any contour inside another cuts a hole regardless of winding. What PDF's `f*`
    /// operator and SVG's `fill-rule: evenodd` mean.
    EvenOdd,
}

/// An arbitrary 2-D path: any number of contours, straight or curved, with a fill rule.
#[derive(Clone, Debug, PartialEq, Default)]
pub struct Path {
    pub segs: Vec<PathSeg>,
    pub rule: FillRule,
}

impl Path {
    /// A conservative bounding box: the hull of every point including control points, which
    /// contains the true curve bounds (a bezier stays inside its control hull). Used only to
    /// resolve gradient unit points, where being slightly generous costs nothing and computing
    /// exact curve extrema would not.
    pub fn bounds(&self) -> Rect {
        let mut pts: Vec<Point> = Vec::with_capacity(self.segs.len() * 3);
        for seg in &self.segs {
            match seg {
                PathSeg::Move(p) | PathSeg::Line(p) => pts.push(*p),
                PathSeg::Quad(c, p) => pts.extend_from_slice(&[*c, *p]),
                PathSeg::Cubic(c1, c2, p) => pts.extend_from_slice(&[*c1, *c2, *p]),
                PathSeg::Close => {}
            }
        }
        points_bounds(&pts)
    }
}

/// A radius for each corner of a rectangle, clockwise from the top left (docs/canvas.md "Rounded
/// corners"). The shape a bar in a chart wants (rounded at its value end, square against its
/// axis), a tab (rounded on top), or a card joined to its neighbor.
///
/// Radii are in points and never negative. [`CornerRadii::fitted`] shrinks them the way CSS
/// does when two radii on one side would overlap, which is what a caller animating a radius or
/// drawing a short bar needs to not think about.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct CornerRadii {
    pub top_left: f64,
    pub top_right: f64,
    pub bottom_right: f64,
    pub bottom_left: f64,
}

impl CornerRadii {
    /// The same radius on every corner: what [`Shape::RoundedRect`] draws.
    pub fn uniform(r: f64) -> Self {
        CornerRadii {
            top_left: r,
            top_right: r,
            bottom_right: r,
            bottom_left: r,
        }
    }
    /// Rounded along the top edge, square along the bottom: a bar standing on its axis.
    pub fn top(r: f64) -> Self {
        CornerRadii {
            top_left: r,
            top_right: r,
            ..Default::default()
        }
    }
    /// Rounded along the bottom edge: a bar hanging below its axis.
    pub fn bottom(r: f64) -> Self {
        CornerRadii {
            bottom_right: r,
            bottom_left: r,
            ..Default::default()
        }
    }
    /// Rounded along the left edge: a bar growing leftward from its axis.
    pub fn left(r: f64) -> Self {
        CornerRadii {
            top_left: r,
            bottom_left: r,
            ..Default::default()
        }
    }
    /// Rounded along the right edge: a bar growing rightward from its axis.
    pub fn right(r: f64) -> Self {
        CornerRadii {
            top_right: r,
            bottom_right: r,
            ..Default::default()
        }
    }

    /// The four radii, clockwise from the top left.
    pub fn to_array(self) -> [f64; 4] {
        [
            self.top_left,
            self.top_right,
            self.bottom_right,
            self.bottom_left,
        ]
    }

    /// Whether every corner is square.
    pub fn is_zero(self) -> bool {
        self.to_array().iter().all(|r| *r <= 0.0)
    }

    /// Whether every corner has the same radius, so the rectangle is a [`Shape::RoundedRect`].
    pub fn is_uniform(self) -> bool {
        let [a, b, c, d] = self.to_array();
        a == b && b == c && c == d
    }

    /// These radii made to fit a `size` rectangle, the rule CSS uses for `border-radius`: a
    /// negative or non-finite radius is square, and when the two radii along any side add up to
    /// more than that side, every radius is scaled down by the same factor until none overlap.
    /// Scaling all four together keeps the corners in proportion, where clamping each one alone
    /// would turn a pill into a lopsided shape.
    pub fn fitted(self, size: Size) -> Self {
        let clean = |r: f64| if r.is_finite() && r > 0.0 { r } else { 0.0 };
        let [tl, tr, br, bl] = self.to_array().map(clean);
        let (w, h) = (size.width.max(0.0), size.height.max(0.0));
        let factor = [(w, tl + tr), (w, bl + br), (h, tl + bl), (h, tr + br)]
            .into_iter()
            .filter(|(_, sum)| *sum > 0.0)
            .map(|(side, sum)| side / sum)
            .fold(1.0f64, f64::min);
        CornerRadii {
            top_left: tl * factor,
            top_right: tr * factor,
            bottom_right: br * factor,
            bottom_left: bl * factor,
        }
    }
}

/// The point `angle_deg` round a circle: degrees, `0` = the +x axis, positive clockwise in device
/// space (y down), the convention [`Shape::Arc`] and every arc helper here use.
pub fn arc_point(center: Point, radius: f64, angle_deg: f64) -> Point {
    let a = angle_deg.to_radians();
    Point::new(center.x + radius * a.cos(), center.y + radius * a.sin())
}

/// A circular arc as cubic beziers: `sweep_deg` of a circle of `radius` about `center`, from
/// `start_deg` ([`arc_point`]'s convention). The segments start *from* the arc's first point, which
/// the caller reaches itself (a move or a line); nothing for a zero or non-finite radius or sweep.
///
/// The arc is split into quarter turns at most, where a cubic tracks a circle best: the radial
/// error peaks at 2.7 × 10⁻⁴ of the radius, a quarter of a pixel on a circle a thousand points
/// across (docs/canvas.md "Paths"). The same beziers on every backend mean the same pixels on
/// every backend, which an arc op interpreted by nine rasterizers would not.
pub fn arc_cubics(center: Point, radius: f64, start_deg: f64, sweep_deg: f64) -> Vec<PathSeg> {
    let (start, sweep) = (start_deg.to_radians(), sweep_deg.to_radians());
    if !radius.is_finite() || radius <= 0.0 || !sweep.is_finite() || sweep == 0.0 {
        return Vec::new();
    }
    let at = |a: f64| Point::new(center.x + radius * a.cos(), center.y + radius * a.sin());
    let steps = (sweep.abs() / std::f64::consts::FRAC_PI_2).ceil() as usize;
    let delta = sweep / steps as f64;
    // The exact control-handle length for a circular arc of this sweep. Negative for a negative
    // sweep, which is what turns the handles around for a counter-clockwise arc.
    let k = 4.0 / 3.0 * (delta / 4.0).tan() * radius;
    (0..steps)
        .map(|i| {
            let a = start + delta * i as f64;
            let b = a + delta;
            let (p0, p1) = (at(a), at(b));
            PathSeg::Cubic(
                Point::new(p0.x - k * a.sin(), p0.y + k * a.cos()),
                Point::new(p1.x + k * b.sin(), p1.y - k * b.cos()),
                p1,
            )
        })
        .collect()
}

/// The closed contour of a rectangle rounded corner by corner, clockwise from the top left, with
/// the radii [fitted](CornerRadii::fitted) first. A square corner is a sharp point, not a
/// zero-length curve.
pub fn rounded_rect_segs(rect: Rect, radii: CornerRadii) -> Vec<PathSeg> {
    let r = radii.fitted(rect.size);
    let (x0, y0) = (rect.origin.x, rect.origin.y);
    let (x1, y1) = (x0 + rect.size.width, y0 + rect.size.height);
    // Each corner: the point where its curve starts, then the quarter turn round its center.
    let corners = [
        (
            Point::new(x0 + r.top_left, y0 + r.top_left),
            r.top_left,
            180.0,
        ),
        (
            Point::new(x1 - r.top_right, y0 + r.top_right),
            r.top_right,
            270.0,
        ),
        (
            Point::new(x1 - r.bottom_right, y1 - r.bottom_right),
            r.bottom_right,
            0.0,
        ),
        (
            Point::new(x0 + r.bottom_left, y1 - r.bottom_left),
            r.bottom_left,
            90.0,
        ),
    ];
    let mut segs = Vec::with_capacity(14);
    for (i, (center, radius, start)) in corners.into_iter().enumerate() {
        let first = arc_point(center, radius, start);
        segs.push(if i == 0 {
            PathSeg::Move(first)
        } else {
            PathSeg::Line(first)
        });
        segs.extend(arc_cubics(center, radius, start, 90.0));
    }
    segs.push(PathSeg::Close);
    segs
}

/// How a stroked line ends (docs/canvas.md). Names match PDF's `J`, SVG's `stroke-linecap`, and
/// every native 2-D API.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum LineCap {
    #[default]
    Butt,
    Round,
    Square,
}

/// How two stroked segments meet (docs/canvas.md). Matches PDF's `j` and SVG's
/// `stroke-linejoin`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum LineJoin {
    #[default]
    Miter,
    Round,
    Bevel,
}

/// Everything about a stroke except its paint.
///
/// [`StrokeStyle::width`] and `From<f64>` keep the common "just a width" case a single
/// argument, so plain `stroke(shape, color, 2.0)` call sites read the same as they always did.
#[derive(Clone, Debug, PartialEq)]
pub struct StrokeStyle {
    pub width: f64,
    pub cap: LineCap,
    pub join: LineJoin,
    /// Ignored unless `join` is [`LineJoin::Miter`]. The 2-D convention: past this ratio of miter
    /// length to line width the join falls back to a bevel.
    pub miter_limit: f64,
    /// On/off run lengths, repeating. Empty means solid.
    pub dash: Vec<f64>,
    /// How far into the dash pattern the line starts.
    pub dash_phase: f64,
}

impl Default for StrokeStyle {
    fn default() -> Self {
        // 10.0 is the miter limit PDF, PostScript, SVG and Cairo all default to.
        StrokeStyle {
            width: 1.0,
            cap: LineCap::Butt,
            join: LineJoin::Miter,
            miter_limit: 10.0,
            dash: Vec::new(),
            dash_phase: 0.0,
        }
    }
}

impl StrokeStyle {
    /// A solid stroke of `width`, everything else default.
    pub fn width(width: f64) -> Self {
        StrokeStyle {
            width,
            ..Default::default()
        }
    }
    /// A dashed stroke: `dash` is on/off run lengths, repeating.
    pub fn dashed(width: f64, dash: Vec<f64>) -> Self {
        StrokeStyle {
            width,
            dash,
            ..Default::default()
        }
    }
    /// Rounded ends and joins, the shape a data line usually wants.
    pub fn round(width: f64) -> Self {
        StrokeStyle {
            width,
            cap: LineCap::Round,
            join: LineJoin::Round,
            ..Default::default()
        }
    }
    /// Is this the plain width-only stroke every pre-existing call site asks for? Backends use
    /// it to skip setting dash/cap/join state they would only have to set back.
    pub fn is_plain(&self) -> bool {
        self.cap == LineCap::Butt
            && self.join == LineJoin::Miter
            && self.dash.is_empty()
            && self.miter_limit == 10.0
    }
}

impl From<f64> for StrokeStyle {
    fn from(width: f64) -> Self {
        StrokeStyle::width(width)
    }
}

fn points_bounds(pts: &[Point]) -> Rect {
    let (mut x0, mut y0, mut x1, mut y1) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
    for p in pts {
        x0 = x0.min(p.x);
        y0 = y0.min(p.y);
        x1 = x1.max(p.x);
        y1 = y1.max(p.y);
    }
    if pts.is_empty() {
        return Rect::ZERO;
    }
    Rect::new(x0, y0, x1 - x0, y1 - y0)
}

/// A point in the unit space of a shape's bounding box: (0,0) = top-leading, (1,1) =
/// bottom-trailing. Gradient geometry is expressed in unit points so one paint value works for
/// any shape size (docs/shapes.md §3.2).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct UnitPoint {
    pub x: f64,
    pub y: f64,
}

impl UnitPoint {
    pub const fn new(x: f64, y: f64) -> Self {
        UnitPoint { x, y }
    }
    pub const TOP: UnitPoint = UnitPoint::new(0.5, 0.0);
    pub const BOTTOM: UnitPoint = UnitPoint::new(0.5, 1.0);
    pub const LEADING: UnitPoint = UnitPoint::new(0.0, 0.5);
    pub const TRAILING: UnitPoint = UnitPoint::new(1.0, 0.5);
    pub const TOP_LEADING: UnitPoint = UnitPoint::new(0.0, 0.0);
    pub const TOP_TRAILING: UnitPoint = UnitPoint::new(1.0, 0.0);
    pub const BOTTOM_LEADING: UnitPoint = UnitPoint::new(0.0, 1.0);
    pub const BOTTOM_TRAILING: UnitPoint = UnitPoint::new(1.0, 1.0);
    pub const CENTER: UnitPoint = UnitPoint::new(0.5, 0.5);

    /// Resolve to an absolute point within `rect`.
    pub fn resolve(&self, rect: Rect) -> Point {
        Point::new(
            rect.origin.x + self.x * rect.size.width,
            rect.origin.y + self.y * rect.size.height,
        )
    }
}

/// A linear gradient (docs/shapes.md §3.2 / §7): color stops along the line from `start` to
/// `end`, both in the unit space of the filled shape's bounding box. Stops are
/// `(offset 0..=1, color)`, ascending.
#[derive(Clone, Debug, PartialEq)]
pub struct LinearGradient {
    pub start: UnitPoint,
    pub end: UnitPoint,
    pub stops: Vec<(f64, Color)>,
}

impl LinearGradient {
    pub fn new(start: UnitPoint, end: UnitPoint, stops: Vec<(f64, Color)>) -> Self {
        LinearGradient { start, end, stops }
    }
    /// Top-to-bottom between two colors: the everyday sky/backdrop case.
    pub fn vertical(top: Color, bottom: Color) -> Self {
        LinearGradient::new(
            UnitPoint::TOP,
            UnitPoint::BOTTOM,
            vec![(0.0, top), (1.0, bottom)],
        )
    }
    /// Leading-to-trailing between two colors.
    pub fn horizontal(leading: Color, trailing: Color) -> Self {
        LinearGradient::new(
            UnitPoint::LEADING,
            UnitPoint::TRAILING,
            vec![(0.0, leading), (1.0, trailing)],
        )
    }
}

/// A radial gradient (docs/shapes.md §3.2 / §7): color stops from `center` outward. Both the
/// center and the radius live in the unit space of the filled shape's bounding box, so the
/// gradient stretches into an ellipse when the bounds aren't square (the XAML relative-brush
/// behavior; the other backends reproduce it with a local matrix on a circular gradient). A
/// `radius` of `0.5` from the default center touches the edge midpoints of the bounds.
#[derive(Clone, Debug, PartialEq)]
pub struct RadialGradient {
    pub center: UnitPoint,
    pub radius: f64,
    pub stops: Vec<(f64, Color)>,
}

impl RadialGradient {
    pub fn new(center: UnitPoint, radius: f64, stops: Vec<(f64, Color)>) -> Self {
        RadialGradient {
            center,
            radius,
            stops,
        }
    }
    /// Centered, edge-touching (radius 0.5) between two colors: the everyday glow case.
    pub fn centered(inner: Color, outer: Color) -> Self {
        RadialGradient::new(UnitPoint::CENTER, 0.5, vec![(0.0, inner), (1.0, outer)])
    }
}

/// The payload of [`DrawOp::Stamp`]: one shape drawn at every position in `at`.
///
/// A scatter plot is the case this exists for. Drawn as individual ops, fifty thousand points are
/// fifty thousand `DrawOp`s, rebuilt, compared and cloned on every frame that re-records, before
/// a backend draws anything. As one `Stamp` they are one op and a flat array of coordinates, and
/// a backend can put every copy into one path and hand the rasterizer a single fill.
///
/// Every copy shares the shape, the size and the paint. Varying any of those means more than one
/// stamp: group by what varies, which for a chart is usually the series color.
#[derive(Clone, Debug, PartialEq)]
pub struct Stamp {
    /// The template, authored around the origin: each copy is this shape translated by one point.
    /// A 6-point dot is `Shape::Ellipse(Rect::new(-3.0, -3.0, 6.0, 6.0))`.
    pub shape: Shape,
    /// Where the copies go. Order is the drawing order, so later points paint over earlier ones.
    pub at: Vec<Point>,
    pub paint: Paint,
    /// `None` fills each copy; `Some` strokes it with this style.
    pub stroke: Option<StrokeStyle>,
}

/// A fill source: a solid color, or a linear/radial gradient (docs/shapes.md §3.2; angular and
/// semantic tokens are later phases). `From<Color>` keeps every existing `fill(shape, color)`
/// call site compiling unchanged.
#[derive(Clone, Debug, PartialEq)]
pub enum Paint {
    Solid(Color),
    Linear(LinearGradient),
    Radial(RadialGradient),
}

impl From<Color> for Paint {
    fn from(c: Color) -> Self {
        Paint::Solid(c)
    }
}

impl From<LinearGradient> for Paint {
    fn from(g: LinearGradient) -> Self {
        Paint::Linear(g)
    }
}

impl From<RadialGradient> for Paint {
    fn from(g: RadialGradient) -> Self {
        Paint::Radial(g)
    }
}

/// Where `at` sits vertically. `Top`, `Middle` and `Bottom` are edges of the line box (ascent +
/// descent at the font's size, the box [`Toolkit::measure_text`] reports); `Baseline` is the
/// typographic baseline itself.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum TextVAlign {
    /// `at` is the top of the line box.
    #[default]
    Top,
    /// `at` is the vertical middle of the line box.
    Middle,
    /// `at` is the baseline itself: what every native 2-D text call takes, and what a run of labels
    /// sharing a line should align on rather than their individual boxes.
    Baseline,
    /// `at` is the bottom of the line box.
    Bottom,
}

/// How canvas text hangs on its `at` point: one placement per axis (docs/canvas.md "Text").
///
/// Two axes rather than a list of named positions, because that is the shape of the problem and
/// of every native API underneath: `NSAttributedString` drawing, Pango extents,
/// `QFontMetricsF`, `Paint.Align`, Canvas2D's `textAlign`/`textBaseline`. The alignment is done
/// by the backend, which is both cheaper and more accurate than doing it in app code: it already
/// has the laid-out metrics, where an app has to ask for them through
/// [`Toolkit::measure_text`] first.
///
/// [`TextAnchor::LEADING`] and [`TextAnchor::CENTERED`] name the two placements that used to be
/// this type's only variants.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub struct TextAnchor {
    /// The horizontal placement: the same three-way leading/center/trailing a wrapped label's
    /// lines take ([`props::TextAlign`]), because it is the same question with the same RTL rule.
    /// `Trailing` is what an axis label right-aligned against its axis wants, and the reason the
    /// horizontal axis is settable at all: emulating it in app code costs a
    /// [`Toolkit::measure_text`] call per label, where the backend already holds the width it is
    /// about to draw with.
    pub h: props::TextAlign,
    pub v: TextVAlign,
}

impl TextAnchor {
    /// The top-leading corner of the line box, the default.
    pub const LEADING: TextAnchor = TextAnchor {
        h: props::TextAlign::Leading,
        v: TextVAlign::Top,
    };
    /// The center of the line box, both ways.
    pub const CENTERED: TextAnchor = TextAnchor {
        h: props::TextAlign::Center,
        v: TextVAlign::Middle,
    };
    /// The top-trailing corner of the line box.
    pub const TRAILING: TextAnchor = TextAnchor {
        h: props::TextAlign::Trailing,
        v: TextVAlign::Top,
    };

    /// Where the text's top-leading corner goes, as an offset from `at`, given the line box this
    /// text measures to. The single definition of what an anchor means: every backend that draws
    /// in Rust calls this, and the C++/Java/JS shims repeat exactly this arithmetic.
    ///
    /// `height` is the line box (ascent + descent) and `ascent` the baseline's offset from its
    /// top, the two numbers [`TextMetrics`] carries.
    pub fn offset(self, width: f64, height: f64, ascent: f64) -> (f64, f64) {
        let dx = match self.h {
            props::TextAlign::Leading => 0.0,
            props::TextAlign::Center => -width / 2.0,
            props::TextAlign::Trailing => -width,
        };
        let dy = match self.v {
            TextVAlign::Top => 0.0,
            TextVAlign::Middle => -height / 2.0,
            TextVAlign::Baseline => -ascent,
            TextVAlign::Bottom => -height,
        };
        (dx, dy)
    }

    /// The anchor as one number, for the numeric op stream the serializing backends share:
    /// `h * 4 + v`, so it still occupies the single slot the two-variant enum did.
    pub fn pack(self) -> f64 {
        (self.h as u8 * 4 + self.v as u8) as f64
    }

    /// Inverse of [`TextAnchor::pack`]. An unrecognized code answers the default rather than
    /// failing: a stream is only ever written by a matching encoder, and a drawing with text in
    /// the wrong corner beats one that panics inside a native draw callback.
    pub fn unpack(code: f64) -> TextAnchor {
        let c = code.round().clamp(0.0, 11.0) as u8;
        let h = match c / 4 {
            1 => props::TextAlign::Center,
            2 => props::TextAlign::Trailing,
            _ => props::TextAlign::Leading,
        };
        let v = match c % 4 {
            1 => TextVAlign::Middle,
            2 => TextVAlign::Baseline,
            3 => TextVAlign::Bottom,
            _ => TextVAlign::Top,
        };
        TextAnchor { h, v }
    }
}

#[derive(Clone, Debug, PartialEq)]
pub enum DrawOp {
    Fill(Shape, Paint),
    /// Stroke `shape`. The paint may be a gradient, and [`StrokeStyle`] carries width, dash, cap
    /// and join; `Draw::stroke` builds the plain width-only case.
    Stroke(Shape, Paint, StrokeStyle),
    /// One line of text. `size` is absolute canvas points (no accessibility scale: canvas
    /// text is a label inside a drawing, docs/canvas.md); `font` picks the family, weight and
    /// slant, and its default is the platform's own UI face.
    Text {
        text: String,
        at: Point,
        size: f64,
        color: Color,
        anchor: TextAnchor,
        font: CanvasFont,
    },
    /// Draw one shape at many positions, the batched form of [`DrawOp::Fill`]/[`DrawOp::Stroke`]
    /// (docs/canvas.md "Stamping").
    ///
    /// Boxed because the payload is wider than the largest other op, and a bigger `DrawOp` would
    /// cost every op in every drawing, the exact thing this variant exists to stop paying.
    Stamp(Box<Stamp>),
    /// Draw an image into `rect` (docs/images.md).
    ///
    /// The source is a [`BitmapId`] and never bytes: a canvas re-records on every tracked read,
    /// so carrying a buffer here would hand the backend a megabyte to compare, and re-decode, on
    /// every frame. The app decodes once with `day::decode_image` and draws the handle.
    ///
    /// `opacity` multiplies the image's own alpha. A backend that cannot draw a bitmap at all
    /// draws nothing rather than a placeholder rectangle, the same way an unknown op is skipped.
    Image {
        image: BitmapId,
        rect: Rect,
        opacity: f64,
    },
    /// Intersect the clip with `shape`; everything drawn afterwards is confined to it.
    ///
    /// Scoped by [`DrawOp::Save`]/[`DrawOp::Restore`], which is the only way to widen a clip
    /// again; every native 2-D context works this way, so there is no "unclip".
    Clip(Shape),
    /// Push the current transform + clip (§11, shapes). Backends map to save/restore of the
    /// native 2-D context; `Concat` multiplies an affine onto the CTM (shape rotate/scale/offset).
    Save,
    Restore,
    Concat(day_geometry::Affine),
}

// ---------------------------------------------------------------------------
// Built-in piece descriptors: full props (realize) + sparse patches (update).
// One binding = one attribute = one patch value: sparseness by construction (§8.1).
// ---------------------------------------------------------------------------

/// A semantic (logical) text style. Each maps to the platform's native text style where the
/// toolkit has one: `UIFont`/`NSFont.preferredFont(forTextStyle:)` on Apple (Dynamic Type), the
/// `*TextBlockStyle` resources on XAML. A Day app thus matches the OS's own typography and
/// inherits its accessibility text scaling with no extra work. Backends without semantic styles
/// (GTK/Qt/Android) approximate with sizes that still track the platform's text-scale /
/// font-scale accessibility setting.
///
/// The set mirrors SwiftUI `Font.TextStyle` (largest → smallest).
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum Font {
    LargeTitle,
    Title,
    Title2,
    Title3,
    Headline,
    Subheadline,
    #[default]
    Body,
    Callout,
    Footnote,
    Caption,
    Caption2,
    /// A custom point size. Backends scale it by the platform's accessibility text-scale (iOS via
    /// `UIFontMetrics`, Android via `sp`, GTK via text-scaling-factor) so it stays legible.
    System(f64),
    /// A bundled custom font by **family name**, at a point size (`Font::Custom("Pacifico",
    /// 24.0)`). The family must ship in the project's `fonts/` directory; `day build` stages the
    /// file into each platform's native font store and the backend registers it at startup
    /// (§18.4). The name is the family name baked into the font file (what Font Book /
    /// fontconfig report), not the file name. The size scales with the platform accessibility
    /// text-scale exactly like [`Font::System`]; weight/italic apply only where the family ships
    /// (or the platform synthesizes) such a face. An unknown family falls back to the system font
    /// of the same size, with a warning in the log.
    Custom(&'static str, f64),
}

impl Font {
    /// A bundled custom font by **typed family**, at a point size, the checked form of
    /// [`Font::Custom`]. Pass a generated `res::fonts::…` constant
    /// (`Font::custom(res::fonts::pacifico, 24.0)`), which exists only if the family ships in the
    /// project's `fonts/` directory, so the font is guaranteed bundled. For a family name known
    /// another way, the untyped [`Font::Custom`] variant is the escape hatch.
    pub const fn custom(family: FontFamily, size: f64) -> Font {
        Font::Custom(family.as_str(), size)
    }
}

/// Font weight, matching `UIFont.Weight` / SwiftUI `Font.Weight` (lightest → heaviest).
/// Ordered by heaviness, so backends can e.g. map `>= Semibold` to a synthesized bold face.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum FontWeight {
    UltraLight,
    Thin,
    Light,
    Regular,
    Medium,
    Semibold,
    Bold,
    Heavy,
    Black,
}

impl FontWeight {
    /// Every rung, lightest first.
    pub const ALL: [FontWeight; 9] = [
        FontWeight::UltraLight,
        FontWeight::Thin,
        FontWeight::Light,
        FontWeight::Regular,
        FontWeight::Medium,
        FontWeight::Semibold,
        FontWeight::Bold,
        FontWeight::Heavy,
        FontWeight::Black,
    ];

    /// The CSS / OpenType numeric weight (100 … 900), the one number every platform font API
    /// also speaks (`Typeface.create(base, weight, italic)`, `QFont::Weight`,
    /// `DWRITE_FONT_WEIGHT`, `OH_Drawing_FontWeight`), and what the canvas wire carries.
    pub const fn css(self) -> u16 {
        match self {
            FontWeight::UltraLight => 100,
            FontWeight::Thin => 200,
            FontWeight::Light => 300,
            FontWeight::Regular => 400,
            FontWeight::Medium => 500,
            FontWeight::Semibold => 600,
            FontWeight::Bold => 700,
            FontWeight::Heavy => 800,
            FontWeight::Black => 900,
        }
    }

    /// The nearest rung to a CSS weight (ties round heavier, like CSS font matching); anything
    /// outside 100 … 900 clamps.
    pub fn from_css(n: u16) -> FontWeight {
        let n = n.clamp(100, 900);
        let idx = (usize::from(n) + 50) / 100; // 100 → 1 … 900 → 9
        FontWeight::ALL[idx.clamp(1, 9) - 1]
    }

    /// The English face name for a rung ("Semibold"), for platforms whose enumeration names
    /// no face (see [`FontFace::synthesized_name`]).
    pub const fn name(self) -> &'static str {
        match self {
            FontWeight::UltraLight => "Ultra Light",
            FontWeight::Thin => "Thin",
            FontWeight::Light => "Light",
            FontWeight::Regular => "Regular",
            FontWeight::Medium => "Medium",
            FontWeight::Semibold => "Semibold",
            FontWeight::Bold => "Bold",
            FontWeight::Heavy => "Heavy",
            FontWeight::Black => "Black",
        }
    }
}

/// One face a font family ships (docs/fonts.md): its display name ("Bold Italic"), weight and
/// slant. What [`FontFamilyInfo::faces`] lists and what a font menu's style picker offers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FontFace {
    pub name: String,
    pub weight: FontWeight,
    pub italic: bool,
}

impl FontFace {
    /// A display name from weight + slant ("Semibold Italic") for platforms whose enumeration
    /// API names no face (Android's `fonts.xml`, the CSS generic families).
    pub fn synthesized_name(weight: FontWeight, italic: bool) -> String {
        if italic {
            format!("{} Italic", weight.name())
        } else {
            weight.name().to_string()
        }
    }
}

/// A platform (or bundled) font family and the faces it can draw canvas text in
/// ([`Toolkit::font_families`], docs/fonts.md).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FontFamilyInfo {
    pub family: String,
    pub faces: Vec<FontFace>,
}

impl FontFamilyInfo {
    /// Whether any face is [`FontWeight::Bold`] or heavier.
    pub fn has_bold(&self) -> bool {
        self.faces.iter().any(|f| f.weight >= FontWeight::Bold)
    }
    /// Whether any face is italic.
    pub fn has_italic(&self) -> bool {
        self.faces.iter().any(|f| f.italic)
    }
    /// The nearest face: an exact slant match preferred, then the smallest weight distance
    /// (ties go heavier, like CSS font matching). `None` only when the family lists no faces.
    pub fn face_for(&self, weight: FontWeight, italic: bool) -> Option<&FontFace> {
        let want = i32::from(weight.css());
        self.faces.iter().min_by_key(|f| {
            let slant = i32::from(f.italic != italic);
            let dist = (i32::from(f.weight.css()) - want).abs();
            // Heavier wins a tie: subtracting the bool sorts the heavier face first.
            (slant, dist, i32::from(i32::from(f.weight.css()) < want))
        })
    }
}

/// Single-line text measurement in canvas points ([`Toolkit::measure_text`], docs/fonts.md).
///
/// Two boxes, and the difference between them matters. `width`/`height` is the **line box**: the
/// typographic slot the text occupies, the same for every string in a face at a size, and what
/// [`TextAnchor`] positions. [`ink`](TextMetrics::ink) is the **ink box**: where the glyphs
/// put marks. A line of digits leaves the descender space of its line box empty, so the
/// two disagree, and which one is wanted depends on the question: laying text out in a column
/// wants the line box, and centering it on a rule or keeping it clear of a mark wants the ink.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextMetrics {
    /// The advance width of the whole string.
    pub width: f64,
    /// The line box: ascent + descent at this size (plus the line gap where the engine reports
    /// one), which is the box [`TextAnchor`] positions.
    pub height: f64,
    /// The baseline's offset from the top of the line box.
    pub ascent: f64,
    /// The face's cap height at this size: baseline to the top of a capital.
    ///
    /// A property of the font, not of this string, reported here because it is what optical
    /// centering needs and asking for it separately would be a second measurement. Text made of
    /// capitals and digits looks centered on a rule when its cap box straddles it, not its line
    /// box: the line box reserves descender room that digits never use, so centering by it sits
    /// every label a little low. The cap middle is `ascent - cap_height / 2.0` below the line
    /// box's top.
    pub cap_height: f64,
    /// The ink box, the tight bounds of what is drawn, with its origin relative to the line
    /// box's top-leading corner, so `ink.origin` is where the marks start inside the slot.
    ///
    /// Empty (zero-size) for text that draws nothing, a space included. Where a toolkit cannot
    /// report ink it answers the whole line box, which is a superset: an overlap test against it
    /// can only be too cautious, never wrong.
    pub ink: Rect,
}

impl TextMetrics {
    /// The portable guess `day::measure_text` falls back to when a toolkit cannot measure:
    /// 0.6 × size per character, 1.2 × size tall, the baseline at 0.9 × size, caps at 0.7 × size.
    /// Its ink is the whole line box, the safe direction to be wrong in (see
    /// [`ink`](TextMetrics::ink)).
    pub fn approximate(text: &str, size: f64) -> TextMetrics {
        let (width, height) = (0.6 * size * text.chars().count() as f64, 1.2 * size);
        TextMetrics {
            width,
            height,
            ascent: 0.9 * size,
            cap_height: 0.7 * size,
            ink: Rect::new(0.0, 0.0, width, height),
        }
    }

    /// Read the eight-slot form the serializing backends (qt, xaml, arkui, web) fill across their
    /// C ABI: advance, line height, ascent, cap height, then the ink box relative to the line
    /// box's top-leading corner. One definition so four shims cannot drift from each other.
    pub fn from_slots(out: &[f64; 8]) -> TextMetrics {
        TextMetrics {
            width: out[0],
            height: out[1],
            ascent: out[2],
            cap_height: out[3],
            ink: Rect::new(out[4], out[5], out[6], out[7]),
        }
    }

    /// The line box's top-leading corner, given a baseline-relative measurement, the shape every
    /// backend's metrics come in. `ink_*` are relative to the drawing origin on the baseline
    /// (`ink_top` negative above it), the convention Skia, Core Text and Qt all report in.
    pub fn from_baseline(
        width: f64,
        ascent: f64,
        descent: f64,
        cap_height: f64,
        ink: Rect,
    ) -> TextMetrics {
        TextMetrics {
            width,
            height: ascent + descent,
            ascent,
            cap_height,
            // Baseline-relative to line-box-relative is one shift by the ascent.
            ink: Rect::new(
                ink.origin.x,
                ink.origin.y + ascent,
                ink.size.width,
                ink.size.height,
            ),
        }
    }
}

/// What canvas text is drawn with beyond its size (docs/canvas.md "Text"): a family, a weight and
/// a slant. The default is the platform's own UI face, regular, upright, which is what every
/// backend drew before the field existed, so a default font encodes to nothing on the wire.
#[derive(Clone, Debug, PartialEq, Eq, Default)]
pub struct CanvasFont {
    /// A platform or bundled family name (as [`Toolkit::font_families`] lists it); `None` =
    /// the platform's default UI face.
    pub family: Option<String>,
    /// `None` = Regular.
    pub weight: Option<FontWeight>,
    pub italic: bool,
}

impl CanvasFont {
    /// The family name to send over the wire, empty for the default.
    pub fn family_str(&self) -> &str {
        self.family.as_deref().unwrap_or("")
    }
    /// The CSS weight to send over the wire, 0 for the default.
    pub fn css_weight(&self) -> u16 {
        self.weight.map(FontWeight::css).unwrap_or(0)
    }
}

/// Field separator inside one family of the shim-side font list ([`parse_font_list`]).
pub const FONT_LIST_FIELD: char = '\u{1f}';
/// Family separator of the shim-side font list ([`parse_font_list`]).
pub const FONT_LIST_FAMILY: char = '\u{1e}';

/// Decode the text a non-Rust font enumerator hands back (the Qt, XAML and ArkUI shims, the
/// Android bridge, the web shim all produce this one format): families separated by U+001E;
/// inside a family, U+001F-separated fields: the family name, then one (name, CSS weight,
/// italic `0`/`1`) triple per face. Tolerant: a malformed face or family is skipped, an empty
/// face name is synthesized from its weight and slant, and a family with no faces is kept
/// with none (the caller decides what a face-less family means).
pub fn parse_font_list(s: &str) -> Vec<FontFamilyInfo> {
    let mut out = Vec::new();
    for fam in s.split(FONT_LIST_FAMILY) {
        let mut fields = fam.split(FONT_LIST_FIELD);
        let Some(family) = fields.next().map(str::trim).filter(|f| !f.is_empty()) else {
            continue;
        };
        let rest: Vec<&str> = fields.collect();
        let mut faces = Vec::new();
        for face in rest.chunks(3) {
            let [name, weight, italic] = face else {
                continue;
            };
            let Ok(weight) = weight.trim().parse::<u16>() else {
                continue;
            };
            let weight = FontWeight::from_css(weight);
            let italic = matches!(italic.trim(), "1" | "true");
            let name = name.trim();
            let name = if name.is_empty() {
                FontFace::synthesized_name(weight, italic)
            } else {
                name.to_string()
            };
            if !faces
                .iter()
                .any(|f: &FontFace| f.weight == weight && f.italic == italic)
            {
                faces.push(FontFace {
                    name,
                    weight,
                    italic,
                });
            }
        }
        out.push(FontFamilyInfo {
            family: family.to_string(),
            faces,
        });
    }
    out
}

/// The full font descriptor a label carries: a semantic (or custom) [`Font`] style plus an optional
/// weight override, an italic flag, and the tabular-figures request. Backends resolve this to one
/// native font.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FontSpec {
    pub style: Font,
    pub weight: Option<FontWeight>,
    pub italic: bool,
    /// Ask for tabular (monospaced) figures: every digit takes the same advance, so a number that
    /// changes stops changing width.
    ///
    /// In a proportional system font `1` is narrower than `8`, so a readout beside a slider
    /// wobbles as the value changes even when the digit count is fixed. Every platform ships this
    /// as a font feature, so Day asks for the platform's own rather than substituting a monospaced
    /// family: the text keeps the system face, and only the digits change metrics.
    ///
    /// Reserving space (`Decorate::reserving`) and tabular figures solve the two halves of the
    /// same problem (reservation stops the box resizing, tabular stops the glyphs shifting inside
    /// it), and a numeric readout usually wants both.
    ///
    /// This rides the existing label realize/patch path rather than adding a Toolkit method, so it
    /// is not a backend duty and has no duty-matrix row. Every in-tree backend honors it: AppKit
    /// and UIKit re-pick the system face (`monospacedDigitSystemFont`), GTK and Qt and ArkUI set
    /// the `tnum` OpenType feature, Android `setFontFeatureSettings`, XAML the `Typography`
    /// NumeralAlignment property, and web-dom `font-variant-numeric`. A font with no `tnum` table,
    /// or an SDK predating the attribute, renders the stock proportional figures.
    pub tabular: bool,
    /// Ask for the platform's monospaced face at this style's size, what `` `code` `` in a
    /// markdown run needs (docs/text-runs.md).
    ///
    /// A flag rather than a `Font::Monospace(pt)` variant so the run keeps its semantic style:
    /// code inside a `Footnote` paragraph must stay footnote-sized and keep tracking the
    /// reader's text-size setting, which a fixed point size would throw away.
    ///
    /// Like [`Self::tabular`], this rides the label realize/patch path and is not a backend duty:
    /// every toolkit has a system monospace face (`monospacedSystemFont`, Pango's `monospace`
    /// family, `QFontDatabase::FixedFont`, `Typeface.MONOSPACE`, CSS `monospace`).
    pub monospace: bool,
    /// Multiply the resolved size. `1.0` is the style's own size, `1.6` a heading against a body
    /// paragraph, `0.8` a caption inside one.
    ///
    /// Relative rather than an absolute point size, so that an editor's font-size control can
    /// move this while text a person reads for an hour still tracks the platform's
    /// accessibility text-scale. `Font::System(pt)` remains the absolute escape hatch, and it
    /// is where an imported document's `\fs28` or `font-size: 14px` lands (docs/texteditor.md):
    /// faithful to the file, and no longer responsive to the reader, which is the trade that
    /// form makes.
    ///
    /// Three toolkits take it directly (`GtkTextTag::scale`, Android's `RelativeSizeSpan`, CSS
    /// `em`); the rest multiply it into the size they already compute.
    pub scale: f64,
}

impl Default for FontSpec {
    fn default() -> Self {
        FontSpec {
            style: Font::Body,
            weight: None,
            italic: false,
            tabular: false,
            monospace: false,
            scale: 1.0,
        }
    }
}

impl From<Font> for FontSpec {
    fn from(style: Font) -> Self {
        FontSpec {
            style,
            ..FontSpec::default()
        }
    }
}

impl FontSpec {
    /// The plain descriptor for a style: no weight override, no italic, scale 1.0.
    pub fn new(style: Font) -> Self {
        FontSpec::from(style)
    }
    /// This descriptor at a different relative size (see [`FontSpec::scale`]).
    pub fn scaled(mut self, scale: f64) -> Self {
        self.scale = scale;
        self
    }
    /// The point size this descriptor resolves to, given the size the platform assigns its
    /// semantic style. The one place `scale` is applied, so every backend's font resolver
    /// multiplies the same way.
    pub fn resolved_points(&self, style_points: f64) -> f64 {
        let base = match self.style {
            Font::System(pt) | Font::Custom(_, pt) => pt,
            _ => style_points,
        };
        (base * self.scale).max(1.0)
    }
}

/// One styled span of a label's text (docs/text-runs.md).
///
/// `range` is a byte range into the label's `text`. Bytes, not chars: every backend that takes a
/// structured attributed string wants UTF-16 or byte offsets, `str` slicing is byte-based, and a
/// char count would have to be converted at every boundary. Ranges must be non-overlapping and
/// ascending; a gap between them is unstyled text, drawn with the label's own font.
///
/// A run says only what differs. `font` is the whole descriptor rather than a delta because a
/// bold run inside a Body paragraph is `FontSpec { style: Body, weight: Some(Bold), .. }`. The
/// style has to travel with the weight or the run loses its semantic size.
#[derive(Clone, Debug, PartialEq)]
pub struct TextRun {
    pub range: std::ops::Range<usize>,
    pub font: FontSpec,
    pub color: Option<Color>,
    /// A highlight painted behind the glyphs. Every native text editor carries this attribute
    /// (docs/texteditor.md), and search hits and review comments are the two things an app is
    /// asked for the moment it has styled text at all.
    pub background: Option<Color>,
    /// A line under the text.
    pub underline: Underline,
    /// A line through the text. Separate from `FontSpec` because it is a decoration, not a face:
    /// no platform expresses it by picking a different font.
    pub strikethrough: bool,
    /// Makes this run a link to the given target. Rendering it is [`Cap::TextRuns`]; making it
    /// activatable is [`Cap::TextLinks`], which is a smaller set (see the docs).
    pub link: Option<String>,
}

impl Default for TextRun {
    fn default() -> Self {
        TextRun {
            range: 0..0,
            font: FontSpec::default(),
            color: None,
            background: None,
            underline: Underline::None,
            strikethrough: false,
            link: None,
        }
    }
}

impl TextRun {
    /// A run that only changes the font, the common case for emphasis.
    pub fn font(range: std::ops::Range<usize>, font: FontSpec) -> Self {
        TextRun {
            range,
            font,
            ..TextRun::default()
        }
    }

    /// This run's attributes without its range: what a selection's style is compared against
    /// and what an editor's toolbar toggles (docs/texteditor.md).
    pub fn style(&self) -> RunStyle {
        RunStyle {
            font: self.font,
            color: self.color,
            background: self.background,
            underline: self.underline,
            strikethrough: self.strikethrough,
            link: self.link.clone(),
        }
    }

    /// A run of `style` over `range`.
    pub fn styled(range: std::ops::Range<usize>, style: RunStyle) -> Self {
        TextRun {
            range,
            font: style.font,
            color: style.color,
            background: style.background,
            underline: style.underline,
            strikethrough: style.strikethrough,
            link: style.link,
        }
    }
}

/// Serialize a label's text + runs as markup, for the two backends whose text widgets take a
/// string in their own dialect rather than a structured attributed string: GTK (Pango markup)
/// and Qt (its HTML subset). Shared so the escaping is written and tested once: a translated
/// string containing `&` or `<` corrupts the whole label otherwise, and it will be a translated
/// string that finds the bug.
///
/// `dialect` decides the spelling: Pango wants `<span foreground="#rrggbb"
/// font_family="monospace">`, Qt wants `<span style="color:#rrggbb">` with `<code>`. Both accept
/// `<b>`, `<i>`, `<u>`, `<s>` and `<a href>`, which is why one function can serve them.
///
/// `base_points` is the size the label itself resolved to. Only a relative-size run
/// ([`FontSpec::scale`]) needs it, and only in the Qt dialect: Pango markup takes a percentage
/// directly, while Qt's CSS subset understands `pt` and `px` and ignores `%`.
pub fn runs_to_markup(
    text: &str,
    runs: &[TextRun],
    dialect: MarkupDialect,
    base_points: f64,
) -> String {
    let mut out = String::with_capacity(text.len() + runs.len() * 24);
    let mut at = 0usize;
    for r in runs {
        // Skip a run whose range does not address this string, without advancing `at`: dropping
        // the run loses styling, but advancing past it would drop the rest of the sentence.
        // `runs_are_valid` rejects these upstream; this keeps the failure cheap if one slips by.
        let Some(styled) = text.get(r.range.clone()) else {
            continue;
        };
        if r.range.start > at
            && let Some(plain) = text.get(at..r.range.start)
        {
            escape_markup_in(plain, &mut out, dialect);
        }
        open_run(r, dialect, base_points, &mut out);
        escape_markup_in(styled, &mut out, dialect);
        close_run(r, dialect, &mut out);
        at = r.range.end;
    }
    if let Some(tail) = text.get(at..) {
        escape_markup_in(tail, &mut out, dialect);
    }
    out
}

impl Symbol {
    /// A 24×24 outline path for this symbol, Day's own drawing of it.
    ///
    /// The platform's icon comes first on every backend that has one (SF Symbols, the freedesktop
    /// icon theme, Fluent's glyph font). This is the fallback for when that lookup finds nothing,
    /// which is not an edge case: `view-filter-symbolic` exists on a GNOME desktop and nowhere
    /// else, so a GTK or Qt app run off that desktop drew a toolbar item with no icon at all.
    /// One table here means the same fallback shape everywhere instead of a gap per platform.
    ///
    /// `None` for a variant with no drawing yet: `Symbol` is `#[non_exhaustive]`, so a new one
    /// degrades to a label rather than failing to compile.
    pub fn outline_path(self) -> Option<&'static str> {
        use Symbol as S;
        // The wildcard is unreachable today (every variant is drawn below) and it is here for
        // the next one, which should degrade to a label rather than fail to compile.
        #[allow(unreachable_patterns)]
        Some(match self {
            S::Add => "M11 5h2v6h6v2h-6v6h-2v-6H5v-2h6z",
            S::Remove => "M5 11h14v2H5z",
            S::Delete => "M9 3h6l1 2h4v2H4V5h4zM6 8h12l-1 13H7z",
            S::Edit => {
                "M3 17.3V21h3.7L17.8 9.9l-3.7-3.7zM20.7 7a1 1 0 0 0 0-1.4l-2.3-2.3a1 1 0 0 0-1.4 0l-1.8 1.8 3.7 3.7z"
            }
            S::New => "M13 2H6v20h12V7h-5zm2 .5L19.5 7H15z",
            S::Open => "M2 5h7l2 2h11v12H2z",
            S::Save => "M3 3h13l5 5v13H3zm5 0h7v6H8zm-1 11h10v7H7z",
            S::Print => "M7 3h10v4H7zM4 8h16v8h-3v6H7v-6H4z",
            S::Refresh => "M12 4V1L8 5l4 4V6a6 6 0 1 1-6 6H4a8 8 0 1 0 8-8z",
            S::Search => {
                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4m0 2a4 4 0 1 1 0 8 4 4 0 0 1 0-8"
            }
            S::Share => "M12 3l5 5h-3v7h-4V8H7zM5 17h14v4H5z",
            // An eight-tooth gear, round about the center (radius 10 at the teeth, 7.6 at the
            // roots) with a 3.2 hole: square in its box, so it sits in a row's 24-point icon
            // slot at the same size as its neighbors.
            S::Settings => {
                "M9.9 4.7L10.2 2.2L13.8 2.2L14.1 4.7A7.6 7.6 0 0 1 15.7 5.4L17.7 3.8L20.2 6.3L18.6 8.3A7.6 7.6 0 0 1 19.3 9.9L21.8 10.2L21.8 13.8L19.3 14.1A7.6 7.6 0 0 1 18.6 15.7L20.2 17.7L17.7 20.2L15.7 18.6A7.6 7.6 0 0 1 14.1 19.3L13.8 21.8L10.2 21.8L9.9 19.3A7.6 7.6 0 0 1 8.3 18.6L6.3 20.2L3.8 17.7L5.4 15.7A7.6 7.6 0 0 1 4.7 14.1L2.2 13.8L2.2 10.2L4.7 9.9A7.6 7.6 0 0 1 5.4 8.3L3.8 6.3L6.3 3.8L8.3 5.4A7.6 7.6 0 0 1 9.9 4.7zM12 8.8a3.2 3.2 0 1 0 0 6.4a3.2 3.2 0 1 0 0-6.4z"
            }
            S::Info => "M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20m-1 5h2v2h-2zm0 4h2v6h-2z",
            S::Star => {
                "M12 2l2.9 6.3 6.9.8-5.1 4.7 1.4 6.8L12 17.3 5.9 20.6l1.4-6.8L2.2 9.1l6.9-.8z"
            }
            S::Bookmark => "M6 2h12v20l-6-4-6 4z",
            S::Back => "M15.4 5.4L14 4l-8 8 8 8 1.4-1.4L8.8 12z",
            S::Forward => "M8.6 5.4L10 4l8 8-8 8-1.4-1.4L15.2 12z",
            S::Up => "M5.4 15.4L4 14l8-8 8 8-1.4 1.4L12 8.8z",
            S::Down => "M5.4 8.6L4 10l8 8 8-8-1.4-1.4L12 15.2z",
            S::Home => "M12 3l9 8h-3v10h-5v-6h-2v6H6V11H3z",
            S::Sidebar => "M3 4h18v16H3zm2 2v12h4V6zm6 0v12h8V6z",
            S::Filter => "M3 5h18l-7 8v6l-4 2v-8z",
            S::Sort => "M8 4v12H4l4 4 4-4H10V4zM14 6h7v2h-7zm0 4h5v2h-5zm0 4h3v2h-3z",
            S::More => {
                "M6 10a2 2 0 1 0 0 4 2 2 0 0 0 0-4m6 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4m6 0a2 2 0 1 0 0 4 2 2 0 0 0 0-4"
            }
            S::Play => "M8 5l11 7-11 7z",
            S::Pause => "M7 5h3v14H7zm7 0h3v14h-3z",
            S::Stop => "M6 6h12v12H6z",
            S::Camera => {
                "M9 3h6l1.5 2H20a2 2 0 0 1 2 2v12H2V7a2 2 0 0 1 2-2h3.5zm3 6a4.5 4.5 0 1 0 0 9 4.5 4.5 0 0 0 0-9m0 1.6a2.9 2.9 0 1 1 0 5.8 2.9 2.9 0 0 1 0-5.8"
            }
            S::Code => {
                "M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0l4.6-4.6L14.6 7.4 16 6l6 6-6 6z"
            }
            S::Light => {
                "M12 7a5 5 0 1 0 0 10 5 5 0 0 0 0-10M11 1h2v3h-2zm0 19h2v3h-2zM1 11h3v2H1zm19 0h3v2h-3zM3.5 4.9l1.4-1.4 2.1 2.1-1.4 1.4zm13.5 13.5l1.4-1.4 2.1 2.1-1.4 1.4zM4.9 20.5l-1.4-1.4 2.1-2.1 1.4 1.4zm13.5-13.5l-1.4-1.4 2.1-2.1 1.4 1.4z"
            }
            S::Dark => "M12 3a9 9 0 1 0 9 9 7 7 0 0 1-9-9",
            // "Automatic": the half-filled circle every platform uses: the left half solid, the
            // right half an outline, which `evenodd` below turns into the ring it should be.
            S::Auto => "M12 2a10 10 0 0 0 0 20zM12 4a8 8 0 0 1 0 16v-1.6a6.4 6.4 0 0 0 0-12.8z",
            S::ZoomIn => {
                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4M9 7h2v2h2v2h-2v2H9v-2H7V9h2z"
            }
            S::ZoomOut => {
                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4M7 9h6v2H7z"
            }
            // The ZoomIn lens with a numeral 1 in it, "back to actual size".
            S::ZoomReset => {
                "M10 4a6 6 0 1 0 3.5 10.9l4.8 4.8 1.4-1.4-4.8-4.8A6 6 0 0 0 10 4M12 13h-1.7V9.3l-1.2.8-.9-1.3 2.4-1.8H12z"
            }
            S::Undo => "M12 5V2L7 7l5 5V9a5 5 0 1 1 0 10H8v2h4a7 7 0 0 0 0-14z",
            S::Redo => "M12 5V2l5 5-5 5V9a5 5 0 1 0 0 10h4v2h-4a7 7 0 0 1 0-14z",
            S::Copy => "M8 2h10v14H8zM4 6h2v14h12v2H4z",
            S::Cut => {
                "M9 4l5.5 9.5-1.2 2L7.8 6zM15 4L9.5 13.5l1.2 2L16.2 6zM6 16a3 3 0 1 0 0 6 3 3 0 0 0 0-6m12 0a3 3 0 1 0 0 6 3 3 0 0 0 0-6"
            }
            S::Paste => "M9 2h6v2h3v18H6V4h3zm0 2v2h6V4z",
            S::Mail => "M2 5h20v14H2zm2 3.2V17h16V8.2l-8 5z",
            S::Folder => "M2 5h7l2 2h11v12H2z",
            S::Document => "M14 2H6v20h12V6zm.5.8L17.2 6H14.5z",
            S::Check => "M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4z",
            S::Close => {
                "M19 6.4L17.6 5 12 10.6 6.4 5 5 6.4 10.6 12 5 17.6 6.4 19 12 13.4 17.6 19 19 17.6 13.4 12z"
            }
            S::Warning => "M12 2l10 19H2zm-1 7h2v6h-2zm0 8h2v2h-2z",
            // Shape outlines, stroked as a 2-unit band (an even-odd ring), so they read as
            // outlines at any size rather than filled blocks.
            S::Rectangle => "M3 5h18v14H3zm2 2v10h14V7z",
            S::Oval => {
                "M12 5c5 0 9 3.1 9 7s-4 7-9 7-9-3.1-9-7 4-7 9-7zm0 2c-3.9 0-7 2.2-7 5s3.1 5 7 5 7-2.2 7-5-3.1-5-7-5z"
            }
            // A circular ring (even-odd: outer disc minus inner) and its filled twin.
            S::Circle => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16zm0 2a6 6 0 1 1 0 12 6 6 0 0 1 0-12z",
            S::CircleFilled => "M12 4a8 8 0 1 0 0 16 8 8 0 0 0 0-16z",
            S::Line => "M4.7 17.9l13.2-13.2 1.4 1.4L6.1 19.3z",
            // Group: a solid square stacked on another (the visible L of the back one);
            // Ungroup: the same two squares pulled apart.
            S::Group => "M8 4h12v12h-4V8H8zM4 8h12v12H4z",
            S::Ungroup => "M3 3h8v8H3zM13 13h8v8h-8z",
            // `Symbol` is `#[non_exhaustive]`: a variant added upstream draws nothing here rather
            // than failing to compile, and its item keeps its label.
            _ => return None,
        })
    }

    /// [`Self::outline_path`] wrapped as a standalone SVG document.
    pub fn outline_svg(self) -> Option<String> {
        self.outline_path().map(|d| {
            format!(
                "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\">\
                 <path fill-rule=\"evenodd\" d=\"{d}\"/></svg>"
            )
        })
    }
}

/// Which markup dialect [`runs_to_markup`] should emit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MarkupDialect {
    /// Pango markup (GTK).
    Pango,
    /// Qt's rich-text HTML subset.
    QtHtml,
}

/// XML-escape a run of plain text into `out`. `&` first, or the escapes escape each other.
///
/// Newlines are dialect-specific. Pango lays a literal `\n` out as a line break, but Qt's rich
/// text is HTML, where any run of whitespace collapses to one space, which silently ran a
/// two-paragraph body together into a single block. `<br>` is what says "break here" in HTML, so
/// the same string wraps the same way on both.
fn escape_markup_in(s: &str, out: &mut String, dialect: MarkupDialect) {
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            '\n' if dialect == MarkupDialect::QtHtml => out.push_str("<br>"),
            _ => out.push(c),
        }
    }
}

/// [`escape_markup_in`] for the URL slot, where a newline cannot appear.
fn escape_markup(s: &str, out: &mut String) {
    escape_markup_in(s, out, MarkupDialect::Pango);
}

fn hex(c: Color) -> String {
    format!(
        "#{:02x}{:02x}{:02x}",
        (c.r.clamp(0.0, 1.0) * 255.0) as u8,
        (c.g.clamp(0.0, 1.0) * 255.0) as u8,
        (c.b.clamp(0.0, 1.0) * 255.0) as u8
    )
}

/// Does this run need a `<span>` in `dialect`, or do the plain tags cover it?
fn needs_span(r: &TextRun, dialect: MarkupDialect) -> bool {
    let extras = r.color.is_some() || r.background.is_some() || r.font.scale != 1.0;
    match dialect {
        // Pango expresses the monospace family as a span attribute; Qt cannot (see below).
        MarkupDialect::Pango => extras || r.font.monospace,
        MarkupDialect::QtHtml => extras,
    }
}

fn open_run(r: &TextRun, dialect: MarkupDialect, base_points: f64, out: &mut String) {
    if let Some(url) = r.link.as_deref() {
        out.push_str("<a href=\"");
        escape_markup(url, out);
        out.push_str("\">");
    }
    // The span carries the attributes that have no tag: colors, relative size, and (on Pango)
    // the monospace family. Bold/italic/strike/underline are tags in both dialects, which keeps
    // the attribute string short and the escaping trivial.
    let color = r.color.map(hex);
    let background = r.background.map(hex);
    let mono = r.font.monospace;
    if needs_span(r, dialect) {
        match dialect {
            MarkupDialect::Pango => {
                out.push_str("<span");
                if let Some(c) = &color {
                    out.push_str(&format!(" foreground=\"{c}\""));
                }
                if let Some(c) = &background {
                    out.push_str(&format!(" background=\"{c}\""));
                }
                if mono {
                    out.push_str(" font_family=\"monospace\"");
                }
                if r.font.scale != 1.0 {
                    // Absolute, in Pango units (1/1024 pt), not the `font_scale`/`size="N%"`
                    // pair: those are Pango 1.50 attributes, and a Pango that does not know an
                    // attribute fails the whole markup parse, which renders the label empty
                    // rather than merely unscaled. A point size still tracks the desktop's text
                    // scaling, since Pango resolves points through the Xft DPI.
                    let pts = r.font.resolved_points(base_points);
                    out.push_str(&format!(" size=\"{}\"", (pts * 1024.0).round() as i64));
                }
                out.push('>');
            }
            MarkupDialect::QtHtml => {
                // Color only. Qt's rich text does not resolve the generic `monospace` family
                // from a style attribute (it rendered proportional), so the fixed face comes
                // from the `<code>` tag below, which Qt maps to its own fixed font.
                out.push_str("<span style=\"");
                if let Some(c) = &color {
                    out.push_str(&format!("color:{c};"));
                }
                if let Some(c) = &background {
                    out.push_str(&format!("background-color:{c};"));
                }
                if r.font.scale != 1.0 {
                    // Points, not a percentage: Qt's rich-text CSS subset understands `pt` and
                    // `px` and silently ignores `%`, which is why a scaled run rendered at the
                    // base size here while every other backend scaled it.
                    let pt = r.font.resolved_points(base_points);
                    out.push_str(&format!("font-size:{pt}pt;"));
                }
                out.push_str("\">");
            }
        }
    }
    if dialect == MarkupDialect::QtHtml && mono {
        out.push_str("<code>");
    }
    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
        out.push_str("<b>");
    }
    if r.font.italic {
        out.push_str("<i>");
    }
    if r.underline.is_on() {
        out.push_str("<u>");
    }
    if r.strikethrough {
        out.push_str("<s>");
    }
}

fn close_run(r: &TextRun, dialect: MarkupDialect, out: &mut String) {
    if r.strikethrough {
        out.push_str("</s>");
    }
    if r.underline.is_on() {
        out.push_str("</u>");
    }
    if r.font.italic {
        out.push_str("</i>");
    }
    if r.font.weight.is_some_and(|w| w >= FontWeight::Semibold) {
        out.push_str("</b>");
    }
    if dialect == MarkupDialect::QtHtml && r.font.monospace {
        out.push_str("</code>");
    }
    if needs_span(r, dialect) {
        out.push_str("</span>");
    }
    if r.link.is_some() {
        out.push_str("</a>");
    }
}

/// Are these runs well formed for `text`: ascending, non-overlapping, inside the string, and on
/// character boundaries?
///
/// Checked once in the pieces layer rather than in eight backends. A backend handed overlapping
/// ranges would produce a different wrong answer per platform, and a range splitting a multi-byte
/// character would panic on `str` slicing in some and render mojibake in others.
pub fn runs_are_valid(text: &str, runs: &[TextRun]) -> Result<(), String> {
    let mut prev_end = 0usize;
    for (i, r) in runs.iter().enumerate() {
        if r.range.start < prev_end {
            return Err(format!(
                "run {i} starts at {} but the previous run ends at {prev_end} — runs must be \
                 ascending and non-overlapping",
                r.range.start
            ));
        }
        if r.range.end > text.len() {
            return Err(format!(
                "run {i} ends at {} but the text is {} bytes",
                r.range.end,
                text.len()
            ));
        }
        if r.range.start > r.range.end {
            return Err(format!("run {i} has an inverted range {:?}", r.range));
        }
        if !text.is_char_boundary(r.range.start) || !text.is_char_boundary(r.range.end) {
            return Err(format!(
                "run {i} range {:?} splits a multi-byte character",
                r.range
            ));
        }
        prev_end = r.range.end;
    }
    Ok(())
}

pub mod props {
    use super::*;

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ContainerProps {
        pub background: Option<Color>,
        pub corner_radius: f64,
        pub clips: bool,
        /// Semantic, theme-adaptive surface, mapped by each backend to a native material that
        /// follows the platform's light/dark appearance automatically (unlike the fixed-RGBA
        /// `background`, which it overrides when set).
        pub role: Option<super::SurfaceRole>,
    }
    /// Reactive surface update for a `background(..)` decorator whose color is a signal/closure:
    /// the backend re-applies the fill on the container's native backing view. Corner radius and
    /// clipping are fixed at realize (the `corner_radius(r)` decorator takes a plain `f64`).
    #[derive(Clone, Debug, PartialEq)]
    pub enum ContainerPatch {
        Background(Option<Color>),
    }

    /// Realize props for a `scroll` container: which axis it scrolls. Backends create the matching
    /// native scroll view (vertical `UIScrollView`/`ScrollView`, horizontal
    /// `HorizontalScrollView`, etc.).
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ScrollProps {
        pub horizontal: bool,
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct LabelProps {
        pub text: String,
        pub font: FontSpec,
        pub color: Option<Color>,
        /// What the text means, for the color the platform gives it (docs/text.md).
        ///
        /// Semantic the way [`crate::Font`] is semantic: an app says "this is secondary text"
        /// and each platform answers with its own answer: `secondaryLabelColor` on Apple,
        /// `?android:textColorSecondary`, GTK's `dim-label`. That is the only way a de-emphasized
        /// label stays correct in both appearances, since a literal grey that reads well on white
        /// is wrong on black. An explicit [`Self::color`] still wins; a backend that has no such
        /// color renders primary, which is legible and correct, just not dimmed.
        pub role: TextRole,
        pub wraps: bool,
        /// Maximum rendered lines; zero is unlimited. Native Apple plain labels truncate
        /// the last line. Other backends may retain their ordinary wrapping behavior.
        pub max_lines: u32,
        /// How the label's lines sit within its own width. Only observable on a label that
        /// wraps or carries explicit newlines: a single line fills its box, so its alignment is
        /// the container's business, not the label's.
        ///
        /// `Leading` is the default and is what running text wants; `Center` is for the short,
        /// centered block a welcome screen or an empty state uses. A backend that cannot set
        /// it renders leading-aligned, which is legible and correct, just not centered.
        pub align: TextAlign,
        /// Styled spans within `text` (docs/text-runs.md). Empty is the overwhelmingly common
        /// case and means exactly what a label has always meant: one font, one color. A backend
        /// that cannot draw runs ignores this and renders `text` uniformly, which is legible and
        /// correct, just unstyled.
        pub runs: Vec<crate::TextRun>,
    }
    /// What a label's text means, for the color the platform gives it (`LabelProps::role`).
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum TextRole {
        /// Ordinary text, in the platform's primary label color.
        #[default]
        Primary,
        /// De-emphasized text: a caption, a hint, the "nothing selected" line an empty detail
        /// pane shows. Rendered in the platform's secondary label color.
        Secondary,
    }

    /// How a wrapped label's lines sit within its width (`LabelProps::align`).
    ///
    /// There is no `Justified` variant because no toolkit in Day's set agrees on how to justify
    /// the last line, and the ones that can do it at all need a paragraph style the others have
    /// no equivalent for.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum TextAlign {
        /// Left in a left-to-right locale, right in an RTL one (docs/localization.md).
        #[default]
        Leading,
        Center,
        Trailing,
    }

    #[derive(Clone, Debug, PartialEq)]
    pub enum LabelPatch {
        Text(String),
        Color(Option<Color>),
        Font(FontSpec),
        /// New text and its runs together. One patch, not two: a run's byte range is only
        /// meaningful against a particular string, so applying them separately would leave the
        /// widget briefly holding ranges that point into the wrong text.
        Runs(String, Vec<crate::TextRun>),
    }

    /// A button's native styling tier. `Automatic` is the toolkit's stock look; `Bordered`
    /// asks for a visually contained button where the stock look is borderless (iOS's plain
    /// system button reads as a link); `Prominent` asks for the platform's accent-filled /
    /// default-action affordance. Toolkits whose stock buttons are already contained treat
    /// `Bordered` as `Automatic`.
    // `Eq` is gone with the `Tinted` color: `Color` holds floats. `PartialEq` is what the
    // props diff uses, and that is unaffected.
    #[derive(Clone, Copy, Debug, Default, PartialEq)]
    pub enum ButtonStyleSpec {
        #[default]
        Automatic,
        Bordered,
        Prominent,
        /// A filled button in an app-chosen color, still drawn by the native control: the
        /// platform keeps its own pressed, hover, focus and disabled rendering, its button role,
        /// and its keyboard activation. The label color is not carried; each backend picks the
        /// readable one for the fill (see [`ButtonStyleSpec::on_tint`]), the same call the
        /// platform's own tinted buttons make.
        ///
        /// A backend with no way to recolor its button ignores this and draws its ordinary
        /// button. That is the trade: a plain button everywhere beats a colored
        /// rectangle that is no longer a button on the platforms that cannot.
        Tinted(Color),
        /// A button no wider than its title asks for (a one-glyph "−" or "+" in a stepper,
        /// a "×" on a chip) on toolkits whose stock button carries a minimum width and wide
        /// insets (Material's 88 dp button turns a two-button stepper into 240 dp). The native
        /// control stays: only its minimum width and horizontal padding are reduced. A toolkit
        /// whose buttons already hug their title (AppKit, UIKit's plain button, Qt) draws its
        /// ordinary button.
        Compact,
        /// Borderless native action button; compact horizontal insets on Material.
        Plain,
    }

    impl ButtonStyleSpec {
        /// The label color to draw on a [`ButtonStyleSpec::Tinted`] fill: whichever of black or
        /// white contrasts better against it, by WCAG's contrast ratio.
        ///
        /// Comparing the two ratios rather than thresholding the luminance is the difference
        /// between right and nearly right. A mid amber (`#F0A64C`) has a relative luminance of
        /// 0.44; under a "brighter than half" test it reads as dark and takes white text, at a
        /// hopeless 2.2:1. Its contrast against black is 9.7:1. The two ratios cross at a
        /// luminance of 0.179, not 0.5, and everything between those two numbers is a button
        /// nobody can read.
        pub fn on_tint(fill: Color) -> Color {
            // WCAG relative luminance: sRGB channels linearized, then weighted by the eye's
            // sensitivity to each.
            let lin = |c: f64| {
                let c = c.clamp(0.0, 1.0);
                if c <= 0.04045 {
                    c / 12.92
                } else {
                    ((c + 0.055) / 1.055).powf(2.4)
                }
            };
            let l = 0.2126 * lin(fill.r) + 0.7152 * lin(fill.g) + 0.0722 * lin(fill.b);
            // Contrast ratio is (lighter + 0.05) / (darker + 0.05); white is 1.0, black is 0.0.
            let against_white = 1.05 / (l + 0.05);
            let against_black = (l + 0.05) / 0.05;
            if against_black >= against_white {
                Color::BLACK
            } else {
                Color::WHITE
            }
        }
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    /// The visible content and accessible title of a button with an icon.
    pub struct ButtonContent {
        /// Also serves as the accessible name when only the icon is visible.
        pub title: String,
        pub icon: Option<Icon>,
        pub icon_only: bool,
    }
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ButtonProps {
        pub title: String,
        pub icon: Option<Icon>,
        pub icon_only: bool,
        pub enabled: bool,
        pub style: ButtonStyleSpec,
        /// The button stands for the current choice among its siblings (a document tab, a
        /// view switcher): the platform's own checked or selected rendering, which keeps the
        /// button enabled, focusable and activatable, and tells assistive tech it is selected.
        /// A click never toggles it natively; only the app's next patch changes it.
        pub selected: bool,
    }
    #[derive(Clone, Debug, PartialEq)]
    pub enum ButtonPatch {
        Title(String),
        /// Update an icon button's label and icon together. Plain buttons still use `Title`.
        Content(ButtonContent),
        Enabled(bool),
        /// The selected state (see [`ButtonProps::selected`]).
        Selected(bool),
        /// A live style change: what a reactive `.tint(…)` sends, so a button can recolor with
        /// app state without being torn down and realized again.
        Style(ButtonStyleSpec),
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ToggleProps {
        pub on: bool,
        pub enabled: bool,
    }
    #[derive(Clone, Debug, PartialEq)]
    pub enum TogglePatch {
        On(bool),
        Enabled(bool),
    }

    #[derive(Clone, Debug, PartialEq)]
    pub struct SliderProps {
        pub value: f64,
        pub min: f64,
        pub max: f64,
        pub step: Option<f64>,
        pub enabled: bool,
    }
    impl Default for SliderProps {
        fn default() -> Self {
            SliderProps {
                value: 0.0,
                min: 0.0,
                max: 1.0,
                step: None,
                enabled: true,
            }
        }
    }
    #[derive(Clone, Debug, PartialEq)]
    pub enum SliderPatch {
        Value(f64),
        Enabled(bool),
    }

    /// SwiftUI's `pickerStyle` analogue (kinds::PICKER). Each maps to a distinct native
    /// control per toolkit (docs/picker.md).
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum PickerStyle {
        /// A dropdown/pop-up menu (NSPopUpButton / GtkDropDown / QComboBox / UIButton+UIMenu / Spinner).
        #[default]
        Menu,
        /// A horizontal segmented control (NSSegmentedControl / UISegmentedControl / linked toggles / …).
        Segmented,
        /// A vertical radio-button group laid out inline (NSButton radios / GtkCheckButton group / …).
        Inline,
    }

    /// Full picker props (realize). `style` is set once at build; `options`, `selected` and
    /// `enabled` patch (via [`PickerPatch`]).
    #[derive(Clone, Debug, PartialEq)]
    pub struct PickerProps {
        /// Decorative boundaries before option indexes (not selectable options). Native menu
        /// grouping on AppKit/UIKit; ignored by other backends and non-menu styles.
        pub separators_before: Vec<usize>,
        pub options: Vec<String>,
        pub selected: usize,
        pub style: PickerStyle,
        /// Whether the picker takes input. Default `true`.
        pub enabled: bool,
    }
    impl Default for PickerProps {
        fn default() -> Self {
            PickerProps {
                separators_before: Vec::new(),
                options: Vec::new(),
                selected: 0,
                style: PickerStyle::default(),
                enabled: true,
            }
        }
    }

    #[derive(Clone, Debug, PartialEq)]
    pub enum PickerPatch {
        Selected(usize),
        /// New option labels, for a picker whose choices come from data (a document list, a
        /// live count). The backend rebuilds its items and keeps the selected index where it
        /// still exists, clamping to the last option otherwise; a fresh
        /// [`PickerPatch::Selected`] follows whenever the app's own binding disagrees.
        Options(Vec<String>),
        /// Enable or disable the whole control, every style alike.
        Enabled(bool),
    }

    /// Full text-area props (realize, kinds::TEXT_AREA; docs/textarea.md). `text` seeds the
    /// editor; `min_lines`/`max_lines` bound the auto-growing height in text lines
    /// (`max_lines == 0` = unbounded). `editable`/`selectable`/`spellcheck` control the native
    /// editor attributes (all default `true`); a backend that can't honor one answers
    /// `Cap::Text{Editable,Selectable,SpellCheck}` = `Unsupported`. `text` and the three attributes
    /// change after build (via [`TextAreaPatch`]); the rest are build-only.
    #[derive(Clone, Debug, PartialEq)]
    pub struct TextAreaProps {
        pub text: String,
        pub placeholder: String,
        pub min_lines: u32,
        pub max_lines: u32,
        /// Whether the user can edit the text (`false` = read-only). Default `true`.
        pub editable: bool,
        /// Whether the text can be selected (and copied). Default `true`.
        pub selectable: bool,
        /// Whether spell-check / autocorrect highlighting is on. Default `true`.
        pub spellcheck: bool,
        /// Plain Enter emits `Event::Submitted` instead of inserting a newline (Shift+Enter
        /// still inserts one where the platform can distinguish). Chat composers. Default
        /// `false`.
        pub submit_on_enter: bool,
    }

    impl Default for TextAreaProps {
        fn default() -> Self {
            TextAreaProps {
                text: String::new(),
                placeholder: String::new(),
                min_lines: 1,
                max_lines: 0,
                editable: true,
                selectable: true,
                spellcheck: true,
                submit_on_enter: false,
            }
        }
    }

    /// Imperative text-area updates: replace the text (programmatic sync), or flip one of the
    /// live attributes.
    #[derive(Clone, Debug, PartialEq)]
    pub enum TextAreaPatch {
        SetText(String),
        SetEditable(bool),
        SetSelectable(bool),
        SetSpellCheck(bool),
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct TextFieldProps {
        pub text: String,
        pub placeholder: String,
        pub enabled: bool,
    }
    #[derive(Clone, Debug, PartialEq)]
    pub enum TextFieldPatch {
        /// Origin-tagged write (§4.4): `from_native` suppresses the echo back into the widget.
        Text {
            text: String,
            from_native: bool,
        },
        Placeholder(String),
        Enabled(bool),
    }

    /// How an image is scaled to fill its frame (§18.3). Maps to each toolkit's native scaling.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum ContentMode {
        /// Scale to fit entirely inside the frame, preserving aspect ratio (letterboxed). The
        /// default: an image never stretches unless asked. SwiftUI's `.scaledToFit`.
        #[default]
        Fit,
        /// Scale to fill the frame, preserving aspect ratio and cropping the overflow. SwiftUI's
        /// `.scaledToFill`.
        Fill,
        /// Stretch to fill the frame exactly, ignoring aspect ratio.
        Stretch,
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ImageProps {
        /// Which pixels to draw: a staged asset name, encoded bytes, or an already-decoded
        /// image ([`ImageSource`], docs/images.md). A name resolves through the backend's own
        /// pipeline (§18.2); bytes and decoded ids need [`Cap::ImageDecode`], and a backend
        /// without it draws nothing rather than guessing.
        pub source: ImageSource,
        pub decorative: bool,
        /// How the image scales within its frame (default [`ContentMode::Fit`], no stretching).
        pub content_mode: ContentMode,
        /// Optional width:height ratio the view is constrained to (e.g. `16.0/9.0`). `None` lets the
        /// image take its allocated frame.
        pub aspect_ratio: Option<f64>,
        /// Monochrome tint for a template/vector glyph (docs/vectors.md): backends that can,
        /// recolor natively (template rendering on Apple, drawable tint on Android, pixel
        /// recolor on GTK); backends that can't yet ignore it and draw the source colors.
        /// `None` (the default, and every raster `image(…)`) means "as authored".
        pub tint: Option<Color>,
        /// A monochrome template glyph (docs/vectors.md "Template"): with no `tint`, it draws
        /// in the foreground of the surface it sits on — the theme's label color on the
        /// desktops, the cell's tint on UIKit, `currentColor` on the web — and follows a
        /// theme switch. What a sidebar row's untinted icon is: a tinted glyph recolors the
        /// same way with or without this, and `false` (the default) draws an untinted glyph as
        /// authored. [`ImagePatch::Tint`]`(None)` on a template returns to that foreground,
        /// not to the authored colors.
        pub template: bool,
    }

    /// A list row's standard content (`kinds::LIST_ITEM`, docs/list.md "List items"). Empty
    /// text means the part is absent.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ListItemProps {
        pub title: String,
        /// A second line under the title, in the platform's secondary style.
        pub subtitle: String,
        /// Trailing text (a count, a value), in the platform's secondary style.
        pub detail: String,
        /// The leading glyph: a symbol or a bundled image.
        pub icon: Option<crate::Icon>,
        /// The glyph's color; `None` takes the platform's own (template glyphs follow the
        /// foreground, the tint color on UIKit).
        pub icon_tint: Option<Color>,
        /// A trailing check mark: the platform's selected-option mark (UIKit's checkmark
        /// accessory, a Material check icon), announced as checked.
        pub checked: bool,
    }

    /// A live change to a realized list item; every part changes in place.
    #[derive(Clone, Debug, PartialEq)]
    pub enum ListItemPatch {
        Title(String),
        Subtitle(String),
        Detail(String),
        Icon(Option<crate::Icon>),
        IconTint(Option<Color>),
        Checked(bool),
    }

    /// A live change to a realized image or vector glyph.
    ///
    /// `content_mode` and the rest still describe which art this is and how it fills its frame,
    /// which a rebuild expresses better than a patch. Two things do want to follow a signal: the
    /// tint (a glyph that recolors with the selection or the theme should repaint, not be torn
    /// down and realized again, docs/vectors.md "Tint") and the source, now that it can be a
    /// buffer the app swaps (a download landing, a new photo picked, docs/images.md). Replacing
    /// the pixels of a view that is already on screen is what a patch is for; realizing a second
    /// view would flash.
    #[derive(Clone, Debug, PartialEq)]
    pub enum ImagePatch {
        /// Recolor the glyph, or `None` to draw the authored colors again.
        Tint(Option<Color>),
        /// Draw different pixels in the same view. A backend that cannot decode the new source
        /// (bytes where [`Cap::ImageDecode`] is `Unsupported`) leaves what it was drawing.
        Source(ImageSource),
    }

    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct CanvasProps {
        pub ops: Vec<DrawOp>,
    }

    /// Progress indicator. `value` is the completed fraction in `0.0..=1.0`; `None` means
    /// indeterminate (an animated spinner / busy bar, no known extent). Backends map this to
    /// their native determinate/indeterminate widgets (docs/progress.md).
    #[derive(Clone, Debug, PartialEq)]
    pub struct ProgressProps {
        pub value: Option<f64>,
        /// Whether an indeterminate indicator animates; ignored for a determinate bar.
        pub animating: bool,
        /// The platform's large indicator size.
        pub large: bool,
    }
    impl Default for ProgressProps {
        fn default() -> Self {
            Self {
                value: None,
                animating: true,
                large: false,
            }
        }
    }
    #[derive(Clone, Debug, PartialEq)]
    pub enum ProgressPatch {
        Animating(bool),
        /// New completed fraction, or `None` to switch to indeterminate.
        Value(Option<f64>),
    }

    /// A rule between neighbors (`divider()`): a hairline across the width it is offered, or,
    /// with `vertical`, down the height it is offered (`divider().vertical()`, between a
    /// row's panes). A toolkit measures both the same way, as a horizontal rule, because the
    /// pieces layer swaps the axes of a vertical one's proposal and answer; realization is
    /// where the orientation matters, for the few widgets that draw a horizontal line
    /// regardless of their frame.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct DividerProps {
        pub vertical: bool,
    }

    /// How a navigation host lays its panes out (docs/navigation.md).
    ///
    /// This is the resolved presentation, what the toolkit must draw right now. The app asks for
    /// one through `Nav::presentation`, where leaving it unset means "automatic": the pieces
    /// layer resolves it from the window's [`SizeClass`] and the toolkit's `Cap::NavSplit`, and
    /// re-resolves it whenever the class changes. There is no `Auto` variant here because a
    /// backend can only ever draw a concrete one, so the undecided state stays on the app's side
    /// of the boundary where it can still be decided.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum NavPresentation {
        /// Sidebar beside detail, both visible (`NSSplitViewController`, nested `GtkPaned`s,
        /// a `NavigationView`). The sidebar pane gets its own container.
        Split,
        /// One page at a time, back-navigable. The sidebar pane becomes the stack's root.
        #[default]
        Stack,
        /// The rows drawn as a tab bar, one page's content beside it, no back stack: what a
        /// phone-shaped window wants from a one-of-N surface (`UITabBarController`, a Material
        /// `NavigationBarView`, `NavigationView.PaneDisplayMode = Top`). The `Pane::Sidebar` page
        /// is not drawn at all: its rows are the chrome.
        Tabs,
        /// The rows drawn as a narrow icon strip beside the content, the `Medium`-width answer
        /// between [`Self::Tabs`] and [`Self::Split`] (a Material `NavigationRailView`,
        /// `PaneDisplayMode = LeftCompact`, an ArkUI vertical `Tabs`).
        ///
        /// A backend with no rail rounds it to a neighbor of its own choosing rather than
        /// failing: UIKit answers `Tabs` (which is what iPadOS does at that width), GTK the same.
        /// Rounding is expected and correct; this variant is a request, not a contract.
        Rail,
    }

    impl NavPresentation {
        /// `true` for [`NavPresentation::Split`], the shape most backend code wants.
        pub fn is_split(self) -> bool {
            self == NavPresentation::Split
        }

        /// `true` when the rows are the chrome rather than a drawn page: [`Self::Tabs`] and
        /// [`Self::Rail`]. Both hide the `Pane::Sidebar` page and render its rows themselves, so
        /// backend code that only cares about that distinction asks this instead of matching both.
        pub fn rows_are_chrome(self) -> bool {
            matches!(self, NavPresentation::Tabs | NavPresentation::Rail)
        }
    }

    /// Navigation host (docs/navigation.md).
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct NavProps {
        /// Document-tab chrome, independent of navigation destinations.
        pub documents: Option<DocumentTabsConfig>,
        pub title: String,
        /// The presentation to draw now; re-presented in place by [`NavPatch::Presentation`].
        pub presentation: NavPresentation,
        /// The app left the presentation automatic (`NavStyle::Automatic`, or a `Sidebar`
        /// nav host with no `.presentation(…)` pin), so it is free to follow the window.
        ///
        /// Only a toolkit answering `Cap::NavRepresent = Emulated` needs this: its own adaptive
        /// container owns the morph, and it must know whether the app asked for one at all before
        /// building it. With two presentations that bit could be inferred from a lowered `Split`;
        /// with four it cannot, so it is carried explicitly rather than encoded.
        ///
        /// `Native` re-presenters ignore it (they are told each presentation as it is resolved),
        /// and so do toolkits that cannot re-present.
        pub adaptive: bool,
        /// Draw the platform's own show/hide-sidebar affordance on this host's chrome
        /// (docs/toolbars.md). `true` for every `nav(Sidebar)` unless the app opted out:
        /// the toolkit owns both the button and the behavior
        /// (`NSToolbarToggleSidebarItemIdentifier`, the split view's collapse on GTK,
        /// `NavigationView.IsPaneOpen` on XAML), so an app that once declared the item by hand
        /// now declares nothing. Hosts with no sidebar ignore it.
        pub sidebar_toggle: bool,
        /// Search over this navigation surface (`Nav::searchable`, docs/search.md).
        /// `None` = the surface is not searchable and no field is rendered anywhere.
        pub search: Option<SearchProps>,
        /// `Some(width)` = this host has a content-list pane ([`Pane::List`]) at this preferred
        /// width in points, between the sidebar and the detail (docs/navigation.md). Read at
        /// realize, because a backend that builds a different container for a three-pane host
        /// (UIKit's triple-column style is init-only) needs to know before it builds. `None` on
        /// every host without one, including all of them on backends answering
        /// [`crate::Cap::NavContentList`] `Unsupported`: the pieces layer composes there and
        /// the prop is never set.
        pub list_width: Option<f64>,
        /// Whether that pane is showing for the destination the host opens on
        /// (`Nav::content_list_for`). Read at realize, like `list_width`, and for a
        /// related reason: a backend whose pane is a real split item can only honor a
        /// collapsed state reliably by setting it before the item joins the split. Told
        /// afterwards (by `NavPatch::ListVisible`, on a window that has not been displayed
        /// yet), AppKit reports the item collapsed and then lays it back out from its holding
        /// priorities, and the app opens with a list beside a page that does not own one.
        /// `true` on every host whose first destination has a list, and on hosts with no pane
        /// at all, where it means nothing.
        pub list_visible: bool,
    }

    /// Switch only tab chrome; resident contents must retain their native identity.
    #[derive(Clone, Copy, Debug, PartialEq)]
    pub struct DocumentTabsPatch {
        pub native: bool,
    }

    /// Localized document-tab chrome. Native callbacks emit stable route keys.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct DocumentTabsConfig {
        pub new_label: String,
        pub close_label: String,
        pub can_add: bool,
    }

    /// Where a searchable surface's field should be drawn.
    ///
    /// A preference, not an instruction: a backend that cannot honor the request falls back to
    /// whatever its platform does, exactly as SwiftUI's `searchable(placement:)` does ("depending
    /// on the containing view hierarchy and platform, the requested placement may not be able to
    /// be fulfilled"). `Automatic` is the one to reach for: it is what lets the field live in the
    /// window toolbar on a wide window and move into the navigation list on a narrow one.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum SearchPlacement {
        /// The platform decides, from the window's size class and its own convention.
        #[default]
        Automatic,
        /// In the window's toolbar (`NSSearchToolbarItem`, an `AdwHeaderBar` entry, a
        /// `CommandBar` `AutoSuggestBox`). `Inline` where the toolbar cannot hold a search field
        /// (`Cap::ToolbarSearch`).
        Toolbar,
        /// Attached to the navigation surface itself: above the sidebar list, or in the
        /// navigation bar's search drawer on the phones.
        Inline,
    }

    /// Search over a navigation surface (docs/search.md). The query itself stays an app-owned
    /// signal; this carries only what the toolkit must draw, so moving the field between
    /// placements never moves the state.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct SearchProps {
        /// Current text. Two-way: the user typing emits [`Event::SearchChanged`], and the app's
        /// own writes arrive as [`SearchPatch::Text`].
        pub text: String,
        /// Empty-state prompt.
        pub prompt: String,
        pub placement: SearchPlacement,
        /// Opt into native scrolling search/title chrome on mobile. Default false keeps
        /// the field pinned. Desktop toolbar search is unchanged.
        pub hides_on_scroll: bool,
        /// Start the UIKit navigation search drawer collapsed, with a compact toolbar title.
        /// Implies scrolling search on UIKit; ignored by other backends. Default false.
        pub initially_hidden: bool,
        /// Scope titles, empty = no scope bar. One-of-N: a `UISearchBar` scope bar, a Material
        /// `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
        /// `NSSegmentedControl` (docs/search.md has the per-backend table).
        pub scopes: Vec<String>,
        /// Index into `scopes`; meaningless when `scopes` is empty.
        pub scope: usize,
        /// Completions offered for the current text. On a navigation surface these complete the
        /// field rather than replacing the list: the list is already the result set, so an
        /// overlay of results would cover the thing it is filtering.
        pub suggestions: Vec<String>,
    }

    /// A targeted update to a live search field, the path a bound signal writes through, so
    /// syncing text never rebuilds (and refocuses) the field mid-word.
    #[derive(Clone, Debug, PartialEq)]
    pub enum SearchPatch {
        Focus,
        Text(String),
        Scope(usize),
        Suggestions(Vec<String>),
    }
    /// Applied to the nav host after a page child is attached / before it is removed;
    /// the toolkit animates its native presentation accordingly.
    #[derive(Clone, Debug, PartialEq)]
    pub enum NavPatch {
        /// The just-attached last page child became the top of the stack. `immersive` marks a
        /// page that keeps the floating transparent chrome on backends with an immersive nav
        /// mode (day-toolkit-material edge-to-edge today; ignored elsewhere). Unmarked pages get the
        /// standard opaque bar.
        Pushed { title: String, immersive: bool },
        /// The top page is about to be removed; present its predecessor.
        Popped,
        /// Current top-of-stack title changed.
        Title(String),
        /// The top page has a back guard (`NavStack::on_back`, docs/navigation.md): while `true`,
        /// the toolkit must not auto-pop on a native back gesture/button but route it to
        /// Day as `Event::NavBack { already_popped: false }` so the app's guard decides. On
        /// backends whose back already routes through Day (AppKit/Qt/XAML/web custom headers)
        /// this is a no-op; iOS disables the swipe, Android holds its callback, GTK sets the
        /// page `can-pop=false`, ArkUI consumes `onBackPressed`.
        GuardTop(bool),
        /// Re-present the host: the window's size class crossed a breakpoint, or the app wrote a
        /// new `presentation`. The page children do not change: the toolkit rebuilds its
        /// chrome and re-homes the pages it already has, each one landing by its
        /// [`NavPageProps::pane`]. Rebuilding them instead would drop scroll offsets, field
        /// focus, and every native animation in flight, which is why this is a patch and not
        /// a rebuild.
        ///
        /// Backends with no split container ignore it and stay stacked.
        Presentation(NavPresentation),
        /// Show the resident [`Pane::Detail`] page at this index, counting the host's detail
        /// children in attach order. The counterpart to [`Self::Pushed`]/[`Self::Popped`] for the
        /// presentations where pages are resident rather than stacked
        /// ([`NavPresentation::rows_are_chrome`]): a tab bar switches between pages that all stay
        /// alive, so there is nothing to push and nothing to pop.
        ///
        /// Applied without re-emitting [`crate::Event::SelectionChanged`], per the from-native
        /// echo rule: this is the programmatic-sync direction.
        ///
        /// A backend drawing a stacked presentation never receives it; the pieces layer sends
        /// push/pop there instead.
        Select(usize),
        /// Reorder resident detail pages by their previous indices without rebuilding them.
        Reorder(Vec<usize>),
        /// Show or collapse the content-list pane ([`Pane::List`]), the per-destination
        /// visibility switch (`Nav::content_list_for`, docs/navigation.md): a nav host
        /// section that spans the whole detail area (a settings page) collapses the pane, and
        /// selecting a list-backed section brings it back. Only sent to hosts whose
        /// [`NavProps::list_width`] is set. Applied directly, not through an animator proxy:
        /// the screenshot step captures the instant the patch returns (the sidebar-toggle rule).
        ListVisible(bool),
        /// Stacked presentations on a merged-pane backend ([`crate::Cap::NavContentList`]
        /// `Emulated`) only: the resident [`Pane::List`] page joins (`true`) or leaves
        /// (`false`) the navigation stack directly above the sidebar root. The pieces layer
        /// sends it as the selection gains or loses a list-backed destination; the backend
        /// realizes the membership change through its platform's navigation APIs (UIKit:
        /// `showColumn(.supplementary)` / a pop to the root; never a manual splice, which
        /// destroys the split's collapse bookkeeping). Never sent to `Native` backends (their
        /// pane persists through every presentation) nor while split.
        ListInStack(bool),
    }

    /// Which pane of a navigation host a page belongs to (docs/navigation.md).
    ///
    /// A page's pane is a fact about the model, not about how the host currently draws it: a
    /// nav host's list page is [`Pane::Sidebar`] whether the toolkit is showing a sidebar beside
    /// a detail or stacking the two. What the presentation decides is where each pane lands:
    /// its own splitter pane in [`NavPresentation::Split`], the root of the stack in
    /// [`NavPresentation::Stack`]. Keeping the two separate is what lets a host re-present on a
    /// size-class change (`NavPatch::Presentation`) by re-homing the pages it already has,
    /// instead of tearing the tree down and rebuilding it.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum Pane {
        /// The list / master pane of a nav host. At most one page per host.
        Sidebar,
        /// The content-list pane between the sidebar and the detail, Mail's message list
        /// (`Nav::content_list`, docs/navigation.md). At most one page per host, and only
        /// on hosts whose [`NavProps::list_width`] is set; a backend answering
        /// [`crate::Cap::NavContentList`] `Unsupported` never sees one.
        List,
        /// A destination page. Every page of a `nav_stack` presentation is one of these.
        #[default]
        Detail,
    }

    /// One destination's native container.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct NavPageProps {
        pub title: String,
        pub pane: Pane,
    }

    /// A fullscreen cover's content container (docs/cover.md). Realized detached and hidden;
    /// `CoverPatch::Present` shows it over the whole window.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct CoverProps {
        /// Prefer a native sheet; toolkits without sheet presentation keep their modal cover.
        pub sheet: bool,
        /// A half-height sheet rising from the bottom edge, the window content above it
        /// staying on show and, where the platform allows, interactive: an inspector over the
        /// canvas it describes. Implies `sheet`. The toolkit reports the sheet's own content
        /// size through `FrameChanged`, as for any cover (docs/cover.md "Half sheet").
        pub half: bool,
    }

    /// Applied to a `kinds::COVER` node as its bound signal opens and closes it.
    #[derive(Clone, Debug, PartialEq)]
    pub enum CoverPatch {
        /// Present the cover fullscreen (slide up where the platform animates modals).
        /// `background` paints the whole surface edge-to-edge (under the status bar / home
        /// indicator); the content container is inset to the safe area within it.
        /// `dismiss_disabled` = the user must not be able to dismiss it interactively
        /// (system back / sheet gestures); programmatic dismissal still works.
        Present {
            background: Option<Color>,
            dismiss_disabled: bool,
        },
        /// The `interactive_dismiss_disabled` state changed while presented.
        DismissDisabled(bool),
        /// Dismiss the cover. When the hide transition finishes the backend emits
        /// [`crate::Event::CoverHidden`] on the node (trampoline backends send
        /// `BridgeKind::CoverHidden`), letting the piece dispose the content only after it
        /// left the screen.
        Dismiss,
    }

    /// A `kinds::INSPECTOR` split (docs/inspector.md): content beside a trailing inspector
    /// pane. The pane's visibility is Day-owned state (the piece's bound signal), so the
    /// props carry the value to draw and [`InspectorPatch::Visible`] keeps it current;
    /// a native affordance hiding the pane (a dock close button, a dragged-shut divider)
    /// reports back with [`crate::Event::InspectorChanged`].
    #[derive(Clone, Debug, PartialEq)]
    pub struct InspectorProps {
        /// Whether the pane is showing now.
        pub visible: bool,
        /// The pane's preferred width in points. A backend with a user-draggable divider
        /// treats it as the initial width; one without draws it at exactly this.
        pub width: f64,
        /// Which side of the content the pane sits on. `Trailing` is the classic inspector;
        /// `Leading` is a utility pane like a layer panel (docs/tree.md).
        pub edge: PaneEdge,
    }

    /// Which side an inspector pane occupies (docs/inspector.md).
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum PaneEdge {
        #[default]
        Trailing,
        Leading,
    }

    /// Applied to a `kinds::INSPECTOR` node as its bound signal changes.
    #[derive(Clone, Debug, PartialEq)]
    pub enum InspectorPatch {
        /// Show or hide the pane (animated where the platform animates panes). The
        /// programmatic-sync direction: applying it must not re-emit
        /// [`crate::Event::InspectorChanged`], per the from-native echo rule.
        Visible(bool),
    }

    /// One pane of a `kinds::INSPECTOR` split (docs/inspector.md).
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct InspectorPaneProps {
        /// `true` for the inspector panel itself, `false` for the content pane.
        pub panel: bool,
    }

    /// How a `kinds::SPLIT` lays its two panes (docs/split.md): beside each other, the divider
    /// standing, or stacked, the divider lying. Named by where the panes go, since that is
    /// what an app's "layout" toggle means; the divider runs the other way.
    #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
    pub enum SplitAxis {
        /// The panes side by side (first leading), the divider vertical.
        #[default]
        Horizontal,
        /// The panes stacked (first on top), the divider horizontal.
        Vertical,
    }

    /// A `kinds::SPLIT` (docs/split.md): two panes with a divider the user drags. The first
    /// pane's share is Day-owned state (the piece's bound signal): the props carry the value
    /// to draw, [`SplitPatch::Fraction`] keeps it current, and a divider the user moved
    /// reports back as [`crate::Event::ValueChanged`] with the new share, which applying the
    /// patch must never re-emit (the from-native echo rule).
    #[derive(Clone, Debug, PartialEq)]
    pub struct SplitProps {
        pub axis: SplitAxis,
        /// The first pane's share of the split's length along `axis`, `0.0..=1.0`.
        pub fraction: f64,
        /// The least length either pane may be dragged to, in points.
        pub min_pane: f64,
    }

    /// Applied to a `kinds::SPLIT` node as its bound signals change.
    #[derive(Clone, Debug, PartialEq)]
    pub enum SplitPatch {
        /// Turn the split the other way, keeping the share.
        Axis(SplitAxis),
        /// Move the divider so the first pane takes this share. The programmatic-sync
        /// direction: applying it must not re-emit [`crate::Event::ValueChanged`].
        Fraction(f64),
    }

    /// One pane of a `kinds::SPLIT` (docs/split.md).
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct SplitPaneProps {
        /// `false` for the first pane, `true` for the second.
        pub second: bool,
    }

    /// Native navigation item list. `items` are display titles in route order;
    /// `selected` highlights the active route (split presentation; None on mobile roots).
    /// `icons` (parallel to `items`, `None` = no icon) are bundled image names resolved by each
    /// backend via `resource::resolve_image_file`; a backend that can't decorate its rows just
    /// ignores them.
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct NavMenuProps {
        /// Stable document identities, parallel to items; empty for ordinary navigation.
        pub document_keys: Vec<String>,
        pub items: Vec<String>,
        pub icons: Vec<Option<String>>,
        /// A trailing accessory per row: an unread count, a status. Rendered right-aligned and
        /// de-emphasized, opposite the label. Parallel to `items`; `None` draws nothing.
        pub badges: Vec<Option<String>>,
        /// A trailing symbol accessory per row, in the same slot as [`Self::badges`] and drawn
        /// after it: a bundled image name resolved the way [`Self::icons`] is. This is what a
        /// row-level status glyph rides on (a starred page's star) where `badges` carries only
        /// text. Parallel to `items`; `None` draws nothing.
        pub badge_icons: Vec<Option<String>>,
        /// The tint for [`Self::badge_icons`], parallel to `items`. `None` leaves the glyph at
        /// the backend's neutral template tint; a status glyph that means something (a yellow
        /// star) names its own color here, exactly as [`Self::tints`] does for the leading icon.
        pub badge_tints: Vec<Option<Color>>,
        /// A per-row icon tint (docs/vectors.md): the row's glyph recolored to this instead of
        /// the backend's neutral template tint. Parallel to `items`; `None` keeps the default.
        pub tints: Vec<Option<Color>>,
        /// A section header introducing the row at the same index. `Some` opens a new group
        /// before that row; `None` continues the current one. Parallel to `items`, so adding a
        /// header never shifts the selection indices the rows are addressed by.
        pub sections: Vec<Option<String>>,
        /// A per-row context menu (docs/menus.md): shown on secondary-click / long-press on
        /// that row, the same [`crate::MenuItem`] model as everywhere else: items carry
        /// registered action ids, so a chosen entry dispatches [`crate::Event::MenuAction`]
        /// exactly like a piece context menu. Parallel to `items`; empty = no menu.
        pub menus: Vec<Vec<crate::MenuItem>>,
        /// Which rows drag to reorder (docs/navigation.md "Reordering sidebar destinations"),
        /// parallel to `items`; empty when the sidebar does not reorder. A row moves only
        /// within the run of movable rows around it, which a section header or a fixed row
        /// ends. A toolkit whose `Cap::NavReorder` is `Native` drags the rows in its own
        /// sidebar and reports a drop as [`crate::Event::ListReorder`] in item indices: `from`
        /// is the moved row, `to` the row whose position it takes, in the order before the move.
        pub movable: Vec<bool>,
        /// The sidebar regroups (docs/navigation.md "Moving rows between sections"): a movable
        /// row may also cross section headers, into any section whose rows are all movable. A
        /// toolkit whose `Cap::NavReorder` is `Native` offers those drops too and reports every
        /// drop as [`crate::Event::NavRegroup`] instead of [`crate::Event::ListReorder`]. `false`
        /// keeps [`Self::movable`]'s run rule.
        pub regroup: bool,
        /// Which movable rows keep the app's sorted order within their own section, parallel to
        /// `items`; empty when the sidebar does not regroup. Under [`Self::regroup`], a sorted
        /// row drops only into another section: no gap in its own section is offered.
        pub sorted: Vec<bool>,
        pub selected: Option<usize>,
    }
    #[derive(Clone, Debug, PartialEq)]
    // `Items` carries every row array; a patch travels boxed (`Box<dyn Any>`) and lives for one
    // update, so the variants' size difference costs nothing worth an indirection.
    #[allow(clippy::large_enum_variant)]
    pub enum NavMenuPatch {
        /// Active icon overlays by row index: None spins, Some(0..=1) fills a circle.
        /// Rows absent from this complete snapshot have no overlay. Does not relayout rows.
        /// Currently rendered by AppKit/UIKit; other backends may ignore this decoration.
        IconProgress(Vec<(usize, Option<f64>)>),
        /// Programmatic highlight sync: toolkits apply without re-emitting
        /// SelectionChanged (the TextField from_native echo rule).
        Selected(Option<usize>),
        /// The item set changed (data-driven `nav().items(signal, …)`): rebuild the rows
        /// from these labels/icons, then apply `selected` (docs/navigation.md). Applied without
        /// re-emitting SelectionChanged.
        ///
        /// `rows_changed` is `Some` when the rows themselves are the ones already shown (same
        /// keys, sections and row menus) and only these rows' title, icon, tint or badge moved:
        /// a count ticking, a language change. A backend updates those rows in place (a tab's
        /// badge, a menu item's title) rather than rebuilding, which on most platforms re-lays
        /// the bar and replays its selection animation; one that cannot rebuilds as for `None`.
        Items {
            rows_changed: Option<Box<[usize]>>,
            document_keys: Box<[String]>,
            items: Vec<String>,
            icons: Vec<Option<String>>,
            badges: Vec<Option<String>>,
            badge_icons: Vec<Option<String>>,
            badge_tints: Vec<Option<Color>>,
            sections: Vec<Option<String>>,
            tints: Vec<Option<Color>>,
            menus: Vec<Vec<crate::MenuItem>>,
            /// [`NavMenuProps::movable`] for the new rows.
            movable: Vec<bool>,
            /// [`NavMenuProps::sorted`] for the new rows ([`NavMenuProps::regroup`] holds for
            /// the sidebar's life).
            sorted: Vec<bool>,
            selected: Option<usize>,
        },
    }

    /// How a recycling list sizes its rows (docs/list.md).
    #[derive(Clone, Copy, Debug, PartialEq, Default)]
    pub enum RowHeight {
        /// Every row is this tall, a true layout boundary; the fastest path.
        Uniform(f64),
        /// Rows self-size from their content (host re-measures on change; slower).
        #[default]
        Automatic,
    }

    /// Configure a navigation sidebar's native pull-to-refresh control. Not a synthetic pan:
    /// supported toolkits own gesture arbitration and the progress indicator. A false state
    /// ends a pull, including a request the application declines. Never emits an event.
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub struct RefreshPatch {
        pub refreshing: bool,
    }

    /// Native recycling list (docs/list.md). The host owns scrolling + cell reuse; Day supplies
    /// row content on demand through the injected `ListSource` (see `Toolkit::attach_list`).
    #[derive(Clone, Debug, Default, PartialEq)]
    pub struct ListProps {
        /// Whether the app handles row activation. Do not claim activation keys when false.
        pub activatable: bool,
        pub row_height: RowHeight,
        /// Whether the native list reports row selection (`Event::SelectionChanged` with the row).
        pub selectable: bool,
        /// Whether the native list allows selecting several rows at once. Where honored
        /// (docs/list.md has the matrix), every selection change reports the full set via
        /// `Event::SelectionSet`; single-selection backends keep reporting
        /// `Event::SelectionChanged` and treat this as `selectable`.
        pub multi_select: bool,
        /// Whether rows can be drag-reordered. The toolkit enables its native drag machinery and
        /// drives `ListSource::reorder` (validate via `can_move`, commit via `move_row`);
        /// probe `Cap::ListReorder` for per-backend support (docs/list.md).
        pub reorderable: bool,
        /// Whether rows can be deleted by the platform's own delete gesture: a trailing swipe on
        /// iOS and ArkUI, an `ItemTouchHelper` swipe on Android. The toolkit drives
        /// `ListSource::delete` (offer via `can_delete`, commit via `delete_row`); probe
        /// `Cap::ListDelete` for per-backend support (docs/list.md). Desktop toolkits have no such
        /// gesture and answer `Unsupported`; an app that must delete everywhere pairs this with an
        /// explicit control (a menu item, a button) rather than relying on the swipe.
        pub deletable: bool,
        /// The label on that affordance, already localized by the app. A toolkit cannot invent
        /// translated text (it has no access to the app's catalog), so the string arrives with
        /// the props. Empty means "no text": each backend falls back to its platform's own
        /// wordless idiom (a trash glyph), which works in every language.
        pub delete_label: String,
        /// The rows offer edge swipe actions (docs/list.md) through the injected
        /// `ListSource::swipe` (offer via `actions_at`, commit via `perform`); probe
        /// [`crate::Cap::ListSwipeActions`] for per-backend support. A backend without the
        /// affordance never shows one; an app that must offer the command everywhere
        /// pairs the swipe with an explicit control, exactly as `deletable` documents.
        pub swipe_actions: bool,
        /// Row separators, drawn by the host at the row boundary (docs/list.md), so they
        /// align with the native selection and ride the platform's own row animations (a
        /// macOS/iOS swipe slides the row content past a stationary separator, exactly as
        /// Mail's does). `None` keeps each platform's own default (iOS draws them, the
        /// desktops don't); `Some(true)`/`Some(false)` forces. A backend without a separator
        /// mechanism ignores a force (the matrix in docs/list.md says which); rows there
        /// separate by their pitch alone.
        pub separators: Option<bool>,
        /// The list starts in the platform's editing mode (docs/list.md): delete controls on
        /// the rows `deletable` offers, reorder grips on the rows `reorderable` moves, and a
        /// tap that still activates. Later changes arrive as [`ListPatch::Editing`]. Probe
        /// [`crate::Cap::ListEditing`]; a backend without an editing mode ignores it.
        pub editing: bool,
        /// The rows fall into sections, each opened by a header row (docs/list.md
        /// "Sections"): `ListSource::is_header` says which rows. Probe
        /// [`crate::Cap::ListSections`] for whether headers float natively.
        pub sections: bool,
    }

    /// One row-level result-set change. Indexes are sequential (each delta describes the
    /// set as the previous ones left it), so a host applies them one at a time (or falls back
    /// to a reload; the source's snapshot already holds the final state either way).
    #[derive(Clone, Copy, Debug, PartialEq, Eq)]
    pub enum RowDelta {
        Insert(usize),
        Remove(usize),
        Move(usize, usize),
    }

    /// Immutable-at-realize props of a `kinds::TREE` host (docs/tree.md). Everything that
    /// changes after realize flows through [`TreePatch`] or the injected `TreeSource`.
    #[derive(Clone, Debug, PartialEq)]
    pub struct TreeProps {
        /// Two-level sectioned list: root branches are non-selectable headings.
        pub section_headers: bool,
        pub row_height: RowHeight,
        /// Rows highlight and report selection ([`crate::Event::TreeSelection`]).
        pub selectable: bool,
        /// Several rows may be selected at once; every change reports the full token set.
        pub multi_select: bool,
        /// Rows drag to a new parent/position through the platform's own mechanism, driving
        /// `TreeSource::moves`. Probe [`crate::Cap::TreeMove`] for support.
        pub movable: bool,
        /// Indentation per depth level, in points. `None` = the platform's default step.
        pub indent: Option<f64>,
    }

    /// Post-realize changes to a `kinds::TREE` host (docs/tree.md). Token-addressed
    /// throughout; see [`crate::TreeSource`] for why indices cannot address tree rows.
    #[derive(Clone, Debug, PartialEq)]
    pub enum TreePatch {
        /// The node set changed (count/order/parentage/content): the host re-queries its
        /// `TreeSource`. Expansion and selection survive by token (docs/tree.md).
        Reload,
        /// Programmatically disclose (`true`) or collapse (`false`) one row. Applied without
        /// re-emitting [`crate::Event::TreeExpanded`] (the from-native echo rule).
        Expand(u64, bool),
        /// Programmatic selection sync (tokens; empty = clear), applied without re-emitting
        /// [`crate::Event::TreeSelection`].
        Selected(Vec<u64>),
        /// Scroll this row into view, realizing it if needed. The piece has already expanded
        /// the row's ancestors (through the app's expansion signal) before issuing this.
        Reveal(u64),
    }

    #[derive(Clone, Debug, PartialEq)]
    pub enum ListPatch {
        /// The row set changed (count/order/content): the host re-queries its `ListSource`.
        Reload,
        /// The row set changed by exactly these deltas: a host that can, animates each row
        /// in, out, or across; one that cannot treats this as [`ListPatch::Reload`]. The
        /// data source answers with the final state throughout.
        Splice(Vec<RowDelta>),
        /// An `Automatic`-height row was re-laid at a new height after its first layout (its
        /// text changed, a wrapped line appeared, the backend corrected its width): the host
        /// gives the row bound to physical cell `cell` (the handle `ListSource::bind_row` got,
        /// as `usize`) the new `height`, padding included, the same value
        /// `ListSource::cell_height` now answers for it.
        ///
        /// Sent from inside a day-core layout pass, with the tree borrowed: a host applies it
        /// after the pass (posted to its main loop), never by asking the source anything
        /// synchronously, which would read a `0.0` height (docs/list.md "Row heights").
        RowSizeInvalidated { cell: usize, height: f64 },
        /// Imperatively scroll the native list so its last row is fully visible (a chat timeline
        /// sticking to the newest message). No-op when the list is empty (docs/list.md).
        ScrollToEnd,
        /// Imperatively scroll the native list so this row is visible, realizing it if needed
        /// (docs/list.md). Clamped to the row count; no-op when the list is empty.
        ScrollToRow(usize),
        /// Programmatic selection sync (row indices; empty = clear): toolkits apply without
        /// re-emitting a selection event, like every other programmatic sync.
        Selected(Vec<usize>),
        /// Enter (`true`) or leave (`false`) the platform's list editing mode, animated
        /// (docs/list.md, [`ListProps::editing`]). Ignored where `Cap::ListEditing` is
        /// `Unsupported`.
        Editing(bool),
    }
}

// ---------------------------------------------------------------------------
// Imperative presentation (docs/dialogs.md)
// ---------------------------------------------------------------------------

pub mod present {
    /// A dialog button's semantic role: styling + default/cancel placement on each toolkit.
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
    pub enum ButtonRole {
        #[default]
        Default,
        Cancel,
        Destructive,
    }

    #[derive(Clone, Debug, PartialEq)]
    pub struct PresentButton {
        pub label: String,
        pub role: ButtonRole,
    }

    /// A named group of file extensions for a file dialog (e.g. "Text" → `["txt", "md"]`).
    /// An empty `extensions` list means "all files".
    #[derive(Clone, Debug, PartialEq, Default)]
    pub struct FileFilter {
        pub name: String,
        pub extensions: Vec<String>,
    }

    /// What a backend should present for a `req`. Kept toolkit-agnostic; the pieces layer
    /// maps a chosen button index back to a typed payload.
    #[derive(Clone, Debug, PartialEq)]
    pub enum PresentSpec {
        /// Alert / confirmation / action sheet: title + optional message + ordered buttons.
        /// `sheet` = present from the bottom on mobile (desktop falls back to an alert).
        Dialog {
            title: String,
            message: Option<String>,
            buttons: Vec<PresentButton>,
            sheet: bool,
        },
        /// A dialog with a single text field.
        Prompt {
            title: String,
            message: Option<String>,
            placeholder: String,
            initial: String,
            ok: String,
            cancel: String,
        },
        /// Native "open file" picker (docs/files.md). The backend must answer with
        /// `PresentResult::Files` whose entries are **readable local paths**: desktop returns
        /// the chosen path directly; iOS/Android copy the selection into app storage first, so
        /// the pieces layer can read it with `std::fs` regardless of platform. `multiple` lets
        /// the user pick several files at once; the answer then carries every chosen path, in
        /// the picker's order. A backend that cannot select more than one file still answers
        /// with the single pick.
        OpenFile {
            title: String,
            filters: Vec<FileFilter>,
            multiple: bool,
        },
        /// Native "choose folder" picker (docs/files.md). The backend answers with
        /// `PresentResult::Files` holding the one chosen directory path, or `Dismissed`. Only
        /// backends answering [`Cap::FolderDialog`](crate::Cap::FolderDialog) as `Native` show a
        /// chooser; the others resolve the request as `Dismissed` at once, so the await never hangs.
        OpenFolder { title: String },
        /// Native "save file" picker (docs/files.md). `src_path` is a Day-written temp file
        /// holding the bytes to save; iOS/Android deliver it to the chosen destination natively,
        /// and the pieces layer best-effort copies it to a chosen local path otherwise.
        SaveFile {
            title: String,
            suggested_name: String,
            src_path: String,
            filters: Vec<FileFilter>,
        },
    }

    /// The user's answer to a presentation.
    #[derive(Clone, Debug, PartialEq)]
    pub enum PresentResult {
        /// A dialog button at `index` (in spec order) was chosen.
        Button(i64),
        /// A prompt was confirmed with `text`.
        Text(String),
        /// One or more file locators chosen from an open/save picker (docs/files.md). Each is a
        /// local filesystem path or, on Android save, a `content://` URI.
        Files(Vec<String>),
        /// Dismissed without choosing (tap-outside / Esc / cancel gesture).
        Dismissed,
    }

    /// The unit-separator that joins string lists across the C ABI (Qt shim / Android JNI), the
    /// same encoding the nav menu, combobox, and dialog-button shims use.
    pub const UNIT_SEP: char = '\u{1f}';

    std::thread_local! {
        /// An app-writable scratch directory. Backends whose OS temp dir isn't app-writable
        /// (Android → `getCacheDir()`) set this at startup; elsewhere it stays `None` and callers
        /// fall back to `std::env::temp_dir()`.
        // False positive, and only when checking an android target: the initializer already is
        // the `const` block the lint asks for. Android's TLS model makes the macro expand to a
        // form clippy reads as lazy, so the suggestion is unfollowable as well as unneeded.
        #[allow(clippy::missing_const_for_thread_local)]
        static APP_TEMP_DIR: std::cell::RefCell<Option<std::path::PathBuf>> =
            const { std::cell::RefCell::new(None) };
    }

    /// Record an app-writable scratch directory (see [`app_temp_dir`]). Called by a backend at
    /// startup when the OS temp dir isn't writable by the app (Android).
    pub fn set_app_temp_dir(dir: impl Into<std::path::PathBuf>) {
        APP_TEMP_DIR.with(|d| *d.borrow_mut() = Some(dir.into()));
    }

    /// An app-writable scratch directory: the backend-supplied one, else `std::env::temp_dir()`.
    /// Used by the file-save flow (docs/files.md) to stage bytes before the native save picker.
    pub fn app_temp_dir() -> std::path::PathBuf {
        APP_TEMP_DIR.with(|d| {
            d.borrow().clone().unwrap_or_else(|| {
                #[cfg(target_arch = "wasm32")]
                {
                    // A browser has no filesystem and std's `temp_dir()` panics on wasm. A
                    // nominal path keeps join/display plumbing alive; actual reads and writes
                    // fail with ordinary io errors the file flows already surface.
                    std::path::PathBuf::from("/day-tmp")
                }
                #[cfg(not(target_arch = "wasm32"))]
                std::env::temp_dir()
            })
        })
    }

    /// The web build's file bytes (wasm32-unknown-unknown only): a browser has no filesystem,
    /// so the open/save flows carry bytes through this per-page store instead of `std::fs`:
    /// day-toolkit-dom writes a picked file's bytes here and answers with its virtual path; the pieces
    /// layer stages save bytes here for the shim to download. Paths are plain strings under
    /// `/day-web/`; lifetimes are one picker round-trip (the flows remove what they stage).
    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
    pub mod web_files {
        std::thread_local! {
            static FILES: std::cell::RefCell<std::collections::HashMap<String, Vec<u8>>> =
                std::cell::RefCell::new(std::collections::HashMap::new());
        }

        /// Store `bytes` under `path` (replacing any prior content).
        pub fn write(path: &str, bytes: Vec<u8>) {
            FILES.with(|f| f.borrow_mut().insert(path.to_string(), bytes));
        }

        /// The bytes at `path`, if present.
        pub fn read(path: &str) -> Option<Vec<u8>> {
            FILES.with(|f| f.borrow().get(path).cloned())
        }

        /// Drop `path`'s bytes.
        pub fn remove(path: &str) {
            FILES.with(|f| {
                f.borrow_mut().remove(path);
            });
        }
    }

    impl PresentResult {
        /// Flat wire tag for the C ABI (Qt shim / Android JNI): 0 dismissed, 1 button, 2 text,
        /// 3 files (`text` is the chosen locators joined by the unit separator).
        pub fn decode(tag: i32, index: i64, text: String) -> PresentResult {
            match tag {
                1 => PresentResult::Button(index),
                2 => PresentResult::Text(text),
                3 => PresentResult::Files(
                    text.split(UNIT_SEP)
                        .filter(|s| !s.is_empty())
                        .map(str::to_string)
                        .collect(),
                ),
                _ => PresentResult::Dismissed,
            }
        }
    }

    impl PresentSpec {
        /// Backend-facing flattening for the C ABI: `(title, message, button labels, button
        /// roles as ints, sheet-or-prompt fields)`. Pure-Rust backends read the enum directly.
        pub fn title(&self) -> &str {
            match self {
                PresentSpec::Dialog { title, .. }
                | PresentSpec::Prompt { title, .. }
                | PresentSpec::OpenFile { title, .. }
                | PresentSpec::OpenFolder { title }
                | PresentSpec::SaveFile { title, .. } => title,
            }
        }
        pub fn message(&self) -> Option<&str> {
            match self {
                PresentSpec::Dialog { message, .. } | PresentSpec::Prompt { message, .. } => {
                    message.as_deref()
                }
                _ => None,
            }
        }
        /// Button labels joined with [`UNIT_SEP`], the encoding the nav menu and combobox
        /// shims already use for string lists.
        pub fn buttons_joined(&self) -> String {
            match self {
                PresentSpec::Dialog { buttons, .. } => buttons
                    .iter()
                    .map(|b| b.label.as_str())
                    .collect::<Vec<_>>()
                    .join(&UNIT_SEP.to_string()),
                PresentSpec::Prompt { ok, cancel, .. } => format!("{ok}{UNIT_SEP}{cancel}"),
                _ => String::new(),
            }
        }
        /// Button roles as ints (0 default, 1 cancel, 2 destructive), joined with commas.
        pub fn roles_joined(&self) -> String {
            let roles: Vec<i32> = match self {
                PresentSpec::Dialog { buttons, .. } => {
                    buttons.iter().map(|b| b.role as i32).collect()
                }
                PresentSpec::Prompt { .. } => {
                    vec![ButtonRole::Default as i32, ButtonRole::Cancel as i32]
                }
                _ => vec![],
            };
            roles
                .iter()
                .map(|r| r.to_string())
                .collect::<Vec<_>>()
                .join(",")
        }

        // --- file-dialog accessors (docs/files.md) ---

        /// The file filters, if this is a file dialog.
        pub fn filters(&self) -> &[FileFilter] {
            match self {
                PresentSpec::OpenFile { filters, .. } | PresentSpec::SaveFile { filters, .. } => {
                    filters
                }
                _ => &[],
            }
        }
        /// Whether an open-file dialog lets the user pick several files (`false` for every
        /// other spec).
        pub fn multiple(&self) -> bool {
            matches!(self, PresentSpec::OpenFile { multiple: true, .. })
        }
        /// The suggested file name for a save dialog (empty otherwise).
        pub fn suggested_name(&self) -> &str {
            match self {
                PresentSpec::SaveFile { suggested_name, .. } => suggested_name,
                _ => "",
            }
        }
        /// The Day-written temp source path for a save dialog (empty otherwise).
        pub fn src_path(&self) -> &str {
            match self {
                PresentSpec::SaveFile { src_path, .. } => src_path,
                _ => "",
            }
        }
        /// Filters flattened for the C ABI: each filter is `name|ext1,ext2`, joined by
        /// [`UNIT_SEP`]. A trailing `|` (no extensions) means "all files". Empty when unfiltered.
        pub fn filters_joined(&self) -> String {
            self.filters()
                .iter()
                .map(|f| format!("{}|{}", f.name, f.extensions.join(",")))
                .collect::<Vec<_>>()
                .join(&UNIT_SEP.to_string())
        }
    }
}

// ---------------------------------------------------------------------------
// The Toolkit trait (§8.1)
// ---------------------------------------------------------------------------

/// Timing supplied by a native display scheduler. Seconds on a monotonic clock; its epoch
/// is platform-specific. `target_timestamp` is absent when the platform cannot predict presentation.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameStamp {
    pub timestamp: f64,
    pub target_timestamp: Option<f64>,
}
impl FrameStamp {
    pub fn new(timestamp: f64) -> Self {
        Self {
            timestamp,
            target_timestamp: None,
        }
    }
}
/// A one-shot native frame callback, always delivered asynchronously on the UI thread.
pub type FrameCallback = Box<dyn FnOnce(FrameStamp)>;
/// Cancels a pending callback and releases its native registration. UI-thread only, idempotent
/// in effect, and safe during/after delivery. Dropping without calling is allowed after delivery.
pub type CancelFrame = Box<dyn FnOnce()>;

/// The margins and minimum height a native list gives each row ([`Toolkit::list_row_metrics`],
/// docs/list.md "Row metrics"): a `UITableView` cell's layout margins, a Material list item's
/// 16dp sides and 56dp height.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RowMetrics {
    /// Space between the row's edges and its content.
    pub insets: Insets,
    /// The least height a row takes, margins included; content centers vertically in it.
    pub min_height: f64,
}

pub trait Toolkit: Sized + 'static {
    // `'static` so a handle clone can cross the object-safe TreeOps boundary boxed as `Any`
    // (`node_handle_any`, the tweaks door, docs/tweaks.md).
    type Handle: Clone + 'static;

    /// Request one frame for the window containing `host`. Never call inline. Each native source
    /// must stop after delivery unless requested again; no polling timer. Hidden/unmapped windows
    /// may defer delivery until visible. Native callbacks must reach the UI thread before calling
    /// Rust. The returned closure cancels safely, including when the window has closed.
    /// The mock intentionally stays pending: tests inject a manual scheduler in day-core.
    fn request_frame(&mut self, _host: &Self::Handle, _cb: FrameCallback) -> CancelFrame {
        Box::new(|| {})
    }

    fn capability(&self, _cap: Cap) -> Support {
        Support::Unsupported
    }

    // node lifecycle
    fn realize(&mut self, kind: PieceKind, props: &dyn Any, id: NodeId) -> Self::Handle;
    fn update(
        &mut self,
        h: &Self::Handle,
        kind: PieceKind,
        patch: &dyn Any,
        anim: Option<&AnimSpec>,
    );
    /// Called from the turn-boundary release queue; backends may defer destruction further.
    fn release(&mut self, h: Self::Handle);
    /// Give a satellite piece a chance to drop its own per-view state, immediately before
    /// [`release`](Toolkit::release) frees `h` (§15.2).
    ///
    /// A backend that hosts third-party pieces implements this by looking `kind` up in its renderer
    /// registry and calling that piece's `release` hook. Defaulted to nothing: a backend with no
    /// registry has nothing to dispatch, and one that has not wired this yet leaves piece
    /// teardown unrun rather than failing to build.
    fn release_piece(&mut self, _kind: PieceKind, _h: &Self::Handle) {}

    // tree
    fn insert(&mut self, parent: &Self::Handle, child: &Self::Handle, index: usize);
    fn remove(&mut self, parent: &Self::Handle, child: &Self::Handle);
    /// Put `child` at index `to` among `parent`'s native children: day's z-order resync, which
    /// walks the whole sibling row and asks for every position in turn. A child already at `to`
    /// must therefore cost nothing: a backend that re-parents unconditionally pays for the
    /// untouched siblings too, and where re-parenting means detach-then-add (no ViewGroup move
    /// primitive on Android) the detach resigns the focus of everything inside the subtree,
    /// which is how a text field being typed into loses the keyboard (docs/focus.md).
    fn move_child(&mut self, parent: &Self::Handle, child: &Self::Handle, to: usize);

    // geometry (§7): frames are in the nearest realized native ancestor's space, in points.
    fn measure(&mut self, h: &Self::Handle, kind: PieceKind, p: Proposal) -> Size;
    /// Distance from the top of the widget's frame to its first text baseline, in points, when
    /// the widget is `size` (docs/baseline.md). `None` ⇒ it has no text baseline (an image, a
    /// slider, a bare container) and a baseline-aligned row falls back to box alignment for it.
    ///
    /// This is a measurement, not a layout mode: day places every frame itself (§7.1) and never
    /// hands a row to a native baseline-aligning container, so what it needs from the toolkit is
    /// where the text sits inside the box. Backends that cannot answer keep the default and rows
    /// stay centered, which is what every row did before this existed.
    fn first_baseline(&mut self, _h: &Self::Handle, _kind: PieceKind, _size: Size) -> Option<f64> {
        None
    }
    fn set_frame(&mut self, h: &Self::Handle, frame: Rect, anim: Option<&AnimSpec>);

    // animatable visual channels (§8.4): cheap per-node opacity + transform that don't relayout.
    // Defaulted no-ops so backends adopt them incrementally; `anim = Some` ⇒ animate to the value
    // on the toolkit's own compositor, `None` ⇒ set instantly.
    fn set_opacity(&mut self, _h: &Self::Handle, _opacity: f64, _anim: Option<&AnimSpec>) {}
    fn set_transform(
        &mut self,
        _h: &Self::Handle,
        _t: Transform,
        _size: Size,
        _anim: Option<&AnimSpec>,
    ) {
    }

    // text selection (docs/text.md): make this node's text user-selectable (copy/drag). Applied
    // once from the `.selectable()` modifier (day-pieces) to the widget it wraps (a `label`'s
    // native text view, most usefully). Unmanaged: Day sets it here and never patches it, so it
    // survives text updates. The default no-op means a backend without a selection affordance
    // silently leaves the text unselectable.
    //
    // Returns `Some(replacement)` when the toolkit had to rebuild the widget as a different
    // native class to gain a selection affordance (UIKit: `UILabel` has none, so the label
    // becomes a read-only `UITextView`); day-core re-points the node's handle at the
    // replacement, so later patches and layout reach the widget that is actually on screen.
    // Every property-flip backend returns `None`.
    fn set_selectable(&mut self, _h: &Self::Handle, _selectable: bool) -> Option<Self::Handle> {
        None
    }

    // text entry (docs/textfield.md): how a `text_field` takes its text: hidden characters,
    // read-only, the keyboard and autofill purpose, the action key, the length bound. Called
    // once after `realize` when a field asks for anything but the defaults, and again with the
    // whole set whenever a reactive member changes, so the setter is idempotent.
    //
    // Returns `Some(replacement)` when hiding the characters takes a different native class
    // (AppKit: `NSSecureTextField`; WinUI: `PasswordBox`), the same contract as
    // `set_selectable`: the backend carries the text, the placeholder and its own event wiring
    // over, takes the old widget's place in the native tree, and day-core re-points the node's
    // handle. Required, with no default: a backend that left this out would show a password in
    // the clear. A member the toolkit has no notion of (an action key on a desktop) is ignored.
    fn set_input_traits(&mut self, h: &Self::Handle, traits: &InputTraits) -> Option<Self::Handle>;

    // pointer shape (docs/cursor.md): the cursor to show while the pointer is over this node
    // and its descendants, from the `.cursor()` modifier. Called again whenever a reactive
    // cursor changes, so the setter is idempotent and cheap; `Cursor::Default` releases the
    // node. The default no-op is a backend with no pointer API to reach (`Cap::Cursor`
    // answers `Unsupported` there).
    fn set_cursor(&mut self, _h: &Self::Handle, _cursor: Cursor) {}

    /// Show or hide a retained subtree, including its input and accessibility participation.
    /// The layout and reactive scope stay alive while hidden.
    fn set_presented(&mut self, _h: &Self::Handle, _visible: bool) {}

    /// Attach overscroll delivery to a refresh host; the caller owns the mounted scope.
    fn attach_refresh(&mut self, _h: &Self::Handle, _host: NodeId) {}

    // scroll (§7.6)
    fn set_scroll_content(&mut self, _h: &Self::Handle, _content: Size) {}
    // The room a classic (non-overlay) scroll bar takes out of a scroll view's content area
    // while the content overflows along `vertical`'s axis: its width for a vertical scroll, its
    // height for a horizontal one (docs/scroll.md). Day lays overflowing content out that much
    // narrower, so it fits beside the bar instead of reaching under it. 0 — the default — is
    // every backend whose bars overlay the content (AppKit, GTK, UIKit, Android, XAML, DOM).
    fn scroll_bar_inset(&mut self, _h: &Self::Handle, _vertical: bool) -> f64 {
        0.0
    }
    // The margins and minimum height the platform's own list gives a row (docs/list.md "Row
    // metrics"), asked of list `h` each time day-core lays a row. Day insets the row's content by
    // the margins and keeps it at least that tall, so a row reads at the platform's size without
    // the app padding it per platform. Zero — the default — leaves the row to its content.
    fn list_row_metrics(&mut self, _h: &Self::Handle) -> RowMetrics {
        RowMetrics::default()
    }
    fn scroll_to(&mut self, _h: &Self::Handle, _target: Rect, _animated: bool) {}
    /// Scroll a native navigation menu to its top or bottom without changing selection.
    /// The widget owns its content extent. Return false when the handle is unsupported.
    fn nav_scroll_to_edge(&mut self, _h: &Self::Handle, _bottom: bool) -> bool {
        false
    }
    fn scroll_offset(&mut self, _h: &Self::Handle) -> Point {
        Point::ZERO
    }

    // events: one trampoline, node-id keyed; enqueue-only contract (§8.3).
    fn set_event_sink(&mut self, sink: EventSink);

    // gestures (docs/shapes.md): attach a native recognizer for `kind` to `h`, emitting
    // `Event::Tap/LongPress/Drag` for `node` (enqueue-only). Default no gesture; a piece opts in
    // when it has a handler. Idempotent per (handle, kind).
    fn enable_gesture(&mut self, _h: &Self::Handle, _node: NodeId, _kind: GestureKind) {}

    // focus (docs/focus.md): move native keyboard focus to (or away from) this control.
    // `focused = true` requests focus (on mobile this also raises the soft keyboard for text
    // inputs); `false` resigns it (dismissing the keyboard; platforms without a "focus nothing"
    // state resign to a focusable root). Backends report the resulting state, user- or
    // programmatic, with `Event::FocusChanged(bool)` through the sink; a request that cannot
    // be honored (unfocusable, unmounted) produces no event. The default no-op means a
    // backend without focus support neither moves nor reports focus.
    fn focus(&mut self, _h: &Self::Handle, _node: NodeId, _focused: bool) {}

    // focusability (docs/focus.md): opt this container into the platform's focus system, the
    // canvas contract generalized (`Decorate::focusable`). A focusable container accepts focus,
    // takes it on a press (before the press reaches its gesture recognizers), reports both
    // directions with `Event::FocusChanged`, and delivers the non-text keys it hears while
    // focused as `Event::Key` for `node` (gated on `keys::handled`, like a canvas). The default
    // no-op means the piece renders normally but never joins the focus order: `.focused(…)`
    // bindings stay quiet and `.on_key(…)` never fires, the same graceful silence unfocusable
    // controls already have. Idempotent; only `true` is ever sent today (a piece opts in at
    // build, it does not opt back out).
    fn set_focusable(&mut self, _h: &Self::Handle, _node: NodeId, _focusable: bool) {}

    // recycling list (docs/list.md, §10): day-core hands the `LIST` host its row-pull `source`
    // once, right after realize. A recycling backend stores it and calls it from its native
    // data-source; the default no-op means a backend without list support renders nothing.
    fn attach_list(&mut self, _host: &Self::Handle, _source: ListSource) {}

    // hierarchical tree (docs/tree.md): day-core hands the `TREE` host its token-addressed
    // row-pull `source` once, right after realize. A backend with a native tree stores it and
    // answers its data-source from it; the default no-op means a backend without tree support
    // renders nothing (`Cap::Tree` answers `Unsupported`, and apps gate on that).
    fn attach_tree(&mut self, _host: &Self::Handle, _source: TreeSource) {}

    // routes (docs/navigation.md): day-core reports the app's current route path here whenever
    // it changes ("" = everything at its root), so a backend with a native notion of location
    // can mirror it: web-dom writes the URL hash (`#controls`), and browser back/forward or a
    // hand-edited hash comes back as `Event::RouteRequested`. Default no-op: most toolkits
    // have nowhere to put a route.
    fn set_route(&mut self, _route: &str) {}

    // undo bridge (docs/model.md): mirror the app's undo stack into the platform's own undo
    // objects, so the stock Edit menu retitles and enables itself and the platform's gestures
    // land: the native front of one Day-owned history. The state flows down whenever it
    // changes; the user's invocation comes back up as `Event::Undo`. Default no-op: a backend
    // without a native undo system answers `Cap::UndoBridge` `Unsupported`, and the app's own
    // affordances (menu items, buttons, accelerators) drive the stack instead.
    fn set_undo_state(&mut self, _state: &UndoState) {}

    // edit bridge (docs/menus.md): mirror what the app's standard-edit handlers can do, so
    // the platform's own menu validation enables Cut/Copy/Paste exactly as it does for text
    // widgets; invocations come back up as `Event::Edit`. Default no-op: a backend without
    // a native edit-command route answers `Cap::EditBridge` accordingly.
    fn set_edit_state(&mut self, _state: &EditState) {}

    // ambient modifiers (docs/menus.md): the keyboard modifiers held right now, for
    // interactions whose meaning they change (shift-click multi-select). Pull-based: the
    // platforms expose exactly this query (NSEvent.modifierFlags, the shim's tracked mask).
    // Touch-only backends keep the all-false default.
    fn modifiers(&mut self) -> Modifiers {
        Modifiers::default()
    }

    // Dynamic context menu (docs/menus.md): the menu is built when it is summoned. The provider
    // is called synchronously from the platform's own menu callback (UI thread, outside any
    // day-core borrow) with the location in the node's local coordinates, and its result is
    // shown. The static `set_context_menu` below stays the simple path; this one exists for
    // surfaces whose menu depends on what is under the pointer (a canvas selection,
    // docs/tree.md). Default no-op: a backend without the affordance shows nothing.
    fn set_drag_source(&mut self, _h: &Self::Handle, _source: transfer::Source) {}
    fn set_drop_target(&mut self, _h: &Self::Handle, _target: transfer::Target) {}

    fn set_context_menu_fn(&mut self, _h: &Self::Handle, _node: NodeId, _f: ContextMenuFn) {}

    // menus (§ menus): render `items` with the backend's native menu affordance, firing
    // `Event::MenuAction(id)` (enqueue-only) for each id'd item; `role` items use the native standard
    // command. Default no-op: a toolkit without a menu bar / context menu shows nothing.
    /// The application menu (macOS/Windows/Linux menu bar; the app-bar overflow on Android; the
    /// UIMenuBuilder main menu on iPadOS/Catalyst). Replaces any previous app menu.
    fn set_app_menu(&mut self, _items: &[MenuItem]) {}
    /// A context menu for `h`, shown on secondary-click (desktop) or long-press (mobile). Passing an
    /// empty slice removes it.
    fn set_context_menu(&mut self, _h: &Self::Handle, _node: NodeId, _items: &[MenuItem]) {}

    // toolbars (docs/toolbars.md): a window's native toolbar: NSToolbar, AdwHeaderBar, QToolBar,
    // CommandBar. `h` is the window root's handle (the same handle `open_window` returned, or the
    // primary root's); the backend walks from it to the window it belongs to. Default no-op: a
    // toolkit with no toolbar shows nothing rather than a drawn imitation, and reports
    // `Cap::Toolbar` as `Unsupported` so an app can put the command somewhere else.
    /// Edit the window's toolbar (docs/toolbars.md): the [`ToolbarOp`]s, removals first, then
    /// insertions in ascending position. The bar starts empty, and becomes empty again when every
    /// item has been removed, at which point the backend takes it off the window.
    ///
    /// An item no op names must keep its native widget untouched, which is what keeps a search
    /// field focused while the page around it changes. Day sends an edit only when the bar
    /// changed, at most once per turn, and an item keeps its [`ToolbarItem::action`] for as long
    /// as its window shows an item with that id, so a native item's handler never needs
    /// repointing. Keep a [`ToolbarMirror`] and place each new item after
    /// [`ToolbarMirror::prev_where`] its group.
    ///
    /// Returns whether the edit was applied. `false` (the window has no bar to edit yet) makes
    /// Day send the whole bar again at the next change rather than assume this one landed.
    fn edit_toolbar(&mut self, _h: &Self::Handle, _ops: &[ToolbarOp]) -> bool {
        true
    }
    /// Apply a targeted change to one live toolbar item, the path a bound signal writes through,
    /// so syncing a search field does not rebuild the bar. No-op if the item is not present.
    fn update_toolbar(&mut self, _h: &Self::Handle, _patch: &ToolbarPatch) {}

    // lifecycle (docs/lifecycle.md): does this backend deliver `phase`? The default answers "yes" for
    // the universal phases (launch/activation/termination) and "no" for the mobile-only ones. Backends
    // that wire up more (the mobile ones) override this; it must agree with the crate's
    // `const fn lifecycle_supported`, which drives compile-time guards in `day::require_lifecycle!`.
    fn supports_lifecycle(&self, phase: Lifecycle) -> bool {
        phase.is_universal()
    }

    // pillars
    /// Apply a node's accessibility annotations (docs/accessibility.md): the label, hint and
    /// value the screen reader speaks, an explicit role, whether the node is hidden from
    /// assistive technology, and the automation identifier. Called with the node's whole
    /// accumulated set each time any of it changes, so every member is written on every call.
    /// Only an explicit role is applied: a native control reports its own.
    fn set_a11y(&mut self, _h: &Self::Handle, _a11y: &A11yProps) {}
    /// Speak `text` through the screen reader without moving its focus (docs/accessibility.md;
    /// probe [`Cap::Announce`]). `urgent` interrupts what is being read; otherwise the sentence
    /// waits its turn. Nothing happens when no screen reader is running. The default is a
    /// backend that reaches no announcement API.
    fn announce(&mut self, _text: &str, _urgent: bool) {}
    /// Read a widget's native state back from the platform for `a11y_audit` and
    /// `assert_native` (§14.2, docs/testing.md) to diff against Day's expectation. Default:
    /// nothing read; the audit skips the node and `assert_native` records each field as unread.
    fn read_native(&self, _h: &Self::Handle) -> NativeSnapshot {
        NativeSnapshot::default()
    }
    fn replay(&mut self, _h: &Self::Handle, _ops: &[DrawOp], _size: Size) {}

    /// Every family this toolkit can draw canvas text in, with the faces each ships
    /// (docs/fonts.md; probe [`Cap::FontList`]). Default: none. `day::font_families` calls
    /// this once per process and caches the answer: enumeration is slow on every platform
    /// (fontconfig, a DirectWrite collection, an XML parse on Android) and the set does not
    /// change under a running app.
    fn font_families(&mut self) -> Vec<FontFamilyInfo> {
        Vec::new()
    }

    /// Measure one line of canvas text at `size` points in `font`, in the same engine
    /// [`Toolkit::replay`] draws [`DrawOp::Text`] with, so a `TextAnchor::LEADING` anchor plus
    /// the returned `ascent` lands on the drawn baseline. `None` = cannot measure; the facade
    /// then answers [`TextMetrics::approximate`].
    fn measure_text(&mut self, _text: &str, _size: f64, _font: &CanvasFont) -> Option<TextMetrics> {
        None
    }
    // --- raster images (docs/images.md) -------------------------------------------------
    //
    // Request-id shaped rather than blocking, because one backend can never answer
    // synchronously: a browser decodes through `createImageBitmap`, which is a promise. Every
    // other backend decodes inline and raises the completion before returning, so the shape
    // costs them nothing but a line, and the app-facing API can be one thing everywhere
    // instead of two (docs/async.md rule 3: a callback and a future, never a runtime).

    /// Decode encoded image bytes (PNG/JPEG/…) into a native image, answering `req` with
    /// [`Event::ImageDecoded`].
    ///
    /// The id in that event is minted by the caller (day-core), not the backend: the backend
    /// keeps its own side table from that id to whatever it decoded.
    ///
    /// The default does nothing because a default body cannot reach the event sink
    /// (it is installed per backend by [`Toolkit::set_event_sink`], not reachable through this
    /// trait), so there is no way for it to answer. day-core asks [`Cap::ImageDecode`] first and
    /// resolves the request as [`ImageError::Unsupported`] itself, which is why a backend with
    /// no decoder needs no code here at all.
    fn decode_image(&mut self, _req: u64, _id: BitmapId, _bytes: &[u8]) {}

    /// What a decoded image is: pixel size, scale, format, alpha ([`BitmapInfo`]).
    ///
    /// Synchronous: every backend that decoded the image already holds these facts. `None` means
    /// the id names nothing live.
    fn image_info(&mut self, _id: BitmapId) -> Option<BitmapInfo> {
        None
    }

    /// The metadata beyond the pixels: EXIF orientation, DPI, capture time
    /// ([`ImageProperties`], probe [`Cap::ImageProperties`]). `None` where the backend has no
    /// metadata reader, which is most of them.
    fn image_properties(&mut self, _id: BitmapId) -> Option<ImageProperties> {
        None
    }

    /// Encode a decoded image back to bytes per `spec`, answering `req` with
    /// [`Event::ImageEncoded`]. A format outside [`Self::encode_formats`] answers
    /// [`ImageError::Encode`] rather than silently substituting another one.
    ///
    /// Defaulted to nothing for the same reason as [`Self::decode_image`]: day-core probes
    /// [`Cap::ImageEncode`] and answers `Unsupported` without ever calling this.
    fn encode_image(&mut self, _req: u64, _id: BitmapId, _spec: &EncodeSpec) {}

    /// Which formats [`Self::encode_image`] can write, the [`Cap::ImageEncode`]
    /// counterpart of [`Self::font_families`]/[`Cap::FontList`]. Empty by default.
    fn encode_formats(&mut self) -> Vec<ImageFormat> {
        Vec::new()
    }

    /// Drop a decoded image and everything the backend cached for it. Called when the app's
    /// last handle to it goes away; an id the backend never saw is a no-op.
    fn release_image(&mut self, _id: BitmapId) {}

    // --- canvas export (docs/canvas.md "Exporting") --------------------------------------
    //
    // Request-id shaped like the image duties above, for the same reason: the browser's
    // `createImageBitmap` is a promise. Every other backend renders inline and raises the
    // completion before returning. day-core validates sizes, enforces the pixel limits and
    // probes the caps first, so a backend sees only requests it can attempt.

    /// Replay `ops` into a new offscreen bitmap of `size` points at `scale` pixels per point
    /// ([`export_pixels`] gives the pixel size), with a transparent background and the
    /// canvas's top-left origin. Store it under `id` in the same table [`Self::decode_image`]
    /// fills, so `image_info`, `encode_image`, `release_image`, the `image` piece and
    /// [`DrawOp::Image`] all take it, then answer `req` with [`Event::BitmapRendered`] (its
    /// [`BitmapInfo::scale`] is `scale`).
    ///
    /// The painter must be the one [`Self::replay`] uses, so text, gradients, clips and stamps
    /// match the screen. Defaulted to nothing: day-core probes [`Cap::CanvasBitmap`] and answers
    /// [`ExportError::Unsupported`] itself.
    fn render_bitmap(
        &mut self,
        _req: u64,
        _id: BitmapId,
        _ops: &[DrawOp],
        _size: Size,
        _scale: f64,
    ) {
    }

    /// Replay each page into one PDF document and answer `req` with [`Event::PdfRendered`].
    /// Units are PDF points, top-left origin; shapes and text stay vector, and images embed at
    /// their pixel size. `pages` is never empty. Defaulted to nothing: day-core probes
    /// [`Cap::CanvasPdf`] first.
    fn render_pdf(&mut self, _req: u64, _pages: &[PdfPage], _info: &PdfInfo) {}

    fn snapshot_window(&mut self) -> Result<Vec<u8>, String> {
        Err("snapshot unsupported".into())
    }
    /// Where `root`, the primary window's root container, sits in [`Self::snapshot_window`]'s
    /// image, in points from its top-left. A reader of the capture (dayscript `sample_pixel`)
    /// maps Day's frames into it with this; it matters where the capture spans more than Day's
    /// content on more than one side, as Android's edge-to-edge content does (status bar
    /// above, navigation bar below).
    ///
    /// Defaulted to `None`, which the reader takes as "any rows beyond Day's content are
    /// above it", true where the only extra area is a title bar.
    fn snapshot_origin(&mut self, _root: &Self::Handle) -> Option<Point> {
        None
    }
    /// Establish a fresh screenshot checkpoint after reactive work and native transitions.
    /// `revision` is stable across retries and unique to the request; `host` selects a
    /// secondary window, or None for the primary. Never block the UI thread waiting for
    /// a frame. Pending requests are retried within the dayscript deadline.
    ///
    /// Ready means the platform render checkpoint completed, not that a vsync callback
    /// proves pixels were displayed. OnCapture delegates freshness to snapshot_window.
    fn prepare_snapshot(
        &mut self,
        _host: Option<&Self::Handle>,
        _revision: u32,
    ) -> Result<capture::Readiness, String> {
        // Compatible with external toolkits predating this hook: their synchronous
        // snapshot owns freshness, and no external-capture acknowledgment is fabricated.
        Ok(capture::Readiness::OnCapture)
    }

    /// The same capture with the window's own chrome: title bar, toolbar, whatever the platform
    /// draws around the content (docs/window-image.md).
    ///
    /// Defaulted to [`Self::snapshot_window`]: a backend that cannot separate the two
    /// (or has no chrome to speak of, a phone) answers with the content shot rather than an
    /// error, so an app asking for chrome degrades to "what there was" instead of failing. The
    /// dayscript `screenshot` step never calls this, which is what keeps every captured gallery
    /// baseline byte-identical to before it existed.
    fn snapshot_window_chrome(&mut self) -> Result<Vec<u8>, String> {
        self.snapshot_window()
    }
    /// Show/hide the sidebar pane of the navigation host `host`, which is what the sidebar
    /// affordance a `nav(Sidebar)` contributes for itself drives ([`SIDEBAR_TOGGLE_ID`]).
    /// `false` when `host` has no pane to toggle (a stack, a tab bar, no sidebar concept at all).
    ///
    /// Per host, not per process: a second window's button collapses that window's sidebar
    /// and not the first's. The item's own action makes the call, and dayscript's `toolbar:`
    /// step presses the item like any other, so a walkthrough drives exactly the path a click
    /// takes. Defaulted, so a backend with no sidebar needs no code. docs/toolbars.md,
    /// docs/navigation.md.
    fn toggle_sidebar(&mut self, _host: &Self::Handle) -> bool {
        false
    }
    /// Press the platform's own back affordance (the navigation bar's back button on iOS,
    /// the system back on Android) on the innermost navigation host that has something to
    /// pop. What `nav_back()` does not do: that is Day's rail, which pops the model and lets the
    /// backend follow, while this runs the native path first (the bar's `shouldPop`, the
    /// dispatcher's callbacks, the pop itself) and lets the backend report it to Day as a user
    /// back, guard and all. dayscript's `nav_back: { native: true }` drives it, so a walkthrough
    /// can cover the code that a real tap runs and Day's rail never reaches. `false` when this
    /// toolkit has no native back or nothing is popped by it. Defaulted, so a desktop needs no
    /// code. docs/navigation.md.
    fn native_back(&mut self) -> bool {
        false
    }
    /// Whether the UI has settled, with no native transition (modal present/dismiss, nav push)
    /// still animating. The dayscript `screenshot` step polls this before capturing so shots
    /// never catch a half-faded dialog or half-pushed page. Backends without async
    /// transitions (or without a way to know) report `true`.
    fn ui_idle(&mut self) -> bool {
        true
    }

    // imperative presentation (docs/dialogs.md): show a native modal for request `req`;
    // the backend answers by enqueuing `Event::PresentResult { req, .. }`. `dismiss` is
    // used only when Day resolves programmatically (dayscript) while the modal is still up.
    fn present(&mut self, _req: u64, _spec: &present::PresentSpec) {}
    fn dismiss(&mut self, _req: u64) {}

    /// Open `url` in the platform's default handler: the system browser for `http(s)`, the mail
    /// client for `mailto:`, etc. Backs the [`link`](/api/day_pieces/fn.link.html) piece. Fire and
    /// forget: there is no result, and an unopenable URL is ignored. The default no-ops so a
    /// backend that hasn't wired it up still compiles.
    fn open_url(&mut self, _url: &str) {}

    /// Whether a native share chooser is available. Does not probe installed share targets.
    fn share_support(&self) -> Support {
        Support::Unsupported
    }
    /// Present the system share chooser. True means presentation started, not that sharing
    /// completed. Never sends data without the user's choice of a target.
    fn share_url(&mut self, _url: &str, _title: &str) -> bool {
        false
    }

    /// Read current OS associations. Unsupported platforms must not fabricate a default.
    fn application_handlers(
        &mut self,
        _query: &applications::HandlerQuery,
    ) -> Result<applications::ApplicationHandlers, applications::ApplicationError> {
        Err(applications::ApplicationError::Unsupported)
    }

    /// Open with an opaque application identifier returned by `application_handlers`.
    fn open_url_with_application(
        &mut self,
        _url: &str,
        _application: &str,
        completion: applications::OpenApplicationCompletion,
    ) {
        completion(Err(applications::ApplicationError::Unsupported));
    }

    /// Ask the OS to require a second swipe for its edge gestures on `edges` (docs/cover.md):
    /// the union requested by every mounted `defers_system_gestures` modifier, re-sent whenever
    /// that set changes (`Edges::NONE` when the last one unmounts). iOS defers the home
    /// indicator / notification edges; Android enters swipe-to-reveal immersive mode while
    /// non-empty. The default no-ops (desktop has no system edge gestures).
    fn defer_system_gestures(&mut self, _edges: Edges) {}

    /// Hide (`true`) or show the system status bar (docs/cover.md): whether any mounted
    /// `status_bar_hidden` modifier currently asks for it hidden, re-sent whenever that answer
    /// may have changed (`false` when the last request unmounts). iOS answers the root and
    /// cover view controllers' `prefersStatusBarHidden`; Android and HarmonyOS hide the status
    /// bar through their window inset controls. The default no-ops (desktop and web have no
    /// status bar); report `Cap::StatusBarHidden` alongside an implementation.
    fn set_status_bar_hidden(&mut self, _hidden: bool) {}

    /// Whether the platform is rendering in dark appearance right now. Apps painting
    /// custom surfaces (opaque overlay panels, scrims) branch on this so their fills track
    /// the theme the default text colors already follow; hardcoding either theme's
    /// surface produces dark-on-dark or light-on-light text on the other. Queried at
    /// build time (a piece rebuilt after a theme change re-queries). The default honors a
    /// `DAY_THEME` launch override and otherwise answers light.
    fn dark_mode(&mut self) -> bool {
        std::env::var("DAY_THEME").ok().as_deref() == Some("dark")
    }
    /// Whether the user asked the system for less motion (docs/accessibility.md; probe
    /// [`Cap::ReduceMotion`]): macOS and iOS "Reduce Motion", Android "Remove animations" (an
    /// animator duration scale of zero), GTK's `gtk-enable-animations` off, Windows "Show
    /// animations" off, the web's `prefers-reduced-motion`. Read at launch; a backend that
    /// watches the setting calls `day_core::note_motion_changed` when it flips. Day then applies
    /// every finite animation at its destination and keeps only indeterminate motion. The default
    /// is a backend that reads no such setting.
    fn reduce_motion(&mut self) -> bool {
        false
    }

    /// App-level appearance override: `Some(true)` forces dark, `Some(false)` forces light,
    /// `None` returns to following the system. Backends restyle their native widgets in
    /// place and answer the override from [`dark_mode`](Self::dark_mode); app-painted
    /// surfaces pick it up on their next rebuild. `Cap::Appearance` reports whether the
    /// backend honors this; the default ignores the call.
    fn set_appearance(&mut self, _dark: Option<bool>) {}

    /// Put `badge` on the app's icon in the Dock / launcher / home screen (docs/badge.md).
    ///
    /// Fire-and-forget, like `set_appearance`: a payload this toolkit cannot render is ignored, and
    /// the app probes `Cap::AppBadge{Count,Text,Dot}` before choosing one. Never substitute: a
    /// backend that turned `Text("beta")` into `Count(1)` would put a wrong number on a user's
    /// icon, which is worse than showing nothing. The default ignores every call.
    fn set_app_badge(&mut self, _badge: &AppBadge) {}

    // app lifecycle (mobile; desktop backends no-op)
    fn on_suspend(&mut self) {}
    fn on_resume(&mut self) {}
    fn on_memory_warning(&mut self) {}

    // adoption of foreign native handles (polyglot pieces, §15.3)
    fn adopt(&mut self, _raw: RawHandle) -> Self::Handle {
        unimplemented!("this toolkit does not adopt foreign handles yet")
    }

    // secondary windows (docs/windows.md)

    /// Open a native OS window per `options` + `kind`: create and show the window, wire its
    /// events to `id` (`WindowResized` with the content size in points, `WindowClosed` after
    /// the native close, `WindowFocused` on key/active changes), and answer with its content
    /// container handle, the same contract as the `ready` root container. Backends whose
    /// window creation is asynchronous (a scene, an activity, an ability) answer
    /// [`WindowOpenReply::Pending`] and complete later through
    /// `day_core::finish_window_open(id, raw, size)`, which goes through [`Toolkit::adopt`].
    /// The default answers `Unsupported`; day-core then presents the content as a
    /// fullscreen cover in the primary window instead.
    fn open_window(
        &mut self,
        _id: NodeId,
        _options: &WindowOptions,
        _kind: WindowKind,
    ) -> WindowOpenReply<Self::Handle> {
        WindowOpenReply::Unsupported
    }

    /// Close the native window whose content container is `host` (a handle `open_window`
    /// produced). Asynchronous: the platform confirms with `Event::WindowClosed` on the
    /// window's root node, and only then does day-core tear the subtree down. Idempotent; unknown
    /// hosts are ignored. Never called with the primary window's container.
    fn close_window(&mut self, _host: &Self::Handle) {}

    /// End the application: the last window with [`WindowRole::Primary`] has closed
    /// (docs/windows.md). day-core decides when, since it owns the window registry and the role
    /// each window carries; the backend supplies only the platform's exit:
    /// `NSApplication.terminate`, `QCoreApplication::quit`, `GtkApplication.quit`,
    /// `PostQuitMessage`. Everything day-core wanted to happen first (secondary windows
    /// disposed, `WillTerminate` delivered) already has by the time this is called.
    ///
    /// The default does nothing, which is right for the backends whose process lifetime is
    /// not theirs to end: a browser tab, an Android activity, an iOS scene.
    fn quit_app(&mut self) {}

    /// Bring the window whose content container is `host` to front and make it key/active:
    /// the focus half of open-or-focus singleton windows. Default no-op.
    fn focus_window(&mut self, _host: &Self::Handle) {}

    /// Retitle the window whose content container is `host`. Default no-op.
    fn set_window_title(&mut self, _host: &Self::Handle, _title: &str) {}

    /// Resize the window whose content container is `host` to fit `size` of content, and pin it
    /// there: what `WindowOptions::size_to_fit` asks for (docs/windows.md).
    ///
    /// `size` is the content size Day measured, not the window's outer frame: the backend adds
    /// its chrome. A settings panel is the case this exists for, and every desktop platform
    /// sizes one to its content rather than to a number the app guessed; a fixed height either
    /// clips the last row or leaves a band of empty panel under it, and which one you get depends
    /// on the user's text size.
    ///
    /// Default no-op, so a toolkit that cannot resize a live window keeps the size it was
    /// opened at, which is what every backend did before this existed.
    fn fit_window(&mut self, _host: &Self::Handle, _size: Size) {}

    /// Snapshot the window whose content container is `host` (the dayscript `screenshot`
    /// step's `window:` target). The default answers the primary snapshot, so backends that
    /// never open windows stay correct without changes.
    fn snapshot_window_of(&mut self, _host: &Self::Handle) -> Result<Vec<u8>, String> {
        self.snapshot_window()
    }

    /// Apply one property change to the window whose content container is `host`
    /// (docs/windows.md "Window properties"). The primary window arrives with its root container,
    /// like [`set_window_title`](Self::set_window_title).
    ///
    /// Fire-and-forget, like [`set_app_badge`](Self::set_app_badge): a change this toolkit cannot
    /// make is ignored, and the app probes the matching `Cap` (named on each [`WindowChange`]
    /// variant) before relying on it. A change the platform completes later (a fullscreen
    /// transition, a zoom animation) reports its outcome through
    /// [`Event::WindowStateChanged`], never by assuming the request took. The default ignores
    /// every change.
    fn apply_window(&mut self, _host: &Self::Handle, _change: &WindowChange) {}

    /// True OS window groups, as distinct from native tab widgets.
    fn native_window_tabs(&self) -> bool {
        false
    }
    /// Native in-window document/section tab control; OS grouping is reported separately.
    fn native_document_tabs(&self) -> bool {
        false
    }
    /// Join/reorder these windows in an OS tab group. Content remains window-owned.
    fn group_windows(&mut self, _hosts: &[Self::Handle]) {}
    /// Current native order of the group containing this window, including detached groups.
    fn window_tab_order(&self, _host: &Self::Handle) -> Vec<NodeId> {
        Vec::new()
    }

    /// Install the app's Dock menu (docs/menus.md "Dock menu"): the items macOS shows above
    /// its own when the user right-clicks the app's Dock icon, built from the app's
    /// `[[shortcuts]]` and its `dock_menu(..)` entries. Same item model and dispatch as
    /// [`set_app_menu`](Self::set_app_menu); an empty slice removes the menu. `Cap::DockMenu`
    /// reports support; the default ignores the call.
    fn set_dock_menu(&mut self, _items: &[MenuItem]) {}

    /// Make the node at `h` move its window when the user drags it, as a title bar does
    /// (`.window_drag_region()`, docs/window-chrome.md): the region's own background starts a
    /// native window drag (with the platform's snapping and edge tiling), a double click does
    /// what the user's title-bar double-click setting says, and controls inside the region keep
    /// receiving their own clicks. `false` releases it. `Cap::DragRegion`; the default ignores
    /// the call, so on a phone the region is an ordinary view.
    fn set_drag_region(&mut self, _h: &Self::Handle, _drag: bool) {}

    /// Show these status items, replacing the previous set (docs/status-item.md): add the
    /// ones whose `id` is new, update the ones that changed, remove the ones no longer listed.
    /// A click on an item runs its `activate` action or opens its menu; menu choices dispatch
    /// [`Event::MenuAction`] like the app menu's. `Cap::StatusItem`; the default ignores the
    /// call, which is what a phone and the web do.
    fn set_status_items(&mut self, _items: &[StatusItemSpec]) {}

    /// Show `progress` on the app's Dock or taskbar icon (docs/status-item.md).
    /// `Cap::AppProgress`; the default ignores it.
    fn set_app_progress(&mut self, _progress: AppProgress) {}

    /// Show or hide the app's Dock icon while it runs: a menu-bar app hides it and lives in its
    /// status item (macOS activation policy). `Cap::DockVisibility`; the default ignores it.
    fn set_dock_visible(&mut self, _visible: bool) {}

    /// Keep the process running when its last window closes (docs/windows.md "Keeping the app
    /// running"). When `true`, the backend must not end the app on its own as windows close: it
    /// reports every close, the first window's included, as `Event::WindowClosed`, and day-core
    /// decides whether to call [`quit_app`](Self::quit_app). When `false`, the backend keeps its
    /// platform's own rule. A backend whose process lifetime is not its own (a phone, a browser
    /// tab) ignores it, which is the default.
    fn set_keep_running(&mut self, _keep: bool) {}

    /// The displays attached now (docs/windows.md "Monitors"). `Cap::Monitors`; the default
    /// answers none, and day-core then describes the primary window's own size as one display.
    fn monitors(&self) -> Vec<Monitor> {
        Vec::new()
    }

    /// The outer frame of the window whose content container is `host`, in points on the
    /// desktop's coordinate space (top-left origin), or `None` where the platform does not say
    /// (a phone, Wayland's positions). Read when the app asks for it and when day-core saves a
    /// remembered frame (`WindowOptions::remember_frame`).
    fn window_frame(&self, _host: &Self::Handle) -> Option<Rect> {
        None
    }

    /// Replace the launcher shortcuts the app set while running (docs/deep-links.md "Launcher
    /// shortcuts"), shown beside the ones Day.toml declares: iOS Home Screen quick actions,
    /// Android dynamic shortcuts, the macOS Dock menu. Each opens its route through the deep-link
    /// intake. `Cap::DynamicShortcuts`; the default ignores the call.
    fn set_launcher_shortcuts(&mut self, _shortcuts: &[LauncherShortcut]) {}
}

/// What a secondary window is, so backends can apply platform conventions (docs/windows.md).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum WindowKind {
    /// A regular document/tool window: resizable, miniaturizable, platform-default tabbing.
    Normal,
    /// A settings/preferences window: singleton by convention; macOS disallows window
    /// tabbing and drops the resize/minimize chrome, mobile presents it modally. Pairs with
    /// day-core's key-singleton reopen (`open_window` with a key).
    Preferences,
    /// The About window (docs/settings.md): the same fixed, centered, untabbed panel chrome
    /// as [`Self::Preferences`] (every desktop treats the two alike), presented modally on
    /// mobile. Singleton under day-core's `day.about` key.
    About,
}

impl WindowKind {
    /// Whether this is a panel (settings or About) rather than a document window: the kinds
    /// every desktop draws fixed-size, centered and out of the Window menu, and mobile presents
    /// as a cover.
    pub fn is_panel(self) -> bool {
        !matches!(self, WindowKind::Normal)
    }
}

/// Whether a window keeps the app alive (docs/windows.md close policy).
///
/// A separate axis from [`WindowKind`], which describes chrome. They correlate (a
/// preferences panel is the archetypal window that should not hold an app open), but they are
/// not the same question, and conflating them would leave no way to say "an ordinary-looking
/// tool window that shouldn't outlive the documents".
///
/// Note the word "secondary" is overloaded around windows: elsewhere in day it means "a window
/// other than the first one opened". Here it means "does not keep the app alive", which is
/// about lifetime, not about order of creation.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WindowRole {
    /// Closing the last one of these ends the app.
    #[default]
    Primary,
    /// Never keeps the app alive: when the last `Primary` closes, the app exits and takes
    /// these with it, however many are open.
    Secondary,
}

impl From<WindowKind> for WindowRole {
    /// The default pairing: an ordinary window holds the app open, a preferences panel does
    /// not. An app that needs a different answer sets the role itself.
    fn from(kind: WindowKind) -> WindowRole {
        match kind {
            WindowKind::Normal => WindowRole::Primary,
            WindowKind::Preferences | WindowKind::About => WindowRole::Secondary,
        }
    }
}

/// A backend's answer to [`Toolkit::open_window`] (docs/windows.md).
pub enum WindowOpenReply<H> {
    /// The window exists now; here is its content container (desktop backends).
    Open(H),
    /// Native creation started but completes asynchronously (a scene, an activity, an
    /// ability); the backend will call `day_core::finish_window_open` when the content
    /// container exists. day-core parks the window record until then.
    Pending,
    /// This toolkit cannot open windows (`Cap::MultiWindow` = `Unsupported`); day-core
    /// falls back to presenting the content as a fullscreen cover in the primary window.
    Unsupported,
}

/// How a window is shown (docs/windows.md "Window properties"): what the window's `state()`
/// signal holds and what [`WindowChange::State`] asks for.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WindowState {
    /// On screen at its own size: neither minimized, maximized nor fullscreen.
    #[default]
    Normal,
    /// Minimized to the Dock, taskbar or shelf. `Cap::WindowStates`.
    Minimized,
    /// Zoomed to fill the screen's work area, keeping its chrome. `Cap::WindowStates`.
    Maximized,
    /// Covering the whole screen with no window chrome; on a phone, the system bars hidden.
    /// `Cap::WindowFullscreen`.
    Fullscreen,
}

impl WindowState {
    /// The wire code of [`bridge::BridgeKind::WindowStateChanged`].
    pub const fn code(self) -> i32 {
        match self {
            WindowState::Normal => 0,
            WindowState::Minimized => 1,
            WindowState::Maximized => 2,
            WindowState::Fullscreen => 3,
        }
    }

    /// The state a wire code names; an unknown code reads as `Normal`.
    pub const fn from_code(code: i32) -> WindowState {
        match code {
            1 => WindowState::Minimized,
            2 => WindowState::Maximized,
            3 => WindowState::Fullscreen,
            _ => WindowState::Normal,
        }
    }
}

/// How a window stacks against other apps' windows ([`WindowChange::Level`], `Cap::WindowLevel`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WindowLevel {
    /// Ordinary stacking: the focused app's windows come forward.
    #[default]
    Normal,
    /// Stays above other apps' ordinary windows: a palette, a timer, a video peek.
    Floating,
}

/// How strongly a window asks for the user's attention ([`WindowChange::RequestAttention`]).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Attention {
    /// Once: one Dock bounce, a taskbar button that flashes a few times.
    #[default]
    Informational,
    /// Until the user switches to the app.
    Critical,
}

/// One change to one window (docs/windows.md "Window properties"), carried by
/// [`Toolkit::apply_window`]. Each variant names the `Cap` that reports whether the running
/// toolkit makes it.
#[derive(Clone, Debug, PartialEq)]
pub enum WindowChange {
    /// Minimize, zoom, take fullscreen, or return to normal. `Cap::WindowStates` for the
    /// first two, `Cap::WindowFullscreen` for fullscreen. The outcome comes back as
    /// [`Event::WindowStateChanged`].
    State(WindowState),
    /// Keep the window's content out of screenshots, recordings and screen sharing.
    /// `Cap::ContentProtection`.
    ContentProtected(bool),
    /// Move and/or resize. `origin` is the outer frame's top-left corner in points on the
    /// desktop's coordinate space (top-left origin, `Cap::WindowPosition`); `size` is the size Day
    /// lays the content out at, in points, the same size `WindowResized` reports
    /// (`Cap::WindowGeometry`): the backend adds its own chrome around it.
    Frame {
        origin: Option<Point>,
        size: Option<Size>,
    },
    /// The content size the user can resize the window to. `None` lifts that bound.
    /// `Cap::WindowGeometry`.
    Limits {
        min: Option<Size>,
        max: Option<Size>,
    },
    /// Stacking against other apps' windows. `Cap::WindowLevel`.
    Level(WindowLevel),
    /// Show the window on every virtual desktop / Space. `Cap::WindowLevel`.
    OnAllWorkspaces(bool),
    /// Leave the window out of the taskbar and the window switcher. `Cap::WindowLevel`.
    SkipTaskbar(bool),
    /// Whether the user can resize the window. `Cap::WindowGeometry`.
    Resizable(bool),
    /// Whether the window offers a minimize control. `Cap::WindowStates`.
    Minimizable(bool),
    /// Whether the window offers a maximize / zoom control. `Cap::WindowStates`.
    Maximizable(bool),
    /// Whether the window offers a close control. `Cap::WindowStates`.
    Closable(bool),
    /// Hide the window without closing it, or show it again. `Cap::WindowStates`.
    Visible(bool),
    /// This window's light/dark override over the app-wide [`Toolkit::set_appearance`].
    /// `Cap::WindowAppearance`.
    Appearance(Option<bool>),
    /// Bounce the Dock icon, flash the taskbar button. `Cap::RequestAttention`.
    RequestAttention(Attention),
}

/// The frame a window wears (docs/window-chrome.md), set once when it opens.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WindowChrome {
    /// The platform's title bar and frame.
    #[default]
    Standard,
    /// The content runs to the window's top edge, under the title bar, and the platform's own
    /// window controls (close, minimize, zoom) stay where they are. For a custom title bar: the
    /// backend reports the bar's height as the window's safe-area top inset (`day::safe_area()`),
    /// so the app pads its content by it and paints its background under it. Mark the draggable
    /// part with `.window_drag_region()`. `Cap::OverlayTitleBar`; where unsupported the window
    /// keeps its standard bar.
    Overlay,
    /// No title bar and no frame: a splash screen, a heads-up panel, a borderless utility. The
    /// window still resizes from its edges when resizable; mark the part that moves it with
    /// `.window_drag_region()`. `Cap::FramelessWindow`; where unsupported the window keeps its
    /// standard frame.
    Frameless,
}

/// What shows behind a window's content (docs/window-chrome.md).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum WindowBackground {
    /// The platform's window background.
    #[default]
    Opaque,
    /// Nothing: pixels the content leaves unpainted show the desktop through the window. For
    /// rounded or shaped splash screens and overlays. `Cap::TransparentWindow`.
    Transparent,
    /// A translucent system material that blurs what is behind the window.
    /// `Cap::WindowMaterial`; where unsupported the window stays opaque.
    Material(WindowMaterial),
}

/// The system materials a window background can use ([`WindowBackground::Material`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WindowMaterial {
    /// The main-window material: macOS's window background, Windows 11's Mica.
    Window,
    /// A sidebar or source list: macOS's sidebar material, Windows 11's Mica Alt (tabbed).
    Sidebar,
    /// A transient surface (a popover, a menu-like panel, a heads-up display): macOS's popover
    /// material, Windows 11's Acrylic.
    Transient,
}

/// Where a window opens ([`WindowOptions::placement`]).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum WindowPlacement {
    /// The platform's choice: macOS cascades, Windows and Linux let the window manager decide.
    #[default]
    Automatic,
    /// Centered on the screen with the active window.
    Centered,
    /// The outer frame's top-left corner at this point, in points on the desktop's coordinate
    /// space (top-left origin). Falls back to `Automatic` without `Cap::WindowPosition`.
    At(Point),
}

/// A small runtime RGBA image for a status item: charts, meters, or a grid of results.
///
/// Rows run top to bottom; samples are tightly packed, non-premultiplied sRGB RGBA8.
/// `scale` is pixels per logical point (2 for Retina). This owns its bytes, independent of
/// any window or decoded-image registry. Currently rendered by AppKit; other backends use
/// [`StatusItemSpec::icon`] as a fallback. See docs/status-item.md.
#[derive(Clone, PartialEq)]
pub struct StatusImage {
    width: u32,
    height: u32,
    scale: f64,
    rgba: std::sync::Arc<[u8]>,
}

impl StatusImage {
    /// Validate a runtime image. Rejects empty/mismatched pixels, invalid scales, and images
    /// exceeding 16 MiB or 4096 logical points on either axis. No platform allocation occurs.
    pub fn rgba(
        width: u32,
        height: u32,
        scale: f64,
        pixels: impl Into<std::sync::Arc<[u8]>>,
    ) -> Option<Self> {
        let rgba = pixels.into();
        let expected = (width as usize)
            .checked_mul(height as usize)?
            .checked_mul(4)?;
        if width == 0
            || height == 0
            || expected > 16 * 1024 * 1024
            || rgba.len() != expected
            || !scale.is_finite()
            || scale <= 0.0
            || f64::from(width) / scale > 4096.0
            || f64::from(height) / scale > 4096.0
        {
            return None;
        }
        Some(Self {
            width,
            height,
            scale,
            rgba,
        })
    }

    pub fn width(&self) -> u32 {
        self.width
    }
    pub fn height(&self) -> u32 {
        self.height
    }
    pub fn scale(&self) -> f64 {
        self.scale
    }
    pub fn pixels(&self) -> &[u8] {
        &self.rgba
    }
    pub fn size(&self) -> Size {
        Size::new(
            f64::from(self.width) / self.scale,
            f64::from(self.height) / self.scale,
        )
    }
}

impl std::fmt::Debug for StatusImage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StatusImage")
            .field("width", &self.width)
            .field("height", &self.height)
            .field("scale", &self.scale)
            .field("bytes", &self.rgba.len())
            .finish()
    }
}

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

    #[test]
    fn validates_pixel_layout_and_logical_size() {
        let image = StatusImage::rgba(120, 36, 2.0, vec![255; 120 * 36 * 4]).unwrap();
        assert_eq!(image.size(), Size::new(60.0, 18.0));
        assert_eq!(image.clone(), image);
        assert!(StatusImage::rgba(0, 1, 1.0, vec![]).is_none());
        assert!(StatusImage::rgba(1, 1, 1.0, vec![0; 3]).is_none());
        assert!(StatusImage::rgba(u32::MAX, u32::MAX, 1.0, vec![]).is_none());
        for scale in [0.0, -1.0, f64::NAN, f64::INFINITY, 0.00001] {
            assert!(StatusImage::rgba(1, 1, scale, vec![0; 4]).is_none());
        }
    }
}

/// One status item: an icon in the menu bar (macOS), the notification area (Windows) or a
/// StatusNotifierItem host's tray (Linux), with a menu (docs/status-item.md).
#[derive(Clone, Debug, PartialEq)]
pub struct StatusItemSpec {
    /// The app's name for the item, stable across updates: what a backend diffs by.
    pub id: String,
    /// The glyph. `None` shows the title alone (macOS) or the app's icon (elsewhere).
    pub icon: Option<Icon>,
    /// A runtime image. AppKit prefers this over `icon`, preserving aspect ratio and point
    /// size up to 18pt high; other backends ignore it and show `icon`/`title` as before.
    pub raster: Option<StatusImage>,
    /// Draw the icon as a template: its shape only, in the menu bar's or panel's own color, so
    /// it reads in light and dark. Symbols are always templates.
    pub template: bool,
    /// Text beside the icon where the platform shows one (the macOS menu bar). Empty: icon only.
    pub title: String,
    /// The hover text.
    pub tooltip: String,
    /// The menu the item opens. Same model and dispatch as the app menu.
    pub menu: Vec<MenuItem>,
    /// A dispatch id (the [`Event::MenuAction`] registry) run when the user clicks the item
    /// itself, where the platform separates a click from opening the menu (a left click on macOS
    /// and Windows, the host's "activate" on Linux). 0: a click opens the menu.
    pub activate: u64,
}

/// One display (docs/windows.md "Monitors"), in points on the desktop's coordinate space:
/// top-left origin at the primary display's top-left corner.
#[derive(Clone, Debug, PartialEq)]
pub struct Monitor {
    /// Stable for the display across launches where the platform offers it (a display UUID, a
    /// connector name); an index otherwise.
    pub id: String,
    /// The display's name, for a picker ("Built-in Retina Display", "DELL U2720Q").
    pub name: String,
    /// The display's whole area.
    pub frame: Rect,
    /// The part windows should use: the frame minus the menu bar, Dock, taskbar or panels.
    pub work_area: Rect,
    /// Device pixels per point.
    pub scale: f64,
    /// The display the desktop's menu bar or primary taskbar is on.
    pub primary: bool,
}

/// A launcher shortcut the app sets while it runs (docs/deep-links.md "Launcher shortcuts"): a
/// route to open and the label the launcher shows, already localized.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LauncherShortcut {
    /// The route the shortcut opens, through the deep-link intake.
    pub route: String,
    /// What the launcher shows.
    pub label: String,
}

/// A progress indicator on the app's Dock or taskbar icon ([`Toolkit::set_app_progress`],
/// docs/status-item.md).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum AppProgress {
    /// No indicator.
    #[default]
    None,
    /// Work of unknown length.
    Indeterminate,
    /// A fraction done, 0.0 to 1.0.
    Value(f64),
    /// A fraction done, paused. Platforms without a paused state show `Value`.
    Paused(f64),
    /// A fraction done when the work failed. Platforms without an error state show `Value`.
    Error(f64),
}

/// Whether and how a window joins macOS window tabs ([`WindowOptions::tabbing`],
/// `Cap::WindowTabbing`). Other platforms have no system window tabs and ignore it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum WindowTabbing {
    /// The platform default for the window's kind: an ordinary window tabs with the app's other
    /// ordinary windows when the user's "Prefer tabs" setting says so; preferences never tab.
    #[default]
    Automatic,
    /// Tab only with windows of the same group, following the user's setting. The tab bar's
    /// "+" opens the builder registered for this group (`register_new_window_for`).
    Group(String),
    /// Always open as a tab of an existing window of the same group, whatever the setting.
    Preferred(String),
    /// Never become a tab.
    Disallowed,
}

/// An app's generated locale catalog: `(DEFAULT, CATALOG)`, exactly what `day-build` emits as
/// `res::locales::{DEFAULT, CATALOG}` (§18.5). Carried in [`WindowOptions::locales`] so the
/// framework can install it at the one moment that is correct.
pub type AppLocales = (&'static str, &'static [(&'static str, &'static str)]);

#[derive(Clone, Debug)]
pub struct WindowOptions {
    pub title: String,
    pub size: Size,
    pub min_size: Option<Size>,
    /// Create and mount the window without showing it or activating the app. Supported on
    /// AppKit; other backends currently ignore this option. Defaults to false.
    ///
    /// Menu-bar apps can keep their initial host hidden and open Preferences on demand.
    /// The window still exists and can be shown with `WindowHandle::set_visible(true)`;
    /// this does not change the app's keep-running policy.
    pub start_hidden: bool,
    /// Ask the backend to size this window to its content once it has been built and laid out,
    /// rather than keeping [`Self::size`] (docs/windows.md). `size` still decides the width and
    /// acts as the height ceiling, so a panel with more content than fits the screen scrolls
    /// instead of growing past it.
    ///
    /// What a preferences panel wants on every desktop. Ignored by backends that cannot resize a
    /// live window, and by the ones with no windows at all.
    pub size_to_fit: bool,
    /// The app's display name for the standard application menu / About (macOS). `None` falls back
    /// to `title`; set it when `title` carries extra decoration you don't want in `About <name>`
    /// (e.g. the showcase's window title is "Day Showcase (AppKit)" but its app name is "Showcase").
    pub app_name: Option<String>,
    /// The app's locale catalog, installed by `day::launch` (docs/localization.md).
    ///
    /// The order is why this is the framework's job: the OS's languages reach day-localization from the
    /// live backend, and the catalog has to be registered after that hint and before the first
    /// localized string is read. An app that installs it itself (before `launch`, where there
    /// is no backend yet) registers against an empty hint list and resolves to `DEFAULT`, so a
    /// French device opens an English window.
    pub locales: Option<AppLocales>,
    /// The title, computed once the catalog above is installed: how a window title comes from
    /// the catalog rather than a literal. Takes precedence over [`Self::title`], which stays the
    /// fallback for the moment before (and for apps with nothing to translate).
    ///
    /// A plain `fn` rather than a closure: this struct is `Clone`, and the callers are a
    /// non-capturing `|| res::str::app_title().format()`, which coerces.
    pub title_fn: Option<fn() -> String>,
    /// The app's version, for Day's exit line (`Clean exit for <app> v<version> …`,
    /// docs/lifecycle.md): `env!("CARGO_PKG_VERSION")` in the app crate, which the scaffold's
    /// `window()` sets. `None` falls back to the `DAY_APP_VERSION` the `day` CLI sets on a launch.
    pub version: Option<String>,
    /// macOS window tabbing for this window (`Cap::WindowTabbing`); ignored elsewhere.
    pub tabbing: WindowTabbing,
    /// The window's frame: standard, a title bar the content runs under, or none
    /// (docs/window-chrome.md). Desktop only; phones and the web ignore it.
    pub chrome: WindowChrome,
    /// What shows behind the content: the window background, nothing, or a system material.
    pub background: WindowBackground,
    /// Whether the window casts the platform's drop shadow. A transparent, shaped window often
    /// wants none.
    pub shadow: bool,
    /// Whether the user can resize the window by its edges.
    pub resizable: bool,
    /// Where the window opens.
    pub placement: WindowPlacement,
    /// The largest content size the user can resize the window to (`Cap::WindowGeometry`).
    pub max_size: Option<Size>,
    /// Remember this window's size, position and maximized state under this key, and reopen it
    /// that way next launch (docs/windows.md "Remembered frames"). A position that no attached
    /// display shows any more is dropped, so a window never reopens off-screen.
    pub remember_frame: Option<String>,
    /// The logical window this opens (docs/windows.md): `open_window` focuses an already-open
    /// window with the same key instead of opening a second (the preferences pattern). `None`
    /// always opens a new one.
    pub key: Option<String>,
    /// The kind of window: a regular one, a preferences panel, an About panel.
    pub kind: WindowKind,
}

impl WindowOptions {
    /// The window title. Replaces a [`title_fn`](Self::title_fn) set earlier (the generated
    /// `res::window_options()` sets one), so the last title named wins.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self.title_fn = None;
        self
    }
    /// The content size the window opens at (desktop; phones fill the screen).
    pub fn size(mut self, width: f64, height: f64) -> Self {
        self.size = Size::new(width, height);
        self
    }
    /// The smallest content size the user can resize to.
    pub fn min_size(mut self, width: f64, height: f64) -> Self {
        self.min_size = Some(Size::new(width, height));
        self
    }
    /// The largest content size the user can resize to (`Cap::WindowGeometry`).
    pub fn max_size(mut self, width: f64, height: f64) -> Self {
        self.max_size = Some(Size::new(width, height));
        self
    }
    /// Create and mount the window without showing it; see [`Self::start_hidden`].
    pub fn start_hidden(mut self) -> Self {
        self.start_hidden = true;
        self
    }
    /// Size the window to its content once built; see [`Self::size_to_fit`].
    pub fn size_to_fit(mut self) -> Self {
        self.size_to_fit = true;
        self
    }
    /// The app's display name for the application menu and About; see [`Self::app_name`].
    pub fn app_name(mut self, name: impl Into<String>) -> Self {
        self.app_name = Some(name.into());
        self
    }
    /// The app's locale catalog, as `res::locales::{DEFAULT, CATALOG}`; see [`Self::locales`].
    pub fn locales(
        mut self,
        default: &'static str,
        catalog: &'static [(&'static str, &'static str)],
    ) -> Self {
        self.locales = Some((default, catalog));
        self
    }
    /// The title, computed once the catalog is installed; see [`Self::title_fn`].
    pub fn title_fn(mut self, f: fn() -> String) -> Self {
        self.title_fn = Some(f);
        self
    }
    /// The app's version, for Day's exit line; see [`Self::version`].
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.version = Some(version.into());
        self
    }
    /// macOS window tabbing for this window; see [`Self::tabbing`].
    pub fn tabbing(mut self, tabbing: WindowTabbing) -> Self {
        self.tabbing = tabbing;
        self
    }
    /// The window's frame; see [`Self::chrome`].
    pub fn chrome(mut self, chrome: WindowChrome) -> Self {
        self.chrome = chrome;
        self
    }
    /// What shows behind the content; see [`Self::background`].
    pub fn background(mut self, background: WindowBackground) -> Self {
        self.background = background;
        self
    }
    /// No drop shadow, for a transparent or shaped window; see [`Self::shadow`].
    pub fn no_shadow(mut self) -> Self {
        self.shadow = false;
        self
    }
    /// A window the user cannot resize; see [`Self::resizable`].
    pub fn fixed_size(mut self) -> Self {
        self.resizable = false;
        self
    }
    /// Where the window opens; see [`Self::placement`].
    pub fn placement(mut self, placement: WindowPlacement) -> Self {
        self.placement = placement;
        self
    }
    /// Remember and restore this window's frame under `key`; see [`Self::remember_frame`].
    pub fn remember_frame(mut self, key: impl Into<String>) -> Self {
        self.remember_frame = Some(key.into());
        self
    }
    /// The logical window this opens; see [`Self::key`].
    pub fn key(mut self, key: impl Into<String>) -> Self {
        self.key = Some(key.into());
        self
    }
    /// The kind of window; see [`Self::kind`].
    pub fn kind(mut self, kind: WindowKind) -> Self {
        self.kind = kind;
        self
    }
}

impl Default for WindowOptions {
    fn default() -> Self {
        WindowOptions {
            title: "Day".into(),
            size: Size::new(480.0, 640.0),
            min_size: None,
            start_hidden: false,
            size_to_fit: false,
            app_name: None,
            locales: None,
            title_fn: None,
            version: None,
            tabbing: WindowTabbing::Automatic,
            chrome: WindowChrome::Standard,
            background: WindowBackground::Opaque,
            shadow: true,
            resizable: true,
            placement: WindowPlacement::Automatic,
            max_size: None,
            remember_frame: None,
            key: None,
            kind: WindowKind::Normal,
        }
    }
}

/// A platform backend: owns the native main loop and exactly one window in v1 (§8.1).
///
/// `run` sets up the native app + window, installs the reactive scheduler + main poster,
/// then hands `(self, root_container, content_size)` to `ready` (which mounts the tree and
/// takes ownership of the backend), and finally runs the native main loop.
pub trait Platform: Toolkit {
    /// The process-constant target id, e.g. `"macos-appkit"`.
    const TARGET: &'static str;
    /// The toolkit half of the target, e.g. `"appkit"`.
    const TOOLKIT: &'static str;
    /// Whether [`Platform::run`] returning means the app is over. True for a backend that
    /// drives the native loop itself until the app quits (GTK, Qt, XAML; AppKit's never
    /// returns). False where the host owns the loop and `run` hands back at once, with the
    /// app still to come (ArkUI's ability, Android's activity, the web page, the mock's test):
    /// their `DidExit` is the host's last callback, not the return (docs/lifecycle.md).
    const RUN_ENDS_APP: bool = true;

    fn run(self, options: WindowOptions, ready: Box<dyn FnOnce(Self, Self::Handle, Size)>);

    /// Post a closure onto the native main loop. Callable from any thread; this is the
    /// single door the reactive scheduler and `Setter` deliveries ride (§3.3).
    fn post(f: Box<dyn FnOnce() + Send>);

    /// Post `f` onto the native main loop after (at least) `ms` milliseconds: the timer
    /// door behind `day::sleep` (docs/async.md). Every shipped backend overrides it with the
    /// loop's own timer (`dispatch_after`, `Handler.postDelayed`, `g_timeout_add`,
    /// `QTimer::singleShot`, `SetTimer`, `setTimeout`), so a sleep costs no thread. The
    /// default is the fallback for a backend without one: a helper thread that sleeps the
    /// whole delay and rides [`Platform::post`] home. It is correct, but a thread per sleep
    /// adds up under a ticking loop, so the first use says so once in the log.
    fn post_delayed(ms: u32, f: Box<dyn FnOnce() + Send>) {
        static SAID: std::sync::Once = std::sync::Once::new();
        SAID.call_once(|| {
            log::warn!(
                "day: {} has no native timer door; `day::sleep` falls back to a helper thread \
                 per delay (implement `Platform::post_delayed`)",
                Self::TARGET
            );
        });
        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(u64::from(ms)));
            Self::post(f);
        });
    }

    /// Ordered OS locale preference list (BCP-47), for fluent-langneg (§12.2).
    fn locale_hints(&self) -> Vec<String> {
        Vec::new()
    }
}

// ---------------------------------------------------------------------------
// Open renderer registry (§8.2)
// ---------------------------------------------------------------------------

/// The scale a window snapshot is rendered at, when a scripted run states one
/// (`DAY_CAPTURE_SCALE=2`, set by `day launch --script` from Day.toml `[screenshots]`).
///
/// For the backends that render their own snapshot (GTK, Qt): the capture then measures
/// window points times this, whatever display the host has, which is what makes a CI capture
/// under a 1x xvfb the same 2560x1600 pixels a HiDPI laptop produces. A backend that reads the
/// compositor's pixels back (AppKit, XAML) captures at the display's own scale and ignores it.
/// `None` when unset or unparseable: capture at the backend's natural scale.
pub fn capture_scale() -> Option<f64> {
    std::env::var("DAY_CAPTURE_SCALE")
        .ok()
        .and_then(|v| v.trim().parse::<f64>().ok())
        .filter(|s| s.is_finite() && (0.5..=4.0).contains(s))
}

/// Seconds on a monotonic clock since the first call: the frame timestamp for a backend that
/// does not expose a native timestamp (§8.4). The origin is arbitrary. Not for the web
/// build, where `Instant` is unavailable and `requestAnimationFrame` stamps the frame itself.
pub fn frame_timestamp() -> f64 {
    static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
    ORIGIN
        .get_or_init(std::time::Instant::now)
        .elapsed()
        .as_secs_f64()
}

/// The user's language preference from the POSIX environment, newest-first, as BCP-47 tags.
///
/// `LANGUAGE` is the GNU multi-language list (`fr:en`); `LC_ALL`, `LC_MESSAGES` and `LANG` each
/// carry one locale in POSIX form (`fr_FR.UTF-8`), which becomes `fr-FR`. Shared by the backends
/// whose platform has no richer API to ask (§12.2, docs/localization.md).
pub fn posix_locale_hints() -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut push = |tag: &str| {
        // "C" and "POSIX" are the absence of a preference, not a language.
        let tag = tag.split('.').next().unwrap_or(tag).replace('_', "-");
        if tag.is_empty() || tag == "C" || tag == "POSIX" {
            return;
        }
        if !out.contains(&tag) {
            out.push(tag);
        }
    };
    if let Ok(list) = std::env::var("LANGUAGE") {
        for tag in list.split(':') {
            push(tag);
        }
    }
    for key in ["LC_ALL", "LC_MESSAGES", "LANG"] {
        if let Ok(v) = std::env::var(key) {
            push(&v);
        }
    }
    out
}

/// Optional custom measure for a third-party piece (§8.2).
pub type MeasureFn<B> = fn(&mut B, &<B as Toolkit>::Handle, Proposal) -> Size;

/// A third-party piece's per-toolkit implementation. `make` receives the concrete backend
/// (public helper surface) and returns a native handle the backend then owns like any built-in.
pub struct Renderer<B: Toolkit> {
    pub kind: PieceKind,
    pub make: fn(&mut B, &dyn Any, NodeId) -> B::Handle,
    pub update: fn(&mut B, &B::Handle, &dyn Any),
    pub measure: Option<MeasureFn<B>>,
    /// Teardown, run from the release queue just before [`Toolkit::release`] frees the handle.
    ///
    /// A piece that keeps per-view state (a retained delegate, a session map, a native
    /// observer) has no other place to drop it: `make`/`update` are the only other hooks, and a
    /// disposed node never calls them again. Without this a piece leaks one entry per realized
    /// view, and any map keyed by the handle's address can go on to answer for a later view that
    /// the allocator hands the same address.
    ///
    /// `None` for the pieces that own nothing (most of them).
    pub release: Option<fn(&mut B, &B::Handle)>,
}

pub struct Registry<B: Toolkit> {
    map: HashMap<PieceKind, Renderer<B>>,
}

impl<B: Toolkit> Default for Registry<B> {
    fn default() -> Self {
        Registry {
            map: HashMap::new(),
        }
    }
}

impl<B: Toolkit> Registry<B> {
    pub fn register(&mut self, r: Renderer<B>) {
        let kind = r.kind;
        if self.map.insert(kind, r).is_some() {
            // Two pieces claiming one kind is last-linked-wins in link order, effectively
            // nondeterministic. Fail loudly in debug; in release, say so once at boot rather
            // than render the wrong widget silently.
            debug_assert!(
                false,
                "duplicate renderer registered for piece kind {kind:?}"
            );
            log::warn!("duplicate renderer for piece kind {kind:?} — later registration wins");
        }
    }
    pub fn get(&self, kind: PieceKind) -> Option<&Renderer<B>> {
        self.map.get(kind)
    }
    pub fn kinds(&self) -> impl Iterator<Item = PieceKind> + '_ {
        self.map.keys().copied()
    }
}

/// The canvas wire op codes (§11, §15.3): slot 0 of every 9-number record in
/// [`encode_ops`]'s output. The numeric values are the frozen wire contract: the JNI, C++,
/// and JS decoders each hand-write these as constants, so a value here may never be reused
/// or renumbered; new ops append. `ALL` drives the density test that keeps this enum and
/// the encoder in step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
pub enum OpCode {
    /// Fill a rect (a,b=origin, c,d=size).
    FillRect = 0,
    /// Stroke a rect (g=width).
    StrokeRect = 1,
    /// Fill a rounded rect (e=radius).
    FillRrect = 2,
    /// Fill an ellipse in a rect.
    FillEllipse = 3,
    /// Stroke an ellipse (g=width).
    StrokeEllipse = 4,
    /// Stroke an arc (e=start°, f=sweep°, g=width). `Fill(Shape::Arc)` also encodes as
    /// this with width 0, the known asymmetry; see [`encode_ops`].
    StrokeArc = 5,
    /// Line a,b → c,d (g=width).
    Line = 6,
    /// Text at a,b (e=size, f=anchor: 0 leading / 1 centered); the string rides the texts
    /// channel.
    Text = 7,
    /// Save the graphics state.
    Save = 8,
    /// Restore the graphics state.
    Restore = 9,
    /// Concat an affine transform (a..f).
    Concat = 10,
    /// Fill a polygon; points ride the texts channel as "x,y x,y …" (closed automatically).
    /// `a` = the [`geometry_key`] of those points, or 0 for none.
    FillPolygon = 11,
    /// Stroke a polygon (g=width); points and key as [`OpCode::FillPolygon`].
    StrokePolygon = 12,
    /// Stroke a rounded rect (e=radius, g=width).
    StrokeRrect = 13,
    /// Set a gradient for the next shape record (f=type: 0 linear with a,b=start / c,d=end
    /// unit points; 1 radial with a,b=center unit point, c=unit radius; e=stop count).
    /// Stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …". Unit geometry
    /// resolves against the shape's bounding box.
    SetGradient = 14,
    /// Fill a path (f=fill rule: 0 non-zero / 1 even-odd); segments ride the texts channel
    /// (see [`encode_path`]). `a` = the [`geometry_key`] of those segments, or 0 for none.
    ///
    /// The key is a cache handle, not a payload: a decoder that recognizes it may keep the
    /// native geometry it built last time and skip re-parsing the segments, but it must still
    /// consume the texts entry either way, because that channel is positional and a skipped
    /// entry desynchronizes every record after it.
    FillPath = 15,
    /// Stroke a path (g=width); segments and key as [`OpCode::FillPath`].
    StrokePath = 16,
    /// Clip to a shape (f=shape kind: 0 rect / 1 rrect(e=radius) / 2 ellipse / 3 path
    /// (e=fill rule) / 4 polygon; a..d=geometry; path/polygon payloads ride the texts
    /// channel).
    ///
    /// For the two payload-bearing kinds (3 and 4) there is no geometry in the slots, so `a`
    /// carries the [`geometry_key`] instead and b..d stay 0. The other three kinds put real
    /// geometry in a..d and have nothing to cache.
    Clip = 17,
    /// Stroke style for the next stroke record (a=cap, b=join, c=miter limit, d=dash
    /// phase, e=dash count; the dash array rides the texts channel).
    StrokeStyle = 18,
    /// Font for the next text record (a=CSS weight 100 … 900, 0 = default; b=italic 0/1); the
    /// family name rides the texts channel, `""` = the platform's default face. Like
    /// [`OpCode::SetGradient`] and [`OpCode::StrokeStyle`] it is consumed by the record that
    /// follows and then cleared; a default [`CanvasFont`] emits no record at all, so a drawing
    /// without fonts encodes exactly as it did before this op existed.
    SetFont = 19,
    /// The next shape record is a template, drawn once per stamped position rather than once
    /// (docs/canvas.md "Stamping"). `a` = how many positions follow. Like [`OpCode::SetGradient`],
    /// [`OpCode::StrokeStyle`] and [`OpCode::SetFont`] it is a prefix, consumed by the record it
    /// applies to and then cleared.
    ///
    /// Between this and that template record come `ceil(a / 4)` [`OpCode::StampPoints`] records
    /// carrying the coordinates. A drawing with no stamps encodes exactly as it did before.
    Stamp = 20,
    /// Four stamped positions, filling the record edge to edge: `[op, x0, y0, x1, y1, x2, y2,
    /// x3, y3]`, the one record that uses its last slot for geometry instead of a color, because
    /// it carries no color of its own. The final record of a run is padded; the count in the
    /// [`OpCode::Stamp`] header says how many of the pairs are real.
    StampPoints = 21,
    /// Draw a decoded image: `a,b` = origin, `c,d` = size, `e` = the [`BitmapId`], `f` = opacity
    /// in `0.0..=1.0` (docs/images.md).
    ///
    /// The id rides the numeric channel because it is a number, and an `f64` carries a `u64` id
    /// exactly up to 2^53; ids are minted from 1 per process, so that ceiling is unreachable.
    /// Nothing rides the texts channel for this op.
    Image = 22,
}

impl OpCode {
    /// Every code, in wire order. The density test iterates this so a new variant that
    /// forgets to join fails loudly.
    pub const ALL: [OpCode; 23] = [
        OpCode::FillRect,
        OpCode::StrokeRect,
        OpCode::FillRrect,
        OpCode::FillEllipse,
        OpCode::StrokeEllipse,
        OpCode::StrokeArc,
        OpCode::Line,
        OpCode::Text,
        OpCode::Save,
        OpCode::Restore,
        OpCode::Concat,
        OpCode::FillPolygon,
        OpCode::StrokePolygon,
        OpCode::StrokeRrect,
        OpCode::SetGradient,
        OpCode::FillPath,
        OpCode::StrokePath,
        OpCode::Clip,
        OpCode::StrokeStyle,
        OpCode::SetFont,
        OpCode::Stamp,
        OpCode::StampPoints,
        OpCode::Image,
    ];

    /// The code back from a wire number (a decoder-side aid and the round-trip test's
    /// reference); `None` for anything outside the table.
    pub fn from_wire(n: f64) -> Option<OpCode> {
        OpCode::ALL.into_iter().find(|c| *c as i32 as f64 == n)
    }
}

/// Flat numeric encoding of a display list for shim/JNI boundaries (§11, §15.3): per op
/// 9 numbers [kind, a, b, c, d, e, f, g, rgba-bits]; text payloads ride separately in order.
/// The kind slot carries an [`OpCode`]; its doc comments are the per-slot contract.
///
/// Transports join `texts` with the unit separator U+001F (one entry per text-carrying
/// record, in order), so text payloads must not contain U+001F. Known asymmetry:
/// `Fill(Shape::Arc)` encodes as [`OpCode::StrokeArc`] with width 0. Filled arcs render
/// only on the direct-replay backends (AppKit/UIKit); use a polygon fan if a filled arc
/// must be portable.
/// Serialize a path for the `texts` side-channel: one space-separated token per segment,
/// `M x y` / `L x y` / `Q cx cy x y` / `C c1x c1y c2x c2y x y` / `Z`.
///
/// Text rather than numbers because that is the channel the encoder already has for
/// variable-length payloads, and every decoder (JS, Java, C++) can already split a string. The
/// numeric channel is a flat `[f64; 9]`-per-record array with no length prefix, so a path could
/// not ride it without changing the record shape for every backend at once.
/// A content key for a shape's variable-length geometry: the handle a backend caches decoded
/// native geometry under (a `Path2D`, a `QPainterPath`, an `android.graphics.Path`) so an
/// unchanged path is rebuilt once instead of re-parsed out of the texts channel every frame.
///
/// It hashes the geometry, not the op's position or its identity, so that a draw closure that
/// rebuilds its `PathBuilder` chain from scratch on every frame (which is what canvas consumers
/// do) produces an equal path, hashes the same and hits the same entry. An identity would miss
/// every time.
///
/// Two different paths that collided would draw each other, so the width matters: FNV-1a over the
/// IEEE bits, masked to the 53 bits an `f64` wire slot carries exactly. `0.0` is reserved for "no
/// key": a decoder seeing it must decode the payload as it always did, which is also what every
/// decoder written before this key existed does with the slot.
pub fn geometry_key(shape: &Shape) -> f64 {
    fn mix(h: &mut u64, v: f64) {
        for byte in v.to_bits().to_le_bytes() {
            *h ^= u64::from(byte);
            *h = h.wrapping_mul(0x0000_0100_0000_01b3);
        }
    }
    fn mix_point(h: &mut u64, p: Point) {
        mix(h, p.x);
        mix(h, p.y);
    }
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    match shape {
        Shape::Polygon(pts) => {
            // The discriminant joins the hash so a polygon and a path of the same points can
            // never share an entry: they decode to different geometry.
            mix(&mut h, 11.0);
            for p in pts {
                mix_point(&mut h, *p);
            }
        }
        Shape::Path(path) => {
            mix(&mut h, 15.0);
            mix(&mut h, rule_bits(path.rule));
            for seg in &path.segs {
                match seg {
                    PathSeg::Move(a) => {
                        mix(&mut h, 0.0);
                        mix_point(&mut h, *a);
                    }
                    PathSeg::Line(a) => {
                        mix(&mut h, 1.0);
                        mix_point(&mut h, *a);
                    }
                    PathSeg::Quad(c, a) => {
                        mix(&mut h, 2.0);
                        mix_point(&mut h, *c);
                        mix_point(&mut h, *a);
                    }
                    PathSeg::Cubic(c1, c2, a) => {
                        mix(&mut h, 3.0);
                        mix_point(&mut h, *c1);
                        mix_point(&mut h, *c2);
                        mix_point(&mut h, *a);
                    }
                    PathSeg::Close => mix(&mut h, 4.0),
                }
            }
        }
        // Everything else puts its whole geometry in the record's own slots, so there is nothing
        // to parse and nothing worth caching.
        _ => return 0.0,
    }
    let masked = h & ((1u64 << 53) - 1);
    // 0 means "no key", so the one hash that lands there borrows its neighbor.
    if masked == 0 { 1.0 } else { masked as f64 }
}

pub fn encode_path(path: &Path) -> String {
    let mut out = String::with_capacity(path.segs.len() * 16);
    for seg in &path.segs {
        if !out.is_empty() {
            out.push(' ');
        }
        match seg {
            PathSeg::Move(p) => out.push_str(&format!("M {} {}", p.x, p.y)),
            PathSeg::Line(p) => out.push_str(&format!("L {} {}", p.x, p.y)),
            PathSeg::Quad(c, p) => out.push_str(&format!("Q {} {} {} {}", c.x, c.y, p.x, p.y)),
            PathSeg::Cubic(a, b, p) => out.push_str(&format!(
                "C {} {} {} {} {} {}",
                a.x, a.y, b.x, b.y, p.x, p.y
            )),
            PathSeg::Close => out.push('Z'),
        }
    }
    out
}

/// `FillRule` as a wire number: 0 non-zero, 1 even-odd.
fn rule_bits(rule: FillRule) -> f64 {
    match rule {
        FillRule::NonZero => 0.0,
        FillRule::EvenOdd => 1.0,
    }
}

pub fn encode_ops(ops: &[DrawOp]) -> (Vec<f64>, Vec<String>) {
    fn color_bits(c: Color) -> f64 {
        let r = (c.r.clamp(0.0, 1.0) * 255.0) as u32;
        let g = (c.g.clamp(0.0, 1.0) * 255.0) as u32;
        let b = (c.b.clamp(0.0, 1.0) * 255.0) as u32;
        let a = (c.a.clamp(0.0, 1.0) * 255.0) as u32;
        ((a << 24) | (r << 16) | (g << 8) | b) as f64
    }
    #[allow(clippy::too_many_arguments)]
    fn push(
        k: OpCode,
        a: f64,
        b: f64,
        c: f64,
        d: f64,
        e: f64,
        f: f64,
        g: f64,
        col: Color,
        nums: &mut Vec<f64>,
    ) {
        nums.extend_from_slice(&[k as i32 as f64, a, b, c, d, e, f, g, color_bits(col)]);
    }
    /// The kind-18 prefix a non-plain stroke style emits, applying to the next stroke record,
    /// the same "modifier record" rule the gradient and font records follow. A plain style emits
    /// nothing, so a drawing without dashes or caps encodes exactly as it always did.
    fn stroke_style_record(style: &StrokeStyle, nums: &mut Vec<f64>, texts: &mut Vec<String>) {
        if style.is_plain() {
            return;
        }
        push(
            OpCode::StrokeStyle,
            match style.cap {
                LineCap::Butt => 0.0,
                LineCap::Round => 1.0,
                LineCap::Square => 2.0,
            },
            match style.join {
                LineJoin::Miter => 0.0,
                LineJoin::Round => 1.0,
                LineJoin::Bevel => 2.0,
            },
            style.miter_limit,
            style.dash_phase,
            style.dash.len() as f64,
            0.0,
            0.0,
            Color::CLEAR,
            nums,
        );
        texts.push(
            style
                .dash
                .iter()
                .map(|d| d.to_string())
                .collect::<Vec<_>>()
                .join(" "),
        );
    }

    /// One shape record (the fill/stroke kinds shared by both ops).
    fn shape_record(
        stroke: bool,
        shape: &Shape,
        w: f64,
        col: Color,
        nums: &mut Vec<f64>,
        texts: &mut Vec<String>,
    ) {
        match shape {
            Shape::Rect(r) => push(
                if stroke {
                    OpCode::StrokeRect
                } else {
                    OpCode::FillRect
                },
                r.origin.x,
                r.origin.y,
                r.size.width,
                r.size.height,
                0.0,
                0.0,
                w,
                col,
                nums,
            ),
            Shape::RoundedRect(r, rad) => push(
                if stroke {
                    OpCode::StrokeRrect
                } else {
                    OpCode::FillRrect
                },
                r.origin.x,
                r.origin.y,
                r.size.width,
                r.size.height,
                *rad,
                0.0,
                w,
                col,
                nums,
            ),
            Shape::Ellipse(r) => push(
                if stroke {
                    OpCode::StrokeEllipse
                } else {
                    OpCode::FillEllipse
                },
                r.origin.x,
                r.origin.y,
                r.size.width,
                r.size.height,
                0.0,
                0.0,
                w,
                col,
                nums,
            ),
            Shape::Arc {
                rect,
                start_deg,
                sweep_deg,
            } => push(
                OpCode::StrokeArc,
                rect.origin.x,
                rect.origin.y,
                rect.size.width,
                rect.size.height,
                *start_deg,
                *sweep_deg,
                w,
                col,
                nums,
            ),
            Shape::Line(p1, p2) => {
                push(OpCode::Line, p1.x, p1.y, p2.x, p2.y, 0.0, 0.0, w, col, nums)
            }
            Shape::Polygon(pts) => {
                // Variable-length points ride the texts side-channel ("x,y x,y …"),
                // consumed in record order exactly like text payloads.
                push(
                    if stroke {
                        OpCode::StrokePolygon
                    } else {
                        OpCode::FillPolygon
                    },
                    geometry_key(shape),
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    w,
                    col,
                    nums,
                );
                texts.push(
                    pts.iter()
                        .map(|p| format!("{},{}", p.x, p.y))
                        .collect::<Vec<_>>()
                        .join(" "),
                );
            }
            Shape::Path(path) => {
                // Same side-channel as Polygon, one token per segment (see `encode_path`).
                // The fill rule rides slot f; stroking ignores it.
                push(
                    if stroke {
                        OpCode::StrokePath
                    } else {
                        OpCode::FillPath
                    },
                    geometry_key(shape),
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    rule_bits(path.rule),
                    w,
                    col,
                    nums,
                );
                texts.push(encode_path(path));
            }
        }
    }
    /// A gradient applies to the next shape record, fill or stroke. Geometry per type rides
    /// slots a..d and the type discriminant slot f: one record shape, so every decoder keeps a
    /// single gradient code path.
    fn gradient_record(
        geo: [f64; 4],
        kind: f64,
        stops: &[(f64, Color)],
        nums: &mut Vec<f64>,
        texts: &mut Vec<String>,
    ) {
        push(
            OpCode::SetGradient,
            geo[0],
            geo[1],
            geo[2],
            geo[3],
            stops.len() as f64,
            kind,
            0.0,
            Color::CLEAR,
            nums,
        );
        texts.push(
            stops
                .iter()
                .map(|(o, c)| format!("{o},{:08x}", color_bits(*c) as u32))
                .collect::<Vec<_>>()
                .join(" "),
        );
    }
    let mut nums = Vec::with_capacity(ops.len() * 9);
    let mut texts = Vec::new();
    for op in ops {
        match op {
            DrawOp::Fill(shape, paint) => {
                // A gradient emits one kind-14 set-gradient record before its shape record;
                // the stops ride the texts channel as "offset,aarrggbb offset,aarrggbb …".
                // Geometry per type rides slots a..d, the type discriminant slot f: one
                // record shape, so every decoder keeps a single gradient code path.
                let col = match paint {
                    Paint::Solid(c) => *c,
                    Paint::Linear(g) => {
                        gradient_record(
                            [g.start.x, g.start.y, g.end.x, g.end.y],
                            0.0,
                            &g.stops,
                            &mut nums,
                            &mut texts,
                        );
                        // The gradient replaces the shape record's color, but it must be
                        // opaque, not clear: Skia-based decoders (Android Paint, OH_Drawing)
                        // modulate a shader by the paint alpha, so a clear slot would render
                        // the whole gradient invisible.
                        Color::WHITE
                    }
                    Paint::Radial(g) => {
                        gradient_record(
                            [g.center.x, g.center.y, g.radius, 0.0],
                            1.0,
                            &g.stops,
                            &mut nums,
                            &mut texts,
                        );
                        Color::WHITE
                    }
                };
                shape_record(false, shape, 0.0, col, &mut nums, &mut texts);
            }
            DrawOp::Stamp(st) => {
                // No copies means no drawing. Some native decoders use an empty point
                // buffer to mean an ordinary (unstamped) template, so omit the entire op.
                if st.at.is_empty() {
                    continue;
                }
                // A prefix record, then the coordinates, then the template shape record: the
                // "applies to the next record" rule the gradient, stroke style and font records
                // already follow, so a decoder needs no new kind of state, only one more slot in
                // the state it keeps. The template goes last because a decoder has to hold the
                // points before it can draw with them.
                //
                // The points are numbers on the numeric channel, not the texts channel a
                // polygon's points ride: this op exists for tens of thousands of them, and
                // formatting that many floats into a string every frame would cost more than
                // the individual ops it replaces.
                let col = match &st.paint {
                    Paint::Solid(c) => *c,
                    Paint::Linear(g) => {
                        gradient_record(
                            [g.start.x, g.start.y, g.end.x, g.end.y],
                            0.0,
                            &g.stops,
                            &mut nums,
                            &mut texts,
                        );
                        Color::WHITE
                    }
                    Paint::Radial(g) => {
                        gradient_record(
                            [g.center.x, g.center.y, g.radius, 0.0],
                            1.0,
                            &g.stops,
                            &mut nums,
                            &mut texts,
                        );
                        Color::WHITE
                    }
                };
                push(
                    OpCode::Stamp,
                    st.at.len() as f64,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    0.0,
                    Color::CLEAR,
                    &mut nums,
                );
                for chunk in st.at.chunks(4) {
                    // Written directly rather than through `push`: this is the one record whose
                    // last slot is a coordinate rather than a color, which is what lets four
                    // points fit with nothing wasted.
                    let mut rec = [
                        OpCode::StampPoints as i32 as f64,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                    ];
                    for (i, p) in chunk.iter().enumerate() {
                        rec[1 + i * 2] = p.x;
                        rec[2 + i * 2] = p.y;
                    }
                    nums.extend_from_slice(&rec);
                }
                match &st.stroke {
                    None => shape_record(false, &st.shape, 0.0, col, &mut nums, &mut texts),
                    Some(style) => {
                        stroke_style_record(style, &mut nums, &mut texts);
                        shape_record(true, &st.shape, style.width, col, &mut nums, &mut texts);
                    }
                }
            }
            DrawOp::Stroke(shape, paint, style) => {
                // A styled stroke emits one kind-18 record first, applying to the next stroke
                // only, the same "modifier record" shape the gradient uses, so decoders keep
                // one rule: consume, apply to the next shape record, reset.
                stroke_style_record(style, &mut nums, &mut texts);
                let col = match paint {
                    Paint::Solid(c) => *c,
                    Paint::Linear(g) => {
                        gradient_record(
                            [g.start.x, g.start.y, g.end.x, g.end.y],
                            0.0,
                            &g.stops,
                            &mut nums,
                            &mut texts,
                        );
                        Color::WHITE
                    }
                    Paint::Radial(g) => {
                        gradient_record(
                            [g.center.x, g.center.y, g.radius, 0.0],
                            1.0,
                            &g.stops,
                            &mut nums,
                            &mut texts,
                        );
                        Color::WHITE
                    }
                };
                shape_record(true, shape, style.width, col, &mut nums, &mut texts);
            }
            DrawOp::Clip(shape) => {
                // One record for every clip shape, with the shape kind in slot f and the
                // geometry in a..e; a path or polygon puts its points on the texts channel.
                // Encoding clips as a variant of `shape_record` instead would need a third
                // kind code per shape, which is five more numbers every decoder must learn.
                let (kind, geo, extra, payload): (f64, [f64; 4], f64, Option<String>) = match shape
                {
                    Shape::Rect(r) => (
                        0.0,
                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
                        0.0,
                        None,
                    ),
                    Shape::RoundedRect(r, rad) => (
                        1.0,
                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
                        *rad,
                        None,
                    ),
                    Shape::Ellipse(r) => (
                        2.0,
                        [r.origin.x, r.origin.y, r.size.width, r.size.height],
                        0.0,
                        None,
                    ),
                    // Slot a carries the geometry key for these two sub-kinds only. The other
                    // three put real geometry there, which is why the key rides the same slot
                    // the payload-bearing kinds leave empty.
                    Shape::Path(p) => (
                        3.0,
                        [geometry_key(shape), 0.0, 0.0, 0.0],
                        rule_bits(p.rule),
                        Some(encode_path(p)),
                    ),
                    Shape::Polygon(pts) => (
                        4.0,
                        [geometry_key(shape), 0.0, 0.0, 0.0],
                        0.0,
                        Some(
                            pts.iter()
                                .map(|p| format!("{},{}", p.x, p.y))
                                .collect::<Vec<_>>()
                                .join(" "),
                        ),
                    ),
                    // A clip to a line or an arc has no interior to clip to. Clipping to an
                    // empty region would blank everything after it, so clip to the shape's
                    // bounds instead: wrong in the same direction as no clip at all.
                    Shape::Line(..) | Shape::Arc { .. } => {
                        let r = shape.bounds();
                        (
                            0.0,
                            [r.origin.x, r.origin.y, r.size.width, r.size.height],
                            0.0,
                            None,
                        )
                    }
                };
                push(
                    OpCode::Clip,
                    geo[0],
                    geo[1],
                    geo[2],
                    geo[3],
                    extra,
                    kind,
                    0.0,
                    Color::CLEAR,
                    &mut nums,
                );
                if let Some(s) = payload {
                    texts.push(s);
                }
            }
            DrawOp::Text {
                text,
                at,
                size,
                color,
                anchor,
                font,
            } => {
                if *font != CanvasFont::default() {
                    push(
                        OpCode::SetFont,
                        f64::from(font.css_weight()),
                        f64::from(u8::from(font.italic)),
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        0.0,
                        Color::CLEAR,
                        &mut nums,
                    );
                    texts.push(
                        font.family_str()
                            .replace([FONT_LIST_FIELD, FONT_LIST_FAMILY], " "),
                    );
                }
                push(
                    OpCode::Text,
                    at.x,
                    at.y,
                    0.0,
                    0.0,
                    *size,
                    anchor.pack(),
                    0.0,
                    *color,
                    &mut nums,
                );
                texts.push(text.clone());
            }
            DrawOp::Image {
                image,
                rect,
                opacity,
            } => push(
                OpCode::Image,
                rect.origin.x,
                rect.origin.y,
                rect.size.width,
                rect.size.height,
                image.0 as f64,
                *opacity,
                0.0,
                Color::CLEAR,
                &mut nums,
            ),
            DrawOp::Save => push(
                OpCode::Save,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                Color::CLEAR,
                &mut nums,
            ),
            DrawOp::Restore => push(
                OpCode::Restore,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                0.0,
                Color::CLEAR,
                &mut nums,
            ),
            DrawOp::Concat(m) => push(
                OpCode::Concat,
                m.a,
                m.b,
                m.c,
                m.d,
                m.tx,
                m.ty,
                0.0,
                Color::CLEAR,
                &mut nums,
            ),
        }
    }
    (nums, texts)
}

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

    #[test]
    fn css_weights_round_trip_and_snap_to_the_nearest_rung() {
        for w in FontWeight::ALL {
            assert_eq!(FontWeight::from_css(w.css()), w);
        }
        assert_eq!(FontWeight::from_css(0), FontWeight::UltraLight);
        assert_eq!(FontWeight::from_css(350), FontWeight::Regular); // ties go heavier
        assert_eq!(FontWeight::from_css(649), FontWeight::Semibold);
        assert_eq!(FontWeight::from_css(1200), FontWeight::Black);
    }

    fn sans() -> FontFamilyInfo {
        FontFamilyInfo {
            family: "Day Sans".into(),
            faces: vec![
                FontFace {
                    name: "Regular".into(),
                    weight: FontWeight::Regular,
                    italic: false,
                },
                FontFace {
                    name: "Bold".into(),
                    weight: FontWeight::Bold,
                    italic: false,
                },
                FontFace {
                    name: "Light Italic".into(),
                    weight: FontWeight::Light,
                    italic: true,
                },
            ],
        }
    }

    #[test]
    fn face_for_prefers_the_slant_then_the_nearest_weight() {
        let f = sans();
        assert!(f.has_bold() && f.has_italic());
        assert_eq!(f.face_for(FontWeight::Bold, false).unwrap().name, "Bold");
        assert_eq!(
            f.face_for(FontWeight::Semibold, false).unwrap().name,
            "Bold"
        );
        assert_eq!(
            f.face_for(FontWeight::Medium, false).unwrap().name,
            "Regular"
        );
        let tie = FontFamilyInfo {
            family: "Tie".into(),
            faces: vec![
                FontFace {
                    name: "Light".into(),
                    weight: FontWeight::Light,
                    italic: false,
                },
                FontFace {
                    name: "Bold".into(),
                    weight: FontWeight::Bold,
                    italic: false,
                },
            ],
        };
        // Medium sits 200 from both; the heavier face wins the tie.
        assert_eq!(
            tie.face_for(FontWeight::Medium, false).unwrap().name,
            "Bold"
        );
        assert_eq!(
            f.face_for(FontWeight::Black, true).unwrap().name,
            "Light Italic"
        );
        let none = FontFamilyInfo {
            family: "Empty".into(),
            faces: vec![],
        };
        assert!(none.face_for(FontWeight::Regular, false).is_none());
        assert!(!none.has_bold());
    }

    #[test]
    fn the_shim_list_format_decodes_tolerantly() {
        let s = "Day Sans\u{1f}Regular\u{1f}400\u{1f}0\u{1f}\u{1f}700\u{1f}1\u{1f}Broken\u{1f}x\u{1f}0\
                 \u{1e}\u{1e}Day Mono\u{1f}Regular\u{1f}400\u{1f}0\u{1e}Faceless";
        let list = parse_font_list(s);
        assert_eq!(list.len(), 3);
        assert_eq!(list[0].family, "Day Sans");
        assert_eq!(list[0].faces.len(), 2, "the bad weight is skipped");
        assert_eq!(list[0].faces[1].name, "Bold Italic"); // synthesized from 700 + italic
        assert_eq!(list[1].family, "Day Mono");
        assert_eq!(list[2].family, "Faceless");
        assert!(list[2].faces.is_empty());
    }

    #[test]
    fn approximate_metrics_scale_with_size_and_length() {
        let m = TextMetrics::approximate("abc", 10.0);
        assert_eq!((m.width, m.height, m.ascent), (18.0, 12.0, 9.0));
        assert_eq!(TextMetrics::approximate("", 10.0).width, 0.0);
    }

    #[test]
    fn a_default_canvas_font_is_the_platform_face() {
        let f = CanvasFont::default();
        assert_eq!((f.family_str(), f.css_weight(), f.italic), ("", 0, false));
    }
}

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

    /// A 4×2 PNG: signature, then an IHDR whose width and height are big-endian.
    fn png(w: u32, h: u32) -> Vec<u8> {
        let mut v = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
        v.extend(13u32.to_be_bytes());
        v.extend(b"IHDR");
        v.extend(w.to_be_bytes());
        v.extend(h.to_be_bytes());
        v
    }

    /// A JPEG whose frame header sits behind one other segment, so the walk has to skip it.
    fn jpeg(w: u16, h: u16) -> Vec<u8> {
        let mut v = vec![0xFF, 0xD8]; // SOI
        v.extend([0xFF, 0xE0, 0x00, 0x04, 0x00, 0x00]); // APP0, length 4
        v.extend([0xFF, 0xC0, 0x00, 0x11, 0x08]); // SOF0, length 17, precision 8
        v.extend(h.to_be_bytes());
        v.extend(w.to_be_bytes());
        v
    }

    #[test]
    fn a_header_states_the_size_before_anything_decodes() {
        assert_eq!(ImageFormat::dimensions(&png(512, 512)), Some((512, 512)));
        assert_eq!(ImageFormat::dimensions(&png(1, 65535)), Some((1, 65535)));
        // The JPEG walk must step over the APP0 segment to reach the frame header.
        assert_eq!(ImageFormat::dimensions(&jpeg(640, 480)), Some((640, 480)));

        let mut gif = b"GIF89a".to_vec();
        gif.extend(320u16.to_le_bytes());
        gif.extend(240u16.to_le_bytes());
        assert_eq!(ImageFormat::dimensions(&gif), Some((320, 240)));

        // A top-down BMP states its height as a negative number; the size is still positive.
        let mut bmp = b"BM".to_vec();
        bmp.resize(18, 0);
        bmp.extend(64i32.to_le_bytes());
        bmp.extend((-32i32).to_le_bytes());
        assert_eq!(ImageFormat::dimensions(&bmp), Some((64, 32)));
    }

    #[test]
    fn a_truncated_or_unknown_header_answers_nothing_rather_than_a_guess() {
        assert_eq!(ImageFormat::dimensions(&[]), None);
        // The signature is there but the IHDR is not.
        assert_eq!(ImageFormat::dimensions(&png(8, 8)[..12]), None);
        // Not an image at all.
        assert_eq!(ImageFormat::dimensions(b"not an image"), None);
        // A JPEG that never reaches a frame header must not loop or invent a size.
        assert_eq!(
            ImageFormat::dimensions(&[0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x04, 0, 0]),
            None
        );
    }
}

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

    /// The wire codes are a frozen dense table: any gap, duplicate, or variant missing from
    /// `ALL` breaks a decoder somewhere, so it must break here first.
    #[test]
    fn op_codes_are_dense_and_round_trip() {
        for (i, code) in OpCode::ALL.into_iter().enumerate() {
            assert_eq!(code as i32, i as i32, "{code:?} broke wire density");
            assert_eq!(OpCode::from_wire(i as f64), Some(code));
        }
        assert_eq!(OpCode::from_wire(OpCode::ALL.len() as f64), None);
        assert_eq!(OpCode::from_wire(-1.0), None);
        assert_eq!(OpCode::from_wire(0.5), None);
    }

    /// Reference decode of a display list covering every op arm: the record stream must be
    /// whole 9-slot records of known codes, and the texts channel must carry exactly one
    /// entry per text-carrying record, in order: the contract every shim decoder assumes.
    #[test]
    fn encode_ops_emits_whole_records_and_matched_text_payloads() {
        let r = Rect::new(1.0, 2.0, 3.0, 4.0);
        let red = Color::rgb(1.0, 0.0, 0.0);
        let ops = vec![
            DrawOp::Fill(Shape::Rect(r), Paint::Solid(red)),
            DrawOp::Stroke(Shape::Rect(r), Paint::Solid(red), StrokeStyle::round(2.0)),
            DrawOp::Fill(Shape::RoundedRect(r, 5.0), Paint::Solid(red)),
            DrawOp::Fill(Shape::Ellipse(r), Paint::Solid(red)),
            // The documented asymmetry: a filled arc encodes as StrokeArc with width 0.
            DrawOp::Fill(
                Shape::Arc {
                    rect: r,
                    start_deg: 0.0,
                    sweep_deg: 90.0,
                },
                Paint::Solid(red),
            ),
            DrawOp::Stroke(
                Shape::Line(Point::new(0.0, 0.0), Point::new(9.0, 9.0)),
                Paint::Solid(red),
                StrokeStyle::width(1.0),
            ),
            DrawOp::Fill(
                Shape::Polygon(vec![
                    Point::new(0.0, 0.0),
                    Point::new(4.0, 0.0),
                    Point::new(2.0, 3.0),
                ]),
                Paint::Solid(red),
            ),
            DrawOp::Fill(
                Shape::Path(Path {
                    segs: vec![
                        PathSeg::Move(Point::new(0.0, 0.0)),
                        PathSeg::Line(Point::new(5.0, 5.0)),
                        PathSeg::Close,
                    ],
                    rule: FillRule::EvenOdd,
                }),
                Paint::Linear(LinearGradient::new(
                    UnitPoint::new(0.0, 0.0),
                    UnitPoint::new(1.0, 1.0),
                    vec![(0.0, red), (1.0, Color::WHITE)],
                )),
            ),
            DrawOp::Clip(Shape::Rect(r)),
            DrawOp::Clip(Shape::Polygon(vec![
                Point::new(0.0, 0.0),
                Point::new(1.0, 0.0),
                Point::new(0.0, 1.0),
            ])),
            DrawOp::Text {
                text: "hi".into(),
                at: Point::new(7.0, 8.0),
                size: 12.0,
                color: red,
                anchor: TextAnchor::LEADING,
                font: CanvasFont::default(),
            },
            DrawOp::Text {
                text: "bold".into(),
                at: Point::new(7.0, 8.0),
                size: 12.0,
                color: red,
                anchor: TextAnchor::CENTERED,
                font: CanvasFont {
                    family: Some("Day Sans".into()),
                    weight: Some(FontWeight::Bold),
                    italic: true,
                },
            },
            DrawOp::Save,
            DrawOp::Concat(Affine::IDENTITY),
            DrawOp::Restore,
            DrawOp::Image {
                image: BitmapId(7),
                rect: r,
                opacity: 0.5,
            },
        ];
        let (nums, texts) = encode_ops(&ops);
        assert_eq!(nums.len() % 9, 0, "partial record on the wire");

        let mut expected_texts = 0usize;
        let mut decoded = Vec::new();
        for rec in nums.chunks(9) {
            let code = OpCode::from_wire(rec[0])
                .unwrap_or_else(|| panic!("unknown op code {} on the wire", rec[0]));
            decoded.push(code);
            expected_texts += match code {
                OpCode::Text
                | OpCode::FillPolygon
                | OpCode::StrokePolygon
                | OpCode::SetGradient
                | OpCode::FillPath
                | OpCode::StrokePath
                | OpCode::StrokeStyle
                | OpCode::SetFont => 1,
                // Clip carries a payload only for its path (3) / polygon (4) sub-kinds.
                OpCode::Clip => usize::from(rec[6] == 3.0 || rec[6] == 4.0),
                _ => 0,
            };
        }
        assert_eq!(
            texts.len(),
            expected_texts,
            "texts channel out of step with the records that consume it"
        );
        // No payload may carry the transport separator.
        assert!(texts.iter().all(|t| !t.contains('\u{1f}')));

        let expected = {
            use OpCode::*;
            vec![
                FillRect,
                StrokeStyle, // ::round(2.0) is not plain, so the style modifier precedes
                StrokeRect,
                FillRrect,
                FillEllipse,
                StrokeArc, // the filled arc's stroke encoding…
                Line,
                FillPolygon,
                SetGradient, // gradient precedes its shape record
                FillPath,
                Clip,
                Clip,
                Text,
                SetFont, // a non-default font precedes its text record…
                Text,
                Save,
                Concat,
                Restore,
                Image,
            ]
        };
        assert_eq!(decoded, expected);
        // The bitmap id rides the numeric channel intact (an f64 holds a u64 id exactly well
        // past any id this process will mint), and nothing of an image reaches the texts channel.
        let img = nums
            .chunks(9)
            .find(|r| r[0] == OpCode::Image as i32 as f64)
            .expect("Image record");
        assert_eq!(&img[1..7], &[1.0, 2.0, 3.0, 4.0, 7.0, 0.5]);
        // …carrying the CSS weight and the slant, with the family on the texts channel.
        let font_rec = nums
            .chunks(9)
            .find(|r| r[0] == OpCode::SetFont as i32 as f64)
            .expect("SetFont record");
        assert_eq!(&font_rec[1..3], &[700.0, 1.0]);
        assert_eq!(texts.iter().filter(|t| *t == "Day Sans").count(), 1);
        // …with width 0, per the documented asymmetry.
        let arc = nums
            .chunks(9)
            .find(|r| r[0] == OpCode::StrokeArc as i32 as f64);
        assert_eq!(arc.map(|r| r[7]), Some(0.0));
        // A gradient-filled shape's color slot is opaque white, never clear (Skia decoders
        // modulate the shader by it).
        let path_rec = nums
            .chunks(9)
            .find(|r| r[0] == OpCode::FillPath as i32 as f64);
        assert_eq!(
            path_rec.map(|r| r[8] as u32),
            Some(0xFFFF_FFFF),
            "gradient shape record must carry opaque white"
        );
    }

    #[test]
    fn variable_length_geometry_carries_a_content_key() {
        let path = |x: f64| {
            Shape::Path(Path {
                segs: vec![
                    PathSeg::Move(Point::new(x, 0.0)),
                    PathSeg::Cubic(
                        Point::new(1.0, 1.0),
                        Point::new(2.0, 2.0),
                        Point::new(3.0, 3.0),
                    ),
                    PathSeg::Close,
                ],
                rule: FillRule::NonZero,
            })
        };
        let poly = Shape::Polygon(vec![
            Point::new(0.0, 0.0),
            Point::new(1.0, 0.0),
            Point::new(0.0, 1.0),
        ]);

        // Equal geometry keys equal though the two were built separately. The key exists for
        // this: a draw closure rebuilds its paths from scratch on every frame.
        assert_eq!(geometry_key(&path(0.0)), geometry_key(&path(0.0)));
        assert_ne!(geometry_key(&path(0.0)), geometry_key(&path(1.0)));
        // The fill rule decides what the path draws, so it belongs to the key.
        let even_odd = Shape::Path(Path {
            segs: match path(0.0) {
                Shape::Path(p) => p.segs,
                _ => unreachable!(),
            },
            rule: FillRule::EvenOdd,
        });
        assert_ne!(geometry_key(&path(0.0)), geometry_key(&even_odd));
        // A polygon and a path decode to different geometry and never share an entry.
        assert_ne!(geometry_key(&poly), geometry_key(&path(0.0)));
        // Fixed-size shapes keep 0: their geometry rides the record's own slots.
        assert_eq!(
            geometry_key(&Shape::Rect(Rect::new(0.0, 0.0, 1.0, 1.0))),
            0.0
        );
        // And a key survives an f64 wire slot exactly, which is what the 53-bit mask buys.
        let k = geometry_key(&path(0.0));
        assert!(
            k > 0.0 && k < (1u64 << 53) as f64 && k.fract() == 0.0,
            "{k}"
        );

        // It reaches the wire in slot a, for exactly the ops whose payload rides the texts
        // channel, and never displaces geometry that is already there.
        let (nums, _) = encode_ops(&[
            DrawOp::Fill(path(0.0), Paint::Solid(Color::WHITE)),
            DrawOp::Fill(poly.clone(), Paint::Solid(Color::WHITE)),
            DrawOp::Clip(path(0.0)),
            DrawOp::Clip(Shape::Rect(Rect::new(1.0, 2.0, 3.0, 4.0))),
        ]);
        let slot_a = |code: OpCode| {
            nums.chunks(9)
                .find(|r| r[0] == code as i32 as f64)
                .unwrap_or_else(|| panic!("no {code:?} record"))[1]
        };
        assert_eq!(slot_a(OpCode::FillPath), geometry_key(&path(0.0)));
        assert_eq!(slot_a(OpCode::FillPolygon), geometry_key(&poly));
        let clips: Vec<&[f64]> = nums
            .chunks(9)
            .filter(|r| r[0] == OpCode::Clip as i32 as f64)
            .collect();
        assert_eq!(clips[0][1], geometry_key(&path(0.0)), "path clip keys");
        assert_eq!(
            &clips[1][1..5],
            &[1.0, 2.0, 3.0, 4.0],
            "a rect clip still puts its geometry in a..d"
        );
    }
}

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

    fn bold(range: std::ops::Range<usize>) -> TextRun {
        TextRun::font(
            range,
            FontSpec {
                style: Font::Body,
                weight: Some(FontWeight::Bold),
                ..Default::default()
            },
        )
    }

    #[test]
    fn plain_text_is_escaped_in_both_dialects() {
        // The case a translated string will find: markup metacharacters in the content.
        let text = "5 < 6 & \"quoted\" <b>not bold</b>";
        for d in [MarkupDialect::Pango, MarkupDialect::QtHtml] {
            let m = runs_to_markup(text, &[], d, 16.0);
            assert!(!m.contains("<b>"), "content tag survived into markup: {m}");
            assert!(m.contains("&lt;b&gt;"), "{m}");
            assert!(m.contains("&amp;"), "{m}");
            assert!(m.contains("5 &lt; 6"), "{m}");
        }
    }

    #[test]
    fn a_styled_run_is_wrapped_and_its_text_escaped() {
        let text = "a <b> c";
        let m = runs_to_markup(text, &[bold(2..5)], MarkupDialect::Pango, 16.0);
        assert_eq!(m, "a <b>&lt;b&gt;</b> c");
    }

    #[test]
    fn color_and_monospace_differ_per_dialect() {
        let text = "code";
        let run = TextRun {
            range: 0..4,
            font: FontSpec {
                style: Font::Body,
                monospace: true,
                ..Default::default()
            },
            color: Some(Color::rgb(1.0, 0.0, 0.0)),
            ..TextRun::default()
        };
        let pango = runs_to_markup(text, std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
        assert!(pango.contains("foreground=\"#ff0000\""), "{pango}");
        assert!(pango.contains("font_family=\"monospace\""), "{pango}");
        let qt = runs_to_markup(
            text,
            std::slice::from_ref(&run),
            MarkupDialect::QtHtml,
            16.0,
        );
        assert!(qt.contains("color:#ff0000"), "{qt}");
        // Qt takes its fixed face from <code>: a `font-family:monospace` style attribute
        // renders proportional (observed on Qt 6.11).
        assert!(qt.contains("<code>") && qt.contains("</code>"), "{qt}");
    }

    #[test]
    fn the_new_attributes_reach_both_dialects() {
        let run = TextRun {
            range: 0..2,
            font: FontSpec::default().scaled(1.5),
            background: Some(Color::rgb(0.0, 1.0, 0.0)),
            underline: Underline::Single,
            ..TextRun::default()
        };
        let pango = runs_to_markup("hi", std::slice::from_ref(&run), MarkupDialect::Pango, 16.0);
        assert!(pango.contains("background=\"#00ff00\""), "{pango}");
        // Pango takes an absolute size in 1/1024 pt (16 pt base × 1.5 = 24 pt), because the
        // relative attributes are Pango 1.50's and an unknown attribute empties the whole label.
        assert!(pango.contains("size=\"24576\""), "{pango}");
        assert!(pango.contains("<u>hi</u>"), "{pango}");
        let qt = runs_to_markup(
            "hi",
            std::slice::from_ref(&run),
            MarkupDialect::QtHtml,
            16.0,
        );
        assert!(qt.contains("background-color:#00ff00"), "{qt}");
        // Qt takes points: 16 pt base × 1.5 (observed; its CSS subset ignores a percentage).
        assert!(qt.contains("font-size:24pt"), "{qt}");
        assert!(qt.contains("<u>hi</u>"), "{qt}");
    }

    #[test]
    fn a_link_target_is_escaped_too() {
        // A URL carrying `&` between query parameters is ordinary, and unescaped it truncates
        // the attribute and swallows the rest of the label.
        let text = "docs";
        let run = TextRun {
            range: 0..4,
            link: Some("https://x.dev/?a=1&b=2".into()),
            ..TextRun::default()
        };
        let m = runs_to_markup(text, &[run], MarkupDialect::Pango, 16.0);
        assert!(m.contains("a=1&amp;b=2"), "{m}");
    }

    #[test]
    fn tags_nest_and_close_in_reverse() {
        let run = TextRun {
            range: 0..2,
            font: FontSpec {
                style: Font::Body,
                weight: Some(FontWeight::Bold),
                italic: true,
                ..Default::default()
            },
            strikethrough: true,
            link: Some("u".into()),
            ..TextRun::default()
        };
        let m = runs_to_markup("hi", &[run], MarkupDialect::Pango, 16.0);
        assert_eq!(m, "<a href=\"u\"><b><i><s>hi</s></i></b></a>");
    }

    #[test]
    fn runs_out_of_bounds_are_skipped_not_panicked() {
        // `runs_are_valid` rejects these upstream; this is the belt-and-braces path.
        let m = runs_to_markup("hi", &[bold(0..99)], MarkupDialect::Pango, 16.0);
        assert_eq!(m, "hi");
    }

    #[test]
    fn validation_catches_the_four_ways_runs_go_wrong() {
        let text = "héllo";
        assert!(runs_are_valid(text, &[bold(0..1)]).is_ok());
        // Overlapping.
        assert!(runs_are_valid(text, &[bold(0..3), bold(2..4)]).is_err());
        // Past the end.
        assert!(runs_are_valid(text, &[bold(0..99)]).is_err());
        // Inverted. Built from parts, since a literal `3..1` is a clippy error in its own right.
        let (hi, lo) = (3, 1);
        assert!(runs_are_valid(text, &[bold(hi..lo)]).is_err());
        // Splitting the 2-byte `é`.
        assert!(runs_are_valid(text, &[bold(0..2)]).is_err());
    }
}

#[cfg(test)]
mod route_of_url_tests {
    use super::route_of_url;

    #[test]
    fn strips_the_scheme_and_keeps_route_and_params() {
        assert_eq!(
            route_of_url("notes://mail/inbox?hint=x"),
            "mail/inbox?hint=x"
        );
        assert_eq!(route_of_url("notes://home"), "home");
        // No scheme: already a route, unchanged.
        assert_eq!(route_of_url("mail/inbox"), "mail/inbox");
        assert_eq!(route_of_url(""), "");
        // Percent-encoding passes through; the route parser decodes, not this mapping.
        assert_eq!(route_of_url("n://a/b%2Fc?q=1%202"), "a/b%2Fc?q=1%202");
    }
}

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

    /// Every built-in round-trips through its wire key, and the keys are unique. Guards the
    /// `builtin_kinds!` expansion: a copy-paste slip in the table would alias two kinds.
    #[test]
    fn keys_round_trip_and_are_unique() {
        let mut seen = std::collections::HashSet::new();
        for &b in Builtin::ALL {
            assert_eq!(Builtin::from_key(b.key()), Some(b), "{b:?} key round-trip");
            assert!(seen.insert(b.key()), "duplicate key {:?}", b.key());
            assert!(
                b.key().starts_with("day."),
                "built-in {b:?} must use the reserved `day.` prefix"
            );
        }
    }

    /// The `kinds::*` constants are the enum's keys, so the two spellings cannot drift.
    #[test]
    fn kinds_constants_match_the_enum() {
        assert_eq!(kinds::LABEL, Builtin::Label.key());
        assert_eq!(kinds::LIST_CELL, Builtin::ListCell.key());
        assert_eq!(kinds::COVER, Builtin::Cover.key());
        assert_eq!(kinds::INSPECTOR, Builtin::Inspector.key());
        assert_eq!(kinds::TREE, Builtin::Tree.key());
        // 19 after `Tabs`/`TabsPage` retired (the tab bar is a NAV presentation, not a kind),
        // +2 for the inspector split and its panes (docs/inspector.md), +1 for the tree
        // (docs/tree.md).
        assert_eq!(Builtin::ALL.len(), 25);
    }

    /// An extension piece's kind is not a built-in.
    #[test]
    fn extension_kinds_are_not_builtin() {
        assert_eq!(Builtin::from_key("acme.combobox"), None);
        assert_eq!(Builtin::from_key("day.not_a_real_kind"), None);
    }
}

#[cfg(test)]
mod locale_tests {
    /// POSIX locale strings are not BCP-47 tags, and "C" is not a language; that difference is
    /// the job of `posix_locale_hints` (§12.2).
    #[test]
    fn posix_hints_parse_and_drop_the_c_locale() {
        // The parsing is exercised through the same normalization the function applies.
        let normalize = |v: &str| v.split('.').next().unwrap_or(v).replace('_', "-");
        assert_eq!(normalize("fr_FR.UTF-8"), "fr-FR");
        assert_eq!(normalize("en_US"), "en-US");
        assert_eq!(normalize("C"), "C");
        // A real read never panics whatever this host's environment holds.
        let hints = super::posix_locale_hints();
        assert!(
            hints
                .iter()
                .all(|h| !h.is_empty() && h != "C" && h != "POSIX")
        );
    }
}

#[cfg(test)]
mod sidetable_tests {
    use super::sidetable::{SideTable, sweep};
    use std::cell::Cell;
    use std::rc::Rc;

    /// The registry exists so that one `sweep(key)` clears every table without any
    /// table needing its own line in a backend's `release()`.
    #[test]
    fn sweep_clears_every_registered_table_and_runs_teardowns() {
        let torn = Rc::new(Cell::new(0u32));
        let t2 = torn.clone();
        let plain: SideTable<&'static str> = SideTable::new();
        let hooked: SideTable<u32> = SideTable::with_teardown(move |_| t2.set(t2.get() + 1));

        plain.insert(7, "a");
        hooked.insert(7, 1);
        hooked.insert(8, 2);
        sweep(7);
        assert!(!plain.contains(7));
        assert!(!hooked.contains(7), "swept from every table");
        assert!(hooked.contains(8), "other keys untouched");
        assert_eq!(torn.get(), 1, "teardown ran for the swept value");

        // remove() runs the teardown too; take() bypasses it for ownership transfer.
        hooked.remove(8);
        assert_eq!(torn.get(), 2);
        hooked.insert(9, 3);
        assert_eq!(hooked.take(9), Some(3));
        assert_eq!(torn.get(), 2, "take() skips the hook");
    }

    #[test]
    fn contain_returns_default_on_panic() {
        let ok = super::ffi_guard::contain(0i32, || 5);
        assert_eq!(ok, 5);
        let prev = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let contained = super::ffi_guard::contain(-1i32, || panic!("boom"));
        std::panic::set_hook(prev);
        assert_eq!(contained, -1, "the panic must not escape the guard");
    }
}

#[cfg(test)]
mod cursor_tests {
    use super::Cursor;

    /// Every named cursor has a distinct CSS keyword, and `NAMED` lists each exactly once: the
    /// gallery and every backend's table key on the keyword.
    #[test]
    fn named_cursors_have_distinct_css_names() {
        let mut seen = std::collections::BTreeSet::new();
        for c in Cursor::NAMED.iter() {
            assert!(
                seen.insert(c.css_name().to_string()),
                "duplicate: {}",
                c.css_name()
            );
            assert!(!matches!(c, Cursor::Native(_)));
        }
        assert_eq!(seen.len(), Cursor::NAMED.len());
        assert_eq!(Cursor::native("dragCopy").css_name(), "dragCopy");
        assert_eq!(Cursor::default(), Cursor::Default);
    }
}

#[cfg(test)]
mod text_anchor_tests {
    /// The anchor arithmetic every backend repeats. A drawing whose text lands in the wrong
    /// corner is a per-backend bug that only a screenshot catches, so the shared definition is
    /// pinned here and each shim is written to match it.
    #[test]
    fn text_anchor_offsets_place_the_line_box() {
        use crate::props::TextAlign;
        use crate::{TextAnchor, TextVAlign};
        // A 40-wide, 20-tall line box whose baseline sits 16 below its top.
        let (w, h, asc) = (40.0, 20.0, 16.0);
        let at = |ha, va| TextAnchor { h: ha, v: va }.offset(w, h, asc);

        // The default is the drawing origin itself, every backend's native "draw here".
        assert_eq!(at(TextAlign::Leading, TextVAlign::Top), (0.0, 0.0));
        assert_eq!(TextAnchor::default(), TextAnchor::LEADING);
        // Horizontal: the box's leading edge, its middle, its trailing edge.
        assert_eq!(at(TextAlign::Center, TextVAlign::Top).0, -20.0);
        assert_eq!(at(TextAlign::Trailing, TextVAlign::Top).0, -40.0);
        // Vertical: top, middle, the baseline itself, bottom.
        assert_eq!(at(TextAlign::Leading, TextVAlign::Middle).1, -10.0);
        assert_eq!(at(TextAlign::Leading, TextVAlign::Baseline).1, -16.0);
        assert_eq!(at(TextAlign::Leading, TextVAlign::Bottom).1, -20.0);
        // The two named placements are the ones the two-variant enum used to have.
        assert_eq!(TextAnchor::CENTERED.offset(w, h, asc), (-20.0, -10.0));
        assert_eq!(TextAnchor::TRAILING.offset(w, h, asc), (-40.0, 0.0));
    }

    /// The wire code the serializing backends (qt, xaml, arkui, android, web) decode by hand.
    #[test]
    fn text_anchor_packs_into_one_slot_and_round_trips() {
        use crate::props::TextAlign;
        use crate::{TextAnchor, TextVAlign};
        let mut seen = std::collections::BTreeSet::new();
        for h in [TextAlign::Leading, TextAlign::Center, TextAlign::Trailing] {
            for v in [
                TextVAlign::Top,
                TextVAlign::Middle,
                TextVAlign::Baseline,
                TextVAlign::Bottom,
            ] {
                let a = TextAnchor { h, v };
                let code = a.pack();
                assert!(
                    (0.0..=11.0).contains(&code),
                    "{code} outside the packed range"
                );
                assert!(seen.insert(code as u64), "two anchors share code {code}");
                assert_eq!(TextAnchor::unpack(code), a);
            }
        }
        assert_eq!(seen.len(), 12);
        // The shims decode as `h = code / 4`, `v = code % 4` in integer arithmetic.
        assert_eq!(TextAnchor::LEADING.pack(), 0.0);
        assert_eq!(TextAnchor::CENTERED.pack(), 5.0);
        // Junk answers the default rather than failing inside a native draw callback.
        assert_eq!(TextAnchor::unpack(-3.0), TextAnchor::LEADING);
        assert_eq!(TextAnchor::unpack(99.0), TextAnchor::unpack(11.0));
    }

    /// The two shapes a backend's own metrics arrive in. Both land on the same contract: the line
    /// box's top-leading corner is the origin, and `ink` is relative to it.
    #[test]
    fn metrics_convert_from_a_backends_own_shape() {
        use crate::{Rect, TextMetrics};
        // Baseline-relative, y up-negative; Core Text, Skia and Qt all report like this.
        let m = TextMetrics::from_baseline(
            40.0,
            16.0,
            4.0,
            11.0,
            // Ink starting 1 right of the origin, from 11 above the baseline to 2 below it.
            Rect::new(1.0, -11.0, 38.0, 13.0),
        );
        assert_eq!(
            (m.width, m.height, m.ascent, m.cap_height),
            (40.0, 20.0, 16.0, 11.0)
        );
        // Shifted down by the ascent: the ink now starts 5 below the line box's top, which is
        // where a cap begins in a slot whose baseline is at 16.
        assert_eq!(m.ink, Rect::new(1.0, 5.0, 38.0, 13.0));
        assert_eq!(m.ascent - m.cap_height, m.ink.origin.y);

        // The eight-slot wire form is already line-box-relative and passes straight through.
        let w = TextMetrics::from_slots(&[40.0, 20.0, 16.0, 11.0, 1.0, 5.0, 38.0, 13.0]);
        assert_eq!(w, m);
    }

    /// The fallback must be usable, not merely present: a caller frames text with it on a toolkit
    /// that cannot measure, and every relation it relies on has to hold.
    #[test]
    fn the_approximation_is_internally_consistent() {
        use crate::TextMetrics;
        let m = TextMetrics::approximate("Agy", 20.0);
        assert!(m.ascent < m.height, "the baseline sits inside the line box");
        assert!(
            m.cap_height < m.ascent,
            "caps do not reach above the ascent"
        );
        // The ink box is the whole line box: a superset, so an overlap test using it can only be
        // too cautious. Never a claim to be tighter than it knows.
        assert_eq!(m.ink.origin.x, 0.0);
        assert_eq!(m.ink.origin.y, 0.0);
        assert_eq!(m.ink.size.width, m.width);
        assert_eq!(m.ink.size.height, m.height);
        // Empty text still answers a usable (zero-width, full-height) slot.
        let e = TextMetrics::approximate("", 20.0);
        assert_eq!(e.width, 0.0);
        assert!(e.height > 0.0);
    }
}

#[cfg(test)]
mod cap_list_tests {
    use super::Cap;

    #[test]
    fn every_capability_is_listed_once_in_its_place() {
        for (i, cap) in Cap::ALL.iter().enumerate() {
            assert_eq!(cap.ordinal(), i, "{cap:?} is out of place in Cap::ALL");
        }
    }
}