rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! The layout-family wrapper controls: `Spacer`, `Center`, `Align`, `SizedBox`, `Padding`,
//! `Expanded`, `Flexible`, `IntrinsicWidth` and `AspectRatio`.
//!
//! # Why a wrapper is a control here, not only a layout manager
//!
//! `src/layout/` already answers "where does this child rectangle go", but it answers it for
//! a **host tree**: every rule needs an `ObjectId` per child and a parent that owns them. A
//! form assembled from JSON, a designer palette or a Rust demo often has no such tree — it
//! has one control per box. These wrappers carry the same intent in a control that owns its
//! content, so the two paths agree on the *rule* rather than on the mechanism:
//!
//! * `Center` and `AspectRatio` delegate to [`crate::layout::CenterLayout`] and
//!   [`crate::layout::AspectRatioLayout`], so their content rectangle is byte-identical to
//!   the layout manager's.
//! * `Expanded`, `Flexible` and `Spacer` are the three answers to "how should my parent
//!   distribute the leftover room", and they publish it through
//!   `Widget::default_layout_params` and `Widget::hints` — the channels the layout
//!   engines already read. They therefore work *inside* a real layout tree as well.
//! * `Align`, `SizedBox`, `Padding` and `IntrinsicWidth` state a single-child rule that had
//!   no layout manager: nine anchors, a fixed box, four independent insets, and "my width is
//!   my content's width".
//!
//! # The content model
//!
//! A wrapper positions **one** content box: a label and the size it asks for. The size is a
//! property in its own right (`content_width` / `content_height`) so a form authored in JSON
//! can describe its content without a second control, and so the wrapper can report a real
//! `Widget::size_hint` instead of guessing.
//!
//! # Painting
//!
//! Every wrapper paints the same three things, through `paint_wrapper`: its own box as a
//! hairline frame (so a wrapper whose content is smaller than itself is still visible), the
//! content area filled with a theme-derived tint, and the content label centred in it. The
//! tint is the theme's accent blended into the resolved surface, which is what makes the
//! wrapper follow an appearance switch without a hardcoded colour.

use crate::core::{Color, Font, HorizontalAlignment, ObjectId, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::layout::LayoutParams;
use crate::layout::{AxisHints, Hints};
use crate::render::RenderContext;
use crate::widget::capability::coercion::{expect_bool, expect_f32, expect_string, expect_u32};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

// ── Shared content model ────────────────────────────────────────────────────

/// The single content a wrapper positions: a label, the size it asks for, and optionally a real
/// control mounted in that box.
///
/// `size` is what the wrapper reports from [`Widget::size_hint`] and what `Center`'s
/// factors are applied to. It is deliberately the *content's* size, not the wrapper's: a
/// wrapper that claimed its own geometry as its hint would give a shrink-wrapping parent
/// nothing to shrink to.
///
/// `child` is the control that fills the content box, if one was mounted. A wrapper previously
/// carried only a caption: it painted a placeholder frame and could not take part in the widget
/// tree, so a fixed box, a padded box or a centred box could not hold a real control. The slot
/// is the id of a mounted child; [`Widget`]'s geometry entry places it in the content rectangle.
#[derive(Debug, Clone, PartialEq)]
pub struct Content {
    label: String,
    size: Size,
    child: Option<ObjectId>,
}

impl Content {
    /// An empty content box with no size and no mounted control.
    pub fn new() -> Self {
        Self { label: String::new(), size: Size::new(0, 0), child: None }
    }

    /// The label drawn in the content area.
    pub fn label(&self) -> &str {
        &self.label
    }

    /// The size the content asks for.
    pub fn size(&self) -> Size {
        self.size
    }

    /// The control mounted in the content area, if any.
    pub fn child(&self) -> Option<ObjectId> {
        self.child
    }

    /// Replaces the label. Returns whether this changed anything.
    pub fn set_label(&mut self, label: String) -> bool {
        if self.label == label {
            return false;
        }
        self.label = label;
        true
    }

    /// Replaces the requested size. Returns whether this changed anything.
    pub fn set_size(&mut self, size: Size) -> bool {
        if self.size == size {
            return false;
        }
        self.size = size;
        true
    }

    /// Reads one of the three content properties, or `None` when `name` is not one of them.
    ///
    /// The `None` is what lets each control's `get` fall through to its own properties and
    /// then to [`base_property_get`] with a single `match` chain, instead of restating the
    /// three names in nine files.
    fn get(&self, name: &str) -> Option<CapabilityValue> {
        match name {
            "content" => Some(CapabilityValue::String(self.label.clone())),
            "content_width" => Some(CapabilityValue::UInt(u64::from(self.size.width))),
            "content_height" => Some(CapabilityValue::UInt(u64::from(self.size.height))),
            _ => None,
        }
    }

    /// Writes one of the three content properties. `None` when `name` is not one of them.
    fn set(
        &mut self,
        name: &str,
        value: CapabilityValue,
    ) -> Option<Result<(), CapabilityAccessError>> {
        let result = match name {
            "content" => expect_string(value).map(|label| {
                self.set_label(label);
            }),
            "content_width" => expect_u32(value).map(|width| {
                self.set_size(Size::new(width, self.size.height));
            }),
            "content_height" => expect_u32(value).map(|height| {
                self.set_size(Size::new(self.size.width, height));
            }),
            _ => return None,
        };
        Some(result)
    }
}

impl Default for Content {
    fn default() -> Self {
        Self::new()
    }
}

// The three content property names, restated as literals in each control's
// `property_names_of!` list because that macro takes literals. Kept here so a reader can see
// the set in one place.

// ── Mounting a real control ─────────────────────────────────────────────────

/// Mounts `widget` in `slot`, replacing whatever the slot held.
///
/// The link is written in **both** directions through [`BaseWidget::add_child_linked`]: `add_child`
/// alone leaves the child believing it has no parent, so a tree walk from the root never reaches a
/// wrapper's content. A replacement unlinks and hides the previous control, because a detached
/// control keeps its own visibility flag and a host that renders by id would still paint it in the
/// box it no longer fills (the same rule `TabWidget::set_tab_widget` follows).
///
/// Returns whether the slot changed.
fn mount_content_child(
    base: &mut BaseWidget,
    slot: &mut Option<ObjectId>,
    widget: Option<ObjectId>,
) -> bool {
    if *slot == widget {
        return false;
    }
    if let Some(previous) = slot.take() {
        base.remove_child_linked(previous);
        crate::set_widget_visible(previous, false);
    }
    *slot = widget;
    if let Some(widget_id) = widget {
        base.add_child_linked(widget_id);
        crate::set_widget_visible(widget_id, true);
    }
    true
}

/// Writes `rect` into the control mounted in `slot`, if any.
///
/// This is the placement half of the contract, not a drawing path: the tree painter already draws
/// mounted children, and it draws each one at its own geometry. Writing through the public
/// geometry entry is what keeps that geometry equal to the box the wrapper's rule produced.
///
/// C-P15: the write is skipped when the rectangle did not change. Every wrapper's `draw` calls
/// this, so an unchanged frame used to perform one global registry write per mounted child for
/// no new information; a read that finds the same rectangle now costs less and invalidates
/// nothing.
fn place_mounted_child(slot: Option<ObjectId>, rect: Rect) {
    let Some(widget_id) = slot else {
        return;
    };
    if crate::widget_geometry(widget_id) == Some((rect.x, rect.y, rect.width, rect.height)) {
        return;
    }
    crate::set_widget_geometry(widget_id, rect.x, rect.y, rect.width, rect.height);
}

/// A parent extent scaled by a `Center` factor, matching `layout::center` exactly.
///
/// Mirrors the engine's `normalise_factor` + `visible_extent`: non-finite factors fall back to
/// `1.0`, the factor is clamped to `0.0..=1.0`, the product is rounded, a positive result keeps
/// at least one visible pixel, and `0` stays `0`. Kept here so `Center::content_rect` is a closed
/// formula rather than an engine instantiation per call (C-P15).
fn center_factor_extent(parent: u32, factor: f32) -> u32 {
    let factor = if factor.is_finite() { factor.clamp(0.0, 1.0) } else { 1.0 };
    if factor == 0.0 || parent == 0 {
        return 0;
    }
    ((parent as f32 * factor).round() as u32).min(parent).max(1)
}

/// Rounds a non-negative extent to pixels, keeping a positive sub-pixel extent visible.
///
/// Mirrors `layout::aspect_ratio`'s `to_px`, so the direct formula and the engine agree at the
/// sub-pixel edge.
fn aspect_to_px(extent: f32) -> u32 {
    if extent <= 0.0 {
        return 0;
    }
    let rounded = extent.round();
    if rounded >= 1.0 {
        rounded as u32
    } else {
        1
    }
}

/// Reads the `widget` property: an id, or `Null` for "nothing mounted".
///
/// Ids travel as `UInt` (the variant `mdi_area`'s `active_subwindow` reads back), so a document can
/// write one and a designer reads the same representation. The whole 64-bit id range is accepted
/// rather than narrowed to a `u32`, because an id is not a size.
fn expect_object_id(value: CapabilityValue) -> Result<Option<ObjectId>, CapabilityAccessError> {
    match value {
        CapabilityValue::Null => Ok(None),
        CapabilityValue::UInt(raw) => Ok(Some(ObjectId::from(raw))),
        CapabilityValue::Int(raw) if raw >= 0 => Ok(Some(ObjectId::from(raw as u64))),
        _ => Err(CapabilityAccessError::TypeMismatch),
    }
}

/// The `widget` property's readable form.
fn object_id_value(slot: Option<ObjectId>) -> CapabilityValue {
    match slot {
        Some(id) => CapabilityValue::UInt(id),
        None => CapabilityValue::Null,
    }
}

// ── Painting ────────────────────────────────────────────────────────────────

/// The colours one wrapper resolves from its style and the active theme.
///
/// Read once per draw and copied out, because the theme read holds the manager's lock: a
/// guard held across the drawing calls would deadlock the first time a primitive took it
/// again (the mutex is not re-entrant).
pub(crate) struct WrapperPalette {
    /// The wrapper's own surface — the colour the frame and the tint are derived against.
    pub(crate) surface: Color,
    /// The resolved ink, used for the frame.
    pub(crate) ink: Color,
    /// The accent the content area is tinted with.
    pub(crate) accent: Color,
    /// The label font.
    pub(crate) font: Font,
}

/// Resolves [`WrapperPalette`] for `base`, preferring an explicit style over the theme.
fn wrapper_palette(base: &BaseWidget, role: &str) -> WrapperPalette {
    let style = base.style();
    let themed = crate::style::resolved_theme_style_shared(role);
    let (theme_background, theme_foreground, theme_accent) = {
        let manager = crate::style::theme_manager();
        match manager.current_theme() {
            Some(theme) => (theme.colors.background, theme.colors.foreground, theme.colors.accent),
            None => (Color::WHITE, Color::BLACK, Color::PRIMARY),
        }
    };
    let surface = style
        .background_color
        .or_else(|| themed.as_ref().and_then(|resolved| resolved.background_color))
        .unwrap_or(theme_background);
    let ink = style
        .text_color
        .or_else(|| themed.as_ref().and_then(|resolved| resolved.text_color))
        .unwrap_or(theme_foreground);
    let accent = themed.as_ref().and_then(|resolved| resolved.border_color).unwrap_or(theme_accent);
    let font = style
        .font
        .clone()
        .or_else(|| themed.as_ref().and_then(|resolved| resolved.font.clone()))
        .unwrap_or_else(|| Font::simple("Arial", 12.0));
    WrapperPalette { surface, ink, accent, font }
}

/// Paints a wrapper: its own frame, the content area, and the content label.
///
/// `outer` is the wrapper's own rectangle and `content` the area its rule produced, which is
/// always inside `outer`. The clip is the wrapper's rectangle, so a rule that produces a
/// rectangle larger than the control cannot paint on a neighbour (nothing clips a widget at
/// this layer).
fn paint_wrapper(
    ctx: &mut RenderContext,
    base: &BaseWidget,
    role: &str,
    outer: Rect,
    content: Rect,
    content_box: &Content,
) {
    if outer.width == 0 || outer.height == 0 {
        return;
    }
    let palette = wrapper_palette(base, role);

    // The wrapper's own box: a hairline frame, so a wrapper whose content is smaller than
    // itself (Align, Padding, SizedBox, IntrinsicWidth) shows where the control ends. It is
    // painted as a stroke rather than a fill so it never hides what the host put behind it.
    ctx.draw_rect(outer, palette.ink.blend(&palette.surface, 0.7));

    if content.width == 0 || content.height == 0 {
        return;
    }

    // The content area is tinted with the accent, so the wrapper follows the appearance:
    // `blend` moves the tint towards the surface in light mode and away from it in dark mode
    // by construction, because both terms come from the theme.
    let tint = palette.accent.blend(&palette.surface, 0.82);
    let radius = (content.height.min(content.width) / 8).clamp(2, 6);
    ctx.fill_rounded_rect(content, radius, tint);
    ctx.draw_rounded_rect_stroke(content, radius, palette.accent.with_alpha_f32(0.55), 1);

    if content_box.label().is_empty() || content_box.child().is_some() {
        return;
    }
    // Bounded text: the label is fitted to the content area, so a long one is truncated with
    // an ellipsis instead of running past the control.
    let label_ink = tint.contrast_color();
    ctx.draw_text_line(
        content,
        content_box.label(),
        &palette.font,
        label_ink,
        HorizontalAlignment::Center,
    );
}

// ── Spacer ──────────────────────────────────────────────────────────────────

/// Spacer — an empty area that consumes free space in a linear layout.
///
/// # What it actually does
///
/// The control paints nothing in an application: its whole contract is the two layout
/// channels. [`Widget::hints`] reports `min = 0`, `pref = base_size`, `max = unbounded`, and
/// [`Widget::default_layout_params`] reports `LayoutParams::stretched(flex)`, which is what
/// tells a `BoxLayout` / `Flex` parent to hand it the leftover room in proportion to
/// `flex`. That is exactly what a spacer is to a box layout.
///
/// `paint_hint` defaults to `true` and draws a faint dashed frame: a form under construction
/// needs to see its spacers, and a spacer that was invisible in the designer was the one
/// control nobody could find. A shipping application sets it to `false`.
pub struct Spacer {
    base: BaseWidget,
    flex: u32,
    base_size: u32,
    paint_hint: bool,
    /// A control mounted in the spacer's own box, if any.
    ///
    /// A spacer is normally empty, but a layout that needs "this much room, and a status line in
    /// it" had no way to express the second half: the wrapper family positions one content box, and
    /// a spacer is the box with no rule of its own. The child fills the spacer's whole rectangle.
    content_child: Option<ObjectId>,
}

impl Spacer {
    /// Creates a spacer with `flex = 1`, `base_size = 0` and the design-time hint enabled.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Spacer, geometry, "Spacer"),
            flex: 1,
            base_size: 0,
            paint_hint: true,
            content_child: None,
        }
    }

    /// The share of the leftover room this spacer claims.
    pub fn flex(&self) -> u32 {
        self.flex
    }

    /// Sets the share of the leftover room. Zero means "do not grow", which is valid: the
    /// spacer then only enforces [`Self::base_size`].
    pub fn set_flex(&mut self, flex: u32) {
        if self.flex == flex {
            return;
        }
        self.flex = flex;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// The size a parent uses before distributing the leftover room.
    pub fn base_size(&self) -> u32 {
        self.base_size
    }

    /// Sets the size a parent uses before distributing the leftover room.
    pub fn set_base_size(&mut self, size: u32) {
        if self.base_size == size {
            return;
        }
        self.base_size = size;
        self.base.request_layout();
    }

    /// Whether the design-time dashed frame is painted.
    pub fn paint_hint(&self) -> bool {
        self.paint_hint
    }

    /// Turns the design-time dashed frame on or off.
    pub fn set_paint_hint(&mut self, paint_hint: bool) {
        if self.paint_hint == paint_hint {
            return;
        }
        self.paint_hint = paint_hint;
        self.base.request_redraw();
    }

    /// The control mounted in the spacer's box, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content_child
    }

    /// Mounts `widget` (or clears it, with `None`) in the spacer's box.
    ///
    /// The child is linked in both directions and fills the spacer's own rectangle — a spacer has
    /// no content rule, so its box *is* the content box.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content_child, widget) {
            place_mounted_child(self.content_child, self.geometry());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }
}

impl Widget for Spacer {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        Size::new(self.base_size, self.base_size)
    }

    /// A spacer may shrink to nothing and grow without bound; only `base_size` is a wish.
    fn hints(&self) -> Hints {
        Hints {
            width: AxisHints::new(0, self.base_size, u32::MAX),
            height: AxisHints::new(0, self.base_size, u32::MAX),
        }
    }

    /// The one statement that makes a spacer a spacer: absorb the leftover room, weighted.
    fn default_layout_params(&self) -> LayoutParams {
        LayoutParams::stretched(self.flex)
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for Spacer {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "flex" => Ok(CapabilityValue::UInt(u64::from(self.flex))),
            "base_size" => Ok(CapabilityValue::UInt(u64::from(self.base_size))),
            "paint_hint" => Ok(CapabilityValue::Bool(self.paint_hint)),
            "widget" => Ok(object_id_value(self.content_child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "flex" => {
                self.set_flex(expect_u32(value)?);
                Ok(())
            }
            "base_size" => {
                self.set_base_size(expect_u32(value)?);
                Ok(())
            }
            "paint_hint" => {
                self.set_paint_hint(expect_bool(value)?);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["flex", "base_size", "paint_hint", "widget", BASE_PROPERTY_NAMES]
    }
}

impl Draw for Spacer {
    fn draw(&mut self, ctx: &mut RenderContext) {
        // The mounted control fills the spacer's box; the hint frame is drawn under it.
        place_mounted_child(self.content_child, self.geometry());
        if !self.paint_hint {
            // The whole contract in an application: occupy the room, paint nothing.
            return;
        }
        let rect = self.geometry();
        if rect.width == 0 || rect.height == 0 {
            return;
        }
        let palette = wrapper_palette(&self.base, "spacer");
        let color = palette.ink.blend(&palette.surface, 0.55);
        paint_dashed_frame(ctx, rect, color);
    }
}

/// Paints a one-pixel dashed frame inside `rect`.
///
/// The dashes are `DASH` long with a `GAP` between them, walking each edge independently so
/// the corners are drawn exactly once. An empty rectangle paints nothing — a zero-extent
/// element is a drawing command with no ink.
pub(crate) fn paint_dashed_frame(ctx: &mut RenderContext, rect: Rect, color: Color) {
    const DASH: u32 = 4;
    const GAP: u32 = 4;
    let step = DASH + GAP;
    if rect.width == 0 || rect.height == 0 {
        return;
    }
    let bottom = rect.y.saturating_add(rect.height as i32).saturating_sub(1);
    let mut x = 0;
    while x < rect.width {
        let dash = DASH.min(rect.width - x);
        ctx.fill_rect(Rect::new(rect.x.saturating_add(x as i32), rect.y, dash, 1), color);
        ctx.fill_rect(Rect::new(rect.x.saturating_add(x as i32), bottom, dash, 1), color);
        x = x.saturating_add(step);
    }
    let right = rect.x.saturating_add(rect.width as i32).saturating_sub(1);
    let mut y = 0;
    while y < rect.height {
        let dash = DASH.min(rect.height - y);
        ctx.fill_rect(Rect::new(rect.x, rect.y.saturating_add(y as i32), 1, dash), color);
        ctx.fill_rect(Rect::new(right, rect.y.saturating_add(y as i32), 1, dash), color);
        y = y.saturating_add(step);
    }
}

impl EventHandler for Spacer {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── Center ──────────────────────────────────────────────────────────────────

/// Center — centres its content in a box that is a fraction of its own size.
///
/// The content rectangle comes from `CenterLayout`, the same rule the layout manager
/// applies to a tree child, so a `Center` control and a centred child of a real layout
/// occupy identical pixels. `width_factor` / `height_factor` are that layout's
/// `0.0..=1.0` fractions; a non-finite factor falls back to `1.0` there, and the value read
/// back here is the one the control stored.
pub struct Center {
    base: BaseWidget,
    content: Content,
    width_factor: f32,
    height_factor: f32,
}

impl Center {
    /// Creates a centre with no content, sized 1:1 with its own box.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Center, geometry, "Center"),
            content: Content::new(),
            width_factor: 1.0,
            height_factor: 1.0,
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced. `set_widget` requests a layout, because the content box is what
    /// the child now occupies and the wrapper's own hint has changed shape.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The fraction of the control's width the content area occupies.
    pub fn width_factor(&self) -> f32 {
        self.width_factor
    }

    /// Sets the fraction of the control's width the content area occupies.
    pub fn set_width_factor(&mut self, factor: f32) {
        if self.width_factor == factor {
            return;
        }
        self.width_factor = factor;
        self.base.request_redraw();
    }

    /// The fraction of the control's height the content area occupies.
    pub fn height_factor(&self) -> f32 {
        self.height_factor
    }

    /// Sets the fraction of the control's height the content area occupies.
    pub fn set_height_factor(&mut self, factor: f32) {
        if self.height_factor == factor {
            return;
        }
        self.height_factor = factor;
        self.base.request_redraw();
    }

    /// The rectangle the content occupies inside this control.
    ///
    /// C-P15: solved directly from the control's own geometry and the two factors. The previous
    /// form instantiated a `CenterLayout` and drove an `update` callback to read back one
    /// rectangle — an engine whose only input was this control's box.
    pub fn content_rect(&self) -> Rect {
        let rect = self.geometry();
        let width = center_factor_extent(rect.width, self.width_factor);
        let height = center_factor_extent(rect.height, self.height_factor);
        Rect::new(
            rect.x + (rect.width.saturating_sub(width) / 2) as i32,
            rect.y + (rect.height.saturating_sub(height) / 2) as i32,
            width,
            height,
        )
    }
}

impl Widget for Center {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.content.size()
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for Center {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "width_factor" => Ok(CapabilityValue::Float(f64::from(self.width_factor))),
            "height_factor" => Ok(CapabilityValue::Float(f64::from(self.height_factor))),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                // The content size is what `size_hint()` reports, so this is a layout change.
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "width_factor" => {
                self.set_width_factor(expect_f32(value)?);
                Ok(())
            }
            "height_factor" => {
                self.set_height_factor(expect_f32(value)?);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "width_factor",
            "height_factor",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for Center {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "center", outer, content, &self.content);
    }
}

impl EventHandler for Center {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── Align ───────────────────────────────────────────────────────────────────

/// The nine anchors [`Align`] can place its content at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignPosition {
    /// Top-left corner.
    TopLeft,
    /// Top edge, horizontally centred.
    TopCentre,
    /// Top-right corner.
    TopRight,
    /// Left edge, vertically centred.
    CentreLeft,
    /// The exact centre.
    #[default]
    Centre,
    /// Right edge, vertically centred.
    CentreRight,
    /// Bottom-left corner.
    BottomLeft,
    /// Bottom edge, horizontally centred.
    BottomCentre,
    /// Bottom-right corner.
    BottomRight,
}

impl AlignPosition {
    /// Every anchor, in reading order.
    pub const ALL: [Self; 9] = [
        Self::TopLeft,
        Self::TopCentre,
        Self::TopRight,
        Self::CentreLeft,
        Self::Centre,
        Self::CentreRight,
        Self::BottomLeft,
        Self::BottomCentre,
        Self::BottomRight,
    ];

    /// The token this anchor is published as.
    pub const fn token(self) -> &'static str {
        match self {
            Self::TopLeft => "top_left",
            Self::TopCentre => "top_centre",
            Self::TopRight => "top_right",
            Self::CentreLeft => "centre_left",
            Self::Centre => "centre",
            Self::CentreRight => "centre_right",
            Self::BottomLeft => "bottom_left",
            Self::BottomCentre => "bottom_centre",
            Self::BottomRight => "bottom_right",
        }
    }

    /// Parses a published token. `None` for a spelling this control does not publish.
    pub fn from_token(token: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|anchor| anchor.token() == token)
    }

    /// Whether the anchor is on the left, centre or right of the horizontal axis.
    fn horizontal(self) -> Anchor {
        match self {
            Self::TopLeft | Self::CentreLeft | Self::BottomLeft => Anchor::Start,
            Self::TopCentre | Self::Centre | Self::BottomCentre => Anchor::Middle,
            Self::TopRight | Self::CentreRight | Self::BottomRight => Anchor::End,
        }
    }

    /// Whether the anchor is on the top, middle or bottom of the vertical axis.
    fn vertical(self) -> Anchor {
        match self {
            Self::TopLeft | Self::TopCentre | Self::TopRight => Anchor::Start,
            Self::CentreLeft | Self::Centre | Self::CentreRight => Anchor::Middle,
            Self::BottomLeft | Self::BottomCentre | Self::BottomRight => Anchor::End,
        }
    }
}

/// One axis' half of an anchor: where the content sits on that axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Anchor {
    /// Against the start edge.
    Start,
    /// Centred.
    Middle,
    /// Against the end edge.
    End,
}

/// Where a box of `content` extent sits inside `available` extent for one anchor.
fn anchored_offset(available: u32, content: u32, anchor: Anchor) -> i32 {
    let free = available.saturating_sub(content);
    match anchor {
        Anchor::Start => 0,
        Anchor::Middle => (free / 2) as i32,
        Anchor::End => free as i32,
    }
}

/// Align — places its content at one of nine anchors.
///
/// # Why this is not a mode of `Center`
///
/// `Center` scales its content area by a factor and then centres it; that is the
/// `CenterLayout` contract. An aligned child keeps its own size and moves between nine
/// positions — the two rules have different inputs (a factor vs an anchor), so making one a
/// flag of the other would give every `Align` a meaningless `width_factor`.
pub struct Align {
    base: BaseWidget,
    content: Content,
    alignment: AlignPosition,
}

impl Align {
    /// Creates an align control with no content, anchored at the centre.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Align, geometry, "Align"),
            content: Content::new(),
            alignment: AlignPosition::default(),
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced. `set_widget` requests a layout, because the content box is what
    /// the child now occupies and the wrapper's own hint has changed shape.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The anchor the content is placed at.
    pub fn alignment(&self) -> AlignPosition {
        self.alignment
    }

    /// Sets the anchor the content is placed at.
    pub fn set_alignment(&mut self, alignment: AlignPosition) {
        if self.alignment == alignment {
            return;
        }
        self.alignment = alignment;
        self.base.request_redraw();
    }

    /// The rectangle the content occupies inside this control.
    ///
    /// The content keeps its own size, clamped to the control's box, and is offset by the
    /// anchor. A content larger than the control is pinned to the start of that axis rather
    /// than underflowing to a negative offset.
    pub fn content_rect(&self) -> Rect {
        let outer = self.geometry();
        let size = Size::new(
            self.content.size().width.min(outer.width),
            self.content.size().height.min(outer.height),
        );
        let dx = anchored_offset(outer.width, size.width, self.alignment.horizontal());
        let dy = anchored_offset(outer.height, size.height, self.alignment.vertical());
        Rect::new(outer.x.saturating_add(dx), outer.y.saturating_add(dy), size.width, size.height)
    }
}

impl Widget for Align {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.content.size()
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for Align {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "alignment" => Ok(CapabilityValue::String(self.alignment.token().to_string())),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                // The content size is what `size_hint()` reports, so this is a layout change.
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "alignment" => {
                let token = expect_string(value)?;
                let alignment =
                    AlignPosition::from_token(&token).ok_or(CapabilityAccessError::OutOfRange)?;
                self.set_alignment(alignment);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "alignment",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for Align {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "align", outer, content, &self.content);
    }
}

impl EventHandler for Align {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── SizedBox ────────────────────────────────────────────────────────────────

/// SizedBox — a box with a fixed width and height, whose content is centred inside it.
///
/// The published `box_width` / `box_height` are the box the *control* asks for, reported
/// through [`Widget::hints`] as a fixed size, which is what makes a `SizedBox` a hard
/// constraint in a layout that honours hints. They are independent of the control's own
/// geometry: the geometry is where the parent put it, the box is what it demanded.
pub struct SizedBox {
    base: BaseWidget,
    content: Content,
    fixed: Size,
}

impl SizedBox {
    /// Creates an empty box whose requested size is its own geometry.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::SizedBox, geometry, "SizedBox"),
            content: Content::new(),
            fixed: Size::new(geometry.width, geometry.height),
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced. `set_widget` requests a layout, because the content box is what
    /// the child now occupies and the wrapper's own hint has changed shape.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The fixed size this control asks its parent for.
    pub fn box_size(&self) -> Size {
        self.fixed
    }

    /// Sets the fixed size this control asks its parent for.
    pub fn set_box_size(&mut self, size: Size) {
        if self.fixed == size {
            return;
        }
        self.fixed = size;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// The rectangle the content occupies: the box, centred in the control's own geometry.
    pub fn content_rect(&self) -> Rect {
        let outer = self.geometry();
        let width = self.fixed.width.min(outer.width);
        let height = self.fixed.height.min(outer.height);
        Rect::new(
            outer.x.saturating_add(((outer.width - width) / 2) as i32),
            outer.y.saturating_add(((outer.height - height) / 2) as i32),
            width,
            height,
        )
    }
}

impl Widget for SizedBox {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.fixed
    }

    /// A box is a hard constraint on both axes: the three hint values coincide.
    fn hints(&self) -> Hints {
        Hints::fixed(self.fixed.width, self.fixed.height)
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for SizedBox {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "box_width" => Ok(CapabilityValue::UInt(u64::from(self.fixed.width))),
            "box_height" => Ok(CapabilityValue::UInt(u64::from(self.fixed.height))),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "box_width" => {
                let width = expect_u32(value)?;
                self.set_box_size(Size::new(width, self.fixed.height));
                Ok(())
            }
            "box_height" => {
                let height = expect_u32(value)?;
                self.set_box_size(Size::new(self.fixed.width, height));
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "box_width",
            "box_height",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for SizedBox {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "sized_box", outer, content, &self.content);
    }
}

impl EventHandler for SizedBox {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── Padding ─────────────────────────────────────────────────────────────────

/// Padding — insets its content by four independent edge paddings.
///
/// Unlike [`Widget::style`]'s `padding` (which a painter may apply to itself), these are the
/// control's *content* insets: they change the rectangle the content occupies, and they are
/// published so a form can set them per instance. Each edge saturates, so padding larger
/// than the control leaves a zero-extent content area rather than underflowing.
pub struct Padding {
    base: BaseWidget,
    content: Content,
    top: u32,
    right: u32,
    bottom: u32,
    left: u32,
}

impl Padding {
    /// Creates a padding wrapper with no content and zero insets.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Padding, geometry, "Padding"),
            content: Content::new(),
            top: 0,
            right: 0,
            bottom: 0,
            left: 0,
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced. `set_widget` requests a layout, because the content box is what
    /// the child now occupies and the wrapper's own hint has changed shape.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The four insets as `(top, right, bottom, left)`.
    pub fn insets(&self) -> (u32, u32, u32, u32) {
        (self.top, self.right, self.bottom, self.left)
    }

    /// Replaces all four insets at once.
    pub fn set_insets(&mut self, top: u32, right: u32, bottom: u32, left: u32) {
        if (self.top, self.right, self.bottom, self.left) == (top, right, bottom, left) {
            return;
        }
        self.top = top;
        self.right = right;
        self.bottom = bottom;
        self.left = left;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// The rectangle the content occupies: the control's box inset by the four paddings.
    pub fn content_rect(&self) -> Rect {
        let outer = self.geometry();
        Rect::new(
            outer.x.saturating_add(self.left as i32),
            outer.y.saturating_add(self.top as i32),
            outer.width.saturating_sub(self.left.saturating_add(self.right)),
            outer.height.saturating_sub(self.top.saturating_add(self.bottom)),
        )
    }
}

impl Widget for Padding {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    /// The content's own size plus the insets: what this control asks its parent for.
    fn size_hint(&self) -> Size {
        Size::new(
            self.content.size().width.saturating_add(self.left.saturating_add(self.right)),
            self.content.size().height.saturating_add(self.top.saturating_add(self.bottom)),
        )
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for Padding {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "padding_top" => Ok(CapabilityValue::UInt(u64::from(self.top))),
            "padding_right" => Ok(CapabilityValue::UInt(u64::from(self.right))),
            "padding_bottom" => Ok(CapabilityValue::UInt(u64::from(self.bottom))),
            "padding_left" => Ok(CapabilityValue::UInt(u64::from(self.left))),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                // `content_width`/`content_height` change what `size_hint()` answers, which is a
                // **layout** change: `request_redraw` only repaints, so the parent's row kept the
                // old allocation and the content was drawn into it. The public setter
                // (`set_content_size`) requests both, and the same rule is applied here.
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        let (top, right, bottom, left) = self.insets();
        match name {
            "padding_top" => {
                self.set_insets(expect_u32(value)?, right, bottom, left);
                Ok(())
            }
            "padding_right" => {
                self.set_insets(top, expect_u32(value)?, bottom, left);
                Ok(())
            }
            "padding_bottom" => {
                self.set_insets(top, right, expect_u32(value)?, left);
                Ok(())
            }
            "padding_left" => {
                self.set_insets(top, right, bottom, expect_u32(value)?);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "padding_top",
            "padding_right",
            "padding_bottom",
            "padding_left",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for Padding {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        // The inset bands are this control's own chrome, so they get a hairline frame; the
        // content area is filled by the shared painter. `Padding` is the one wrapper whose
        // outer frame would otherwise be indistinguishable from a plain container.
        paint_wrapper(ctx, &self.base, "padding", outer, content, &self.content);
    }
}

impl EventHandler for Padding {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── Expanded ────────────────────────────────────────────────────────────────

/// Expanded — a child that takes the leftover room along its parent's main axis, weighted.
///
/// # How it reaches the parent
///
/// Not by painting anything special: [`Widget::default_layout_params`] answers
/// `LayoutParams::stretched(flex)`, and that is the record `BoxLayout` and `Flex` read to
/// decide which child absorbs the free space. A control that only *looked* like an expanded
/// box would be the "declaration without a reader" defect this crate has been bitten by, so
/// the rule is published on the channel the engines actually consume, and a test pins it.
pub struct Expanded {
    base: BaseWidget,
    content: Content,
    flex: u32,
}

impl Expanded {
    /// Creates an expanded child with `flex = 1` and no content.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Expanded, geometry, "Expanded"),
            content: Content::new(),
            flex: 1,
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The share of the leftover room this child claims.
    pub fn flex(&self) -> u32 {
        self.flex
    }

    /// Sets the share of the leftover room this child claims.
    pub fn set_flex(&mut self, flex: u32) {
        if self.flex == flex {
            return;
        }
        self.flex = flex;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// The rectangle the content occupies: this control's whole box.
    pub fn content_rect(&self) -> Rect {
        self.geometry()
    }
}

impl Widget for Expanded {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.content.size()
    }

    fn hints(&self) -> Hints {
        Hints {
            width: AxisHints::new(0, self.content.size().width, u32::MAX),
            height: AxisHints::new(0, self.content.size().height, u32::MAX),
        }
    }

    fn default_layout_params(&self) -> LayoutParams {
        LayoutParams::stretched(self.flex)
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for Expanded {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "flex" => Ok(CapabilityValue::UInt(u64::from(self.flex))),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                // The content size is what `size_hint()`/`hints()` report, so this is a layout
                // change; `request_redraw` alone left the parent's row on the old allocation.
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "flex" => {
                self.set_flex(expect_u32(value)?);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "flex",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for Expanded {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "expanded", outer, content, &self.content);
    }
}

impl EventHandler for Expanded {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── Flexible ────────────────────────────────────────────────────────────────

/// How a [`Flexible`] child reacts when it is given more room than it asked for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexFit {
    /// Take the preferred size and leave the surplus to the siblings.
    #[default]
    Loose,
    /// Grow into the surplus, up to the parent's share.
    Tight,
}

impl FlexFit {
    /// The token this fit is published as.
    pub const fn token(self) -> &'static str {
        match self {
            Self::Loose => "loose",
            Self::Tight => "tight",
        }
    }

    /// Parses a published token. `None` for a spelling this control does not publish.
    pub fn from_token(token: &str) -> Option<Self> {
        match token {
            "loose" => Some(Self::Loose),
            "tight" => Some(Self::Tight),
            _ => None,
        }
    }
}

/// Flexible — a child that may shrink to its floor, and grows only as far as its fit allows.
///
/// # The difference from `Expanded`
///
/// `Expanded` always fills its share (`tight`). `Flexible` defaults to `loose`: it claims a
/// share of the leftover room but may stop at its preferred size, which is what makes a
/// row of flexible labels stay label-sized while a flexible text field grows. Both publish
/// the same `LayoutParams` channel; only `fill` differs.
pub struct Flexible {
    base: BaseWidget,
    content: Content,
    flex: u32,
    fit: FlexFit,
}

impl Flexible {
    /// Creates a flexible child with `flex = 1` and a loose fit.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Flexible, geometry, "Flexible"),
            content: Content::new(),
            flex: 1,
            fit: FlexFit::default(),
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The share of the leftover room this child claims.
    pub fn flex(&self) -> u32 {
        self.flex
    }

    /// Sets the share of the leftover room this child claims.
    pub fn set_flex(&mut self, flex: u32) {
        if self.flex == flex {
            return;
        }
        self.flex = flex;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// How the child reacts to surplus room.
    pub fn fit(&self) -> FlexFit {
        self.fit
    }

    /// Sets how the child reacts to surplus room.
    pub fn set_fit(&mut self, fit: FlexFit) {
        if self.fit == fit {
            return;
        }
        self.fit = fit;
        self.base.request_layout();
    }

    /// The rectangle the content occupies: this control's whole box.
    pub fn content_rect(&self) -> Rect {
        self.geometry()
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }
}

impl Widget for Flexible {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.content.size()
    }

    /// A loose fit has no ceiling; a tight fit may not exceed the size it asked for, so its
    /// hint is a fixed one — the layout then has nothing to grow.
    fn hints(&self) -> Hints {
        let size = self.content.size();
        match self.fit {
            FlexFit::Loose => Hints {
                width: AxisHints::new(0, size.width, u32::MAX),
                height: AxisHints::new(0, size.height, u32::MAX),
            },
            FlexFit::Tight => Hints::fixed(size.width, size.height),
        }
    }

    fn default_layout_params(&self) -> LayoutParams {
        let mut params = LayoutParams::stretched(self.flex);
        // `LayoutParams::stretched` sets `fill`; a loose fit keeps the weight but refuses to
        // absorb the surplus, which is precisely the difference from `Expanded`.
        params.fill = matches!(self.fit, FlexFit::Tight);
        params
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for Flexible {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "flex" => Ok(CapabilityValue::UInt(u64::from(self.flex))),
            "fit" => Ok(CapabilityValue::String(self.fit.token().to_string())),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                // The content size is what `size_hint()`/`hints()` report, so this is a layout
                // change; `request_redraw` alone left the parent's row on the old allocation.
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "flex" => {
                self.set_flex(expect_u32(value)?);
                Ok(())
            }
            "fit" => {
                let token = expect_string(value)?;
                let fit = FlexFit::from_token(&token).ok_or(CapabilityAccessError::OutOfRange)?;
                self.set_fit(fit);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "flex",
            "fit",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for Flexible {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "flexible", outer, content, &self.content);
    }
}

impl EventHandler for Flexible {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── IntrinsicWidth ──────────────────────────────────────────────────────────

/// IntrinsicWidth — a box whose width is exactly its content's width.
///
/// The request is reported through [`Widget::hints`]: the width is *fixed* at
/// `content_width`, while the height is only a floor, because a row of intrinsic boxes
/// should stretch vertically with the row. The drawn box is exactly that width (clamped to
/// the control's own geometry), so what the control asks for and what it paints agree.
pub struct IntrinsicWidth {
    base: BaseWidget,
    content: Content,
}

impl IntrinsicWidth {
    /// Creates an intrinsic-width wrapper with no content.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::IntrinsicWidth, geometry, "IntrinsicWidth"),
            content: Content::new(),
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for. The width part is this control's width.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The rectangle the content occupies: the content's width, the control's height.
    pub fn content_rect(&self) -> Rect {
        let outer = self.geometry();
        Rect::new(outer.x, outer.y, self.content.size().width.min(outer.width), outer.height)
    }
}

impl Widget for IntrinsicWidth {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.content.size()
    }

    fn hints(&self) -> Hints {
        Hints {
            width: AxisHints::fixed(self.content.size().width),
            height: AxisHints::at_least(self.content.size().height),
        }
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for IntrinsicWidth {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl Draw for IntrinsicWidth {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "intrinsic_width", outer, content, &self.content);
    }
}

impl EventHandler for IntrinsicWidth {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

// ── AspectRatio ─────────────────────────────────────────────────────────────

/// The ratio a freshly created [`AspectRatio`] starts with: 16:9, the shape a video, a
/// thumbnail or a preview pane is normally authored at.
pub const DEFAULT_ASPECT_RATIO: f32 = 16.0 / 9.0;

/// AspectRatio — a box that derives one extent from the other through a fixed ratio.
///
/// The content rectangle comes from `AspectRatioLayout`, the same rule a tree child of that
/// layout gets, so the control and the manager agree. `respect_parent` selects that layout's
/// two modes: bounded on both axes (fit inside) or derived from the parent's width alone.
pub struct AspectRatio {
    base: BaseWidget,
    content: Content,
    ratio: f32,
    respect_parent: bool,
}

impl AspectRatio {
    /// Creates an aspect-ratio box at 16:9, bounded by its parent.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::AspectRatio, geometry, "AspectRatio"),
            content: Content::new(),
            ratio: DEFAULT_ASPECT_RATIO,
            respect_parent: true,
        }
    }

    /// The content this control positions.
    pub fn content(&self) -> &Content {
        &self.content
    }

    /// The control mounted as this wrapper's content, if any.
    pub fn widget(&self) -> Option<ObjectId> {
        self.content.child
    }

    /// Mounts `widget` (or clears it, with `None`) as this control's content.
    ///
    /// The control is linked in both directions and fills [`Self::content_rect`], which is the
    /// placement half of the contract: the tree painter draws mounted children, so no second
    /// drawing path is introduced.
    pub fn set_widget(&mut self, widget: Option<ObjectId>) {
        if mount_content_child(&mut self.base, &mut self.content.child, widget) {
            place_mounted_child(self.content.child, self.content_rect());
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// Replaces the content label.
    pub fn set_content_label(&mut self, label: String) {
        if self.content.set_label(label) {
            self.base.request_redraw();
        }
    }

    /// Replaces the size the content asks for.
    pub fn set_content_size(&mut self, size: Size) {
        if self.content.set_size(size) {
            self.base.request_layout();
            self.base.request_redraw();
        }
    }

    /// The width:height ratio.
    pub fn ratio(&self) -> f32 {
        self.ratio
    }

    /// Sets the width:height ratio.
    ///
    /// A non-finite or non-positive ratio has no rectangle to describe, so it is refused
    /// rather than stored: `AspectRatioLayout` would panic on it, and a control must not be
    /// able to reach that panic from a property write.
    pub fn set_ratio(&mut self, ratio: f32) -> Result<(), CapabilityAccessError> {
        if !ratio.is_finite() || ratio <= 0.0 {
            return Err(CapabilityAccessError::OutOfRange);
        }
        if self.ratio == ratio {
            return Ok(());
        }
        self.ratio = ratio;
        self.base.request_layout();
        self.base.request_redraw();
        Ok(())
    }

    /// Whether the content is bounded on both axes by the control's box.
    pub fn respect_parent(&self) -> bool {
        self.respect_parent
    }

    /// Sets whether the content is bounded on both axes by the control's box.
    pub fn set_respect_parent(&mut self, respect_parent: bool) {
        if self.respect_parent == respect_parent {
            return;
        }
        self.respect_parent = respect_parent;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// The rectangle the content occupies inside this control.
    ///
    /// C-P15: solved directly from the control's own geometry and the ratio, mirroring
    /// `AspectRatioLayout::compute_child_rect` for the two-argument constructor this control
    /// uses (no `AspectMode::Cover`, so containment follows `respect_parent`).
    pub fn content_rect(&self) -> Rect {
        let parent = self.geometry();
        let parent_w = parent.width as f32;
        let parent_h = parent.height as f32;
        let ratio = self.ratio;
        let (child_w, child_h) = if !self.respect_parent {
            let width = parent_w;
            (aspect_to_px(width), aspect_to_px(width / ratio))
        } else if parent_w / ratio <= parent_h {
            (aspect_to_px(parent_w), aspect_to_px(parent_w / ratio))
        } else {
            (aspect_to_px(parent_h * ratio), aspect_to_px(parent_h))
        };
        // The centring offsets are rounded symmetrically so an odd leftover is split evenly
        // rather than truncating toward one edge (the engine's own rule).
        let x_offset = (((parent.width as i32) - (child_w as i32)) as f32 / 2.0).round() as i32;
        let y_offset = (((parent.height as i32) - (child_h as i32)) as f32 / 2.0).round() as i32;
        Rect::new(parent.x + x_offset, parent.y + y_offset, child_w, child_h)
    }

    /// The size this control asks its parent for: the content's height at the configured
    /// ratio, or its width when no height was given.
    fn requested_size(&self) -> Size {
        let content = self.content.size();
        let height = if content.height > 0 {
            content.height
        } else {
            (content.width as f32 / self.ratio).round().max(0.0) as u32
        };
        let width = if content.width > 0 {
            content.width
        } else {
            (height as f32 * self.ratio).round().max(0.0) as u32
        };
        Size::new(width, height)
    }
}

impl Widget for AspectRatio {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        self.requested_size()
    }

    /// The child's hint is the rectangle this control derives from its own box, so the parent
    /// sees the *ratio-corrected* size rather than the raw content size.
    fn hints(&self) -> Hints {
        let rect = self.content_rect();
        Hints::fixed(rect.width, rect.height)
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

impl WidgetProperties for AspectRatio {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        if let Some(value) = self.content.get(name) {
            return Ok(value);
        }
        match name {
            "ratio" => Ok(CapabilityValue::Float(f64::from(self.ratio))),
            "respect_parent" => Ok(CapabilityValue::Bool(self.respect_parent)),
            "widget" => Ok(object_id_value(self.content.child)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        if let Some(result) = self.content.set(name, value.clone()) {
            if result.is_ok() {
                // `requested_size()` derives the ratio-corrected size from the content, so this
                // is a layout change.
                self.base.request_layout();
                self.base.request_redraw();
            }
            return result;
        }
        match name {
            "ratio" => self.set_ratio(expect_f32(value)?),
            "respect_parent" => {
                self.set_respect_parent(expect_bool(value)?);
                Ok(())
            }
            "widget" => {
                self.set_widget(expect_object_id(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "content",
            "content_width",
            "content_height",
            "ratio",
            "respect_parent",
            "widget",
            BASE_PROPERTY_NAMES
        ]
    }
}

/// Formats `ratio` as the smallest whole-number `w:h` pair whose value is within half a percent
/// of the real ratio, falling back to two decimals when no small pair matches.
///
/// The caption under a ratio box must read like the author wrote it — `16:9`, not `1.78` — so the
/// search walks small denominators and stops at the first honest pair. A value outside the domain
/// [`AspectRatio::set_ratio`] enforces (finite, positive) falls back to the decimal form rather
/// than lying with a pair it does not match.
fn ratio_label(ratio: f32) -> String {
    if ratio.is_finite() && ratio > 0.0 {
        for denominator in 1..=32u32 {
            let numerator = (ratio * denominator as f32).round();
            if numerator < 1.0 {
                continue;
            }
            let candidate = numerator / denominator as f32;
            if (candidate - ratio).abs() / ratio < 0.005 {
                return format!("{}:{}", numerator as u32, denominator);
            }
        }
    }
    format!("{ratio:.2}")
}

/// Paints the ratio geometry over the shared wrapper card: the two diagonals that announce "this
/// area holds a shape", corner brackets like a camera viewfinder, and the ratio caption in the
/// content's bottom-left corner.
///
/// Without these the control reads as a plain label — at the default 16:9 the content rectangle
/// fills nearly the whole box, so nothing told "ratio box" from "text label". The guides are
/// geometry, not decoration: the diagonals are the exact shape the content rectangle bounds, so a
/// wrong ratio is visible as a wrong shape.
fn paint_ratio_guides(
    ctx: &mut RenderContext,
    base: &BaseWidget,
    role: &str,
    content: Rect,
    ratio: f32,
) {
    if content.width == 0 || content.height == 0 {
        return;
    }
    let palette = wrapper_palette(base, role);
    // The guides are inset one pixel from the content's own edges: a two-pixel bracket stroke is
    // centred on its line, so a line on the edge itself would spill half a stroke outside the
    // control's box, which the rendering census rightly rejects.
    let content = Rect::new(
        content.x + 1,
        content.y + 1,
        content.width.saturating_sub(2),
        content.height.saturating_sub(2),
    );
    if content.width == 0 || content.height == 0 {
        return;
    }
    let right = content.x + content.width as i32;
    let bottom = content.y + content.height as i32;

    // The two diagonals: the shape the ratio describes, drawn corner to corner. Soft, so the
    // centred label stays readable underneath.
    let guide = palette.accent.with_alpha_f32(0.35);
    ctx.draw_line_aa(Point::new(content.x, content.y), Point::new(right, bottom), guide);
    ctx.draw_line_aa(Point::new(right, content.y), Point::new(content.x, bottom), guide);

    // Corner brackets, like a camera viewfinder: short L strokes in the full accent, so the
    // frame's corners read before the tint does. The inward arm is clamped to half the box, so a
    // squeezed box crosses itself at worst instead of escaping the control.
    let tick = (content.height.min(content.width) / 6).clamp(4, 12);
    let tick = tick.min(content.width / 2).min(content.height / 2).max(1) as i32;
    for (corner_x, corner_y, inward_x, inward_y) in [
        (content.x, content.y, 1, 1),
        (right, content.y, -1, 1),
        (content.x, bottom, 1, -1),
        (right, bottom, -1, -1),
    ] {
        ctx.draw_line_stroke_aa(
            Point::new(corner_x, corner_y),
            Point::new(corner_x + inward_x * tick, corner_y),
            palette.accent,
            2,
        );
        ctx.draw_line_stroke_aa(
            Point::new(corner_x, corner_y),
            Point::new(corner_x, corner_y + inward_y * tick),
            palette.accent,
            2,
        );
    }

    // The caption: the ratio itself, in the content's bottom-left corner, where the centred label
    // cannot collide with it. Secondary ink, so it supports the label rather than competing.
    let advance = palette.font.size().ceil().max(1.0) as u32;
    let line_height = advance + 2;
    let caption_rect = Rect::new(
        content.x + 4,
        content
            .y
            .saturating_add(content.height as i32)
            .saturating_sub(line_height as i32)
            .saturating_sub(4),
        content.width.saturating_sub(8),
        line_height,
    );
    ctx.draw_text_line(
        caption_rect,
        &ratio_label(ratio),
        &palette.font,
        palette.ink.with_alpha_f32(0.8),
        HorizontalAlignment::Left,
    );
}

impl Draw for AspectRatio {
    fn draw(&mut self, ctx: &mut RenderContext) {
        let outer = self.geometry();
        let content = self.content_rect();
        place_mounted_child(self.content.child, content);
        paint_wrapper(ctx, &self.base, "aspect_ratio", outer, content, &self.content);
        // The guides announce the shape the box bounds; a mounted control covers them, so they are
        // only painted for the placeholder spellings.
        if self.content.child.is_none() {
            paint_ratio_guides(ctx, &self.base, "aspect_ratio", content, self.ratio);
        }
    }
}

impl EventHandler for AspectRatio {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
    }
}

/// The shared painter a sibling module uses for its own item boxes.
///
/// Kept `pub(crate)` rather than copied: the distribution layouts in `linear_layouts` paint
/// the same tinted box and fitted label per item, and a second painter would be the "two
/// answers to one question" defect (rule #101).
pub(crate) use self::shared::paint_item_box;

mod shared {
    use super::*;

    /// Paints one item box: the tinted rectangle and its fitted label.
    pub(crate) fn paint_item_box(
        ctx: &mut RenderContext,
        rect: Rect,
        label: &str,
        palette: &WrapperPalette,
        radius: u32,
    ) {
        if rect.width == 0 || rect.height == 0 {
            return;
        }
        let tint = palette.accent.blend(&palette.surface, 0.82);
        ctx.fill_rounded_rect(rect, radius, tint);
        ctx.draw_rounded_rect_stroke(rect, radius, palette.accent.with_alpha_f32(0.55), 1);
        if label.is_empty() {
            return;
        }
        let ink = tint.contrast_color();
        ctx.draw_text_line(rect, label, &palette.font, ink, HorizontalAlignment::Center);
    }
}

/// The palette resolution, re-exported for the distribution layouts so they resolve the same
/// colours through the same precedence ladder.
pub(crate) use self::palette_bridge::resolve_palette;

mod palette_bridge {
    use super::*;

    /// Resolves a palette for `role`, preferring an explicit style over the theme.
    pub(crate) fn resolve_palette(base: &BaseWidget, role: &str) -> WrapperPalette {
        wrapper_palette(base, role)
    }
}

#[cfg(test)]
impl Center {
    /// A centre whose content was set through the public setters.
    fn with_content_for_test(geometry: Rect, size: Size) -> Self {
        let mut center = Self::new(geometry);
        center.set_content_size(size);
        center
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;

    #[test]
    fn every_wrapper_reports_a_real_size_hint() {
        let mut center = Center::new(Rect::new(0, 0, 200, 200));
        center.set_content_size(Size::new(80, 40));
        assert_eq!(center.size_hint(), Size::new(80, 40));

        let mut align = Align::new(Rect::new(0, 0, 200, 200));
        align.set_content_size(Size::new(30, 30));
        assert_eq!(align.size_hint(), Size::new(30, 30));

        let mut padding = Padding::new(Rect::new(0, 0, 200, 200));
        padding.set_content_size(Size::new(50, 20));
        padding.set_insets(4, 8, 4, 8);
        assert_eq!(
            padding.size_hint(),
            Size::new(66, 28),
            "a padding wrapper asks for its content plus its insets"
        );
    }

    #[test]
    fn spacer_publishes_the_channels_a_layout_reads() {
        let mut spacer = Spacer::new(Rect::new(0, 0, 10, 10));
        spacer.set_flex(3);
        spacer.set_base_size(12);
        assert!(spacer.default_layout_params().fill, "a spacer absorbs leftover room");
        assert_eq!(spacer.default_layout_params().stretch, 3);
        assert_eq!(spacer.hints().width.pref, 12);
        assert_eq!(spacer.hints().width.max, u32::MAX);
    }

    #[test]
    fn expanded_fills_while_flexible_may_stay_loose() {
        let mut expanded = Expanded::new(Rect::new(0, 0, 10, 10));
        expanded.set_flex(2);
        assert!(expanded.default_layout_params().fill);
        assert_eq!(expanded.default_layout_params().stretch, 2);

        let mut flexible = Flexible::new(Rect::new(0, 0, 10, 10));
        assert!(!flexible.default_layout_params().fill, "the default fit is loose");
        flexible.set_fit(FlexFit::Tight);
        assert!(flexible.default_layout_params().fill, "a tight fit fills its share");
    }

    #[test]
    fn center_rect_is_the_factor_box_centred() {
        let mut center =
            Center::with_content_for_test(Rect::new(100, 100, 200, 100), Size::new(40, 20));
        center.set_width_factor(0.5);
        center.set_height_factor(0.5);
        let rect = center.content_rect();
        assert_eq!(rect, Rect::new(150, 125, 100, 50));
    }

    #[test]
    fn align_reaches_all_nine_anchors() {
        let geometry = Rect::new(10, 20, 100, 60);
        let expected = [
            (AlignPosition::TopLeft, 10, 20),
            (AlignPosition::TopCentre, 45, 20),
            (AlignPosition::TopRight, 80, 20),
            (AlignPosition::CentreLeft, 10, 40),
            (AlignPosition::Centre, 45, 40),
            (AlignPosition::CentreRight, 80, 40),
            (AlignPosition::BottomLeft, 10, 60),
            (AlignPosition::BottomCentre, 45, 60),
            (AlignPosition::BottomRight, 80, 60),
        ];
        for (anchor, x, y) in expected {
            let mut align = Align::new(geometry);
            align.set_content_size(Size::new(30, 20));
            align.set_alignment(anchor);
            let rect = align.content_rect();
            assert_eq!((rect.x, rect.y), (x, y), "{anchor:?}");
            assert_eq!((rect.width, rect.height), (30, 20), "{anchor:?} keeps its own size");
        }
    }

    #[test]
    fn align_tokens_round_trip() {
        for anchor in AlignPosition::ALL {
            assert_eq!(AlignPosition::from_token(anchor.token()), Some(anchor));
        }
        assert_eq!(AlignPosition::from_token("middle"), None);
    }

    #[test]
    fn sized_box_pins_its_content_to_the_requested_box() {
        let mut sized = SizedBox::new(Rect::new(0, 0, 200, 200));
        sized.set_box_size(Size::new(100, 50));
        assert_eq!(sized.content_rect(), Rect::new(50, 75, 100, 50));
        assert_eq!(sized.hints().width, AxisHints::fixed(100), "a box is a hard constraint");
        assert_eq!(sized.hints().height, AxisHints::fixed(50));
    }

    #[test]
    fn padding_saturates_rather_than_underflowing() {
        let mut padding = Padding::new(Rect::new(0, 0, 40, 40));
        padding.set_insets(30, 30, 30, 30);
        let rect = padding.content_rect();
        assert_eq!(rect.width, 0);
        assert_eq!(rect.height, 0);
    }

    #[test]
    fn intrinsic_width_pins_the_width_and_keeps_the_height() {
        let mut intrinsic = IntrinsicWidth::new(Rect::new(0, 0, 200, 80));
        intrinsic.set_content_size(Size::new(60, 20));
        assert_eq!(intrinsic.content_rect(), Rect::new(0, 0, 60, 80));
        assert_eq!(intrinsic.hints().width, AxisHints::fixed(60));
        assert_eq!(intrinsic.hints().height.min, 20);
    }

    #[test]
    fn aspect_ratio_refuses_a_ratio_that_describes_no_rectangle() {
        let mut ratio = AspectRatio::new(Rect::new(0, 0, 320, 240));
        assert!(ratio.set_ratio(0.0).is_err());
        assert!(ratio.set_ratio(f32::NAN).is_err());
        assert!(ratio.set_ratio(f32::INFINITY).is_err());
        assert_eq!(ratio.ratio(), DEFAULT_ASPECT_RATIO);
    }

    #[test]
    fn aspect_ratio_derives_the_missing_extent() {
        let mut ratio = AspectRatio::new(Rect::new(0, 0, 320, 240));
        ratio.set_ratio(2.0).expect("2:1 is a valid ratio");
        ratio.set_content_size(Size::new(100, 0));
        assert_eq!(ratio.requested_size(), Size::new(100, 50));
        ratio.set_content_size(Size::new(0, 40));
        assert_eq!(ratio.requested_size(), Size::new(80, 40));
    }

    #[test]
    fn aspect_ratio_content_rect_fits_inside_the_control() {
        let ratio = AspectRatio::new(Rect::new(0, 0, 320, 240));
        let rect = ratio.content_rect();
        assert!(rect.width <= 320 && rect.height <= 240, "{rect:?} must fit inside");
        // 16:9 inside 320x240 is width-bound: 320 x 180.
        assert_eq!(rect, Rect::new(0, 30, 320, 180));
    }

    #[test]
    fn the_ratio_caption_reads_like_the_author_wrote_it() {
        assert_eq!(ratio_label(16.0 / 9.0), "16:9");
        assert_eq!(ratio_label(4.0 / 3.0), "4:3");
        assert_eq!(ratio_label(1.0), "1:1");
        assert_eq!(ratio_label(2.0), "2:1");
        assert_eq!(ratio_label(1.25), "5:4");
        assert_eq!(ratio_label(0.5), "1:2");
        // No small pair hugs the golden ratio until 13/8, which lands within half a percent.
        assert_eq!(ratio_label(1.618_034), "13:8");
        // Out-of-domain values cannot be a ratio; the decimal form at least does not lie.
        assert_eq!(ratio_label(f32::INFINITY), "inf");
        assert_eq!(ratio_label(0.0), "0.00");
        assert_eq!(ratio_label(-2.0), "-2.00");
    }

    #[test]
    fn an_aspect_ratio_paints_its_guides_and_caption() {
        let mut ratio = AspectRatio::new(Rect::new(0, 0, 240, 120));
        ratio.set_content_size(Size::new(80, 40));
        ratio.set_content_label("Sample".to_string());
        let svg = crate::widget::svg::render_to_svg(&mut ratio);
        // Two diagonals plus the four corner brackets' two strokes each.
        let lines = svg.lines().filter(|line| line.contains("<line")).count();
        assert_eq!(lines, 10, "{svg}");
        // The caption is text under the centred label: one ink box per text run, so the label
        // and the caption are the two runs, and the caption's is the lower one.
        let boxes = crate::widget::svg::text_ink_boxes(&svg);
        assert_eq!(boxes.len(), 2, "{svg}");
        let lowest = boxes.iter().map(|b| b.1).max().expect("caption ink");
        let highest = boxes.iter().map(|b| b.1).min().expect("label ink");
        assert!(lowest > highest, "caption must sit below the label: {boxes:?}");
    }

    #[test]
    fn a_wrapper_property_route_agrees_with_its_own_accessors() {
        let mut align = Align::new(Rect::new(0, 0, 100, 100));
        align
            .set("alignment", CapabilityValue::String("bottom_right".to_string()))
            .expect("writable");
        assert_eq!(align.alignment(), AlignPosition::BottomRight);
        assert_eq!(
            align.get("alignment").expect("readable"),
            CapabilityValue::String("bottom_right".to_string())
        );
        // An unknown token is refused rather than silently kept.
        assert!(align.set("alignment", CapabilityValue::String("nowhere".to_string())).is_err());
    }

    #[test]
    fn a_wrapper_paints_inside_its_own_rect() {
        let rect = Rect::new(0, 0, 120, 80);

        fn assert_paints<W: Draw + Widget>(widget: &mut W, name: &str) {
            let svg = crate::widget::svg::render_to_svg(widget);
            assert!(svg.starts_with("<svg"), "{name} produced no document: {svg}");
            assert!(svg.contains("fill="), "{name} must paint something: {svg}");
        }

        assert_paints(&mut Spacer::new(rect), "spacer");

        let mut center = Center::new(rect);
        center.set_content_size(Size::new(60, 30));
        center.set_content_label("C".to_string());
        assert_paints(&mut center, "center");

        let mut align = Align::new(rect);
        align.set_content_size(Size::new(60, 30));
        align.set_content_label("A".to_string());
        assert_paints(&mut align, "align");

        let mut sized = SizedBox::new(rect);
        sized.set_box_size(Size::new(60, 40));
        sized.set_content_label("S".to_string());
        assert_paints(&mut sized, "sized_box");

        let mut padding = Padding::new(rect);
        padding.set_insets(6, 6, 6, 6);
        padding.set_content_label("P".to_string());
        assert_paints(&mut padding, "padding");

        let mut expanded = Expanded::new(rect);
        expanded.set_content_label("E".to_string());
        assert_paints(&mut expanded, "expanded");

        let mut flexible = Flexible::new(rect);
        flexible.set_content_label("F".to_string());
        assert_paints(&mut flexible, "flexible");

        let mut intrinsic = IntrinsicWidth::new(rect);
        intrinsic.set_content_size(Size::new(70, 20));
        intrinsic.set_content_label("I".to_string());
        assert_paints(&mut intrinsic, "intrinsic_width");

        assert_paints(&mut AspectRatio::new(rect), "aspect_ratio");
    }

    #[test]
    fn a_wrapper_event_delegation_does_not_panic() {
        let mut center = Center::new(Rect::new(0, 0, 100, 100));
        center.handle_event(&Event::MouseMove { pos: Point::new(5, 5) });
        center.handle_event(&Event::MousePress { pos: Point::new(5, 5), button: 1, modifiers: 0 });
        center.handle_event(&Event::MouseRelease { pos: Point::new(5, 5), button: 1 });
    }

    #[test]
    fn the_spacer_design_hint_can_be_turned_off() {
        let mut spacer = Spacer::new(Rect::new(0, 0, 20, 20));
        assert!(spacer.paint_hint());
        spacer.set("paint_hint", CapabilityValue::Bool(false)).expect("writable");
        let svg = crate::widget::svg::render_to_svg(&mut spacer);
        assert_eq!(
            svg.matches("<rect").count(),
            1,
            "a shipping spacer paints nothing but the document's own background: {svg}"
        );
    }

    /// A content-size property change requests **layout**, not only a repaint.
    ///
    /// `content_width`/`content_height` are what `size_hint()` and `hints()` report for these
    /// wrappers, so the parent's row has to be re-solved. `request_redraw` alone repainted the
    /// wrapper into the allocation it already had, and nothing else forced a relayout. `SizedBox`
    /// is absent on purpose: its hint is its own fixed box, not the content's size.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_content_size_property_change_requests_layout() {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::sync::Arc;

        macro_rules! assert_requests_layout {
            ($widget:expr, $label:literal) => {{
                // Bound to a local: expanding the expression twice would connect the signal on
                // one instance and change the property on another.
                let mut widget = $widget;
                let counter = Arc::new(AtomicUsize::new(0));
                // `ConnectionHandle` is a plain id (copying it does not disconnect), so the
                // binding exists to keep the handle nameable, not to scope the subscription.
                let _guard = widget.base.layout_requested.connect({
                    let counter = Arc::clone(&counter);
                    move || {
                        counter.fetch_add(1, Ordering::Relaxed);
                    }
                });
                widget
                    .set("content_width", CapabilityValue::UInt(300))
                    .expect("content_width is a published property");
                assert!(
                    counter.load(Ordering::Relaxed) > 0,
                    concat!($label, " must request layout when its content size changes")
                );
            }};
        }

        assert_requests_layout!(Center::new(Rect::new(0, 0, 200, 200)), "Center");
        assert_requests_layout!(Align::new(Rect::new(0, 0, 200, 200)), "Align");
        assert_requests_layout!(Padding::new(Rect::new(0, 0, 200, 200)), "Padding");
        assert_requests_layout!(Expanded::new(Rect::new(0, 0, 200, 200)), "Expanded");
        assert_requests_layout!(Flexible::new(Rect::new(0, 0, 200, 200)), "Flexible");
        assert_requests_layout!(AspectRatio::new(Rect::new(0, 0, 200, 200)), "AspectRatio");
    }
}