native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
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
use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::rc::Rc;
use std::sync::Arc;

use crate::access::AccessibilitySpec;
use crate::artprov::IconRole;
use crate::error::{GuiError, GuiResult};
use crate::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
use crate::toolbar::{ToolbarItem, ToolbarOrientation};

/// Opaque identifier for a widget instance managed by [`crate::Ui`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WidgetId(pub u64);

/// Host GPU surfaces that a backend can expose to an external renderer.
///
/// These flags describe host-surface integration, not the presence of a
/// Vulkan SDK, device, or driver. `raw_window_handle` is true only when the
/// backend returns descriptors compatible with `raw-window-handle`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GpuSurfaceCapabilities {
    pub vulkan_surface: bool,
    pub metal_surface: bool,
    pub directx_surface: bool,
    pub raw_window_handle: bool,
    pub diagnostic_placeholder: bool,
    pub headless_emulation: bool,
}

impl GpuSurfaceCapabilities {
    /// Returns a capability set with all flags cleared.
    pub const fn none() -> Self {
        Self {
            vulkan_surface: false,
            metal_surface: false,
            directx_surface: false,
            raw_window_handle: false,
            diagnostic_placeholder: false,
            headless_emulation: false,
        }
    }

    /// Returns a capability set with every currently defined flag enabled.
    pub const fn all() -> Self {
        Self {
            vulkan_surface: true,
            metal_surface: true,
            directx_surface: true,
            raw_window_handle: true,
            diagnostic_placeholder: true,
            headless_emulation: true,
        }
    }

    /// Tests a standard GPU-surface capability identifier. Unknown identifiers
    /// return `false`.
    pub fn supports(self, capability: &str) -> bool {
        match capability {
            "vulkan_surface" => self.vulkan_surface,
            "metal_surface" => self.metal_surface,
            "directx_surface" => self.directx_surface,
            "raw_window_handle" => self.raw_window_handle,
            "diagnostic_placeholder" => self.diagnostic_placeholder,
            "headless_emulation" => self.headless_emulation,
            "gpu_degradation_fallback" => self.diagnostic_placeholder || self.headless_emulation,
            "gpu_surface" => self.vulkan_surface || self.metal_surface || self.directx_surface,
            _ => false,
        }
    }
}

impl Default for GpuSurfaceCapabilities {
    fn default() -> Self {
        Self::none()
    }
}

/// Behavior requested when a Vulkan canvas cannot obtain a host surface.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum GpuDegradationPolicy {
    /// Return `GuiError::UnsupportedCapability("vulkan_surface")`.
    #[default]
    StrictFail,
    /// Substitute a diagnostic placeholder when the backend implements it.
    DiagnosticPlaceholder,
    /// Substitute a 2D canvas when the backend implements it.
    Canvas2DFallback,
}

/// Cross-platform widget kinds supported by the abstraction layer.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WidgetKind {
    Window,
    Container,
    Label,
    Button,
    #[cfg(feature = "widgets-choice")]
    RadioButton,
    #[cfg(feature = "widgets-range")]
    Slider,
    #[cfg(feature = "widgets-range")]
    SpinBox,
    #[cfg(feature = "widgets-containers")]
    Separator,
    #[cfg(feature = "widgets-containers")]
    GroupBox,
    #[cfg(feature = "widgets-containers")]
    Tabs,
    #[cfg(feature = "widgets-media")]
    Image,
    #[cfg(feature = "widgets-pickers")]
    DatePicker,
    #[cfg(feature = "widgets-text")]
    LinkLabel,
    #[cfg(feature = "widgets-data")]
    ListView,
    #[cfg(feature = "widgets-data")]
    TreeView,
    #[cfg(feature = "widgets-containers")]
    SplitPane,
    #[cfg(feature = "widgets-pickers")]
    FileChooserDialog,
    #[cfg(feature = "widgets-containers")]
    AlertDialog,
    #[cfg(feature = "widgets-text")]
    TextInput,
    #[cfg(feature = "widgets-text")]
    TextArea,
    #[cfg(feature = "widgets-canvas")]
    VulkanCanvas,
    #[cfg(feature = "widgets-canvas")]
    /// Native Apple Metal rendering surface backed by `CAMetalLayer` on macOS.
    MetalCanvas,
    #[cfg(feature = "widgets-choice")]
    Checkbox,
    #[cfg(feature = "widgets-choice")]
    ComboBox,
    #[cfg(feature = "widgets-range")]
    ProgressBar,
    #[cfg(feature = "widgets-data")]
    DataList,
    #[cfg(feature = "widgets-data")]
    DataGrid,
    #[cfg(feature = "widgets-canvas")]
    Canvas,
    /// Portable colour picker; the native dialog mappings land in
    /// a later step, so lanes without them report the typed unsupported error.
    #[cfg(feature = "widgets-pickers")]
    ColorDialog,
    /// Portable font picker; the native dialog mappings land in
    /// a later step, so lanes without them report the typed unsupported error.
    #[cfg(feature = "widgets-pickers")]
    FontDialog,
    /// Portable toolbar: stable tool ids, separators, checkable and
    /// radio tools, and dropdown requests. The native compositions land in
    /// a later step, so lanes without them report the typed unsupported error.
    Toolbar,
    /// Portable calendar month grid.
    #[cfg(feature = "widgets-pickers")]
    Calendar,
    /// Editable text widget with styled runs.
    #[cfg(feature = "widgets-text")]
    RichText,
    /// Multiple selection choice list or dropdown.
    #[cfg(feature = "widgets-choice")]
    MultiSelect,
}

/// Every [`WidgetKind`] variant, in declaration order.
///
/// The applicability rows of [`WidgetProperty`] and the table-driven
/// guard-matrix test walk this list, so adding a kind here makes every row
/// re-considered instead of silently stale.
pub const ALL_KINDS: &[WidgetKind] = &[
    WidgetKind::Window,
    WidgetKind::Container,
    WidgetKind::Label,
    WidgetKind::Button,
    #[cfg(feature = "widgets-choice")]
    WidgetKind::RadioButton,
    #[cfg(feature = "widgets-range")]
    WidgetKind::Slider,
    #[cfg(feature = "widgets-range")]
    WidgetKind::SpinBox,
    #[cfg(feature = "widgets-containers")]
    WidgetKind::Separator,
    #[cfg(feature = "widgets-containers")]
    WidgetKind::GroupBox,
    #[cfg(feature = "widgets-containers")]
    WidgetKind::Tabs,
    #[cfg(feature = "widgets-media")]
    WidgetKind::Image,
    #[cfg(feature = "widgets-pickers")]
    WidgetKind::DatePicker,
    #[cfg(feature = "widgets-text")]
    WidgetKind::LinkLabel,
    #[cfg(feature = "widgets-data")]
    WidgetKind::ListView,
    #[cfg(feature = "widgets-data")]
    WidgetKind::TreeView,
    #[cfg(feature = "widgets-containers")]
    WidgetKind::SplitPane,
    #[cfg(feature = "widgets-pickers")]
    WidgetKind::FileChooserDialog,
    #[cfg(feature = "widgets-containers")]
    WidgetKind::AlertDialog,
    #[cfg(feature = "widgets-text")]
    WidgetKind::TextInput,
    #[cfg(feature = "widgets-text")]
    WidgetKind::TextArea,
    #[cfg(feature = "widgets-canvas")]
    WidgetKind::VulkanCanvas,
    #[cfg(feature = "widgets-canvas")]
    WidgetKind::MetalCanvas,
    #[cfg(feature = "widgets-choice")]
    WidgetKind::Checkbox,
    #[cfg(feature = "widgets-choice")]
    WidgetKind::ComboBox,
    #[cfg(feature = "widgets-range")]
    WidgetKind::ProgressBar,
    #[cfg(feature = "widgets-data")]
    WidgetKind::DataList,
    #[cfg(feature = "widgets-data")]
    WidgetKind::DataGrid,
    #[cfg(feature = "widgets-canvas")]
    WidgetKind::Canvas,
    #[cfg(feature = "widgets-pickers")]
    WidgetKind::ColorDialog,
    #[cfg(feature = "widgets-pickers")]
    WidgetKind::FontDialog,
    WidgetKind::Toolbar,
    #[cfg(feature = "widgets-pickers")]
    WidgetKind::Calendar,
    #[cfg(feature = "widgets-text")]
    WidgetKind::RichText,
    #[cfg(feature = "widgets-choice")]
    WidgetKind::MultiSelect,
];

/// A kind-restricted widget property, shared by [`crate::Ui`] and the backends.
///
/// `WidgetSpec` is a flat struct, so a property that only makes sense for some
/// kinds (say `range` on a `Slider`) is rejected at runtime with
/// [`GuiError::UnsupportedWidget`]. This enum single-sources those rejections —
/// ADR decision 1-2 in the `adr-widgetspec-typing.md` decision record: every `Ui::set_*` guard
/// and backend kind guard asks [`WidgetProperty::supports`] (through
/// [`WidgetSpec::ensure_property`]) instead of repeating `matches!` lists, and
/// the table-driven guard-matrix test asserts that every setter rejects every
/// kind outside its row with the typed error.
///
/// Two families stay out of the table on purpose:
///
/// - universally applicable properties (`text`, `size`, `position`,
///   `background_color`, `enabled`, `focusable`, `tooltip`, accessibility
///   metadata) carry no kind restriction to encode, and
/// - per-lane mapping limits (Cocoa's control-scoped `enabled`/`focusable`,
///   the theme-override text kinds) are backend capabilities, not model
///   applicability. A lane that cannot map a valid property reports
///   [`GuiError::UnsupportedCapability`] rather than a kind error.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WidgetProperty {
    /// Checked state (`Checkbox`, `RadioButton`).
    Checked,
    /// Numeric value (`Slider`, `SpinBox`, `ProgressBar`).
    Value,
    /// Numeric `(min, max)` range (`Slider`, `SpinBox`).
    Range,
    /// Numeric step (`Slider`, `SpinBox`).
    Step,
    /// Selected item/page index (`Tabs`, `ComboBox`, `DataList`, `ListView`).
    SelectedIndex,
    /// Tab page labels (`Tabs`).
    TabItems,
    /// Multi-selection indices (`ListView`, `DataList`, `TreeView`).
    SelectedIndices,
    /// Row drag source/drop target flags (`ListView`, `DataList`, `DataGrid`,
    /// `TreeView`).
    RowDrag,
    /// Row strings (`DataList`, `ListView`).
    DataListItems,
    /// Column headers for the columned list contract (`ListView`).
    ListViewColumns,
    /// Row cells for the columned list contract (`ListView`).
    ListViewRows,
    /// Row-major cell values (`DataGrid`).
    DataGridRows,
    /// Virtual data model (`DataGrid`).
    DataGridModel,
    /// Per-row height override (`DataGrid`).
    DataGridRowHeight,
    /// Per-column width override (`DataGrid`).
    DataGridColWidth,
    /// Frozen row/column counts (`DataGrid`).
    DataGridFrozenPanes,
    /// Cell selection overrides (`DataGrid`).
    DataGridSelection,
    /// Hierarchical items (`TreeView`).
    TreeItems,
    /// Alert severity (`AlertDialog`).
    AlertLevel,
    /// Raster image source (`Image`).
    ImageSource,
    /// Image scaling mode (`Image`).
    ImageFit,
    /// Button art: optional stock-art role rendered beside the label
    /// (`Button`, `FileChooserDialog`).
    ButtonIcon,
    /// File chooser pick mode (`FileChooserDialog`).
    FileChooserMode,
    /// Colour-dialog preferences (`ColorDialog`).
    ColorDialogData,
    /// Font-dialog preferences (`FontDialog`).
    FontDialogData,
    /// Toolbar tools and separators (`Toolbar`).
    ToolbarItems,
    /// Toolbar stacking orientation (`Toolbar`).
    ToolbarOrientation,
    /// Date value (`DatePicker`).
    DateValue,
    /// Link URL (`LinkLabel`).
    LinkUrl,
    /// Text selection range in characters (`TextInput`, `TextArea`).
    TextSelection,
    /// Text completion/suggestion items (`TextInput`).
    TextCompletion,
    /// Placeholder/hint text (`TextInput`).
    PlaceholderText,
    /// Container stacking direction (`Container`, `GroupBox`, `SplitPane`).
    ContainerDirection,
    /// Container wrapping mode (`Container`, `GroupBox`, `SplitPane`).
    ContainerWrap,
    /// Container scroll flags (`Container`, `GroupBox`, `SplitPane`).
    ContainerScroll,
    /// Spacing between flow children (`Container`, `GroupBox`).
    ContainerGap,
    /// Inset between the container edges and its flow children (`Container`,
    /// `GroupBox`).
    ContainerPadding,
    /// Retained drawing scene (`Canvas`).
    CanvasScene,
    /// Raster paint surface (`Canvas`).
    CanvasSurface,
    /// Close-request interception (`Window`).
    CloseGuard,
    /// Declarative layout root (`Window`).
    LayoutRoot,
    /// Window event callbacks (`Window`).
    WindowCallback,
    /// Backend-native Vulkan handle (`VulkanCanvas`).
    NativeHandle,
    /// Built-in Vulkan demo scene (`VulkanCanvas`).
    DrawDemoCube,
    /// Clipboard copy sources (`DataList`, `ListView`, `DataGrid`, `TextInput`,
    /// `TextArea`, `Label`).
    CopyToClipboard,
    /// Clipboard paste targets (`DataList`, `ListView`, `DataGrid`,
    /// `TextInput`, `TextArea`, `Label`).
    PasteFromClipboard,
    /// Keyed row updates (`DataList`, `ListView`, `DataGrid`).
    KeyedRows,
    /// Selection clearing on row widgets (`DataList`, `ListView`,
    /// `DataGrid`, `TreeView`).
    ClearSelection,
    /// Topmost-visible-row anchor query (`DataList`, `ListView`, `DataGrid`).
    VisibleAnchor,
    /// Calendar selected dates (`Calendar`).
    CalendarDates,
    /// Calendar min/max selectable bounds (`Calendar`).
    CalendarBounds,
    /// Calendar first day of week convention (`Calendar`).
    CalendarFirstDayOfWeek,
    /// Calendar selection mode (`Calendar`).
    CalendarSelectionMode,
    /// Label text alignment (`Label`).
    LabelAlignment,
    /// Label line wrap mode (`Label`).
    LabelWrap,
    /// Rich text styled runs (`RichText`).
    RichTextRuns,
    /// Inline images in rich text (`RichText`).
    RichTextImages,
    /// Monospace (code/fixed-pitch) font rendering (`TextArea`, `TextInput`, `Label`, `RichText`).
    Monospace,
    /// Backend-native Metal handle (`MetalCanvas`).
    MetalHandle,
    /// Explicit widget font family, point size, weight, and slant (`Label`, `Button`, `TextInput`, `TextArea`).
    Font,
    /// Per-row stock-art icon roles for list controls (`DataList`, `ListView`).
    RowIcons,
}

impl WidgetProperty {
    /// Every property row, in declaration order.
    pub const ALL: &'static [WidgetProperty] = &[
        WidgetProperty::Checked,
        WidgetProperty::Value,
        WidgetProperty::Range,
        WidgetProperty::Step,
        WidgetProperty::SelectedIndex,
        WidgetProperty::TabItems,
        WidgetProperty::SelectedIndices,
        WidgetProperty::RowDrag,
        WidgetProperty::DataListItems,
        WidgetProperty::ListViewColumns,
        WidgetProperty::ListViewRows,
        WidgetProperty::DataGridRows,
        WidgetProperty::DataGridModel,
        WidgetProperty::DataGridRowHeight,
        WidgetProperty::DataGridColWidth,
        WidgetProperty::DataGridFrozenPanes,
        WidgetProperty::DataGridSelection,
        WidgetProperty::TreeItems,
        WidgetProperty::AlertLevel,
        WidgetProperty::ImageSource,
        WidgetProperty::ImageFit,
        WidgetProperty::ButtonIcon,
        WidgetProperty::FileChooserMode,
        WidgetProperty::ColorDialogData,
        WidgetProperty::FontDialogData,
        WidgetProperty::ToolbarItems,
        WidgetProperty::ToolbarOrientation,
        WidgetProperty::DateValue,
        WidgetProperty::LinkUrl,
        WidgetProperty::TextSelection,
        WidgetProperty::TextCompletion,
        WidgetProperty::ContainerDirection,
        WidgetProperty::ContainerWrap,
        WidgetProperty::ContainerScroll,
        WidgetProperty::ContainerGap,
        WidgetProperty::ContainerPadding,
        WidgetProperty::CanvasScene,
        WidgetProperty::CanvasSurface,
        WidgetProperty::CloseGuard,
        WidgetProperty::LayoutRoot,
        WidgetProperty::WindowCallback,
        WidgetProperty::NativeHandle,
        WidgetProperty::DrawDemoCube,
        WidgetProperty::CopyToClipboard,
        WidgetProperty::PasteFromClipboard,
        WidgetProperty::KeyedRows,
        WidgetProperty::ClearSelection,
        WidgetProperty::VisibleAnchor,
        WidgetProperty::CalendarDates,
        WidgetProperty::CalendarBounds,
        WidgetProperty::CalendarFirstDayOfWeek,
        WidgetProperty::CalendarSelectionMode,
        WidgetProperty::LabelAlignment,
        WidgetProperty::LabelWrap,
        WidgetProperty::RichTextRuns,
        WidgetProperty::PlaceholderText,
        WidgetProperty::RichTextImages,
        WidgetProperty::Monospace,
        WidgetProperty::MetalHandle,
        WidgetProperty::Font,
        WidgetProperty::RowIcons,
    ];

    /// The kinds this property accepts — the single source of truth for every
    /// `Ui::set_*` guard and backend kind guard.
    pub const fn applicable_kinds(self) -> &'static [WidgetKind] {
        match self {
            #[cfg(feature = "widgets-choice")]
            WidgetProperty::Checked => &[WidgetKind::Checkbox, WidgetKind::RadioButton],
            #[cfg(not(feature = "widgets-choice"))]
            WidgetProperty::Checked => &[],
            #[cfg(feature = "widgets-range")]
            WidgetProperty::Value => &[
                WidgetKind::Slider,
                WidgetKind::SpinBox,
                WidgetKind::ProgressBar,
            ],
            #[cfg(not(feature = "widgets-range"))]
            WidgetProperty::Value => &[],
            #[cfg(feature = "widgets-range")]
            WidgetProperty::Range | WidgetProperty::Step => {
                &[WidgetKind::Slider, WidgetKind::SpinBox]
            }
            #[cfg(not(feature = "widgets-range"))]
            WidgetProperty::Range | WidgetProperty::Step => &[],
            WidgetProperty::SelectedIndex => {
                const KINDS: &[WidgetKind] = &[
                    #[cfg(feature = "widgets-containers")]
                    WidgetKind::Tabs,
                    #[cfg(feature = "widgets-choice")]
                    WidgetKind::ComboBox,
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::DataList,
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::ListView,
                ];
                KINDS
            }
            #[cfg(feature = "widgets-containers")]
            WidgetProperty::TabItems => &[WidgetKind::Tabs],
            #[cfg(not(feature = "widgets-containers"))]
            WidgetProperty::TabItems => &[],
            #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
            WidgetProperty::SelectedIndices => &[
                WidgetKind::ListView,
                WidgetKind::DataList,
                WidgetKind::TreeView,
                WidgetKind::MultiSelect,
            ],
            #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
            WidgetProperty::SelectedIndices => &[WidgetKind::MultiSelect],
            #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
            WidgetProperty::SelectedIndices => &[
                WidgetKind::ListView,
                WidgetKind::DataList,
                WidgetKind::TreeView,
            ],
            #[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
            WidgetProperty::SelectedIndices => &[],
            #[cfg(feature = "widgets-data")]
            WidgetProperty::RowDrag => &[
                WidgetKind::ListView,
                WidgetKind::DataList,
                WidgetKind::DataGrid,
                WidgetKind::TreeView,
            ],
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::RowDrag => &[],
            #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
            WidgetProperty::DataListItems => &[
                WidgetKind::DataList,
                WidgetKind::ListView,
                WidgetKind::MultiSelect,
            ],
            #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
            WidgetProperty::DataListItems => &[WidgetKind::MultiSelect],
            #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
            WidgetProperty::DataListItems => &[WidgetKind::DataList, WidgetKind::ListView],
            #[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
            WidgetProperty::DataListItems => &[],
            #[cfg(feature = "widgets-data")]
            WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => {
                &[WidgetKind::ListView]
            }
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => &[],
            #[cfg(feature = "widgets-data")]
            WidgetProperty::DataGridRows
            | WidgetProperty::DataGridModel
            | WidgetProperty::DataGridRowHeight
            | WidgetProperty::DataGridColWidth
            | WidgetProperty::DataGridFrozenPanes
            | WidgetProperty::DataGridSelection => &[WidgetKind::DataGrid],
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::DataGridRows
            | WidgetProperty::DataGridModel
            | WidgetProperty::DataGridRowHeight
            | WidgetProperty::DataGridColWidth
            | WidgetProperty::DataGridFrozenPanes
            | WidgetProperty::DataGridSelection => &[],
            #[cfg(feature = "widgets-data")]
            WidgetProperty::TreeItems => &[WidgetKind::TreeView],
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::TreeItems => &[],
            #[cfg(feature = "widgets-containers")]
            WidgetProperty::AlertLevel => &[WidgetKind::AlertDialog],
            #[cfg(not(feature = "widgets-containers"))]
            WidgetProperty::AlertLevel => &[],
            #[cfg(feature = "widgets-media")]
            WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[WidgetKind::Image],
            #[cfg(not(feature = "widgets-media"))]
            WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[],
            #[cfg(feature = "widgets-pickers")]
            WidgetProperty::ButtonIcon => &[WidgetKind::Button, WidgetKind::FileChooserDialog],
            #[cfg(not(feature = "widgets-pickers"))]
            WidgetProperty::ButtonIcon => &[WidgetKind::Button],
            #[cfg(feature = "widgets-pickers")]
            WidgetProperty::FileChooserMode => &[WidgetKind::FileChooserDialog],
            #[cfg(not(feature = "widgets-pickers"))]
            WidgetProperty::FileChooserMode => &[],
            #[cfg(feature = "widgets-pickers")]
            WidgetProperty::ColorDialogData => &[WidgetKind::ColorDialog],
            #[cfg(not(feature = "widgets-pickers"))]
            WidgetProperty::ColorDialogData => &[],
            #[cfg(feature = "widgets-pickers")]
            WidgetProperty::FontDialogData => &[WidgetKind::FontDialog],
            #[cfg(not(feature = "widgets-pickers"))]
            WidgetProperty::FontDialogData => &[],
            WidgetProperty::ToolbarItems | WidgetProperty::ToolbarOrientation => {
                &[WidgetKind::Toolbar]
            }
            #[cfg(feature = "widgets-pickers")]
            WidgetProperty::DateValue => &[WidgetKind::DatePicker],
            #[cfg(not(feature = "widgets-pickers"))]
            WidgetProperty::DateValue => &[],
            #[cfg(feature = "widgets-text")]
            WidgetProperty::LinkUrl => &[WidgetKind::LinkLabel],
            #[cfg(not(feature = "widgets-text"))]
            WidgetProperty::LinkUrl => &[],
            #[cfg(feature = "widgets-text")]
            WidgetProperty::TextSelection => &[
                WidgetKind::TextInput,
                WidgetKind::TextArea,
                WidgetKind::RichText,
            ],
            #[cfg(not(feature = "widgets-text"))]
            WidgetProperty::TextSelection => &[],
            #[cfg(feature = "widgets-text")]
            WidgetProperty::TextCompletion => &[WidgetKind::TextInput],
            #[cfg(not(feature = "widgets-text"))]
            WidgetProperty::TextCompletion => &[],
            WidgetProperty::ContainerDirection
            | WidgetProperty::ContainerWrap
            | WidgetProperty::ContainerScroll => {
                const KINDS: &[WidgetKind] = &[
                    WidgetKind::Container,
                    #[cfg(feature = "widgets-containers")]
                    WidgetKind::GroupBox,
                    #[cfg(feature = "widgets-containers")]
                    WidgetKind::SplitPane,
                ];
                KINDS
            }
            WidgetProperty::ContainerGap | WidgetProperty::ContainerPadding => {
                const KINDS: &[WidgetKind] = &[
                    WidgetKind::Container,
                    #[cfg(feature = "widgets-containers")]
                    WidgetKind::GroupBox,
                ];
                KINDS
            }
            #[cfg(feature = "widgets-canvas")]
            WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[WidgetKind::Canvas],
            #[cfg(not(feature = "widgets-canvas"))]
            WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[],
            WidgetProperty::CloseGuard
            | WidgetProperty::LayoutRoot
            | WidgetProperty::WindowCallback => &[WidgetKind::Window],
            #[cfg(feature = "widgets-canvas")]
            WidgetProperty::NativeHandle => &[WidgetKind::VulkanCanvas],
            #[cfg(not(feature = "widgets-canvas"))]
            WidgetProperty::NativeHandle => &[],
            #[cfg(feature = "widgets-canvas")]
            WidgetProperty::DrawDemoCube => &[WidgetKind::VulkanCanvas, WidgetKind::MetalCanvas],
            #[cfg(not(feature = "widgets-canvas"))]
            WidgetProperty::DrawDemoCube => &[],
            WidgetProperty::CopyToClipboard | WidgetProperty::PasteFromClipboard => {
                const KINDS: &[WidgetKind] = &[
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::DataList,
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::ListView,
                    #[cfg(feature = "widgets-data")]
                    WidgetKind::DataGrid,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextInput,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextArea,
                    WidgetKind::Label,
                ];
                KINDS
            }
            #[cfg(feature = "widgets-data")]
            WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[
                WidgetKind::DataList,
                WidgetKind::ListView,
                WidgetKind::DataGrid,
            ],
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[],
            #[cfg(feature = "widgets-data")]
            WidgetProperty::ClearSelection => &[
                WidgetKind::DataList,
                WidgetKind::ListView,
                WidgetKind::DataGrid,
                WidgetKind::TreeView,
            ],
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::ClearSelection => &[],
            #[cfg(feature = "widgets-pickers")]
            WidgetProperty::CalendarDates
            | WidgetProperty::CalendarBounds
            | WidgetProperty::CalendarFirstDayOfWeek
            | WidgetProperty::CalendarSelectionMode => &[WidgetKind::Calendar],
            #[cfg(not(feature = "widgets-pickers"))]
            WidgetProperty::CalendarDates
            | WidgetProperty::CalendarBounds
            | WidgetProperty::CalendarFirstDayOfWeek
            | WidgetProperty::CalendarSelectionMode => &[],
            WidgetProperty::LabelAlignment => &[WidgetKind::Label, WidgetKind::Button],
            WidgetProperty::LabelWrap => &[WidgetKind::Label],
            #[cfg(feature = "widgets-text")]
            WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => {
                &[WidgetKind::RichText]
            }
            #[cfg(not(feature = "widgets-text"))]
            WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => &[],
            #[cfg(feature = "widgets-text")]
            WidgetProperty::PlaceholderText => &[WidgetKind::TextInput],
            #[cfg(not(feature = "widgets-text"))]
            WidgetProperty::PlaceholderText => &[],
            WidgetProperty::Monospace => {
                const KINDS: &[WidgetKind] = &[
                    WidgetKind::Label,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextArea,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextInput,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::RichText,
                ];
                KINDS
            }
            #[cfg(feature = "widgets-canvas")]
            WidgetProperty::MetalHandle => &[WidgetKind::MetalCanvas],
            #[cfg(not(feature = "widgets-canvas"))]
            WidgetProperty::MetalHandle => &[],
            WidgetProperty::Font => {
                const KINDS: &[WidgetKind] = &[
                    WidgetKind::Label,
                    WidgetKind::Button,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextInput,
                    #[cfg(feature = "widgets-text")]
                    WidgetKind::TextArea,
                ];
                KINDS
            }
            #[cfg(feature = "widgets-data")]
            WidgetProperty::RowIcons => &[WidgetKind::DataList, WidgetKind::ListView],
            #[cfg(not(feature = "widgets-data"))]
            WidgetProperty::RowIcons => &[],
        }
    }

    /// The stable operation name reported by [`GuiError::UnsupportedWidget`];
    /// it matches the setter that performed the check.
    pub const fn operation(self) -> &'static str {
        match self {
            WidgetProperty::Checked => "set_checked",
            WidgetProperty::Value => "set_value",
            WidgetProperty::Range => "set_range",
            WidgetProperty::Step => "set_step",
            WidgetProperty::SelectedIndex => "set_selected_index",
            WidgetProperty::TabItems => "set_tab_items",
            WidgetProperty::SelectedIndices => "set_selected_indices",
            WidgetProperty::RowDrag => "set_row_drag",
            WidgetProperty::DataListItems => "set_data_list_items",
            WidgetProperty::ListViewColumns => "set_list_columns",
            WidgetProperty::ListViewRows => "set_list_rows",
            WidgetProperty::DataGridRows => "set_data_grid_rows",
            WidgetProperty::DataGridModel => "set_data_grid_model",
            WidgetProperty::DataGridRowHeight => "set_data_grid_row_height",
            WidgetProperty::DataGridColWidth => "set_data_grid_col_width",
            WidgetProperty::DataGridFrozenPanes => "set_data_grid_frozen_panes",
            WidgetProperty::DataGridSelection => "set_data_grid_selection",
            WidgetProperty::TreeItems => "set_tree_items",
            WidgetProperty::AlertLevel => "set_alert_level",
            WidgetProperty::ImageSource => "set_image_source",
            WidgetProperty::ImageFit => "set_image_fit",
            WidgetProperty::ButtonIcon => "set_icon",
            WidgetProperty::FileChooserMode => "set_file_chooser_mode",
            WidgetProperty::ColorDialogData => "set_color_dialog_data",
            WidgetProperty::FontDialogData => "set_font_dialog_data",
            WidgetProperty::ToolbarItems => "set_toolbar_items",
            WidgetProperty::ToolbarOrientation => "set_toolbar_orientation",
            WidgetProperty::DateValue => "set_date_value",
            WidgetProperty::LinkUrl => "set_link_url",
            WidgetProperty::TextSelection => "set_text_selection",
            WidgetProperty::TextCompletion => "set_text_completion_items",
            WidgetProperty::ContainerDirection => "set_container_direction",
            WidgetProperty::ContainerWrap => "set_container_wrap",
            WidgetProperty::ContainerScroll => "set_container_scroll",
            WidgetProperty::ContainerGap => "set_container_gap",
            WidgetProperty::ContainerPadding => "set_container_padding",
            WidgetProperty::CanvasScene => "set_canvas_scene",
            WidgetProperty::CanvasSurface => "set_canvas_surface",
            WidgetProperty::CloseGuard => "set_close_guard",
            WidgetProperty::LayoutRoot => "set_layout_root",
            WidgetProperty::WindowCallback => "window_callback",
            WidgetProperty::NativeHandle => "native_handle",
            WidgetProperty::DrawDemoCube => "draw_demo_cube",
            WidgetProperty::CopyToClipboard => "copy_to_clipboard",
            WidgetProperty::PasteFromClipboard => "paste_from_clipboard",
            WidgetProperty::KeyedRows => "set_rows_keyed",
            WidgetProperty::ClearSelection => "clear_selection",
            WidgetProperty::VisibleAnchor => "visible_anchor",
            WidgetProperty::CalendarDates => "set_calendar_selected_dates",
            WidgetProperty::CalendarBounds => "set_calendar_bounds",
            WidgetProperty::CalendarFirstDayOfWeek => "set_calendar_first_day_of_week",
            WidgetProperty::CalendarSelectionMode => "set_calendar_selection_mode",
            WidgetProperty::LabelAlignment => "set_label_alignment",
            WidgetProperty::LabelWrap => "set_label_wrap",
            WidgetProperty::RichTextRuns => "set_rich_text_runs",
            WidgetProperty::PlaceholderText => "set_placeholder_text",
            WidgetProperty::RichTextImages => "set_rich_text_images",
            WidgetProperty::Monospace => "set_monospace",
            WidgetProperty::MetalHandle => "metal_canvas_handle",
            WidgetProperty::Font => "set_font",
            WidgetProperty::RowIcons => "set_row_icons",
        }
    }

    /// The property name, matching its operation name.
    pub const fn name(self) -> &'static str {
        self.operation()
    }

    /// Whether `kind` is inside this property's applicability row.
    pub fn supports(self, kind: WidgetKind) -> bool {
        self.applicable_kinds().contains(&kind)
    }
}

impl WidgetKind {
    /// Checks whether this widget kind supports the specified property.
    pub fn requires_property(self, property: WidgetProperty) -> bool {
        property.supports(self)
    }

    /// Checks whether this widget kind represents a top-level window or dialog surface.
    pub fn is_window_like(self) -> bool {
        match self {
            WidgetKind::Window => true,
            #[cfg(feature = "widgets-pickers")]
            WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
                true
            }
            #[cfg(feature = "widgets-containers")]
            WidgetKind::AlertDialog => true,
            _ => false,
        }
    }

    /// Checks whether this widget kind represents a dialog surface.
    pub fn is_dialog(self) -> bool {
        match self {
            #[cfg(feature = "widgets-pickers")]
            WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
                true
            }
            #[cfg(feature = "widgets-containers")]
            WidgetKind::AlertDialog => true,
            _ => false,
        }
    }
}

/// A Gregorian calendar date with year, month (1..=12), and day (1..=31).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CalendarDate {
    pub year: i32,
    pub month: u32,
    pub day: u32,
}

impl CalendarDate {
    /// Creates a calendar date without validating bounds.
    pub const fn new(year: i32, month: u32, day: u32) -> Self {
        Self { year, month, day }
    }

    /// Returns `true` if the date is a valid Gregorian calendar date.
    pub fn is_valid(&self) -> bool {
        if self.year == 0 || self.month < 1 || self.month > 12 {
            return false;
        }
        let max_days = Self::days_in_month(self.year, self.month);
        self.day >= 1 && self.day <= max_days
    }

    /// Returns `true` if `year` is a leap year in the Gregorian calendar.
    pub const fn is_leap_year(year: i32) -> bool {
        (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
    }

    /// Returns the number of days in `month` for `year`.
    pub const fn days_in_month(year: i32, month: u32) -> u32 {
        match month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => {
                if Self::is_leap_year(year) {
                    29
                } else {
                    28
                }
            }
            _ => 0,
        }
    }
}

/// The first day of the week convention used in calendar views.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CalendarFirstDayOfWeek {
    /// Follow host platform or locale default convention.
    #[default]
    LocaleDefault,
    /// Week starts on Sunday (e.g. US standard).
    Sunday,
    /// Week starts on Monday (ISO 8601 standard).
    Monday,
}

/// Date selection mode supported by a calendar widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CalendarSelectionMode {
    /// Exactly one date can be selected at a time.
    #[default]
    Single,
    /// A contiguous range of dates between a start and end date can be selected.
    Range,
    /// Arbitrary discrete dates can be selected.
    Multiple,
}

/// Text alignment for `WidgetKind::Label`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LabelAlignment {
    /// Left-aligned text (default).
    #[default]
    Left,
    /// Horizontally centered text.
    Center,
    /// Right-aligned text.
    Right,
}

/// Word-wrap behavior for `WidgetKind::Label`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LabelWrap {
    /// No line wrapping (default).
    #[default]
    None,
    /// Wrap lines on word boundaries.
    Word,
    /// Wrap lines on character boundaries.
    Char,
    /// Wrap lines on word boundaries, breaking words if necessary.
    WordChar,
}

/// Convenience alias for [`LabelWrap`].
pub type LabelWrapMode = LabelWrap;

impl LabelWrap {
    /// Alias for [`LabelWrap::None`].
    pub const NO_WRAP: Self = Self::None;

    /// Alias for [`LabelWrap::None`].
    #[allow(non_upper_case_globals)]
    pub const NoWrap: Self = Self::None;

    /// Returns `true` if line wrapping is active.
    pub const fn is_wrapping(self) -> bool {
        !matches!(self, Self::None)
    }
}

impl From<bool> for LabelWrap {
    fn from(wrap: bool) -> Self {
        if wrap {
            Self::Word
        } else {
            Self::None
        }
    }
}

impl From<TextAlignment> for LabelAlignment {
    fn from(alignment: TextAlignment) -> Self {
        match alignment {
            TextAlignment::Left => Self::Left,
            TextAlignment::Center => Self::Center,
            TextAlignment::Right => Self::Right,
        }
    }
}

impl From<LabelAlignment> for TextAlignment {
    fn from(alignment: LabelAlignment) -> Self {
        match alignment {
            LabelAlignment::Left => Self::Left,
            LabelAlignment::Center => Self::Center,
            LabelAlignment::Right => Self::Right,
        }
    }
}

/// Direction used by container widgets to stack their children.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ContainerDirection {
    /// Stack children top-to-bottom.
    Vertical,
    /// Stack children left-to-right.
    Horizontal,
}

/// Wrapping behavior along the flex axis for container widgets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ContainerWrap {
    /// Children are forced into a single line.
    #[default]
    NoWrap,
    /// Children wrap onto multiple lines along the cross axis.
    Wrap,
    /// Children wrap onto multiple lines in reverse cross-axis direction.
    WrapReverse,
}

/// Alert severity for `WidgetKind::AlertDialog`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AlertLevel {
    Info,
    Warning,
    Error,
}

/// How an image scales into its widget bounds.
///
/// Every mode centers its result; `None` draws at the image's natural size
/// (one image pixel per device-independent pixel) and clips to the widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum ImageFit {
    /// Scale uniformly so both axes fit (letterbox on the shorter axis).
    #[default]
    Contain,
    /// Scale uniformly to fill both axes, center-cropping the overflow.
    Cover,
    /// Stretch non-uniformly to both axes (no crop, no letterbox).
    Fill,
    /// Draw at the image's natural size, centered and clipped.
    None,
}

impl ImageFit {
    /// Stable identifier used by docs, diagnostics, and capability errors.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Contain => "contain",
            Self::Cover => "cover",
            Self::Fill => "fill",
            Self::None => "none",
        }
    }
}

/// What a `WidgetKind::FileChooserDialog` lets the user pick.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FileChooserMode {
    /// Pick an existing file (the historical behavior).
    #[default]
    OpenFile,
    /// Pick a folder ("Open Folder…").
    PickFolder,
    /// Choose a (possibly new) file to write ("Save As…").
    SaveFile,
}

impl FileChooserMode {
    /// Stable identifier used by docs, diagnostics, and capability errors.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::OpenFile => "open-file",
            Self::PickFolder => "pick-folder",
            Self::SaveFile => "save-file",
        }
    }
}

/// RGB background color used for widget styling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Color {
    pub r: u8,
    pub g: u8,
    pub b: u8,
}

impl Color {
    /// Creates a color from red, green, and blue channels.
    pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
        Self { r, g, b }
    }
}

/// Visual and semantic style attributes for a text run in a rich text widget.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextStyle {
    pub bold: bool,
    pub italic: bool,
    pub underline: bool,
    pub strikethrough: bool,
    pub monospace: bool,
    pub scale: Option<f32>,
    pub fg_color: Option<Color>,
    pub bg_color: Option<Color>,
    pub link: Option<String>,
    pub dimmed: bool,
    pub paragraph_indent: u32,
}

impl TextStyle {
    /// Creates a default text style with all attributes unset.
    pub const fn new() -> Self {
        Self {
            bold: false,
            italic: false,
            underline: false,
            strikethrough: false,
            monospace: false,
            scale: None,
            fg_color: None,
            bg_color: None,
            link: None,
            dimmed: false,
            paragraph_indent: 0,
        }
    }

    /// Sets bold styling.
    pub const fn bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }

    /// Sets italic styling.
    pub const fn italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    /// Sets underline styling.
    pub const fn underline(mut self, underline: bool) -> Self {
        self.underline = underline;
        self
    }

    /// Sets strikethrough styling.
    pub const fn strikethrough(mut self, strikethrough: bool) -> Self {
        self.strikethrough = strikethrough;
        self
    }

    /// Sets monospace (code) styling.
    pub const fn monospace(mut self, monospace: bool) -> Self {
        self.monospace = monospace;
        self
    }

    /// Sets relative font scale (1.0 = normal body size).
    pub const fn scale(mut self, scale: f32) -> Self {
        self.scale = Some(scale);
        self
    }

    /// Sets foreground text color.
    pub const fn fg_color(mut self, color: Color) -> Self {
        self.fg_color = Some(color);
        self
    }

    /// Sets background highlight color.
    pub const fn bg_color(mut self, color: Color) -> Self {
        self.bg_color = Some(color);
        self
    }

    /// Sets link target URL.
    pub fn link(mut self, link: impl Into<String>) -> Self {
        self.link = Some(link.into());
        self
    }

    /// Sets dimmed styling (marker treatment).
    pub const fn dimmed(mut self, dimmed: bool) -> Self {
        self.dimmed = dimmed;
        self
    }

    /// Sets paragraph indentation level.
    pub const fn paragraph_indent(mut self, indent: u32) -> Self {
        self.paragraph_indent = indent;
        self
    }
}

/// A styled run of text spanning a byte range within a rich text widget.
#[derive(Debug, Clone, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct TextRun {
    pub range: std::ops::Range<usize>,
    pub style: TextStyle,
}

impl TextRun {
    /// Creates a new styled run covering `range` with `style`.
    pub fn new(range: std::ops::Range<usize>, style: TextStyle) -> Self {
        Self { range, style }
    }
}

/// An inline image rendered in-flow within a rich text widget.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RichTextImage {
    pub offset: usize,
    pub source: String,
    pub max_width: Option<u32>,
}

impl RichTextImage {
    /// Creates a new inline image description at `offset` with `source` and optional `max_width`.
    pub fn new(offset: usize, source: impl Into<String>, max_width: Option<u32>) -> Self {
        Self {
            offset,
            source: source.into(),
            max_width,
        }
    }
}

/// Raw image payload from the system clipboard or screenshot buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ClipboardImage {
    pub width: u32,
    pub height: u32,
    /// Raw RGBA8 pixel bytes (row-major, 4 bytes per pixel: [R, G, B, A, ...]).
    pub rgba: Vec<u8>,
    /// Encoded PNG image bytes (from native clipboard or encoded on demand).
    pub png_bytes: Vec<u8>,
}

impl ClipboardImage {
    /// Creates a new `ClipboardImage` from raw RGBA8 pixels, automatically encoding PNG bytes.
    pub fn new(width: u32, height: u32, rgba: Vec<u8>) -> Self {
        let png_bytes = encode_rgba_to_png(width, height, &rgba);
        Self {
            width,
            height,
            rgba,
            png_bytes,
        }
    }

    /// Creates a `ClipboardImage` with pre-encoded PNG bytes.
    pub fn with_png(width: u32, height: u32, rgba: Vec<u8>, png_bytes: Vec<u8>) -> Self {
        Self {
            width,
            height,
            rgba,
            png_bytes,
        }
    }
}

/// Pure, dependency-free RGBA to PNG encoder.
pub fn encode_rgba_to_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
    fn crc32(data: &[u8]) -> u32 {
        let mut crc = 0xFFFF_FFFFu32;
        for &byte in data {
            crc ^= u32::from(byte);
            for _ in 0..8 {
                let mask = (crc & 1).wrapping_neg();
                crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
            }
        }
        !crc
    }

    fn adler32(data: &[u8]) -> u32 {
        let mut s1 = 1u32;
        let mut s2 = 0u32;
        for &byte in data {
            s1 = (s1 + u32::from(byte)) % 65521;
            s2 = (s2 + s1) % 65521;
        }
        (s2 << 16) | s1
    }

    let mut out = Vec::new();
    out.extend_from_slice(b"\x89PNG\r\n\x1a\n");

    // IHDR
    let mut ihdr = Vec::with_capacity(13);
    ihdr.extend_from_slice(&width.to_be_bytes());
    ihdr.extend_from_slice(&height.to_be_bytes());
    ihdr.push(8); // 8-bit depth
    ihdr.push(6); // color type 6: RGBA
    ihdr.push(0); // compression 0
    ihdr.push(0); // filter 0
    ihdr.push(0); // interlace 0

    let mut ihdr_chunk = Vec::new();
    ihdr_chunk.extend_from_slice(b"IHDR");
    ihdr_chunk.extend_from_slice(&ihdr);
    let ihdr_crc = crc32(&ihdr_chunk);

    out.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
    out.extend_from_slice(&ihdr_chunk);
    out.extend_from_slice(&ihdr_crc.to_be_bytes());

    // Scanlines with filter byte 0 (None)
    let w_bytes = (width as usize) * 4;
    let mut raw = Vec::with_capacity((height as usize) * (w_bytes + 1));
    for y in 0..(height as usize) {
        raw.push(0); // Filter type 0
        let start = y * w_bytes;
        let end = (start + w_bytes).min(rgba.len());
        if start < rgba.len() {
            raw.extend_from_slice(&rgba[start..end]);
            if end - start < w_bytes {
                raw.resize(raw.len() + (w_bytes - (end - start)), 0);
            }
        } else {
            raw.resize(raw.len() + w_bytes, 0);
        }
    }

    // zlib stream: 0x78, 0x01 (deflate uncompressed)
    let mut zlib = Vec::new();
    zlib.push(0x78);
    zlib.push(0x01);

    let chunks: Vec<&[u8]> = if raw.is_empty() {
        vec![&[]]
    } else {
        raw.chunks(65535).collect()
    };
    let total_chunks = chunks.len();
    for (i, chunk) in chunks.iter().enumerate() {
        let is_final = i == total_chunks - 1;
        let header = if is_final { 0x01 } else { 0x00 };
        zlib.push(header);
        let len = chunk.len() as u16;
        let nlen = !len;
        zlib.extend_from_slice(&len.to_le_bytes());
        zlib.extend_from_slice(&nlen.to_le_bytes());
        zlib.extend_from_slice(chunk);
    }
    let adler = adler32(&raw);
    zlib.extend_from_slice(&adler.to_be_bytes());

    // IDAT
    let mut idat_chunk = Vec::new();
    idat_chunk.extend_from_slice(b"IDAT");
    idat_chunk.extend_from_slice(&zlib);
    let idat_crc = crc32(&idat_chunk);

    out.extend_from_slice(&(zlib.len() as u32).to_be_bytes());
    out.extend_from_slice(&idat_chunk);
    out.extend_from_slice(&idat_crc.to_be_bytes());

    // IEND
    let mut iend_chunk = Vec::new();
    iend_chunk.extend_from_slice(b"IEND");
    let iend_crc = crc32(&iend_chunk);

    out.extend_from_slice(&0u32.to_be_bytes());
    out.extend_from_slice(&iend_chunk);
    out.extend_from_slice(&iend_crc.to_be_bytes());

    out
}

/// Rectangle geometry used by `CanvasScene` primitives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CanvasRect {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

/// Immutable RGBA8 raster surface painted beneath a `WidgetKind::Canvas`
/// scene.
///
/// The buffer is row-major with four bytes per pixel (`width * height * 4`)
/// and is shared behind an `Arc`, so cloning a surface into the widget spec,
/// the backend, and a paint property is cheap. Backends composite it over the
/// canvas background and clip it to the widget; the retained scene draws on
/// top. Full typed image resources with source rectangles and sampling remain
/// the scope (`docs/design/canvas-api-rfc.md`, superseding note).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CanvasSurface {
    width: u32,
    height: u32,
    pixels: Arc<Vec<u8>>,
}

impl CanvasSurface {
    /// Wraps a row-major RGBA8 buffer after validating its dimensions.
    pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, GuiError> {
        if width == 0 || height == 0 {
            return Err(GuiError::Backend(
                "canvas surface dimensions must be non-zero".to_owned(),
            ));
        }
        let expected = width as usize * height as usize * 4;
        if pixels.len() != expected {
            return Err(GuiError::Backend(format!(
                "canvas surface expects {expected} bytes, found {}",
                pixels.len()
            )));
        }
        Ok(Self {
            width,
            height,
            pixels: Arc::new(pixels),
        })
    }

    /// Surface width in pixels.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Surface height in pixels.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// Row-major RGBA8 bytes.
    pub fn pixels(&self) -> &[u8] {
        &self.pixels
    }
}

/// A canvas scene is a logical drawing surface of primitives.
#[derive(Debug, Clone, PartialEq)]
pub struct CanvasScene {
    pub primitives: Vec<CanvasPrimitive>,
    pub logical_width: f32,
    pub logical_height: f32,
}

impl CanvasScene {
    pub fn new(logical_width: f32, logical_height: f32) -> Self {
        Self {
            primitives: Vec::new(),
            logical_width,
            logical_height,
        }
    }

    /// Validates the scene's logical content size before it reaches a backend.
    pub fn validate(&self) -> GuiResult<()> {
        let invalid = !self.logical_width.is_finite()
            || !self.logical_height.is_finite()
            || self.logical_width <= 0.0
            || self.logical_height <= 0.0;

        if invalid {
            return Err(GuiError::Backend(
                "Canvas scene logical size must be finite and positive".to_owned(),
            ));
        }
        Ok(())
    }
}

/// A primitive in a canvas scene.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CanvasPrimitive {
    Rect {
        rect: CanvasRect,
        fill: Option<Color>,
        stroke: Option<Color>,
        stroke_width: u8,
    },
    Line {
        from: (i32, i32),
        to: (i32, i32),
        color: Color,
        width: u8,
    },
    /// Single-line text. `pos` is the top-left corner of the text box in
    /// scene coordinates (not the baseline), on every backend.
    Text {
        pos: (i32, i32),
        text: String,
        color: Color,
        size: u8,
    },
    Image {
        rect: CanvasRect,
        source: String,
    },
}

/// Hierarchical item for `WidgetKind::TreeView` content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TreeItem {
    /// Display label for this node.
    pub label: String,
    /// Child nodes (empty for leaves).
    pub children: Vec<TreeItem>,
}

impl TreeItem {
    /// Creates a leaf node.
    pub fn new(label: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            children: Vec::new(),
        }
    }

    /// Appends a child node.
    pub fn with_child(mut self, child: TreeItem) -> Self {
        self.children.push(child);
        self
    }

    /// Flattens the tree into display rows, indented by depth (first cut:
    /// tree views render as selectable indented rows).
    pub fn indented_rows(&self) -> Vec<String> {
        let mut rows = Vec::new();
        self.collect_rows(0, &mut rows);
        rows
    }

    fn collect_rows(&self, depth: usize, rows: &mut Vec<String>) {
        rows.push(format!("{}{}", "  ".repeat(depth), self.label));
        for child in &self.children {
            child.collect_rows(depth + 1, rows);
        }
    }
}

/// One column of a columned collection widget.
///
/// This is the shared column vocabulary for `WidgetKind::ListView`'s
/// columned contract; the tree-grid and `TreeView` deepening
/// designs adopt the same type, so one column list describes any of them.
/// Cells are plain strings, mirroring `WidgetSpec::data_grid_rows`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColumnSpec {
    /// Header text.
    pub title: String,
    /// Preferred column width in logical pixels; `None` lets the lane pick
    /// its default (most lanes size to the header and cell content).
    pub width: Option<i32>,
}

impl ColumnSpec {
    /// Creates a column with the given header text and no width preference.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            width: None,
        }
    }

    /// Sets a preferred width in logical pixels. Non-positive values mean
    /// "no preference" (the lane picks its default), matching the shared
    /// size semantics elsewhere.
    pub fn with_width(mut self, width: i32) -> Self {
        self.width = if width > 0 { Some(width) } else { None };
        self
    }
}

/// Application-owned row identity for keyed collection updates.
///
/// Keys are stable for a row's lifetime and never minted or reused by the
/// model - the same contract as [`crate::ToolId`] - so a keyed
/// apply can tell an edit, a move, and a replacement apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RowKey(pub u64);

/// One keyed row: identity plus the cells the widget renders.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RowSet {
    /// Application-owned identity of this row.
    pub key: RowKey,
    /// The row's cells: one for `DataList`/`ListView`, N for `DataGrid`.
    pub cells: Vec<String>,
}

impl RowSet {
    /// Builds a row from a key and its cells.
    pub fn new(key: u64, cells: &[&str]) -> Self {
        Self {
            key: RowKey(key),
            cells: cells.iter().map(|cell| (*cell).to_owned()).collect(),
        }
    }

    /// Single-cell rendering used by `DataList`/`ListView`.
    pub fn text(&self) -> String {
        self.cells.first().cloned().unwrap_or_default()
    }
}

/// What a keyed row update changed.
///
/// Each new row is classified once: `inserted` when its key is new, `updated`
/// when its cells differ (a moved-and-edited row counts as updated), `moved`
/// when the cells are identical but the index changed, `unchanged` otherwise;
/// `removed` counts previous keys missing from the new set. An all-zero delta
/// ([`Self::is_noop`]) means the backend was not touched at all.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct RowDelta {
    pub inserted: usize,
    pub updated: usize,
    pub removed: usize,
    pub moved: usize,
    pub unchanged: usize,
}

impl RowDelta {
    /// True when keys, order, and cells are all identical to the previous
    /// set: a no-op keyed apply performs no backend write.
    pub fn is_noop(&self) -> bool {
        self.inserted == 0 && self.updated == 0 && self.removed == 0 && self.moved == 0
    }
}

/// Classifies `new_rows` against `old_rows` without touching either.
///
/// Duplicate keys in `new_rows` are rejected with
/// [`GuiError::Backend`]`("duplicate row key")` and nothing is classified;
/// the caller keeps its previous rows and selection.
///
/// ```
/// use native_gui_core::widgets::{diff_rows, RowDelta, RowSet};
///
/// let old = [RowSet::new(1, &["a"]), RowSet::new(2, &["b"])];
/// let new = [RowSet::new(2, &["b"]), RowSet::new(3, &["c"])];
/// let delta = diff_rows(&old, &new).expect("unique keys");
/// assert_eq!(delta, RowDelta { inserted: 1, updated: 0, removed: 1, moved: 1, unchanged: 0 });
/// assert!(!delta.is_noop());
/// ```
pub fn diff_rows(old_rows: &[RowSet], new_rows: &[RowSet]) -> GuiResult<RowDelta> {
    let mut new_keys: std::collections::HashSet<u64> =
        std::collections::HashSet::with_capacity(new_rows.len());
    for row in new_rows {
        if !new_keys.insert(row.key.0) {
            return Err(GuiError::Backend("duplicate row key".to_owned()));
        }
    }

    let old_index: std::collections::HashMap<u64, usize> = old_rows
        .iter()
        .enumerate()
        .map(|(index, row)| (row.key.0, index))
        .collect();

    let mut delta = RowDelta::default();
    for (new_pos, row) in new_rows.iter().enumerate() {
        match old_index.get(&row.key.0) {
            None => delta.inserted += 1,
            Some(&old_pos) => {
                if old_rows[old_pos].cells != row.cells {
                    delta.updated += 1;
                } else if old_pos != new_pos {
                    delta.moved += 1;
                } else {
                    delta.unchanged += 1;
                }
            }
        }
    }
    // The duplicate-check set already holds every new key; reuse it instead
    // of building a second set of the same contents.
    delta.removed = old_rows
        .iter()
        .filter(|row| !new_keys.contains(&row.key.0))
        .count();
    Ok(delta)
}

/// An incremental operation to apply to a row widget.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum RowOp {
    /// Inserts a new row at `index`.
    Insert { index: usize, row: RowSet },
    /// Replaces the cells of the row at `index`.
    Update { index: usize, row: RowSet },
    /// Removes the row at `index`.
    Remove { index: usize, key: RowKey },
    /// Moves a row from `from_index` to `to_index`.
    Move {
        from_index: usize,
        to_index: usize,
        key: RowKey,
    },
    /// Reorders all rows according to the specified permutation of original indices.
    Reorder { order: Vec<usize> },
}

/// Computes incremental [`RowOp`]s transforming `old_rows` into `new_rows`.
///
/// Returns `None` when a full rebuild is preferred (e.g. initial population or complex re-orderings).
pub fn diff_row_ops(
    old_rows: &[RowSet],
    new_rows: &[RowSet],
    delta: &RowDelta,
) -> Option<Vec<RowOp>> {
    if old_rows.is_empty() || delta.is_noop() {
        return None;
    }

    // Case 1: Pure updates (same keys and order, cell modifications only)
    if delta.inserted == 0 && delta.removed == 0 && delta.moved == 0 && delta.updated > 0 {
        if old_rows.len() != new_rows.len() {
            return None;
        }
        let mut ops = Vec::with_capacity(delta.updated);
        for (i, (old, new)) in old_rows.iter().zip(new_rows.iter()).enumerate() {
            if old.key != new.key {
                return None;
            }
            if old.cells != new.cells {
                ops.push(RowOp::Update {
                    index: i,
                    row: new.clone(),
                });
            }
        }
        return Some(ops);
    }

    // Case 2: Single row insert
    if delta.inserted == 1 && delta.removed == 0 && delta.updated == 0 {
        if new_rows.len() != old_rows.len() + 1 {
            return None;
        }
        let insert_idx = (0..old_rows.len())
            .find(|&i| old_rows[i].key != new_rows[i].key)
            .unwrap_or(old_rows.len());
        // Verify tail matches
        if new_rows[insert_idx + 1..] == old_rows[insert_idx..] {
            return Some(vec![RowOp::Insert {
                index: insert_idx,
                row: new_rows[insert_idx].clone(),
            }]);
        }
        return None;
    }

    // Case 3: Single row remove
    if delta.removed == 1 && delta.inserted == 0 && delta.updated == 0 {
        if old_rows.len() != new_rows.len() + 1 {
            return None;
        }
        let remove_idx = (0..new_rows.len())
            .find(|&i| old_rows[i].key != new_rows[i].key)
            .unwrap_or(new_rows.len());
        // Verify tail matches
        if old_rows[remove_idx + 1..] == new_rows[remove_idx..] {
            return Some(vec![RowOp::Remove {
                index: remove_idx,
                key: old_rows[remove_idx].key,
            }]);
        }
        return None;
    }

    // Case 4: Single row move or reorder
    if delta.moved > 0 && delta.inserted == 0 && delta.removed == 0 && delta.updated == 0 {
        if old_rows.len() != new_rows.len() {
            return None;
        }
        let old_index: std::collections::HashMap<u64, usize> = old_rows
            .iter()
            .enumerate()
            .map(|(index, row)| (row.key.0, index))
            .collect();
        let order: Vec<usize> = new_rows
            .iter()
            .filter_map(|r| old_index.get(&r.key.0).copied())
            .collect();
        if order.len() != old_rows.len() {
            return None;
        }

        // Check if this permutation is a single element moved
        for (to_idx, &from_idx) in order.iter().enumerate() {
            if to_idx == from_idx {
                continue;
            }
            let mut matches = true;
            let mut expected = 0;
            for (new_i, &old_i) in order.iter().enumerate() {
                if new_i == to_idx {
                    continue;
                }
                if expected == from_idx {
                    expected += 1;
                }
                if old_i != expected {
                    matches = false;
                    break;
                }
                expected += 1;
            }
            if matches {
                return Some(vec![RowOp::Move {
                    from_index: from_idx,
                    to_index: to_idx,
                    key: new_rows[to_idx].key,
                }]);
            }
        }

        return Some(vec![RowOp::Reorder { order }]);
    }

    None
}

/// Applies [`RowOp`] operations in place to a row buffer.
pub fn apply_row_ops_to_rows(rows: &mut Vec<RowSet>, ops: &[RowOp]) {
    for op in ops {
        match op {
            RowOp::Update { index, row } => {
                if let Some(target) = rows.get_mut(*index) {
                    *target = row.clone();
                }
            }
            RowOp::Insert { index, row } => {
                let idx = (*index).min(rows.len());
                rows.insert(idx, row.clone());
            }
            RowOp::Remove { index, .. } => {
                if *index < rows.len() {
                    rows.remove(*index);
                }
            }
            RowOp::Move {
                from_index,
                to_index,
                ..
            } => {
                if *from_index < rows.len() {
                    let r = rows.remove(*from_index);
                    let to = (*to_index).min(rows.len());
                    rows.insert(to, r);
                }
            }
            RowOp::Reorder { order } => {
                if order.len() == rows.len() {
                    let old = std::mem::take(rows);
                    rows.reserve(order.len());
                    let mut old_opt: Vec<Option<RowSet>> = old.into_iter().map(Some).collect();
                    for &old_idx in order {
                        if let Some(opt) = old_opt.get_mut(old_idx) {
                            if let Some(r) = opt.take() {
                                rows.push(r);
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Applies [`RowOp`] operations in place to a cell matrix.
pub fn apply_row_ops_to_cells(cells: &mut Vec<Vec<String>>, ops: &[RowOp]) {
    for op in ops {
        match op {
            RowOp::Update { index, row } => {
                if let Some(target) = cells.get_mut(*index) {
                    *target = row.cells.clone();
                }
            }
            RowOp::Insert { index, row } => {
                let idx = (*index).min(cells.len());
                cells.insert(idx, row.cells.clone());
            }
            RowOp::Remove { index, .. } => {
                if *index < cells.len() {
                    cells.remove(*index);
                }
            }
            RowOp::Move {
                from_index,
                to_index,
                ..
            } => {
                if *from_index < cells.len() {
                    let c = cells.remove(*from_index);
                    let to = (*to_index).min(cells.len());
                    cells.insert(to, c);
                }
            }
            RowOp::Reorder { order } => {
                if order.len() == cells.len() {
                    let old = std::mem::take(cells);
                    cells.reserve(order.len());
                    let mut old_opt: Vec<Option<Vec<String>>> = old.into_iter().map(Some).collect();
                    for &old_idx in order {
                        if let Some(opt) = old_opt.get_mut(old_idx) {
                            if let Some(c) = opt.take() {
                                cells.push(c);
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Applies [`RowOp`] operations in place to a text item list.
pub fn apply_row_ops_to_items(items: &mut Vec<String>, ops: &[RowOp]) {
    for op in ops {
        match op {
            RowOp::Update { index, row } => {
                if let Some(target) = items.get_mut(*index) {
                    *target = row.text();
                }
            }
            RowOp::Insert { index, row } => {
                let idx = (*index).min(items.len());
                items.insert(idx, row.text());
            }
            RowOp::Remove { index, .. } => {
                if *index < items.len() {
                    items.remove(*index);
                }
            }
            RowOp::Move {
                from_index,
                to_index,
                ..
            } => {
                if *from_index < items.len() {
                    let item = items.remove(*from_index);
                    let to = (*to_index).min(items.len());
                    items.insert(to, item);
                }
            }
            RowOp::Reorder { order } => {
                if order.len() == items.len() {
                    let old = std::mem::take(items);
                    items.reserve(order.len());
                    let mut old_opt: Vec<Option<String>> = old.into_iter().map(Some).collect();
                    for &old_idx in order {
                        if let Some(opt) = old_opt.get_mut(old_idx) {
                            if let Some(item) = opt.take() {
                                items.push(item);
                            }
                        }
                    }
                }
            }
        }
    }
}

/// Text alignment for widgets and grid cells.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum TextAlignment {
    Left,
    Center,
    Right,
}

/// Attributes for a `WidgetKind::DataGrid` cell (Phase 2).
#[derive(Debug, Clone, PartialEq, Default)]
pub struct GridCellAttr {
    pub bg_color: Option<Color>,
    pub text_color: Option<Color>,
    pub alignment: Option<TextAlignment>,
    pub font_bold: bool,
    pub font_italic: bool,
    pub font_size: Option<u8>,
}

/// Built-in editors for a `WidgetKind::DataGrid` cell (Phase 3).
#[derive(Debug, Clone, PartialEq)]
pub enum GridCellEditor {
    Text,
    Boolean,
    Enum(Vec<String>),
    Number { min: i32, max: i32, step: i32 },
}

/// Built-in renderers for a `WidgetKind::DataGrid` cell (Phase 4).
#[derive(Debug, Clone, PartialEq)]
pub enum GridCellRenderer {
    Text,
    Boolean,
    Canvas(CanvasScene),
}

/// Virtual data model for `WidgetKind::DataGrid` (Phase 1-5 implementation).
pub trait DataGridModel {
    /// Returns the total number of rows.
    fn row_count(&self) -> usize;
    /// Returns the total number of columns.
    fn col_count(&self) -> usize;
    /// Returns the string value for a given cell.
    fn value_at(&self, row: usize, col: usize) -> String;

    /// Reports whether the row's cells are already resident, so a backend
    /// can repaint precisely when a lazily-loaded row arrives instead of on
    /// every drain (`docs/design/datagrid-model-tiers.md` §8).
    ///
    /// The default is `true`: every eager model answers reads immediately,
    /// so nothing it serves can be "not loaded yet". A lazy model such as
    /// [`WindowedDataGridModel`] overrides this with `false` for in-range
    /// rows whose payload has not been applied yet; `value_at` for those
    /// rows returns the model's placeholder until the fetch is delivered.
    fn is_row_resident(&self, _row: usize) -> bool {
        true
    }

    /// Pins the contiguous visible band `[first_row, first_row + count)` for
    /// one read sequence (a paint or hit-test pass), so a lazy model cannot
    /// evict a row that the pass is about to read (design
    /// `docs/design/datagrid-model-tiers.md` §5.3).
    ///
    /// A backend brackets its read pass with this and
    /// [`DataGridModel::clear_pinned_band`]; `count == 0` clears the band.
    /// A later pin replaces the previous band, so a pass never inherits
    /// stale protection. The default is a no-op: an eager model keeps every
    /// row resident, so nothing can be evicted and the call is free to be
    /// ignored. Only a lazy model such as [`WindowedDataGridModel`] carries
    /// pin state.
    fn pin_visible_band(&self, _first_row: usize, _count: usize) {}

    /// Ends the pin scope opened by [`DataGridModel::pin_visible_band`].
    /// The default is a no-op (see there).
    fn clear_pinned_band(&self) {}

    // Phase 2: Formatting
    fn get_attr(&self, _row: usize, _col: usize) -> Option<GridCellAttr> {
        None
    }

    // Phase 3: Editing
    fn set_value_at(&mut self, _row: usize, _col: usize, _value: String) {}
    fn get_editor(&self, _row: usize, _col: usize) -> Option<GridCellEditor> {
        None
    }

    // Phase 4: Custom Renderers
    fn get_renderer(&self, _row: usize, _col: usize) -> Option<GridCellRenderer> {
        None
    }

    // Phase 5: Cell Merging
    fn cell_span(&self, _row: usize, _col: usize) -> (usize, usize) {
        (1, 1)
    }
}

/// A simple in-memory data grid model used for compatibility with `WidgetSpec::data_grid_rows`.
pub struct SimpleDataGridModel {
    pub rows: Vec<Vec<String>>,
}

impl DataGridModel for SimpleDataGridModel {
    fn row_count(&self) -> usize {
        self.rows.len()
    }

    fn col_count(&self) -> usize {
        self.rows.first().map(|r| r.len()).unwrap_or(0)
    }

    fn value_at(&self, row: usize, col: usize) -> String {
        self.rows
            .get(row)
            .and_then(|r| r.get(col))
            .cloned()
            .unwrap_or_default()
    }
}

/// Configuration for a [`WindowedDataGridModel`]'s resident window.
///
/// The resident window is bounded by **count and bytes**; whichever bound is
/// reached first forces an eviction, so capacity is never inferred from
/// `row_count` (design `docs/design/datagrid-model-tiers.md` §5.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WindowedDataGridConfig {
    /// Maximum number of rows that may be resident at once. Values below 1
    /// are clamped to 1 by [`Self::new`].
    pub max_resident_rows: usize,
    /// Maximum payload bytes summed across all resident rows. Values below
    /// 1 are clamped to 1 by [`Self::new`]. A row's payload is the sum of
    /// [`String::len`] over its (truncated to `col_count`) cells.
    pub max_resident_bytes: usize,
    /// Cell text [`DataGridModel::value_at`] returns for an in-range row
    /// whose payload is not resident yet. Out-of-range coordinates return an
    /// empty string instead, never the placeholder.
    pub placeholder: String,
}

impl WindowedDataGridConfig {
    /// Creates a config with the default `"…"` placeholder.
    pub fn new(max_resident_rows: usize, max_resident_bytes: usize) -> Self {
        Self {
            max_resident_rows: max_resident_rows.max(1),
            max_resident_bytes: max_resident_bytes.max(1),
            placeholder: "…".to_owned(),
        }
    }

    /// Overrides the placeholder returned for non-resident in-range cells.
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = placeholder.into();
        self
    }
}

/// Outcome of [`WindowedDataGridHandle::deliver_row`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WindowedDelivery {
    /// The row became resident. `evicted` lists the rows dropped to honor
    /// the count/byte bounds, least-recently-used first.
    Applied { evicted: Vec<usize> },
    /// The row did not become resident. The fetch state is reset, so a later
    /// `value_at` for the row requests it again; the bounded window is never
    /// exceeded and nothing is partially applied.
    Rejected(WindowedDeliveryRejection),
}

/// Why a delivered row was refused. Every variant is a typed,
/// non-panicking refusal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowedDeliveryRejection {
    /// `row >= row_count`: the result cannot belong to this model (for
    /// example a stale result for a previous model shape).
    RowOutOfRange,
    /// No fetch was in flight for `row`: a late, duplicated, or foreign
    /// result, discarded fail-closed.
    NotInFlight,
    /// The row's payload alone exceeds `max_resident_bytes`, so it can never
    /// be resident (a byte budget that cannot hold one row is a caller
    /// configuration error rather than a panic).
    Oversized,
    /// Making room would require evicting a pinned row: every resident row
    /// lies in the active visible band, so the bounded window wins and the
    /// delivery is refused until the band is cleared or replaced.
    NoEvictableVictim,
}

/// A lazily-loaded, bounded resident row window over an arbitrary source
/// (T1, contract in `docs/design/datagrid-model-tiers.md` §4.2/§5/§8).
///
/// # Protocol
///
/// 1. Reads ([`DataGridModel::value_at`]) never block and never fetch: a
///    resident row returns its cells; an in-range miss records an in-flight
///    request, signals the repaint hook (once per scheduled fetch; repeat
///    reads while in flight only return the placeholder), and returns
///    [`WindowedDataGridConfig::placeholder`].
/// 2. A producer (the app's loader) turns requests into results off the UI
///    thread and applies them through a [`WindowedDataGridHandle`] obtained
///    with [`Self::handle`] - the drain path described in the design record
///    §6 (shape A). [`DataGridModel::is_row_resident`] reports residency so
///    a lane can repaint precisely when a row arrives.
/// 3. Eviction is LRU over resident rows, bounded by count **and** bytes.
///    [`WindowedDataGridHandle::pin_visible_band`] pins the visible band
///    for one `value_at` sequence (a paint/hit-test pass) so the row being
///    asked for can never be evicted while the pass reads it; pins are
///    never time-based and a new band replaces the old one.
/// 4. Dropping the model - or replacing it through
///    `Ui::set_data_grid_model`, which moves and drops the old one - drops
///    the request hook; a producer connected to it observes the closed
///    channel and stops (fail-closed), and a late result has no handle left
///    to be applied to.
///
/// The optional [`DataGridModel`] hooks (`get_attr`, editors, renderers,
/// spans) keep their trait defaults: a lazy model must not fetch from them
/// (design §3). Editing (`set_value_at`) is outside the lazy contract for
/// now (design §11 item 4).
///
/// No capacity or performance claim is attached to this type; a number must
/// be measured per the W2-L evidence rules before it is published.
///
/// ```
/// use native_gui_core::widgets::{DataGridModel, WindowedDataGridConfig, WindowedDataGridModel};
///
/// let requested = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
/// let log = std::rc::Rc::clone(&requested);
/// let model = WindowedDataGridModel::new(
///     500,
///     2,
///     WindowedDataGridConfig::new(8, 64 * 1024),
///     move |row| log.borrow_mut().push(row),
///     || {},
/// );
/// let handle = model.handle();
///
/// // A read of an un-fetched row is a non-blocking miss.
/// assert_eq!(model.value_at(120, 0), "…");
/// assert_eq!(*requested.borrow(), vec![120]);
/// assert!(!model.is_row_resident(120));
///
/// // The drain applies the fetched row; the next read sees it.
/// handle.deliver_row(120, vec!["a".to_owned(), "b".to_owned()]);
/// assert!(model.is_row_resident(120));
/// assert_eq!(model.value_at(120, 1), "b");
/// ```
pub struct WindowedDataGridModel {
    handle: WindowedDataGridHandle,
    on_fetch_requested: Box<dyn Fn(usize)>,
    on_repaint_requested: Box<dyn Fn()>,
}

impl WindowedDataGridModel {
    /// Creates a windowed model with a `row_count` x `col_count` shape.
    ///
    /// * `on_fetch_requested` is called with the row index on the first miss
    ///   for that row. It must schedule work and return promptly (post
    ///   through `UiProxy` in production); it runs after the model's state
    ///   borrow ends, so it may re-enter the window through a handle.
    /// * `on_repaint_requested` is called immediately after, so the layer
    ///   that owns the event loop can arrange a repaint: a miss never blocks
    ///   the paint. Under Mock, count the calls with
    ///   `native_gui_mock::windowed_fixture::RepaintCounter`.
    ///
    /// The hooks run on the calling (UI) thread and the model is `!Send`,
    /// matching the [`DataGridModel`] contract.
    pub fn new(
        row_count: usize,
        col_count: usize,
        config: WindowedDataGridConfig,
        on_fetch_requested: impl Fn(usize) + 'static,
        on_repaint_requested: impl Fn() + 'static,
    ) -> Self {
        Self {
            handle: WindowedDataGridHandle {
                row_count,
                col_count,
                config,
                state: Rc::new(RefCell::new(WindowedState::default())),
            },
            on_fetch_requested: Box::new(on_fetch_requested),
            on_repaint_requested: Box::new(on_repaint_requested),
        }
    }

    /// A cloneable handle to this model's window state.
    ///
    /// The handle is the *apply* path: keep it (for example in the UI
    /// thread's task drain) and call [`WindowedDataGridHandle::deliver_row`]
    /// when a producer has fetched a row, plus the pinning and counter
    /// accessors. The installed model and every handle share one window.
    pub fn handle(&self) -> WindowedDataGridHandle {
        self.handle.clone()
    }
}

impl DataGridModel for WindowedDataGridModel {
    fn row_count(&self) -> usize {
        self.handle.row_count
    }

    fn col_count(&self) -> usize {
        self.handle.col_count
    }

    /// Non-blocking by contract: a resident row returns its cells; an
    /// in-range miss returns the configured placeholder after scheduling
    /// one fetch and one repaint signal; out-of-range coordinates return an
    /// empty string. Reads touch the row's LRU position.
    fn value_at(&self, row: usize, col: usize) -> String {
        if row >= self.handle.row_count || col >= self.handle.col_count {
            return String::new();
        }
        let scheduled = {
            let mut state = self.handle.state.borrow_mut();
            if state.resident.contains_key(&row) {
                state.hits += 1;
                state.touch(row);
                return state
                    .resident
                    .get(&row)
                    .and_then(|resident| resident.cells.get(col))
                    .cloned()
                    .unwrap_or_default();
            }
            state.misses += 1;
            if state.in_flight.insert(row) {
                state.fetches_requested += 1;
                true
            } else {
                false
            }
        };
        if scheduled {
            // Hooks run after the state borrow ends so a hook may re-enter
            // the handle without panicking.
            (self.on_fetch_requested)(row);
            (self.on_repaint_requested)();
        }
        self.handle.config.placeholder.clone()
    }

    /// `false` for an in-range row whose payload is not resident yet (or
    /// whose fetch is still in flight); `true` for resident rows. Rows
    /// outside `0..row_count` are not resident.
    fn is_row_resident(&self, row: usize) -> bool {
        row < self.handle.row_count && self.handle.state.borrow().resident.contains_key(&row)
    }

    /// Forwards the band a backend paint pass opens on the trait object it
    /// holds to this model's window: rows in
    /// `[first_row, first_row + count)` are refused as eviction victims
    /// until [`DataGridModel::clear_pinned_band`].
    fn pin_visible_band(&self, first_row: usize, count: usize) {
        self.handle.pin_visible_band(first_row, count);
    }

    /// Forwards [`DataGridModel::pin_visible_band`]'s release.
    fn clear_pinned_band(&self) {
        self.handle.clear_pinned_band();
    }
}

impl std::fmt::Debug for WindowedDataGridModel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WindowedDataGridModel")
            .field("window", &self.handle)
            .finish()
    }
}

/// A cloneable handle to one [`WindowedDataGridModel`]'s resident window.
///
/// Handles share the model's window: the UI thread's drain applies fetched
/// rows with [`Self::deliver_row`], a render path brackets a paint pass with
/// [`Self::pin_visible_band`]/[`Self::clear_pinned_band`], and tests read
/// the counters. The handle is `!Send` on purpose - the window stays on the
/// UI thread (design §6), and a worker only ever posts a request or a result
/// *toward* it.
#[derive(Clone)]
pub struct WindowedDataGridHandle {
    row_count: usize,
    col_count: usize,
    config: WindowedDataGridConfig,
    state: Rc<RefCell<WindowedState>>,
}

impl WindowedDataGridHandle {
    /// Applies a fetched row to the window (the drain-side path, design §6
    /// shape A). A delivery is only accepted for a row with a fetch in
    /// flight, which makes stale, duplicated, or foreign results fail
    /// closed; `cells` is truncated to `col_count` because trailing cells
    /// are unreachable and must not occupy the byte budget.
    ///
    /// Nothing is applied on a [`WindowedDelivery::Rejected`] outcome and
    /// the fetch state is reset, so a later `value_at` requests the row
    /// again - a refusal never exceeds the bounded window.
    pub fn deliver_row(&self, row: usize, cells: Vec<String>) -> WindowedDelivery {
        if row >= self.row_count {
            self.state.borrow_mut().rejected_deliveries += 1;
            return WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange);
        }
        let mut cells = cells;
        cells.truncate(self.col_count);
        let bytes: usize = cells.iter().map(String::len).sum();

        let mut state = self.state.borrow_mut();
        if !state.in_flight.remove(&row) {
            state.rejected_deliveries += 1;
            return WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight);
        }
        if bytes > self.config.max_resident_bytes {
            state.rejected_deliveries += 1;
            return WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized);
        }

        // Defensive replace: the protocol cannot currently deliver a row
        // that is resident (a fetch only starts on a miss), but keeping the
        // accounting correct here costs nothing if that ever changes.
        if let Some(previous) = state.resident.remove(&row) {
            state.resident_bytes -= previous.bytes;
            state.lru.retain(|resident| *resident != row);
        }

        let mut evicted: Vec<usize> = Vec::new();
        while state.resident.len() >= self.config.max_resident_rows
            || state.resident_bytes.saturating_add(bytes) > self.config.max_resident_bytes
        {
            let victim = state
                .lru
                .iter()
                .copied()
                .find(|candidate| !state.is_pinned(*candidate));
            let Some(victim) = victim else {
                state.rejected_deliveries += 1;
                return WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim);
            };
            state.lru.retain(|resident| *resident != victim);
            if let Some(previous) = state.resident.remove(&victim) {
                state.resident_bytes -= previous.bytes;
                state.evictions += 1;
                evicted.push(victim);
            }
        }

        state.resident.insert(row, ResidentRow { cells, bytes });
        state.resident_bytes += bytes;
        state.lru.push_back(row);
        WindowedDelivery::Applied { evicted }
    }

    /// Pins the contiguous visible band `[first_row, first_row + count)` for
    /// one `value_at` sequence (design §5.3).
    ///
    /// The intended call site is a render path that brackets a paint or
    /// hit-test pass: pin before the first read, [`Self::clear_pinned_band`]
    /// after the last. A new `pin_visible_band` call *replaces* the previous
    /// band, so a later pass never inherits stale protection, and pins never
    /// expire on a timer - the bracket is the only scope. `count == 0`
    /// clears the band like [`Self::clear_pinned_band`].
    pub fn pin_visible_band(&self, first_row: usize, count: usize) {
        let mut state = self.state.borrow_mut();
        state.pinned_band = if count == 0 {
            None
        } else {
            Some((first_row, count))
        };
    }

    /// Ends the current pin scope (see [`Self::pin_visible_band`]).
    pub fn clear_pinned_band(&self) {
        self.state.borrow_mut().pinned_band = None;
    }

    /// The active visible band, when one is pinned.
    pub fn pinned_band(&self) -> Option<(usize, usize)> {
        self.state.borrow().pinned_band
    }

    /// Whether `row`'s payload is currently resident.
    pub fn is_row_resident(&self, row: usize) -> bool {
        row < self.row_count && self.state.borrow().resident.contains_key(&row)
    }

    /// Whether a fetch for `row` has been requested and not applied yet.
    pub fn is_row_in_flight(&self, row: usize) -> bool {
        self.state.borrow().in_flight.contains(&row)
    }

    /// Number of resident rows (never above `max_resident_rows`).
    pub fn resident_row_count(&self) -> usize {
        self.state.borrow().resident.len()
    }

    /// Payload bytes currently held by resident rows (never above
    /// `max_resident_bytes`).
    pub fn resident_bytes(&self) -> usize {
        self.state.borrow().resident_bytes
    }

    /// Number of rows with a fetch requested but not applied yet.
    pub fn in_flight_count(&self) -> usize {
        self.state.borrow().in_flight.len()
    }

    /// Reads answered from the resident window.
    pub fn hits(&self) -> usize {
        self.state.borrow().hits
    }

    /// In-range reads answered with the placeholder, including repeat reads
    /// while the row's fetch is still in flight.
    pub fn misses(&self) -> usize {
        self.state.borrow().misses
    }

    /// Fetches scheduled: one per row-load (the fetch hook ran that many
    /// times). Repeat reads while in flight do not increment it.
    pub fn fetches_requested(&self) -> usize {
        self.state.borrow().fetches_requested
    }

    /// Rows dropped by bounds-driven eviction.
    pub fn evictions(&self) -> usize {
        self.state.borrow().evictions
    }

    /// Deliveries refused, for any [`WindowedDeliveryRejection`] reason.
    pub fn rejected_deliveries(&self) -> usize {
        self.state.borrow().rejected_deliveries
    }
}

impl std::fmt::Debug for WindowedDataGridHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let state = self.state.borrow();
        f.debug_struct("WindowedDataGridHandle")
            .field("row_count", &self.row_count)
            .field("col_count", &self.col_count)
            .field("resident_rows", &state.resident.len())
            .field("resident_bytes", &state.resident_bytes)
            .field("in_flight", &state.in_flight.len())
            .field("hits", &state.hits)
            .field("misses", &state.misses)
            .field("evictions", &state.evictions)
            .finish()
    }
}

#[derive(Default)]
struct WindowedState {
    resident: HashMap<usize, ResidentRow>,
    /// Resident rows in LRU order: front is evicted first, back is MRU.
    lru: VecDeque<usize>,
    /// Rows requested by `value_at` whose payload was not applied yet.
    in_flight: BTreeSet<usize>,
    /// The active visible band, replaced (not extended) by each
    /// `pin_visible_band` call.
    pinned_band: Option<(usize, usize)>,
    resident_bytes: usize,
    hits: usize,
    misses: usize,
    fetches_requested: usize,
    evictions: usize,
    rejected_deliveries: usize,
}

impl WindowedState {
    fn touch(&mut self, row: usize) {
        if let Some(position) = self.lru.iter().position(|resident| *resident == row) {
            self.lru.remove(position);
        }
        self.lru.push_back(row);
    }

    fn is_pinned(&self, row: usize) -> bool {
        match self.pinned_band {
            Some((first, count)) => row >= first && row - first < count,
            None => false,
        }
    }
}

struct ResidentRow {
    cells: Vec<String>,
    bytes: usize,
}

/// In-memory widget description shared between `Ui` and backends.
#[derive(Debug, Clone, PartialEq)]
pub struct WidgetSpec {
    /// Unique widget identifier.
    pub id: WidgetId,
    /// The type of widget to create.
    pub kind: WidgetKind,
    /// Optional display text or initial value.
    pub text: Option<String>,
    /// Optional text selection range in characters (start inclusive, end
    /// exclusive) for `TextInput`/`TextArea`.
    pub text_selection: Option<(usize, usize)>,
    /// Completion/suggestion items for a `TextInput`.
    ///
    /// The shared model keeps the full item list; lanes filter it for the
    /// current text (case-insensitive prefix by default) and own their
    /// popup. Empty means completion is off.
    pub completion_items: Vec<String>,
    /// Optional placeholder/hint text (`TextInput`).
    pub placeholder_text: Option<String>,
    /// Parent widget, if attached.
    pub parent: Option<WidgetId>,
    /// Container orientation (only meaningful for `WidgetKind::Container`).
    pub container_direction: Option<ContainerDirection>,
    /// Container wrapping mode (`Container`, `GroupBox`, `SplitPane`).
    pub container_wrap: Option<ContainerWrap>,
    /// Container vertical scroll setting.
    pub container_scroll_vertical: bool,
    /// Container horizontal scroll setting.
    pub container_scroll_horizontal: bool,
    /// Uniform spacing between flow children in logical pixels
    /// (`Container`, `GroupBox`); negatives clamp to 0.
    pub container_gap: Option<i32>,
    /// Uniform inset between the container edges and its flow children in
    /// logical pixels (`Container`, `GroupBox`); negatives clamp to 0.
    pub container_padding: Option<i32>,
    /// Preferred widget size as `(width, height)` in logical pixels.
    pub size: Option<(i32, i32)>,
    /// Preferred widget position as `(x, y)` in logical pixels.
    pub position: Option<(i32, i32)>,
    /// Rows/items for list widgets.
    pub data_list_items: Vec<String>,
    /// Column headers for the columned list contract (`ListView`).
    /// Empty keeps the shipped single-column row contract,
    /// where rows come from [`Self::data_list_items`].
    pub list_columns: Vec<ColumnSpec>,
    /// Row cells aligned to [`Self::list_columns`] (`ListView`):
    /// row `r`, cell `c` renders the header `c` with text
    /// `list_rows[r][c]`. Missing trailing cells render empty and cells
    /// beyond the column count are ignored.
    pub list_rows: Vec<Vec<String>>,
    /// Row-major cell values for data grid widgets.
    ///
    /// Shared behind an [`Arc`] so the manager's spec and the backend hold a
    /// single resident allocation instead of each keeping a private copy.
    pub data_grid_rows: Arc<Vec<Vec<String>>>,
    /// Hierarchical items for `WidgetKind::TreeView`.
    pub tree_items: Vec<TreeItem>,
    /// Optional background color.
    pub background_color: Option<Color>,
    /// Alert severity metadata (only meaningful for `WidgetKind::AlertDialog`).
    pub alert_level: Option<AlertLevel>,
    /// Optional checked state metadata.
    pub checked: Option<bool>,
    /// Optional enabled/disabled state metadata.
    pub enabled: Option<bool>,
    /// Optional numeric range metadata as `(min, max)`.
    pub range: Option<(i32, i32)>,
    /// Optional numeric step metadata.
    pub step: Option<i32>,
    /// Optional numeric value metadata.
    pub value: Option<i32>,
    /// Optional grouping metadata (radio-like widgets).
    pub group_name: Option<String>,
    /// Optional tab labels metadata (`WidgetKind::Tabs`).
    ///
    /// Tab strip height is dynamically resolved in layout passes from backend measurements
    /// or typography scaling, backed by a minimum floor to prevent collapse.
    pub tab_items: Vec<String>,
    /// Optional selected item index metadata.
    pub selected_index: Option<usize>,
    /// Optional multi-selection indices metadata (list/tree widgets).
    pub selected_indices: Vec<usize>,
    /// Row drag source metadata: rows of this list/tree can be dragged out.
    pub row_drag_source: bool,
    /// Row drop target metadata: rows can be dropped onto this list/tree.
    pub row_drop_target: bool,
    /// File drop target metadata: external files can be dropped onto this widget.
    pub file_drop_target: bool,
    /// Optional image source metadata.
    pub image_source: Option<String>,
    /// How the image scales into its widget bounds.
    pub image_fit: ImageFit,
    /// Optional stock-art icon role rendered beside the button label:
    /// `Button` and `FileChooserDialog` only.
    pub icon: Option<IconRole>,
    /// What the file chooser dialog lets the user pick.
    pub file_chooser_mode: FileChooserMode,
    /// Optional date metadata (`YYYY-MM-DD`).
    pub date_value: Option<String>,
    /// Optional link URL metadata.
    pub link_url: Option<String>,
    /// Optional tooltip text metadata.
    pub tooltip: Option<String>,
    /// Portable accessibility metadata: name, description, role.
    pub accessibility: AccessibilitySpec,
    /// Keyboard focusability override; `None` uses the per-kind
    /// default from [`crate::focus::default_focusable`].
    pub focusable: Option<bool>,
    /// Optional split ratio metadata (`0..=100`).
    pub split_ratio: Option<u8>,
    /// Optional scene data for `WidgetKind::Canvas`.
    pub canvas_scene: Option<CanvasScene>,
    /// Optional raster surface painted beneath the canvas scene.
    pub canvas_surface: Option<CanvasSurface>,
    /// Portable colour-dialog preferences: initial colour, custom
    /// palette, and the full-mode/alpha requests.
    pub color_dialog_data: Option<ColorDialogData>,
    /// Portable font-dialog preferences: initial descriptor,
    /// effects, and the size-range restriction.
    pub font_dialog_data: Option<FontDialogData>,
    /// Portable toolbar rows: tools and separators, in display
    /// order. Ids are application-owned and survive rebuilds.
    pub toolbar_items: Vec<ToolbarItem>,
    /// Toolbar stacking orientation.
    pub toolbar_orientation: ToolbarOrientation,
    /// Selected dates for calendar widgets.
    pub calendar_selected_dates: Vec<CalendarDate>,
    /// Minimum selectable date.
    pub calendar_min_date: Option<CalendarDate>,
    /// Maximum selectable date.
    pub calendar_max_date: Option<CalendarDate>,
    /// First day of week convention.
    pub calendar_first_day_of_week: CalendarFirstDayOfWeek,
    /// Selection mode for calendar widgets.
    pub calendar_selection_mode: CalendarSelectionMode,
    /// Text alignment for label widgets.
    pub label_alignment: LabelAlignment,
    /// Text wrap mode for label widgets.
    pub label_wrap: LabelWrap,
    /// Styled text runs for rich text widgets.
    pub rich_text_runs: Vec<TextRun>,
    /// Inline images for rich text widgets.
    pub rich_text_images: Vec<RichTextImage>,
    /// Monospace font rendering for text-bearing widgets.
    pub monospace: bool,
    /// Explicit widget font descriptor (`None` follows theme/platform defaults).
    pub font: Option<FontDescriptor>,
    /// Per-row stock-art icon roles for `DataList` and `ListView` controls.
    pub row_icons: Vec<Option<IconRole>>,
}

impl WidgetSpec {
    /// Creates a new widget specification.
    ///
    /// Container widgets default to vertical stacking.
    pub fn new(id: WidgetId, kind: WidgetKind) -> Self {
        Self {
            id,
            kind,
            text: None,
            text_selection: None,
            completion_items: Vec::new(),
            parent: None,
            container_direction: if kind == WidgetKind::Container {
                Some(ContainerDirection::Vertical)
            } else {
                None
            },
            container_wrap: if kind == WidgetKind::Container {
                Some(ContainerWrap::NoWrap)
            } else {
                None
            },
            container_scroll_vertical: false,
            container_scroll_horizontal: false,
            container_gap: None,
            container_padding: None,
            size: None,
            position: None,
            data_list_items: Vec::new(),
            list_columns: Vec::new(),
            list_rows: Vec::new(),
            data_grid_rows: Arc::new(Vec::new()),
            tree_items: Vec::new(),
            background_color: None,
            alert_level: {
                #[cfg(feature = "widgets-containers")]
                {
                    if kind == WidgetKind::AlertDialog {
                        Some(AlertLevel::Info)
                    } else {
                        None
                    }
                }
                #[cfg(not(feature = "widgets-containers"))]
                {
                    None
                }
            },
            checked: None,
            enabled: None,
            range: None,
            step: None,
            value: None,
            group_name: None,
            tab_items: Vec::new(),
            selected_index: None,
            selected_indices: Vec::new(),
            row_drag_source: false,
            row_drop_target: false,
            file_drop_target: false,
            image_source: None,
            image_fit: ImageFit::default(),
            icon: None,
            file_chooser_mode: FileChooserMode::default(),
            date_value: None,
            link_url: None,
            tooltip: None,
            accessibility: AccessibilitySpec::for_kind(kind),
            focusable: None,
            split_ratio: None,
            canvas_scene: None,
            canvas_surface: None,
            color_dialog_data: None,
            font_dialog_data: None,
            toolbar_items: Vec::new(),
            toolbar_orientation: ToolbarOrientation::default(),
            calendar_selected_dates: Vec::new(),
            calendar_min_date: None,
            calendar_max_date: None,
            calendar_first_day_of_week: CalendarFirstDayOfWeek::default(),
            calendar_selection_mode: CalendarSelectionMode::default(),
            label_alignment: match kind {
                WidgetKind::Button => LabelAlignment::Center,
                _ => LabelAlignment::default(),
            },
            label_wrap: LabelWrap::default(),
            rich_text_runs: Vec::new(),
            rich_text_images: Vec::new(),
            placeholder_text: None,
            monospace: false,
            font: None,
            row_icons: Vec::new(),
        }
    }

    /// Rejects the property when this spec's kind is outside its
    /// applicability row, returning the shared typed error.
    pub fn ensure_property(&self, property: WidgetProperty) -> GuiResult<()> {
        if property.supports(self.kind) {
            Ok(())
        } else {
            Err(GuiError::UnsupportedWidget(property.operation()))
        }
    }

    /// Alias for [`Self::ensure_property`].
    pub fn requires_property(&self, property: WidgetProperty) -> GuiResult<()> {
        self.ensure_property(property)
    }

    /// Sets the widget text.
    pub fn with_text(mut self, text: impl Into<String>) -> Self {
        self.text = Some(text.into());
        self
    }

    /// Sets completion/suggestion items for a `TextInput`.
    pub fn with_completion_items(mut self, items: Vec<String>) -> Self {
        self.completion_items = items;
        self
    }

    /// Sets the parent widget identifier.
    pub fn with_parent(mut self, parent: WidgetId) -> Self {
        self.parent = Some(parent);
        self
    }

    /// Sets container direction metadata.
    pub fn with_container_direction(mut self, direction: ContainerDirection) -> Self {
        self.container_direction = Some(direction);
        self
    }

    /// Sets container wrap metadata.
    pub fn with_container_wrap(mut self, wrap: ContainerWrap) -> Self {
        self.container_wrap = Some(wrap);
        self
    }

    /// Enables/disables container scrolling metadata.
    pub fn with_container_scroll(mut self, vertical: bool, horizontal: bool) -> Self {
        self.container_scroll_vertical = vertical;
        self.container_scroll_horizontal = horizontal;
        self
    }

    /// Sets the uniform flow spacing between container children.
    pub fn with_container_gap(mut self, gap: i32) -> Self {
        self.container_gap = Some(gap.max(0));
        self
    }

    /// Sets the uniform inset between the container edges and its flow
    /// children.
    pub fn with_container_padding(mut self, padding: i32) -> Self {
        self.container_padding = Some(padding.max(0));
        self
    }

    /// Sets preferred size metadata for a widget.
    pub fn with_size(mut self, width: i32, height: i32) -> Self {
        self.size = Some((width, height));
        self
    }

    /// Sets preferred position metadata for a widget.
    pub fn with_position(mut self, x: i32, y: i32) -> Self {
        self.position = Some((x, y));
        self
    }

    /// Sets list items for `WidgetKind::DataList`.
    pub fn with_data_list_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
        self.data_list_items = items.into_iter().collect();
        self
    }

    /// Sets column headers for the columned list contract (`ListView`);
    /// an empty list keeps the single-column row contract.
    pub fn with_list_columns(mut self, columns: impl IntoIterator<Item = ColumnSpec>) -> Self {
        self.list_columns = columns.into_iter().collect();
        self
    }

    /// Sets row cells for the columned list contract (`ListView`);
    /// see [`Self::list_rows`] for the cell rule.
    pub fn with_list_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
        self.list_rows = rows.into_iter().collect();
        self
    }

    /// Sets row-major data for `WidgetKind::DataGrid`.
    pub fn with_data_grid_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
        self.data_grid_rows = Arc::new(rows.into_iter().collect());
        self
    }

    /// Sets hierarchical items for `WidgetKind::TreeView`.
    pub fn with_tree_items(mut self, items: impl IntoIterator<Item = TreeItem>) -> Self {
        self.tree_items = items.into_iter().collect();
        self
    }

    /// Sets optional background color metadata for a widget.
    pub fn with_background_color(mut self, color: Color) -> Self {
        self.background_color = Some(color);
        self
    }

    /// Sets alert severity metadata for `WidgetKind::AlertDialog`.
    pub fn with_alert_level(mut self, level: AlertLevel) -> Self {
        self.alert_level = Some(level);
        self
    }

    /// Sets optional checked state metadata.
    pub fn with_checked(mut self, checked: bool) -> Self {
        self.checked = Some(checked);
        self
    }

    /// Sets optional enabled/disabled state metadata.
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }

    /// Sets numeric range metadata.
    pub fn with_range(mut self, min: i32, max: i32) -> Self {
        self.range = Some((min, max));
        self
    }

    /// Sets numeric step metadata.
    pub fn with_step(mut self, step: i32) -> Self {
        self.step = Some(step);
        self
    }

    /// Sets numeric value metadata.
    pub fn with_value(mut self, value: i32) -> Self {
        self.value = Some(value);
        self
    }

    /// Sets multi-selection indices metadata.
    pub fn with_selected_indices(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
        self.selected_indices = indices.into_iter().collect();
        self
    }

    /// Marks this widget's rows as a drag source.
    pub fn with_row_drag_source(mut self, enabled: bool) -> Self {
        self.row_drag_source = enabled;
        self
    }

    /// Marks this widget's rows as a drop target.
    pub fn with_row_drop_target(mut self, enabled: bool) -> Self {
        self.row_drop_target = enabled;
        self
    }

    /// Marks this widget as accepting external file drops from the OS shell.
    pub fn with_file_drop_target(mut self, enabled: bool) -> Self {
        self.file_drop_target = enabled;
        self
    }

    /// Sets grouping metadata.
    pub fn with_group_name(mut self, name: impl Into<String>) -> Self {
        self.group_name = Some(name.into());
        self
    }

    /// Sets tab labels metadata.
    ///
    /// When rendered within a layout, tab strips automatically enforce a dynamic
    /// typography- and DPI-aware minimum height floor based on backend measurements
    /// (or falling back to 30.0pt), ensuring empty or short tab pages
    /// do not collapse the tab header strip.
    pub fn with_tab_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
        self.tab_items = items.into_iter().collect();
        self
    }

    /// Sets selected index metadata.
    pub fn with_selected_index(mut self, selected_index: usize) -> Self {
        self.selected_index = Some(selected_index);
        self
    }

    /// Sets image source metadata.
    pub fn with_image_source(mut self, source: impl Into<String>) -> Self {
        self.image_source = Some(source.into());
        self
    }

    /// Sets how the image scales into its bounds.
    pub fn with_image_fit(mut self, fit: ImageFit) -> Self {
        self.image_fit = fit;
        self
    }

    /// Sets what the file chooser dialog lets the user pick.
    pub fn with_file_chooser_mode(mut self, mode: FileChooserMode) -> Self {
        self.file_chooser_mode = mode;
        self
    }

    /// Sets date metadata (`YYYY-MM-DD`).
    pub fn with_date_value(mut self, date: impl Into<String>) -> Self {
        self.date_value = Some(date.into());
        self
    }

    /// Sets link URL metadata.
    pub fn with_link_url(mut self, url: impl Into<String>) -> Self {
        self.link_url = Some(url.into());
        self
    }

    /// Sets tooltip text metadata.
    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
        self.tooltip = Some(tooltip.into());
        self
    }

    /// Sets the accessible name announced by assistive technology.
    pub fn with_accessible_name(mut self, name: impl Into<String>) -> Self {
        self.accessibility.name = Some(name.into());
        self
    }

    /// Sets the accessible description announced after the name.
    pub fn with_accessible_description(mut self, description: impl Into<String>) -> Self {
        self.accessibility.description = Some(description.into());
        self
    }

    /// Overrides whether the widget participates in keyboard focus;
    /// `None` (the default) uses the per-kind default.
    pub fn with_focusable(mut self, focusable: bool) -> Self {
        self.focusable = Some(focusable);
        self
    }

    /// Sets split ratio metadata (`0..=100`).
    pub fn with_split_ratio(mut self, ratio: u8) -> Self {
        self.split_ratio = Some(ratio.min(100));
        self
    }

    /// Sets the canvas drawing scene for `WidgetKind::Canvas`.
    pub fn with_canvas_scene(mut self, scene: CanvasScene) -> Self {
        self.canvas_scene = Some(scene);
        self
    }

    /// Sets the raster surface painted beneath the canvas scene.
    pub fn with_canvas_surface(mut self, surface: CanvasSurface) -> Self {
        self.canvas_surface = Some(surface);
        self
    }

    /// Sets the colour-dialog preferences.
    pub fn with_color_dialog_data(mut self, data: ColorDialogData) -> Self {
        self.color_dialog_data = Some(data);
        self
    }

    /// Sets the font-dialog preferences.
    pub fn with_font_dialog_data(mut self, data: FontDialogData) -> Self {
        self.font_dialog_data = Some(data);
        self
    }

    /// Sets the toolbar rows.
    pub fn with_toolbar_items(mut self, items: Vec<ToolbarItem>) -> Self {
        self.toolbar_items = items;
        self
    }

    /// Sets the toolbar orientation.
    pub fn with_toolbar_orientation(mut self, orientation: ToolbarOrientation) -> Self {
        self.toolbar_orientation = orientation;
        self
    }

    /// Sets the calendar selected dates.
    pub fn with_calendar_selected_dates(
        mut self,
        dates: impl IntoIterator<Item = CalendarDate>,
    ) -> Self {
        self.calendar_selected_dates = dates.into_iter().collect();
        self
    }

    /// Sets the calendar selectable min and max bounds.
    pub fn with_calendar_bounds(
        mut self,
        min: Option<CalendarDate>,
        max: Option<CalendarDate>,
    ) -> Self {
        self.calendar_min_date = min;
        self.calendar_max_date = max;
        self
    }

    /// Sets the calendar first day of the week convention.
    pub fn with_calendar_first_day_of_week(mut self, first_day: CalendarFirstDayOfWeek) -> Self {
        self.calendar_first_day_of_week = first_day;
        self
    }

    /// Sets the calendar selection mode.
    pub fn with_calendar_selection_mode(mut self, mode: CalendarSelectionMode) -> Self {
        self.calendar_selection_mode = mode;
        self
    }

    /// Sets the label text alignment.
    pub fn with_label_alignment(mut self, alignment: impl Into<LabelAlignment>) -> Self {
        self.label_alignment = alignment.into();
        self
    }

    /// Sets the label text wrap mode.
    pub fn with_label_wrap(mut self, wrap: impl Into<LabelWrap>) -> Self {
        self.label_wrap = wrap.into();
        self
    }

    /// Sets the label text wrap mode, alias for [`Self::with_label_wrap`].
    pub fn with_label_wrap_mode(self, wrap: impl Into<LabelWrap>) -> Self {
        self.with_label_wrap(wrap)
    }

    /// Sets the styled text runs for rich text widgets.
    pub fn with_rich_text_runs(mut self, runs: impl IntoIterator<Item = TextRun>) -> Self {
        self.rich_text_runs = runs.into_iter().collect();
        self
    }

    /// Sets the inline images for rich text widgets.
    pub fn with_rich_text_images(
        mut self,
        images: impl IntoIterator<Item = RichTextImage>,
    ) -> Self {
        self.rich_text_images = images.into_iter().collect();
        self
    }

    /// Sets the placeholder/hint text (`TextInput`).
    pub fn with_placeholder_text(mut self, text: impl Into<String>) -> Self {
        self.placeholder_text = Some(text.into());
        self
    }

    /// Sets monospace font rendering metadata.
    pub fn with_monospace(mut self, monospace: bool) -> Self {
        self.monospace = monospace;
        self
    }
}

/// Returns the set of widgets intended to be portable across backends.
pub fn abstractable_widget_types() -> &'static [WidgetKind] {
    // This list is intentionally limited to controls that map cleanly to both
    // Windows Win32 controls and GTK4 widgets without requiring custom drawing.
    &[
        WidgetKind::Window,
        WidgetKind::Container,
        WidgetKind::Label,
        WidgetKind::Button,
        #[cfg(feature = "widgets-choice")]
        WidgetKind::RadioButton,
        #[cfg(feature = "widgets-range")]
        WidgetKind::Slider,
        #[cfg(feature = "widgets-range")]
        WidgetKind::SpinBox,
        #[cfg(feature = "widgets-containers")]
        WidgetKind::Separator,
        #[cfg(feature = "widgets-containers")]
        WidgetKind::GroupBox,
        #[cfg(feature = "widgets-containers")]
        WidgetKind::Tabs,
        #[cfg(feature = "widgets-media")]
        WidgetKind::Image,
        #[cfg(feature = "widgets-pickers")]
        WidgetKind::DatePicker,
        #[cfg(feature = "widgets-text")]
        WidgetKind::LinkLabel,
        #[cfg(feature = "widgets-data")]
        WidgetKind::ListView,
        #[cfg(feature = "widgets-data")]
        WidgetKind::TreeView,
        #[cfg(feature = "widgets-containers")]
        WidgetKind::SplitPane,
        #[cfg(feature = "widgets-pickers")]
        WidgetKind::FileChooserDialog,
        #[cfg(feature = "widgets-containers")]
        WidgetKind::AlertDialog,
        #[cfg(feature = "widgets-text")]
        WidgetKind::TextInput,
        #[cfg(feature = "widgets-text")]
        WidgetKind::TextArea,
        #[cfg(feature = "widgets-canvas")]
        WidgetKind::VulkanCanvas,
        #[cfg(feature = "widgets-choice")]
        WidgetKind::Checkbox,
        #[cfg(feature = "widgets-choice")]
        WidgetKind::ComboBox,
        #[cfg(feature = "widgets-range")]
        WidgetKind::ProgressBar,
        #[cfg(feature = "widgets-data")]
        WidgetKind::DataList,
        #[cfg(feature = "widgets-data")]
        WidgetKind::DataGrid,
        #[cfg(feature = "widgets-canvas")]
        WidgetKind::Canvas,
        #[cfg(feature = "widgets-pickers")]
        WidgetKind::ColorDialog,
        #[cfg(feature = "widgets-pickers")]
        WidgetKind::FontDialog,
        WidgetKind::Toolbar,
        #[cfg(feature = "widgets-pickers")]
        WidgetKind::Calendar,
        #[cfg(feature = "widgets-choice")]
        WidgetKind::MultiSelect,
    ]
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;
    use std::sync::mpsc;
    use std::time::Duration;

    #[test]
    fn widget_spec_builder_sets_fields() {
        let id = WidgetId(1);
        let parent = WidgetId(9);
        let spec = WidgetSpec::new(id, WidgetKind::Button)
            .with_text("Click me")
            .with_parent(parent);

        assert_eq!(spec.id, id);
        assert_eq!(spec.kind, WidgetKind::Button);
        assert_eq!(spec.text.as_deref(), Some("Click me"));
        assert_eq!(spec.parent, Some(parent));
        assert_eq!(spec.container_direction, None);
        assert!(!spec.container_scroll_vertical);
        assert!(!spec.container_scroll_horizontal);
        assert_eq!(spec.size, None);
        assert_eq!(spec.position, None);
        assert_eq!(spec.data_list_items, Vec::<String>::new());
        assert!(spec.data_grid_rows.is_empty());
        assert_eq!(spec.background_color, None);
        assert_eq!(spec.alert_level, None);
        assert_eq!(spec.checked, None);
        assert_eq!(spec.range, None);
        assert_eq!(spec.step, None);
        assert_eq!(spec.value, None);
        assert_eq!(spec.group_name, None);
        assert_eq!(spec.tab_items, Vec::<String>::new());
        assert_eq!(spec.selected_index, None);
        assert_eq!(spec.image_source, None);
        assert_eq!(spec.date_value, None);
        assert_eq!(spec.link_url, None);
        assert_eq!(spec.tooltip, None);
        assert_eq!(spec.split_ratio, None);
        assert_eq!(spec.label_alignment, LabelAlignment::Center);
        assert_eq!(spec.label_wrap, LabelWrap::None);

        let spec = spec.with_tooltip("Helpful hint");
        assert_eq!(spec.tooltip.as_deref(), Some("Helpful hint"));
    }

    #[test]
    fn widget_spec_builder_sets_size() {
        let spec = WidgetSpec::new(WidgetId(5), WidgetKind::Button).with_size(120, 44);

        assert_eq!(spec.size, Some((120, 44)));
    }

    #[test]
    fn widget_spec_builder_sets_position() {
        let spec = WidgetSpec::new(WidgetId(7), WidgetKind::Button).with_position(32, 48);

        assert_eq!(spec.position, Some((32, 48)));
    }

    #[test]
    fn widget_spec_builder_sets_background_color() {
        let color = Color::rgb(24, 42, 64);
        let spec = WidgetSpec::new(WidgetId(6), WidgetKind::Label).with_background_color(color);

        assert_eq!(spec.background_color, Some(color));
    }

    #[test]
    #[cfg(feature = "widgets-data")]
    fn widget_spec_builder_sets_data_items() {
        let list_spec = WidgetSpec::new(WidgetId(10), WidgetKind::DataList)
            .with_data_list_items(vec!["A".to_owned(), "B".to_owned()]);
        assert_eq!(
            list_spec.data_list_items,
            vec!["A".to_owned(), "B".to_owned()]
        );

        let grid_spec =
            WidgetSpec::new(WidgetId(11), WidgetKind::DataGrid).with_data_grid_rows(vec![
                vec!["r1c1".to_owned(), "r1c2".to_owned()],
                vec!["r2c1".to_owned(), "r2c2".to_owned()],
            ]);
        let expected = vec![
            vec!["r1c1".to_owned(), "r1c2".to_owned()],
            vec!["r2c1".to_owned(), "r2c2".to_owned()],
        ];
        assert_eq!(grid_spec.data_grid_rows.as_ref(), &expected);
    }

    #[test]
    fn column_spec_width_preference_follows_shared_size_semantics() {
        let column = ColumnSpec::new("Name");
        assert_eq!(column.title, "Name");
        assert_eq!(column.width, None);
        assert_eq!(ColumnSpec::new("Name").with_width(80).width, Some(80));
        assert_eq!(
            ColumnSpec::new("Name").with_width(0).width,
            None,
            "non-positive width means no preference"
        );
        assert_eq!(ColumnSpec::new("Name").with_width(-4).width, None);
    }

    #[test]
    #[cfg(feature = "widgets-data")]
    fn widget_spec_builder_sets_list_columns_and_rows() {
        let spec = WidgetSpec::new(WidgetId(12), WidgetKind::ListView)
            .with_list_columns(vec![ColumnSpec::new("Name"), ColumnSpec::new("Size")])
            .with_list_rows(vec![
                vec!["a.txt".to_owned(), "12 KB".to_owned()],
                vec!["folder".to_owned()],
            ]);
        assert_eq!(spec.list_columns.len(), 2);
        assert_eq!(spec.list_columns[1].title, "Size");
        assert_eq!(spec.list_rows.len(), 2);
        assert_eq!(spec.list_rows[1], vec!["folder".to_owned()]);

        // Both rows apply to `ListView` only; `DataList` stays on its
        // single-column list contract.
        spec_with_columns(WidgetKind::ListView).expect("ListView accepted");
        assert_eq!(
            spec_with_columns(WidgetKind::DataList).expect_err("DataList rejected"),
            GuiError::UnsupportedWidget("set_list_columns")
        );
    }

    /// `ensure_property` view of the columned rows, used by the test above.
    fn spec_with_columns(kind: WidgetKind) -> GuiResult<()> {
        WidgetSpec::new(WidgetId(13), kind).ensure_property(WidgetProperty::ListViewColumns)
    }

    #[test]
    fn row_diff_classifies_insert_update_move_keep_and_remove() {
        let old = [
            RowSet::new(1, &["a"]),
            RowSet::new(2, &["b"]),
            RowSet::new(3, &["c"]),
        ];
        let new = [
            RowSet::new(4, &["d"]),
            RowSet::new(2, &["b2"]),
            RowSet::new(3, &["c"]),
            RowSet::new(1, &["a"]),
        ];
        assert_eq!(
            diff_rows(&old, &new).expect("diff"),
            RowDelta {
                inserted: 1,
                updated: 1,
                removed: 0,
                moved: 1,
                unchanged: 1,
            }
        );
    }

    #[test]
    fn row_diff_counts_removals_reorders_and_duplicates() {
        let old = [
            RowSet::new(1, &["a"]),
            RowSet::new(2, &["b"]),
            RowSet::new(3, &["c"]),
        ];
        let new = [RowSet::new(1, &["a"])];
        let delta = diff_rows(&old, &new).expect("diff");
        assert_eq!(delta.removed, 2);
        assert_eq!(delta.unchanged, 1);
        assert!(!delta.is_noop());

        // Reordering identical content is moves, never updates; an
        // identical set is the free no-op.
        let reordered = [old[2].clone(), old[0].clone(), old[1].clone()];
        let delta = diff_rows(&old, &reordered).expect("diff");
        assert_eq!(
            delta,
            RowDelta {
                inserted: 0,
                updated: 0,
                removed: 0,
                moved: 3,
                unchanged: 0,
            }
        );
        assert!(diff_rows(&old, &old).expect("diff").is_noop());

        // Duplicate keys are rejected before anything is classified.
        let duplicates = [RowSet::new(9, &["x"]), RowSet::new(9, &["y"])];
        assert_eq!(
            diff_rows(&old, &duplicates),
            Err(GuiError::Backend("duplicate row key".to_owned()))
        );
    }

    #[test]
    fn row_set_builder_and_single_cell_text() {
        let row = RowSet::new(7, &["Name", "12 KB"]);
        assert_eq!(row.key, RowKey(7));
        assert_eq!(row.cells, vec!["Name".to_owned(), "12 KB".to_owned()]);
        assert_eq!(row.text(), "Name");
        assert_eq!(RowSet::new(8, &[]).text(), "");
    }

    #[test]
    fn container_defaults_to_vertical_direction() {
        let spec = WidgetSpec::new(WidgetId(2), WidgetKind::Container);
        assert_eq!(spec.container_direction, Some(ContainerDirection::Vertical));
        assert!(!spec.container_scroll_vertical);
        assert!(!spec.container_scroll_horizontal);
    }

    #[test]
    fn container_builder_sets_scroll_flags() {
        let spec =
            WidgetSpec::new(WidgetId(3), WidgetKind::Container).with_container_scroll(true, false);
        assert!(spec.container_scroll_vertical);
        assert!(!spec.container_scroll_horizontal);
    }

    #[test]
    fn abstractable_widget_types_contains_expected_kinds() {
        let list = abstractable_widget_types();
        assert!(list.contains(&WidgetKind::Window));
        assert!(list.contains(&WidgetKind::Button));
        #[cfg(feature = "widgets-choice")]
        assert!(list.contains(&WidgetKind::RadioButton));
        #[cfg(feature = "widgets-range")]
        assert!(list.contains(&WidgetKind::Slider));
        #[cfg(feature = "widgets-range")]
        assert!(list.contains(&WidgetKind::SpinBox));
        #[cfg(feature = "widgets-containers")]
        assert!(list.contains(&WidgetKind::Separator));
        #[cfg(feature = "widgets-containers")]
        assert!(list.contains(&WidgetKind::GroupBox));
        #[cfg(feature = "widgets-containers")]
        assert!(list.contains(&WidgetKind::Tabs));
        #[cfg(feature = "widgets-media")]
        assert!(list.contains(&WidgetKind::Image));
        #[cfg(feature = "widgets-pickers")]
        assert!(list.contains(&WidgetKind::DatePicker));
        #[cfg(feature = "widgets-text")]
        assert!(list.contains(&WidgetKind::LinkLabel));
        #[cfg(feature = "widgets-data")]
        assert!(list.contains(&WidgetKind::ListView));
        #[cfg(feature = "widgets-data")]
        assert!(list.contains(&WidgetKind::TreeView));
        #[cfg(feature = "widgets-containers")]
        assert!(list.contains(&WidgetKind::SplitPane));
        #[cfg(feature = "widgets-pickers")]
        assert!(list.contains(&WidgetKind::FileChooserDialog));
        #[cfg(feature = "widgets-containers")]
        assert!(list.contains(&WidgetKind::AlertDialog));
        #[cfg(feature = "widgets-text")]
        assert!(list.contains(&WidgetKind::TextArea));
        #[cfg(feature = "widgets-canvas")]
        assert!(list.contains(&WidgetKind::VulkanCanvas));
        #[cfg(feature = "widgets-choice")]
        assert!(list.contains(&WidgetKind::Checkbox));
        #[cfg(feature = "widgets-choice")]
        assert!(list.contains(&WidgetKind::ComboBox));
        #[cfg(feature = "widgets-range")]
        assert!(list.contains(&WidgetKind::ProgressBar));
        #[cfg(feature = "widgets-data")]
        assert!(list.contains(&WidgetKind::DataList));
        #[cfg(feature = "widgets-data")]
        assert!(list.contains(&WidgetKind::DataGrid));
        #[cfg(feature = "widgets-canvas")]
        assert!(list.contains(&WidgetKind::Canvas));
        #[cfg(feature = "widgets-pickers")]
        assert!(list.contains(&WidgetKind::ColorDialog));
        #[cfg(feature = "widgets-pickers")]
        assert!(list.contains(&WidgetKind::FontDialog));
        assert!(list.contains(&WidgetKind::Toolbar));
        #[cfg(feature = "widgets-pickers")]
        assert!(list.contains(&WidgetKind::Calendar));
        #[cfg(feature = "widgets-choice")]
        assert!(list.contains(&WidgetKind::MultiSelect));
        let mut expected_len = 8;
        if cfg!(feature = "widgets-containers") {
            expected_len += 5;
        }
        if cfg!(feature = "widgets-choice") {
            expected_len += 4;
        }
        if cfg!(feature = "widgets-data") {
            expected_len += 4;
        }
        if cfg!(feature = "widgets-media") {
            expected_len += 1;
        }
        if cfg!(feature = "widgets-canvas") {
            expected_len += 2;
        }
        if cfg!(feature = "widgets-range") {
            expected_len += 3;
        }
        if cfg!(feature = "widgets-pickers") {
            expected_len += 5;
        }
        assert_eq!(list.len(), expected_len);
    }

    #[cfg(feature = "widgets-containers")]
    #[test]
    fn alert_dialog_defaults_to_info_level() {
        let spec = WidgetSpec::new(WidgetId(12), WidgetKind::AlertDialog);
        assert_eq!(spec.alert_level, Some(AlertLevel::Info));
    }

    #[cfg(feature = "widgets-containers")]
    #[test]
    fn alert_dialog_builder_sets_level() {
        let spec = WidgetSpec::new(WidgetId(13), WidgetKind::AlertDialog)
            .with_alert_level(AlertLevel::Error);
        assert_eq!(spec.alert_level, Some(AlertLevel::Error));
    }

    #[test]
    fn extended_builder_metadata_sets_fields() {
        let spec = WidgetSpec::new(WidgetId(14), WidgetKind::Button)
            .with_checked(true)
            .with_range(1, 10)
            .with_step(2)
            .with_value(7)
            .with_group_name("group-a")
            .with_tab_items(vec!["One".to_owned(), "Two".to_owned()])
            .with_selected_index(1)
            .with_image_source("./assets/icon.png")
            .with_date_value("2026-03-06")
            .with_link_url("https://example.com")
            .with_split_ratio(80);

        assert_eq!(spec.checked, Some(true));
        assert_eq!(spec.range, Some((1, 10)));
        assert_eq!(spec.step, Some(2));
        assert_eq!(spec.value, Some(7));
        assert_eq!(spec.group_name.as_deref(), Some("group-a"));
        assert_eq!(spec.tab_items, vec!["One".to_owned(), "Two".to_owned()]);
        assert_eq!(spec.selected_index, Some(1));
        assert_eq!(spec.image_source.as_deref(), Some("./assets/icon.png"));
        assert_eq!(spec.date_value.as_deref(), Some("2026-03-06"));
        assert_eq!(spec.link_url.as_deref(), Some("https://example.com"));
        assert_eq!(spec.split_ratio, Some(80));
    }

    #[cfg(feature = "widgets-pickers")]
    #[test]
    fn calendar_date_and_spec_builder_validation() {
        let valid_date = CalendarDate::new(2024, 2, 29);
        assert!(valid_date.is_valid(), "2024 is leap year");
        let invalid_date = CalendarDate::new(2023, 2, 29);
        assert!(!invalid_date.is_valid(), "2023 is not leap year");

        let spec = WidgetSpec::new(WidgetId(20), WidgetKind::Calendar)
            .with_calendar_selected_dates(vec![valid_date])
            .with_calendar_bounds(
                Some(CalendarDate::new(2024, 1, 1)),
                Some(CalendarDate::new(2024, 12, 31)),
            )
            .with_calendar_first_day_of_week(CalendarFirstDayOfWeek::Monday)
            .with_calendar_selection_mode(CalendarSelectionMode::Range);

        assert_eq!(spec.calendar_selected_dates, vec![valid_date]);
        assert_eq!(spec.calendar_min_date, Some(CalendarDate::new(2024, 1, 1)));
        assert_eq!(
            spec.calendar_max_date,
            Some(CalendarDate::new(2024, 12, 31))
        );
        assert_eq!(
            spec.calendar_first_day_of_week,
            CalendarFirstDayOfWeek::Monday
        );
        assert_eq!(spec.calendar_selection_mode, CalendarSelectionMode::Range);
    }

    #[test]
    fn widget_spec_builder_sets_label_alignment_and_wrap() {
        let default_spec = WidgetSpec::new(WidgetId(21), WidgetKind::Label);
        assert_eq!(default_spec.label_alignment, LabelAlignment::Left);
        assert_eq!(default_spec.label_wrap, LabelWrap::None);
        assert!(!default_spec.label_wrap.is_wrapping());

        let spec = WidgetSpec::new(WidgetId(22), WidgetKind::Label)
            .with_label_alignment(LabelAlignment::Center)
            .with_label_wrap(LabelWrap::Word);

        assert_eq!(spec.label_alignment, LabelAlignment::Center);
        assert_eq!(spec.label_wrap, LabelWrap::Word);
        assert!(spec.label_wrap.is_wrapping());

        let right_spec = WidgetSpec::new(WidgetId(23), WidgetKind::Label)
            .with_label_alignment(LabelAlignment::Right)
            .with_label_wrap(true);
        assert_eq!(right_spec.label_alignment, LabelAlignment::Right);
        assert_eq!(right_spec.label_wrap, LabelWrap::Word);

        let nowrap_spec = WidgetSpec::new(WidgetId(24), WidgetKind::Label).with_label_wrap(false);
        assert_eq!(nowrap_spec.label_wrap, LabelWrap::None);

        let char_wrap_spec =
            WidgetSpec::new(WidgetId(25), WidgetKind::Label).with_label_wrap_mode(LabelWrap::Char);
        assert_eq!(char_wrap_spec.label_wrap, LabelWrap::Char);

        let word_char_spec =
            WidgetSpec::new(WidgetId(26), WidgetKind::Label).with_label_wrap(LabelWrap::WordChar);
        assert_eq!(word_char_spec.label_wrap, LabelWrap::WordChar);

        // Conversions between TextAlignment and LabelAlignment
        assert_eq!(
            LabelAlignment::from(TextAlignment::Left),
            LabelAlignment::Left
        );
        assert_eq!(
            LabelAlignment::from(TextAlignment::Center),
            LabelAlignment::Center
        );
        assert_eq!(
            LabelAlignment::from(TextAlignment::Right),
            LabelAlignment::Right
        );
        assert_eq!(
            TextAlignment::from(LabelAlignment::Left),
            TextAlignment::Left
        );
        assert_eq!(
            TextAlignment::from(LabelAlignment::Center),
            TextAlignment::Center
        );
        assert_eq!(
            TextAlignment::from(LabelAlignment::Right),
            TextAlignment::Right
        );

        // with_label_alignment also accepts TextAlignment via Into<LabelAlignment>
        let from_text_align = WidgetSpec::new(WidgetId(27), WidgetKind::Label)
            .with_label_alignment(TextAlignment::Right);
        assert_eq!(from_text_align.label_alignment, LabelAlignment::Right);

        // Property applicability checks
        assert!(default_spec
            .ensure_property(WidgetProperty::LabelAlignment)
            .is_ok());
        assert!(default_spec
            .ensure_property(WidgetProperty::LabelWrap)
            .is_ok());
        let button_spec = WidgetSpec::new(WidgetId(28), WidgetKind::Button);
        assert!(button_spec
            .ensure_property(WidgetProperty::LabelAlignment)
            .is_ok());
        assert_eq!(
            button_spec.ensure_property(WidgetProperty::LabelWrap),
            Err(GuiError::UnsupportedWidget("set_label_wrap"))
        );
    }

    #[test]
    #[cfg(feature = "widgets-text")]
    fn rich_text_runs_and_style_widget_spec() {
        let style = TextStyle::new()
            .bold(true)
            .italic(true)
            .underline(true)
            .strikethrough(true)
            .monospace(true)
            .scale(1.5)
            .fg_color(Color::rgb(255, 0, 0))
            .bg_color(Color::rgb(0, 255, 0))
            .link("https://example.com")
            .dimmed(true)
            .paragraph_indent(2);

        assert!(style.bold);
        assert!(style.italic);
        assert!(style.underline);
        assert!(style.strikethrough);
        assert!(style.monospace);
        assert_eq!(style.scale, Some(1.5));
        assert_eq!(style.fg_color, Some(Color::rgb(255, 0, 0)));
        assert_eq!(style.bg_color, Some(Color::rgb(0, 255, 0)));
        assert_eq!(style.link.as_deref(), Some("https://example.com"));
        assert!(style.dimmed);
        assert_eq!(style.paragraph_indent, 2);

        let run = TextRun::new(0..12, style.clone());
        assert_eq!(run.range, 0..12);
        assert_eq!(run.style, style);

        let spec = WidgetSpec::new(WidgetId(29), WidgetKind::RichText)
            .with_rich_text_runs(vec![run.clone()]);
        assert_eq!(spec.kind, WidgetKind::RichText);
        assert_eq!(spec.rich_text_runs, vec![run]);

        // Property checks
        assert!(spec.ensure_property(WidgetProperty::RichTextRuns).is_ok());
        assert!(spec.requires_property(WidgetProperty::RichTextRuns).is_ok());
        assert_eq!(WidgetProperty::RichTextRuns.name(), "set_rich_text_runs");
        assert_eq!(
            WidgetProperty::RichTextRuns.operation(),
            "set_rich_text_runs"
        );

        let button_spec = WidgetSpec::new(WidgetId(30), WidgetKind::Button);
        assert_eq!(
            button_spec.ensure_property(WidgetProperty::RichTextRuns),
            Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
        );
        assert_eq!(
            button_spec.requires_property(WidgetProperty::RichTextRuns),
            Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
        );
    }

    #[test]
    #[cfg(feature = "widgets-text")]
    fn rich_text_images_widget_spec() {
        let img = RichTextImage::new(10, "assets/diagram.png", Some(640));
        assert_eq!(img.offset, 10);
        assert_eq!(img.source, "assets/diagram.png");
        assert_eq!(img.max_width, Some(640));

        let spec = WidgetSpec::new(WidgetId(31), WidgetKind::RichText)
            .with_rich_text_images(vec![img.clone()]);
        assert_eq!(spec.kind, WidgetKind::RichText);
        assert_eq!(spec.rich_text_images, vec![img]);

        // Property checks
        assert!(spec.ensure_property(WidgetProperty::RichTextImages).is_ok());
        assert!(spec
            .requires_property(WidgetProperty::RichTextImages)
            .is_ok());
        assert_eq!(
            WidgetProperty::RichTextImages.name(),
            "set_rich_text_images"
        );
        assert_eq!(
            WidgetProperty::RichTextImages.operation(),
            "set_rich_text_images"
        );

        let button_spec = WidgetSpec::new(WidgetId(32), WidgetKind::Button);
        assert_eq!(
            button_spec.ensure_property(WidgetProperty::RichTextImages),
            Err(GuiError::UnsupportedWidget("set_rich_text_images"))
        );
        assert_eq!(
            button_spec.requires_property(WidgetProperty::RichTextImages),
            Err(GuiError::UnsupportedWidget("set_rich_text_images"))
        );
    }

    /// Compile-time exhaustive index for [`WidgetProperty`].
    ///
    /// Adding a variant without listing it here fails to compile, which
    /// forces the author to also extend [`WidgetProperty::ALL`]; the
    /// `property_all_covers_every_declared_variant` test then fails until
    /// the row is registered. This is the drift guard for the property table.
    fn variant_index(property: WidgetProperty) -> usize {
        match property {
            WidgetProperty::Checked => 0,
            WidgetProperty::Value => 1,
            WidgetProperty::Range => 2,
            WidgetProperty::Step => 3,
            WidgetProperty::SelectedIndex => 4,
            WidgetProperty::TabItems => 5,
            WidgetProperty::SelectedIndices => 6,
            WidgetProperty::RowDrag => 7,
            WidgetProperty::DataListItems => 8,
            WidgetProperty::ListViewColumns => 9,
            WidgetProperty::ListViewRows => 10,
            WidgetProperty::DataGridRows => 11,
            WidgetProperty::DataGridModel => 12,
            WidgetProperty::DataGridRowHeight => 13,
            WidgetProperty::DataGridColWidth => 14,
            WidgetProperty::DataGridFrozenPanes => 15,
            WidgetProperty::DataGridSelection => 16,
            WidgetProperty::TreeItems => 17,
            WidgetProperty::AlertLevel => 18,
            WidgetProperty::ImageSource => 19,
            WidgetProperty::ImageFit => 20,
            WidgetProperty::ButtonIcon => 21,
            WidgetProperty::FileChooserMode => 22,
            WidgetProperty::ColorDialogData => 23,
            WidgetProperty::FontDialogData => 24,
            WidgetProperty::ToolbarItems => 25,
            WidgetProperty::ToolbarOrientation => 26,
            WidgetProperty::DateValue => 27,
            WidgetProperty::LinkUrl => 28,
            WidgetProperty::TextSelection => 29,
            WidgetProperty::TextCompletion => 30,
            WidgetProperty::ContainerDirection => 31,
            WidgetProperty::ContainerScroll => 32,
            WidgetProperty::ContainerGap => 33,
            WidgetProperty::ContainerPadding => 34,
            WidgetProperty::CanvasScene => 35,
            WidgetProperty::CanvasSurface => 36,
            WidgetProperty::CloseGuard => 37,
            WidgetProperty::LayoutRoot => 38,
            WidgetProperty::WindowCallback => 39,
            WidgetProperty::NativeHandle => 40,
            WidgetProperty::DrawDemoCube => 41,
            WidgetProperty::CopyToClipboard => 42,
            WidgetProperty::PasteFromClipboard => 43,
            WidgetProperty::KeyedRows => 44,
            WidgetProperty::ClearSelection => 45,
            WidgetProperty::VisibleAnchor => 46,
            WidgetProperty::CalendarDates => 47,
            WidgetProperty::CalendarBounds => 48,
            WidgetProperty::CalendarFirstDayOfWeek => 49,
            WidgetProperty::CalendarSelectionMode => 50,
            WidgetProperty::LabelAlignment => 51,
            WidgetProperty::LabelWrap => 52,
            WidgetProperty::RichTextRuns => 53,
            WidgetProperty::PlaceholderText => 54,
            WidgetProperty::RichTextImages => 55,
            WidgetProperty::Monospace => 56,
            WidgetProperty::MetalHandle => 57,
            WidgetProperty::ContainerWrap => 58,
            WidgetProperty::Font => 59,
            WidgetProperty::RowIcons => 60,
        }
    }

    #[test]
    fn property_all_covers_every_declared_variant() {
        let mut indices: Vec<usize> = WidgetProperty::ALL
            .iter()
            .copied()
            .map(variant_index)
            .collect();
        indices.sort_unstable();
        assert_eq!(
            indices,
            (0..WidgetProperty::ALL.len()).collect::<Vec<usize>>(),
            "WidgetProperty::ALL must list every variant exactly once"
        );
    }

    #[test]
    fn property_table_rows_are_well_formed() {
        let mut operations = Vec::new();
        for &property in WidgetProperty::ALL {
            let row = property.applicable_kinds();
            let image_property = matches!(
                property,
                WidgetProperty::ImageSource | WidgetProperty::ImageFit
            );
            let canvas_property = matches!(
                property,
                WidgetProperty::CanvasScene
                    | WidgetProperty::CanvasSurface
                    | WidgetProperty::NativeHandle
                    | WidgetProperty::DrawDemoCube
                    | WidgetProperty::MetalHandle
            );
            let range_property = matches!(
                property,
                WidgetProperty::Value | WidgetProperty::Range | WidgetProperty::Step
            );
            let choice_property = matches!(property, WidgetProperty::Checked);
            let data_property = matches!(property, WidgetProperty::RowIcons);
            if (cfg!(feature = "widgets-media") || !image_property)
                && (cfg!(feature = "widgets-canvas") || !canvas_property)
                && (cfg!(feature = "widgets-range") || !range_property)
                && (cfg!(feature = "widgets-choice") || !choice_property)
                && (cfg!(feature = "widgets-data") || !data_property)
            {
                assert!(
                    !row.is_empty(),
                    "{property:?} must accept at least one kind"
                );
            } else {
                assert!(
                    row.is_empty(),
                    "{property:?} must have no applicable kind when its feature is off"
                );
            }
            for kind in row {
                assert!(
                    ALL_KINDS.contains(kind),
                    "{property:?} row names {kind:?}, which ALL_KINDS does not declare"
                );
            }
            let mut unique = row.to_vec();
            unique.sort_by_key(|kind| variant_kind_index(*kind));
            unique.dedup();
            assert_eq!(
                unique.len(),
                row.len(),
                "{property:?} row contains duplicate kinds"
            );

            let operation = property.operation();
            assert!(
                !operation.is_empty(),
                "{property:?} must have a stable operation name"
            );
            assert!(
                !operations.contains(&operation),
                "operation name {operation:?} is used by two properties"
            );
            operations.push(operation);
        }

        let mut kinds = ALL_KINDS.to_vec();
        kinds.sort_by_key(|kind| variant_kind_index(*kind));
        let declared = kinds.len();
        kinds.dedup();
        assert_eq!(declared, kinds.len(), "ALL_KINDS contains duplicates");

        if !cfg!(feature = "widgets-media") {
            assert!(ALL_KINDS.iter().all(|kind| {
                !WidgetProperty::ImageSource.supports(*kind)
                    && !WidgetProperty::ImageFit.supports(*kind)
            }));
        }

        if !cfg!(feature = "widgets-canvas") {
            assert!(ALL_KINDS.iter().all(|kind| {
                !WidgetProperty::CanvasScene.supports(*kind)
                    && !WidgetProperty::CanvasSurface.supports(*kind)
                    && !WidgetProperty::NativeHandle.supports(*kind)
                    && !WidgetProperty::DrawDemoCube.supports(*kind)
                    && !WidgetProperty::MetalHandle.supports(*kind)
            }));
        }

        if !cfg!(feature = "widgets-range") {
            assert!(ALL_KINDS.iter().all(|kind| {
                !WidgetProperty::Value.supports(*kind)
                    && !WidgetProperty::Range.supports(*kind)
                    && !WidgetProperty::Step.supports(*kind)
            }));
        }

        if !cfg!(feature = "widgets-choice") {
            assert!(ALL_KINDS
                .iter()
                .all(|kind| { !WidgetProperty::Checked.supports(*kind) }));
        }

        if !cfg!(feature = "widgets-data") {
            assert!(ALL_KINDS
                .iter()
                .all(|kind| { !WidgetProperty::RowIcons.supports(*kind) }));
        }
    }

    /// Declaration-order index for [`WidgetKind`], used only to build
    /// deterministic sort keys in the table tests.
    fn variant_kind_index(kind: WidgetKind) -> usize {
        ALL_KINDS
            .iter()
            .position(|candidate| *candidate == kind)
            .expect("ALL_KINDS must declare every kind")
    }

    #[test]
    fn ensure_property_accepts_exactly_the_applicability_row() {
        for &property in WidgetProperty::ALL {
            for &kind in ALL_KINDS {
                let spec = WidgetSpec::new(WidgetId(1), kind);
                let result = spec.ensure_property(property);
                if property.supports(kind) {
                    assert!(
                        result.is_ok(),
                        "{} must accept {kind:?}",
                        property.operation()
                    );
                } else {
                    assert_eq!(
                        result,
                        Err(GuiError::UnsupportedWidget(property.operation())),
                        "{} must reject {kind:?} with the typed error",
                        property.operation()
                    );
                }
            }
        }
    }

    // -----------------------------------------------------------------
    // Windowed lazy DataGridModel adapter
    // -----------------------------------------------------------------

    /// A windowed model plus recorders for the two hooks it fires.
    struct WindowedProbe {
        model: WindowedDataGridModel,
        handle: WindowedDataGridHandle,
        requested: Rc<RefCell<Vec<usize>>>,
        repaints: Rc<Cell<usize>>,
    }

    fn probe(row_count: usize, col_count: usize, config: WindowedDataGridConfig) -> WindowedProbe {
        let requested = Rc::new(RefCell::new(Vec::new()));
        let repaints = Rc::new(Cell::new(0usize));
        let model = WindowedDataGridModel::new(
            row_count,
            col_count,
            config,
            {
                let requested = Rc::clone(&requested);
                move |row| requested.borrow_mut().push(row)
            },
            {
                let repaints = Rc::clone(&repaints);
                move || repaints.set(repaints.get() + 1)
            },
        );
        let handle = model.handle();
        WindowedProbe {
            model,
            handle,
            requested,
            repaints,
        }
    }

    #[test]
    fn windowed_model_schedules_one_fetch_per_row_and_answers_reads_from_the_window() {
        let probe = probe(3, 2, WindowedDataGridConfig::new(2, 1024));

        // In-range miss: placeholder + one scheduled fetch + one repaint.
        assert_eq!(probe.model.value_at(0, 1), "…");
        assert_eq!(probe.handle.misses(), 1);
        assert_eq!(probe.handle.fetches_requested(), 1);
        assert_eq!(*probe.requested.borrow(), vec![0]);
        assert_eq!(probe.repaints.get(), 1);
        assert!(probe.handle.is_row_in_flight(0));
        assert!(!probe.model.is_row_resident(0));

        // Repeat reads while the fetch is in flight: more misses, no
        // duplicate fetch and no extra repaint.
        assert_eq!(probe.model.value_at(1, 0), "…");
        assert_eq!(probe.model.value_at(1, 1), "…");
        assert_eq!(probe.handle.misses(), 3);
        assert_eq!(probe.handle.fetches_requested(), 2);
        assert_eq!(*probe.requested.borrow(), vec![0, 1]);
        assert_eq!(probe.repaints.get(), 2);

        // Delivery makes the row resident and a read is now a hit.
        assert_eq!(
            probe
                .handle
                .deliver_row(1, vec!["1a".to_owned(), "1b".to_owned()]),
            WindowedDelivery::Applied {
                evicted: Vec::new()
            }
        );
        assert!(probe.handle.is_row_resident(1));
        assert!(probe.model.is_row_resident(1));
        assert!(!probe.handle.is_row_in_flight(1));
        assert_eq!(probe.model.value_at(1, 1), "1b");
        assert_eq!(probe.handle.hits(), 1);
        assert_eq!(probe.handle.resident_row_count(), 1);

        // Out-of-range reads are total and empty - never the placeholder -
        // and they are not window reads, so counters do not move.
        assert_eq!(probe.model.value_at(3, 0), "");
        assert_eq!(probe.model.value_at(1, 2), "");
        assert_eq!(probe.handle.misses(), 3);
        assert_eq!(probe.handle.hits(), 1);
        assert!(
            !probe.model.is_row_resident(3),
            "out-of-range is not resident"
        );
    }

    #[test]
    fn windowed_model_lru_eviction_prefers_the_least_recently_used_row() {
        let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
        for row in 0..2 {
            assert_eq!(probe.model.value_at(row, 0), "…");
            assert_eq!(
                probe.handle.deliver_row(row, vec![format!("r{row}")]),
                WindowedDelivery::Applied {
                    evicted: Vec::new()
                }
            );
        }

        // The third row needs room: row 0 is the least recently used.
        assert_eq!(probe.model.value_at(2, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![0] }
        );
        assert!(!probe.handle.is_row_resident(0));
        assert_eq!(probe.handle.resident_row_count(), 2);
        assert_eq!(probe.handle.evictions(), 1);

        // A hit refreshes row 1's recency, so row 2 becomes the LRU victim.
        assert_eq!(probe.model.value_at(1, 0), "r1");
        assert_eq!(probe.model.value_at(3, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(3, vec!["r3".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![2] }
        );
        assert!(probe.handle.is_row_resident(1));
        assert!(probe.handle.is_row_resident(3));
        assert_eq!(probe.handle.evictions(), 2);
    }

    #[test]
    fn windowed_model_evicts_on_the_byte_budget_and_refuses_oversized_rows() {
        let probe = probe(8, 1, WindowedDataGridConfig::new(8, 10));
        assert_eq!(probe.model.value_at(0, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(0, vec!["aaaaa".to_owned()]),
            WindowedDelivery::Applied {
                evicted: Vec::new()
            }
        );
        assert_eq!(probe.model.value_at(1, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(1, vec!["bbbbb".to_owned()]),
            WindowedDelivery::Applied {
                evicted: Vec::new()
            }
        );
        assert_eq!(probe.handle.resident_bytes(), 10);

        // A third 5-byte row needs room: the byte budget evicts the LRU row.
        assert_eq!(probe.model.value_at(2, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(2, vec!["ccccc".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![0] }
        );
        assert_eq!(probe.handle.resident_bytes(), 10);
        assert!(!probe.handle.is_row_resident(0));

        // A row that alone exceeds the byte budget can never be resident;
        // the refusal is typed, leaves the bound intact, and the row stays
        // re-requestable.
        assert_eq!(probe.model.value_at(3, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(3, vec!["ccccccccccc".to_owned()]),
            WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized)
        );
        assert!(!probe.handle.is_row_resident(3));
        assert!(!probe.handle.is_row_in_flight(3));
        assert_eq!(probe.handle.rejected_deliveries(), 1);
        let fetches_before = probe.handle.fetches_requested();
        assert_eq!(probe.model.value_at(3, 0), "…");
        assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
    }

    #[test]
    fn windowed_model_visible_band_pins_survive_until_replaced_or_cleared() {
        let probe = probe(8, 1, WindowedDataGridConfig::new(3, 1024));
        probe.handle.pin_visible_band(0, 2);
        assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
        for row in 0..3 {
            assert_eq!(probe.model.value_at(row, 0), "…");
            assert_eq!(
                probe.handle.deliver_row(row, vec![format!("r{row}")]),
                WindowedDelivery::Applied {
                    evicted: Vec::new()
                }
            );
        }
        assert_eq!(probe.handle.resident_row_count(), 3);

        // Row 2 is the only unpinned resident row: it is the victim even
        // though rows 0 and 1 are older.
        assert_eq!(probe.model.value_at(3, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(3, vec!["r3".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![2] }
        );
        assert!(probe.handle.is_row_resident(0));
        assert!(probe.handle.is_row_resident(1));

        // The band keeps protecting its rows across deliveries.
        assert_eq!(probe.model.value_at(4, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(4, vec!["r4".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![3] }
        );
        assert!(probe.handle.is_row_resident(0));
        assert!(probe.handle.is_row_resident(1));
        assert_eq!(probe.handle.resident_row_count(), 3);

        // Clearing the band returns the window to pure LRU...
        probe.handle.clear_pinned_band();
        assert_eq!(probe.handle.pinned_band(), None);
        assert_eq!(probe.model.value_at(5, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(5, vec!["r5".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![0] }
        );

        // ...and a new band replaces the old one instead of accumulating
        // (pin scope is one pass, not a timer).
        probe.handle.pin_visible_band(1, 1);
        assert_eq!(probe.model.value_at(6, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(6, vec!["r6".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![4] }
        );
        assert!(probe.handle.is_row_resident(1));
        assert!(probe.handle.is_row_resident(5));
        assert!(probe.handle.is_row_resident(6));
        assert_eq!(probe.handle.evictions(), 4);
    }

    #[test]
    fn windowed_model_refuses_delivery_when_every_resident_row_is_pinned() {
        let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
        probe.handle.pin_visible_band(0, 2);
        for row in 0..2 {
            assert_eq!(probe.model.value_at(row, 0), "…");
            assert_eq!(
                probe.handle.deliver_row(row, vec![format!("r{row}")]),
                WindowedDelivery::Applied {
                    evicted: Vec::new()
                }
            );
        }

        assert_eq!(probe.model.value_at(2, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
            WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
        );
        assert_eq!(probe.handle.rejected_deliveries(), 1);
        assert_eq!(probe.handle.evictions(), 0);
        assert!(!probe.handle.is_row_resident(2));
        assert_eq!(probe.handle.resident_row_count(), 2, "the bound held");

        // The refusal released the fetch state: once the band is cleared the
        // row can be requested and delivered normally.
        probe.handle.clear_pinned_band();
        let fetches_before = probe.handle.fetches_requested();
        assert_eq!(probe.model.value_at(2, 0), "…");
        assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
        assert_eq!(
            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
            WindowedDelivery::Applied { evicted: vec![0] }
        );
        assert!(probe.handle.is_row_resident(2));
    }

    #[test]
    fn data_grid_model_trait_forwards_band_pins_to_the_windowed_handle() {
        let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
        let model: &dyn DataGridModel = &probe.model;

        // The trait default is a no-op: an eager model keeps every row
        // resident, so a paint bracket is free to be ignored.
        let eager: &dyn DataGridModel = &SimpleDataGridModel {
            rows: vec![vec!["a".to_owned()]],
        };
        eager.pin_visible_band(0, 8);
        eager.clear_pinned_band();

        // The windowed model carries the band through the same trait object a
        // backend holds, with the pinned rows refused as eviction victims -
        // the bracket a backend paint pass opens.
        model.pin_visible_band(0, 2);
        assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
        for row in 0..2 {
            assert_eq!(model.value_at(row, 0), "…");
            assert_eq!(
                probe.handle.deliver_row(row, vec![format!("r{row}")]),
                WindowedDelivery::Applied {
                    evicted: Vec::new()
                }
            );
        }
        assert_eq!(model.value_at(2, 0), "…");
        assert_eq!(
            probe.handle.deliver_row(2, vec!["r2".to_owned()]),
            WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
        );

        // Releasing through the trait ends the scope.
        model.clear_pinned_band();
        assert_eq!(probe.handle.pinned_band(), None);
    }

    #[test]
    fn windowed_model_discards_stale_duplicate_and_out_of_range_deliveries() {
        let probe = probe(3, 1, WindowedDataGridConfig::new(2, 1024));

        // Never requested: a foreign or late result is discarded.
        assert_eq!(
            probe.handle.deliver_row(1, vec!["stale".to_owned()]),
            WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
        );
        // Beyond the model's shape: cannot belong to this model.
        assert_eq!(
            probe.handle.deliver_row(9, vec!["x".to_owned()]),
            WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange)
        );
        // A duplicated result after the row was applied is discarded too.
        assert_eq!(probe.model.value_at(0, 0), "…");
        assert!(matches!(
            probe.handle.deliver_row(0, vec!["r0".to_owned()]),
            WindowedDelivery::Applied { .. }
        ));
        assert_eq!(
            probe.handle.deliver_row(0, vec!["again".to_owned()]),
            WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
        );
        assert_eq!(probe.model.value_at(0, 0), "r0", "no stale overwrite");
        assert_eq!(probe.handle.rejected_deliveries(), 3);
    }

    #[test]
    fn windowed_model_drop_closes_the_request_channel_fail_closed() {
        let (request_tx, request_rx) = mpsc::channel::<usize>();
        let (result_tx, result_rx) = mpsc::channel::<(usize, Vec<String>)>();
        let (done_tx, done_rx) = mpsc::channel::<()>();

        let worker = std::thread::spawn(move || {
            while let Ok(row) = request_rx.recv() {
                if result_tx.send((row, vec![format!("row {row}")])).is_err() {
                    break;
                }
            }
            let _ = done_tx.send(());
        });

        let model = WindowedDataGridModel::new(
            100,
            1,
            WindowedDataGridConfig::new(4, 4096),
            move |row| {
                let _ = request_tx.send(row);
            },
            || {},
        );

        // Request a row but never apply it: the fetch is in flight when the
        // model is dropped. Dropping the model drops the request hook, which
        // closes the channel; the producer observes the close and stops.
        assert_eq!(model.value_at(7, 0), "…");
        assert!(model.handle().is_row_in_flight(7));
        drop(model);

        done_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("the producer must stop once the model's request channel closes");
        worker.join().expect("worker thread");

        // Whatever raced out before the close is a result for the in-flight
        // row and has no surviving model to be applied to.
        for (row, _) in result_rx.try_iter() {
            assert_eq!(row, 7);
        }
    }

    #[test]
    fn eager_models_report_every_row_resident_by_default() {
        let model = SimpleDataGridModel {
            rows: vec![vec!["a".to_owned()]],
        };
        assert!(model.is_row_resident(0));
        assert!(
            model.is_row_resident(500),
            "the default has no non-resident state; out-of-range reads are still total"
        );
    }

    #[test]
    fn row_ops_diff_and_apply_update_insert_remove_move() {
        let r1 = RowSet::new(1, &["a", "b"]);
        let r2 = RowSet::new(2, &["c", "d"]);
        let r3 = RowSet::new(3, &["e", "f"]);
        let base = vec![r1.clone(), r2.clone(), r3.clone()];

        // 1. Update single row
        let mut updated = base.clone();
        updated[1] = RowSet::new(2, &["c_mod", "d_mod"]);
        let delta = diff_rows(&base, &updated).unwrap();
        let ops = diff_row_ops(&base, &updated, &delta).expect("pure update should yield ops");
        assert_eq!(ops.len(), 1);
        match &ops[0] {
            RowOp::Update { index, row } => {
                assert_eq!(*index, 1);
                assert_eq!(row.cells, vec!["c_mod", "d_mod"]);
            }
            _ => panic!("expected RowOp::Update"),
        }
        let mut rows = base.clone();
        apply_row_ops_to_rows(&mut rows, &ops);
        assert_eq!(rows, updated);

        // 2. Insert single row
        let r_new = RowSet::new(99, &["x", "y"]);
        let inserted = vec![r1.clone(), r_new.clone(), r2.clone(), r3.clone()];
        let delta = diff_rows(&base, &inserted).unwrap();
        let ops = diff_row_ops(&base, &inserted, &delta).expect("single insert should yield ops");
        assert_eq!(ops.len(), 1);
        match &ops[0] {
            RowOp::Insert { index, row } => {
                assert_eq!(*index, 1);
                assert_eq!(row.key.0, 99);
            }
            _ => panic!("expected RowOp::Insert"),
        }
        let mut rows = base.clone();
        apply_row_ops_to_rows(&mut rows, &ops);
        assert_eq!(rows, inserted);

        // 3. Remove single row
        let removed = vec![r1.clone(), r3.clone()];
        let delta = diff_rows(&base, &removed).unwrap();
        let ops = diff_row_ops(&base, &removed, &delta).expect("single remove should yield ops");
        assert_eq!(ops.len(), 1);
        match &ops[0] {
            RowOp::Remove { index, key } => {
                assert_eq!(*index, 1);
                assert_eq!(key.0, 2);
            }
            _ => panic!("expected RowOp::Remove"),
        }
        let mut rows = base.clone();
        apply_row_ops_to_rows(&mut rows, &ops);
        assert_eq!(rows, removed);

        // 4. Move single row
        let moved = vec![r2.clone(), r3.clone(), r1.clone()];
        let delta = diff_rows(&base, &moved).unwrap();
        let ops = diff_row_ops(&base, &moved, &delta).expect("single move should yield ops");
        assert_eq!(ops.len(), 1);
        match &ops[0] {
            RowOp::Move {
                from_index,
                to_index,
                key,
            } => {
                assert_eq!(*from_index, 0);
                assert_eq!(*to_index, 2);
                assert_eq!(key.0, 1);
            }
            _ => panic!("expected RowOp::Move"),
        }
        let mut rows = base.clone();
        apply_row_ops_to_rows(&mut rows, &ops);
        assert_eq!(rows, moved);

        // Test cell and item mutators
        let mut cells = vec![
            vec!["a".to_owned(), "b".to_owned()],
            vec!["c".to_owned(), "d".to_owned()],
        ];
        let op = RowOp::Update {
            index: 0,
            row: RowSet::new(1, &["new_a", "new_b"]),
        };
        apply_row_ops_to_cells(&mut cells, &[op]);
        assert_eq!(cells[0], vec!["new_a", "new_b"]);

        let mut items = vec!["item1".to_owned(), "item2".to_owned()];
        let op_item = RowOp::Insert {
            index: 1,
            row: RowSet::new(10, &["inserted"]),
        };
        apply_row_ops_to_items(&mut items, &[op_item]);
        assert_eq!(items, vec!["item1", "inserted", "item2"]);
    }
}