rust_widgets 2.7.0

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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Flex layout manager — CSS Flexbox-style layout with grow, shrink, and alignment.
use super::{Layout, LayoutContext};
use crate::compat::{Any, Vec};
use crate::core::{ObjectId, Rect, Size};
use crate::layout::hints::ChildInfo;

/// Main-axis direction for flex layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexDirection {
    /// Items placed left-to-right.
    #[default]
    Row,
    /// Items placed right-to-left.
    RowReverse,
    /// Items placed top-to-bottom.
    Column,
    /// Items placed bottom-to-top.
    ColumnReverse,
}

/// Wrapping behaviour when items overflow the main axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum FlexWrap {
    /// No wrapping; items may overflow.
    #[default]
    NoWrap,
    /// Wrap to next line/column.
    Wrap,
    /// Wrap in reverse direction.
    WrapReverse,
}

/// How items are distributed along the main axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum JustifyContent {
    /// Pack items at the start.
    #[default]
    FlexStart,
    /// Pack items at the end.
    FlexEnd,
    /// Pack items in the centre.
    Center,
    /// Distribute with equal space between items.
    SpaceBetween,
    /// Distribute with equal space around each item.
    SpaceAround,
    /// Distribute with equal space between items and edges.
    SpaceEvenly,
}

/// How items are aligned along the cross axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlignItems {
    /// Stretch items to fill the cross axis.
    #[default]
    Stretch,
    /// Align to start of cross axis.
    FlexStart,
    /// Align to end of cross axis.
    FlexEnd,
    /// Align to centre of cross axis.
    Center,
    /// Align baselines (treated as FlexStart for now).
    Baseline,
}

/// A single item managed by the flex layout.
#[derive(Debug, Clone)]
pub struct FlexItem {
    /// Widget identifier, if any (None = spacer).
    pub widget_id: Option<ObjectId>,
    /// Proportion of remaining space this item claims.
    pub flex_grow: f32,
    /// Rate at which this item shrinks when space is tight.
    pub flex_shrink: f32,
    /// Per-item cross-axis override.
    pub align_self: Option<AlignItems>,
    /// Minimum size constraint.
    pub min_size: Size,
    /// Maximum size constraint (0 = no limit).
    pub max_size: Size,
}

impl Default for FlexItem {
    fn default() -> Self {
        Self {
            widget_id: None,
            flex_grow: 0.0,
            flex_shrink: 1.0,
            align_self: None,
            min_size: Size::new(0, 0),
            max_size: Size::new(0, 0),
        }
    }
}

/// CSS Flexbox-style layout manager.
#[derive(Debug, Clone)]
pub struct FlexLayout {
    /// Main-axis direction.
    pub direction: FlexDirection,
    /// Wrapping behaviour.
    pub wrap: FlexWrap,
    /// Main-axis distribution.
    pub justify_content: JustifyContent,
    /// Cross-axis alignment.
    pub align_items: AlignItems,
    /// Gap between items in pixels.
    pub gap: i32,
    /// Outer padding in pixels.
    pub padding: i32,
    /// Managed items.
    items: Vec<FlexItem>,
    /// Size hints indexed by position within items (set before update).
    child_sizes: Vec<Size>,
}

impl FlexLayout {
    /// Create a flex layout with default settings.
    pub fn new() -> Self {
        Self {
            direction: FlexDirection::default(),
            wrap: FlexWrap::default(),
            justify_content: JustifyContent::default(),
            align_items: AlignItems::default(),
            gap: 0,
            padding: 0,
            items: Vec::new(),
            child_sizes: Vec::new(),
        }
    }

    /// Create a flex layout with all parameters.
    #[allow(clippy::too_many_arguments)]
    pub fn with_params(
        direction: FlexDirection,
        wrap: FlexWrap,
        justify_content: JustifyContent,
        align_items: AlignItems,
        gap: i32,
        padding: i32,
    ) -> Self {
        Self {
            direction,
            wrap,
            justify_content,
            align_items,
            gap,
            padding,
            items: Vec::new(),
            child_sizes: Vec::new(),
        }
    }

    /// Returns a reference to the items vector.
    pub fn items(&self) -> &[FlexItem] {
        &self.items
    }

    /// Returns a mutable reference to the items vector.
    pub fn items_mut(&mut self) -> &mut Vec<FlexItem> {
        &mut self.items
    }

    /// Set the child size hints (call before update for proper sizing).
    pub fn set_child_sizes(&mut self, sizes: Vec<Size>) {
        self.child_sizes = sizes;
    }

    /// Returns the number of items.
    pub fn item_count(&self) -> usize {
        self.items.len()
    }

    fn is_row(&self) -> bool {
        matches!(self.direction, FlexDirection::Row | FlexDirection::RowReverse)
    }

    fn is_reverse(&self) -> bool {
        matches!(self.direction, FlexDirection::RowReverse | FlexDirection::ColumnReverse)
    }

    /// Compute resolved sizes for items and return (main_sizes, total_flex_grow, total_main).
    fn compute_main_sizes(&self, available_main: i32, gap: i32) -> (Vec<i32>, f32, i32) {
        let count = self.items.len();
        if count == 0 {
            return (Vec::new(), 0.0, 0);
        }

        // Sum child intrinsic sizes and flex grow factors.
        let mut intrinsic_main: Vec<i32> = Vec::with_capacity(count);
        let mut total_flex_grow: f32 = 0.0;
        let mut total_intrinsic: i32 = 0;

        for (i, item) in self.items.iter().enumerate() {
            let sz = self.child_sizes.get(i).copied().unwrap_or(Size::new(0, 0));
            let main = if self.is_row() { sz.width as i32 } else { sz.height as i32 };
            let main = main.max(if self.is_row() {
                item.min_size.width as i32
            } else {
                item.min_size.height as i32
            });
            intrinsic_main.push(main);
            total_flex_grow += item.flex_grow;
            total_intrinsic += main;
        }

        let gaps = (count.saturating_sub(1)) as i32 * gap;
        let remaining = available_main - total_intrinsic - gaps;

        let mut main_sizes: Vec<i32> = Vec::with_capacity(count);

        if remaining > 0 && total_flex_grow > 0.0 {
            // Distribute surplus according to flex-grow.
            let mut distributed = 0i32;
            for (i, item) in self.items.iter().enumerate() {
                let extra = if total_flex_grow > 0.0 {
                    ((remaining as f32) * (item.flex_grow / total_flex_grow)).round() as i32
                } else {
                    0
                };
                let size = intrinsic_main[i] + extra;
                let max_main = if self.is_row() {
                    if item.max_size.width > 0 {
                        item.max_size.width as i32
                    } else {
                        i32::MAX
                    }
                } else {
                    if item.max_size.height > 0 {
                        item.max_size.height as i32
                    } else {
                        i32::MAX
                    }
                };
                let size = size.min(max_main);
                main_sizes.push(size);
                distributed += size - intrinsic_main[i];
            }
            // # Why the rounding remainder is not dumped on the last child anymore
            //
            // The remainder of an integer split used to be added to `main_sizes[count - 1]`
            // unconditionally. For a row whose children all grow that is harmless — the room
            // was going to be distributed anyway, and one pixel either way is invisible. But
            // the same line also runs for a caller that *did* ask for growth and had some of it
            // refused by a `max_size`, and, more importantly, its sibling branch below (no
            // growth asked for at all) had the identical line — where it did real damage: the
            // entire leftover was added to the last child, so `justify_content` could never see
            // any leftover to distribute.
            //
            // Concretely: a `FlexEnd` row of three fixed-width buttons in a 240 px band had
            // 12 px of leftover, and instead of shifting the row 12 px to the right the layout
            // made its *last button* 12 px wider. The row was then flush left, the trailing
            // button was the wrong size, and "right-aligned" was unreachable — which is why the
            // `dialog_with_actions` template could not be built on `justify_content`. The
            // remainder is still given to the last child here, because in this branch the caller
            // asked for the room to be spent on the children; it is the *no-growth* branch that
            // must leave it for the justification.
            let remainder = remaining - distributed;
            if remainder > 0 && !main_sizes.is_empty() {
                main_sizes[count - 1] += remainder;
            }
        } else if remaining < 0 {
            // Shrink items proportionally to flex-shrink, then spend whatever room the floors
            // would not give up by shrinking the children that *can* still give.
            //
            // # Why one pass is not enough
            //
            // The proportional pass alone leaves the row wider than its band whenever a child's
            // floor is above its proportional share, and the overhang is not distributed — it is
            // simply left after the last child, because the positions are packed from the leading
            // edge. A row of a 110 px label and a 22 px column in a 48 px band therefore came back
            // as `x = 0, width = 110` and `x = 110, width = 22`: the second column was painted at
            // x = 110, i.e. 62 px outside the control it belongs to, and the SVG backend emits
            // absolute coordinates, so it left the picture entirely. A sub-part outside its own
            // control is a worse outcome than a compressed one: it is invisible, and the failure is
            // silent.
            //
            // #6 rule 9 already says the child declares its floor, so the second pass may not
            // cross one; the children that *can* shrink are the ones whose floor is still below
            // their size. If the floors between them leave nothing to give, the row genuinely does
            // not fit and the children stay at their floors — the same refusal the comment below
            // describes. What changes here is only that the room a floor *does* release is used,
            // so "the smallest the children may be" is a reachable layout rather than an
            // aspiration the packing pass never consults.
            let deficit = -remaining;
            let total_flex_shrink: f32 = self.items.iter().map(|i| i.flex_shrink).sum();
            let mut floors: Vec<i32> = Vec::with_capacity(count);
            for (i, item) in self.items.iter().enumerate() {
                let shrink = if total_flex_shrink > 0.0 {
                    ((deficit as f32) * (item.flex_shrink / total_flex_shrink)).round() as i32
                } else {
                    deficit / count as i32
                };
                let min_main = if self.is_row() {
                    item.min_size.width as i32
                } else {
                    item.min_size.height as i32
                };
                let size = (intrinsic_main[i] - shrink).max(min_main);
                main_sizes.push(size);
                floors.push(min_main);
            }
            let mut leftover = -(available_main - gaps - main_sizes.iter().sum::<i32>());
            // Repeated rounds rather than one, because releasing one child's floor can itself
            // expose another's: a child that was already at its floor in the first pass is
            // untouched here, but the *others* can now give more than they did when the deficit was
            // shared between all of them.
            let mut progress = true;
            while leftover > 0 && progress {
                progress = false;
                let give: Vec<i32> = main_sizes
                    .iter()
                    .zip(floors.iter())
                    .map(|(size, floor)| (size - floor).max(0))
                    .collect();
                let total_give: i32 = give.iter().sum();
                if total_give <= 0 {
                    break;
                }
                for (index, room) in give.iter().enumerate() {
                    if *room <= 0 {
                        continue;
                    }
                    let share = ((leftover as i64 * *room as i64) / total_give as i64) as i32;
                    let take = share.min(*room).min(leftover);
                    main_sizes[index] -= take;
                    leftover -= take;
                    if take > 0 {
                        progress = true;
                    }
                }
                // The integer division above always rounds *down*, for every child, so a deficit
                // smaller than the number of givers releases nothing at all and the loop would spin
                // on `leftover` forever. The last giver whose floor allows it takes the remainder.
                if leftover > 0 && progress {
                    if let Some(index) = (0..main_sizes.len())
                        .rev()
                        .find(|index| main_sizes[*index] > floors[*index])
                    {
                        let take = leftover.min(main_sizes[index] - floors[index]);
                        main_sizes[index] -= take;
                        leftover -= take;
                    }
                }
            }
            // # Why the deficit is *not* pushed past the minimum
            //
            // This block used to keep cutting the children until the row fit — "if we couldn't
            // shrink enough, cap at available" — which defeated the `max(min_main)` above it: the
            // floor was applied and then immediately overridden, down to zero. Two 100 px buttons in
            // a 120 px row came back 57 px each, i.e. narrower than their own labels, and a button
            // narrower than its label is a button whose label elides.
            //
            // The floor is a statement about what the *child* can survive, and a layout that
            // ignores it to satisfy its own extent trades a visible overflow for an unreadable
            // control. CSS flexbox makes the same choice (`min-width: auto` item floors win over
            // `flex-shrink`), and the shared `implicitMinimumWidth` is likewise a hard bound.
            //
            // # What happens when even the floors do not fit (the G-1 resolution)
            //
            // The floors are a *declaration*, and a declaration can be unsatisfiable: two 100 px
            // buttons cannot be laid out in a 120 px band. Returning them at 100 px each is the
            // right refusal — the alternative is a 20 px button — but it left the **positions** to
            // be packed from the leading edge, so the 80 px that did not fit was paid entirely by
            // the trailing child: it was painted at `x = 100` in a 120 px band, i.e. 80 px past its
            // own control's edge. Because the SVG backend emits absolute coordinates and nothing
            // clips at this layer, such a child is not "overflowing", it is **absent** from the
            // picture — a silent loss, which is strictly worse than a squeezed control.
            //
            // So the sizes stay, and the *overhang is shared*: every child is scaled by
            // `available / floors` so the run as a whole fits, which keeps each child inside the
            // band and keeps their relative proportions (the tallest child stays the tallest). It
            // is deliberately the smallest possible deviation from the floors — in the common case
            // where the floors *do* fit, this branch is not reached at all — and it trades an
            // invisible child for every child being uniformly narrower than its own declared floor.
            //
            // # Why scaling beats capping the last child
            //
            // The obvious repair is "give each child at most the room that is left". It was
            // implemented and **reverted**: a row of two 100 px buttons in a 120 px band came back
            // `100 + 20`, so the *second* button was drawn 20 px wide — still below its floor, now
            // with the loss concentrated in one child instead of spread over two. It does not
            // resolve the contradiction (nothing can), it only moves which child pays for it,
            // and it does so unevenly. Scaling is the same contradiction acknowledged honestly.
            let floors_sum: i32 = floors.iter().sum();
            if leftover > 0 && floors_sum > 0 {
                // Integer arithmetic throughout, with the remainder distributed one pixel at a
                // time from the leading edge, so the scaled sizes sum to *exactly* `main_sizes`'
                // total rather than to a rounded approximation that could re-introduce an overhang.
                let budget: i32 = main_sizes.iter().sum::<i32>() - leftover;
                let scaled: Vec<i32> = main_sizes
                    .iter()
                    .map(|size| ((*size as i64 * budget as i64) / floors_sum as i64) as i32)
                    .collect();
                let mut short = budget - scaled.iter().sum::<i32>();
                main_sizes = scaled;
                for size in main_sizes.iter_mut() {
                    if short <= 0 {
                        break;
                    }
                    *size += 1;
                    short -= 1;
                }
            }
        } else {
            main_sizes = intrinsic_main;
        }

        let total_main: i32 = main_sizes.iter().sum::<i32>() + gaps;
        (main_sizes, total_flex_grow, total_main)
    }

    /// Apply main-axis justification and produce positions.
    fn justify_positions(
        &self,
        main_sizes: &[i32],
        total_used: i32,
        available_main: i32,
        start_main: i32,
        gap: i32,
    ) -> Vec<i32> {
        let count = main_sizes.len();
        if count == 0 {
            return Vec::new();
        }

        let leftover = available_main - total_used;
        let mut positions = Vec::with_capacity(count);

        let (first_gap, inter_gap) = match self.justify_content {
            JustifyContent::FlexStart | JustifyContent::FlexEnd | JustifyContent::Center => {
                let offset = match self.justify_content {
                    JustifyContent::FlexStart => 0,
                    JustifyContent::FlexEnd => leftover,
                    JustifyContent::Center => leftover / 2,
                    _ => 0,
                };
                (offset, gap)
            }
            JustifyContent::SpaceBetween => {
                let gap = if count > 1 { leftover / (count as i32 - 1) } else { 0 };
                (0, gap)
            }
            JustifyContent::SpaceAround => {
                let gap = if count > 0 { leftover / (count as i32) } else { 0 };
                (gap / 2, gap)
            }
            JustifyContent::SpaceEvenly => {
                let gap = if count > 0 { leftover / (count as i32 + 1) } else { 0 };
                (gap, gap)
            }
        };

        let end = start_main + available_main;

        if self.is_reverse() {
            // Reverse direction: pack from the end (right/bottom) towards start.
            let mut cursor = end - first_gap;
            for &size in main_sizes[..count].iter() {
                let pos = cursor - size;
                positions.push(pos);
                cursor = pos - inter_gap;
            }
        } else {
            let mut cursor = start_main + first_gap;
            for &size in main_sizes[..count].iter() {
                positions.push(cursor);
                cursor += size + inter_gap;
            }
        }

        positions
    }

    /// Compute cross-axis sizes and positions for each item.
    fn compute_cross_positions(&self, main_sizes: &[i32], cross_size: i32) -> Vec<(i32, i32)> {
        let count = main_sizes.len();
        if count == 0 {
            return Vec::new();
        }

        let mut result = Vec::with_capacity(count);
        for (i, _item) in self.items.iter().enumerate() {
            let sz = self.child_sizes.get(i).copied().unwrap_or(Size::new(0, 0));
            let child_cross = if self.is_row() { sz.height as i32 } else { sz.width as i32 };

            let align = self.items[i].align_self.unwrap_or(self.align_items);

            let (cross_start, cross_len) = match align {
                AlignItems::Stretch => (0, cross_size),
                AlignItems::FlexStart => (0, child_cross),
                AlignItems::FlexEnd => (cross_size - child_cross, child_cross),
                AlignItems::Center => ((cross_size - child_cross) / 2, child_cross),
                AlignItems::Baseline => (0, child_cross),
            };

            result.push((cross_start, cross_len));
        }

        result
    }

    /// Compute the rects for all items within the content area.
    /// `scaled_gap` overrides `self.gap` when Some (used for HiDPI/context-aware scaling).
    fn compute_rects(
        &self,
        content_rect: Rect,
        scaled_gap: Option<i32>,
    ) -> Vec<(Option<ObjectId>, Rect)> {
        if self.items.is_empty() {
            return Vec::new();
        }

        let gap = scaled_gap.unwrap_or(self.gap);

        if !matches!(self.wrap, FlexWrap::NoWrap) {
            return self.compute_wrapped_rects(content_rect, gap);
        }

        let (available_main, start_main, available_cross, cross_origin) = if self.is_row() {
            (content_rect.width as i32, content_rect.x, content_rect.height as i32, content_rect.y)
        } else {
            (content_rect.height as i32, content_rect.y, content_rect.width as i32, content_rect.x)
        };

        if available_main <= 0 || available_cross <= 0 {
            return Vec::new();
        }

        let (main_sizes, _total_flex_grow, total_used) =
            self.compute_main_sizes(available_main, gap);

        let main_positions =
            self.justify_positions(&main_sizes, total_used, available_main, start_main, gap);
        let cross_positions = self.compute_cross_positions(&main_sizes, available_cross);

        let mut results = Vec::with_capacity(self.items.len());

        for (i, item) in self.items.iter().enumerate() {
            let main_pos = *main_positions.get(i).unwrap_or(&0);
            let (cross_pos, cross_len) =
                cross_positions.get(i).copied().unwrap_or((0, available_cross));
            let main_len = *main_sizes.get(i).unwrap_or(&0);

            let rect = if self.is_row() {
                Rect::new(main_pos, cross_origin + cross_pos, main_len as u32, cross_len as u32)
            } else {
                Rect::new(cross_origin + cross_pos, main_pos, cross_len as u32, main_len as u32)
            };

            results.push((item.widget_id, rect));
        }

        results
    }

    fn compute_wrapped_rects(&self, content_rect: Rect, gap: i32) -> Vec<(Option<ObjectId>, Rect)> {
        let is_row = self.is_row();
        let available_main =
            if is_row { content_rect.width as i32 } else { content_rect.height as i32 };
        let available_cross =
            if is_row { content_rect.height as i32 } else { content_rect.width as i32 };
        if available_main <= 0 || available_cross <= 0 {
            return Vec::new();
        }

        let item_main = |index: usize| {
            let size = self.child_sizes.get(index).copied().unwrap_or(Size::new(0, 0));
            let intrinsic = if is_row { size.width } else { size.height };
            let minimum = if is_row {
                self.items[index].min_size.width
            } else {
                self.items[index].min_size.height
            };
            intrinsic.max(minimum) as i32
        };
        let item_cross = |index: usize| {
            let size = self.child_sizes.get(index).copied().unwrap_or(Size::new(0, 0));
            let intrinsic = if is_row { size.height } else { size.width };
            let minimum = if is_row {
                self.items[index].min_size.height
            } else {
                self.items[index].min_size.width
            };
            intrinsic.max(minimum) as i32
        };

        let mut lines: Vec<Vec<usize>> = Vec::new();
        for index in 0..self.items.len() {
            let candidate = item_main(index);
            let needs_wrap = lines.last().is_some_and(|line| {
                let used = line.iter().map(|&item| item_main(item)).sum::<i32>()
                    + gap * line.len().saturating_sub(1) as i32;
                used > 0 && used + gap + candidate > available_main
            });
            if needs_wrap {
                lines.push(Vec::new());
            }
            if lines.is_empty() {
                lines.push(Vec::new());
            }
            lines
                .last_mut()
                .expect("a line was just pushed above, so the list is non-empty")
                .push(index);
        }

        let mut line_cross_sizes = Vec::with_capacity(lines.len());
        for line in &lines {
            line_cross_sizes.push(line.iter().map(|&index| item_cross(index)).max().unwrap_or(0));
        }
        let cross_origin = if is_row { content_rect.y } else { content_rect.x };
        let mut results = Vec::with_capacity(self.items.len());
        let mut cross_cursor = if self.wrap == FlexWrap::WrapReverse {
            cross_origin + available_cross
        } else {
            cross_origin
        };

        for (line_index, line) in lines.iter().enumerate() {
            let intrinsic_total = line.iter().map(|&index| item_main(index)).sum::<i32>();
            let gaps = gap * line.len().saturating_sub(1) as i32;
            let remaining = available_main - intrinsic_total - gaps;
            let total_grow =
                line.iter().map(|&index| self.items[index].flex_grow.max(0.0)).sum::<f32>();
            let mut sizes: Vec<i32> = line.iter().map(|&index| item_main(index)).collect();
            if remaining > 0 && total_grow > 0.0 {
                for (slot, &index) in line.iter().enumerate() {
                    let extra = (remaining as f32 * self.items[index].flex_grow / total_grow)
                        .round() as i32;
                    let max_main = if is_row {
                        self.items[index].max_size.width
                    } else {
                        self.items[index].max_size.height
                    };
                    sizes[slot] = if max_main > 0 {
                        (sizes[slot] + extra).min(max_main as i32)
                    } else {
                        sizes[slot] + extra
                    };
                }
            }
            let used = sizes.iter().sum::<i32>() + gaps;
            let positions = self.justify_positions(
                &sizes,
                used,
                available_main,
                if is_row { content_rect.x } else { content_rect.y },
                gap,
            );
            let line_cross = line_cross_sizes[line_index];
            if self.wrap == FlexWrap::WrapReverse {
                cross_cursor -= line_cross;
            }
            for (slot, &index) in line.iter().enumerate() {
                let align = self.items[index].align_self.unwrap_or(self.align_items);
                let child_cross = item_cross(index);
                let (cross_offset, cross_len) = match align {
                    AlignItems::Stretch => (0, line_cross),
                    AlignItems::FlexStart | AlignItems::Baseline => (0, child_cross),
                    AlignItems::FlexEnd => (line_cross - child_cross, child_cross),
                    AlignItems::Center => ((line_cross - child_cross) / 2, child_cross),
                };
                let main_pos = positions[slot];
                let cross_pos = cross_cursor + cross_offset;
                let child_rect = if is_row {
                    Rect::new(
                        main_pos,
                        cross_pos,
                        sizes[slot].max(0) as u32,
                        cross_len.max(0) as u32,
                    )
                } else {
                    Rect::new(
                        cross_pos,
                        main_pos,
                        cross_len.max(0) as u32,
                        sizes[slot].max(0) as u32,
                    )
                };
                results.push((self.items[index].widget_id, child_rect));
            }
            if self.wrap == FlexWrap::WrapReverse {
                cross_cursor -= gap;
            } else {
                cross_cursor += line_cross + gap;
            }
        }
        results
    }
}

crate::impl_default_via_new!(FlexLayout);

impl Layout for FlexLayout {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn add_widget(&mut self, widget_id: ObjectId, stretch: u32) {
        self.items.push(FlexItem {
            widget_id: Some(widget_id),
            flex_grow: stretch as f32,
            ..FlexItem::default()
        });
    }

    fn remove_widget(&mut self, widget_id: ObjectId) {
        self.items.retain(|item| item.widget_id != Some(widget_id));
    }

    fn child_ids(&self) -> Vec<ObjectId> {
        self.items.iter().filter_map(|item| item.widget_id).collect()
    }

    fn has_child(&self, id: ObjectId) -> bool {
        self.items.iter().any(|item| item.widget_id == Some(id))
    }

    fn clear(&mut self) {
        self.items.clear();
        self.child_sizes.clear();
    }

    fn update(&self, rect: Rect, widgets: &mut dyn FnMut(ObjectId, Rect)) {
        let content_rect = Rect::new(
            rect.x + self.padding,
            rect.y + self.padding,
            rect.width.saturating_sub(2 * self.padding as u32),
            rect.height.saturating_sub(2 * self.padding as u32),
        );

        let results = self.compute_rects(content_rect, None);
        for (widget_id, child_rect) in results {
            if let Some(wid) = widget_id {
                widgets(wid, child_rect);
            }
        }
    }

    /// Lays the items out from the children's own hints.
    ///
    /// # What this replaces
    ///
    /// The old path required the caller to call
    /// [`set_child_sizes`](FlexLayout::set_child_sizes) with the children's sizes *before*
    /// asking for a layout — the layout was told the answer instead of asking the
    /// question. Here the sizes arrive with the children, so a caller that has the widgets
    /// (and therefore their hints) needs no second call, and one that does not cannot
    /// silently lay everything out at zero.
    ///
    /// Each child's *preferred* extent is used as the intrinsic size, and its `fill` flag
    /// as the flex-grow weight — which is the same division the shared model draws: `preferredWidth`
    /// says how big it wants to be, `fillWidth` says whether it may absorb the leftover.
    /// A child that declares neither is laid out at its preferred size and no more, which
    /// is the behaviour a caller reading only `size_hint` expects.
    ///
    /// # Why the boxes are placed here rather than by a second packing pass
    ///
    /// The order the children were handed over **is** the order they were built in: a caller
    /// that says `[ok, cancel]` means `ok` then `cancel`, left to right. The hint channel is
    /// the one path a caller can take, so it is also the one path where that intent is known,
    /// and it must not be laundered through a temporary layout that rebuilds its item list and
    /// loses which child was which.
    ///
    /// Margins are paid out of the room a child may occupy, on the child's own sides: its
    /// leading margin separates it from whatever is before it and its trailing margin from
    /// whatever follows. That makes an inter-element gap the caller's own declaration — the
    /// `padding`/`spacing` split — instead of something every call site has to re-derive, and
    /// it is why this path can honour `justify_content` as well: the leftover room is what
    /// remains after the margins, not after the content alone.
    fn arrange(&self, rect: Rect, children: &[ChildInfo], out: &mut dyn FnMut(ObjectId, Rect)) {
        if self.items.is_empty() {
            return;
        }
        // Which entry belongs to which item, resolved once so the two are never indexed by
        // position into two lists that could disagree. An item with no widget id (a spacer) or
        // with no `ChildInfo` gets `None` and keeps whatever size the caller last handed in,
        // so a partially-migrated caller does not lose the children it has not converted yet.
        let described: Vec<Option<ChildInfo>> = self
            .items
            .iter()
            .map(|item| item.widget_id.and_then(|id| ChildInfo::find(children, id).copied()))
            .collect();
        // The room each child *wants including its own margins* — the same sum
        // [`FlexLayout::update`] would have been handed through `set_child_sizes`.
        let sizes: Vec<Size> = described
            .iter()
            .enumerate()
            .map(|(index, info)| match info {
                // The stored size already carries the margins this path adds back below, so it
                // is added only for a child the caller described.
                Some(info) => info.bounds(),
                None => self.child_sizes.get(index).copied().unwrap_or(Size::new(0, 0)),
            })
            .collect();

        let content_rect = Rect::new(
            rect.x + self.padding,
            rect.y + self.padding,
            rect.width.saturating_sub(2 * self.padding as u32),
            rect.height.saturating_sub(2 * self.padding as u32),
        );
        if content_rect.width == 0 || content_rect.height == 0 {
            return;
        }

        let is_row = self.is_row();
        let (available_main, origin_main, cross_origin, available_cross) = if is_row {
            (content_rect.width as i32, content_rect.x, content_rect.y, content_rect.height as i32)
        } else {
            (content_rect.height as i32, content_rect.y, content_rect.x, content_rect.width as i32)
        };

        // The leftover room is what the justification distributes.
        //
        // The sizes themselves come from `update`'s own solver, **not** from the hints directly.
        // That is deliberate and it is the whole of this method's compatibility contract: a
        // caller that adopts the hint channel must get the geometry it already had, and the
        // solver is where `fill`/`stretch` grow, where `flex_shrink` compresses, and where the
        // minimum is floored. Re-deriving sizes here would make the two entry points two
        // algorithms — which is exactly what the "the channel is not a second layout" test
        // exists to forbid, and how adopting the channel would silently change every existing
        // layout.
        let inset = |index: usize| -> (i32, i32, i32, i32) {
            match described[index] {
                Some(info) => (
                    info.params.margins.left as i32,
                    info.params.margins.top as i32,
                    info.params.margins.right as i32,
                    info.params.margins.bottom as i32,
                ),
                None => (0, 0, 0, 0),
            }
        };
        let outer_cross = |index: usize| -> i32 {
            let size = sizes[index];
            if is_row {
                size.height as i32
            } else {
                size.width as i32
            }
        };
        // The solver is driven by the outer sizes (each child's box plus its margins), and it
        // reports what each *item*'s box may be. The margins come back out below, so a margin is
        // room the child's box never takes: it is the declaration that the box sits a gap away
        // from its neighbour, not that the box is wider.
        //
        // The interior gaps are the caller's margins, and the solver's own `gap` is `self.gap`,
        // so a caller that also sets the layout's `gap` gets both — the same double spacing the
        // crate has always allowed, and the reason the assembly rules put inter-element space on
        // one of the two and not both.
        let mut solver = FlexLayout { child_sizes: sizes.clone(), ..self.clone() };
        // Each child's *own floor* is what it may be squeezed to, and the hints channel is the
        // only place that number arrives — `add_widget(id, stretch)` carries no size at all, so
        // `FlexItem::min_size` defaults to zero and the solver's `flex_shrink` step would
        // happily compress a child below the minimum it stated. That is the defect this line
        // fixes: two 100 px buttons in a 120 px row came back 57 px each, i.e. narrower than
        // their own labels, and a button narrower than its label is a button whose label elides
        // (BLUE22 §B.10, the "shrink rather than shrink to nothing" risk).
        //
        // The floor is written into the solver's own items rather than passed alongside them
        // because the solver reads `item.min_size` — and doing it here keeps `add_widget`'s
        // signature unchanged, so the fifteen layouts that never call `arrange` are unaffected
        // (principle #21).
        for (index, info) in described.iter().enumerate() {
            if let (Some(item), Some(info)) = (solver.items.get_mut(index), info) {
                // The solver works in **outer** sizes (a child's box plus its margins — see
                // `sizes` above), while `hints.width.min` describes the child's *box*. The floor
                // therefore has to carry the margins too, or the drawn extent would come out
                // `min - margins`: a button whose floor is 64 px with a 6 px leading margin was
                // laid out at an outer 64 and drawn 58 wide, i.e. below the minimum it stated,
                // which is the very thing the floor was added to prevent. Adding the margins back
                // is what makes the two units agree.
                item.min_size = Size::new(
                    info.hints.width.min.saturating_add(info.params.margins.horizontal_total()),
                    info.hints.height.min.saturating_add(info.params.margins.vertical_total()),
                );
            }
        }
        let (solved_main, _total_grow, _total_main) =
            solver.compute_main_sizes(available_main, self.gap);
        // # A known defect this pass does **not** repair (BLUE22 · logged as G-1)
        //
        // The solver may return a box that exceeds the room, and the positions below are packed
        // from the leading edge, so the *last* children of an over-full row are placed past the
        // band's far edge. Nothing clips at this layer, so such a child is painted outside its own
        // control — and, because the SVG backend emits absolute coordinates, it leaves the picture
        // entirely: `split_button` at 48 px wide put its 22 px arrow column at `x = 48` in a 48 px
        // face, i.e. a sub-part that is not there rather than one that is compressed.
        //
        // The obvious repair — cap each child at the room actually left — was implemented and
        // **reverted**, because it does not fix the row, it moves the failure onto a different
        // child: a row of two 100 px buttons in a 120 px band then came back `100 + 20` instead of
        // `100 + 100`, so the second button was drawn 20 px wide, below its own stated floor. Two
        // hundred-pixel buttons in a hundred-and-twenty-pixel band *cannot* be laid out, and the
        // shrink pass is right to say so by overhanging: `a_child_is_never_squeezed_below_its_own_minimum`
        // pins that, and a silent 20 px button is exactly the defect it was written to prevent.
        //
        // The honest statement is therefore that **the row's own extent and its children's floors
        // can disagree**, and that the disagreement is currently surfaced as an overhang rather
        // than resolved. Resolving it needs a decision this pass does not own — whether the row
        // clips, elides, or pushes back on the caller for more room — so it is left as it was
        // found rather than traded for a quieter but worse failure.
        // The leftover is what the justification distributes, and it is measured as the room the
        // band has minus the room the children **occupy** — their boxes *plus* the margins that
        // produced the gaps.
        //
        // # Why the leading margin is not added a second time here
        //
        // The solver is driven by the outer sizes (`child.bounds()` = preferred extent + margins)
        // and returns the same outer sizes when nothing grows, so each `solved_main[i]` already
        // *includes* that child's margins. The previous form added `inset(index).0` on top for
        // every child but the first, which double-counted every gap: a three-button row wanted
        // 220 px in a 240 px band, so the true leftover was 20 px, but the repeated margin made
        // `consumed` read 232 and the leftover read 8 — and for a wider margin it read zero, at
        // which point `justify_content` had nothing to distribute at all. That is the reason
        // `FlexEnd` appeared to do nothing and the row sat flush left.
        //
        // The solver's own `gap` is a separate term and is *not* part of `solved_main`, so it is
        // still counted once here.
        let consumed: i32 = solved_main.iter().sum::<i32>()
            + self.gap * (solved_main.len().saturating_sub(1)) as i32;
        let leftover = (available_main - consumed).max(0);
        let first_offset = match self.justify_content {
            JustifyContent::FlexStart => 0,
            JustifyContent::FlexEnd => leftover,
            JustifyContent::Center => leftover / 2,
            // `SpaceBetween` puts the leftover *between* the children and none at the edges; the
            // two "space around" variants add half a unit at each edge and a full unit between,
            // which is why their inter-item term is twice their edge term.
            JustifyContent::SpaceBetween => 0,
            JustifyContent::SpaceAround => leftover / (2 * solved_main.len().max(1) as i32),
            JustifyContent::SpaceEvenly => leftover / (solved_main.len().max(1) as i32 + 1),
        };
        let inter_extra = match self.justify_content {
            JustifyContent::SpaceBetween if solved_main.len() > 1 => {
                leftover / (solved_main.len() as i32 - 1)
            }
            JustifyContent::SpaceAround if !solved_main.is_empty() => {
                leftover / solved_main.len() as i32
            }
            JustifyContent::SpaceEvenly if !solved_main.is_empty() => {
                leftover / (solved_main.len() as i32 + 1)
            }
            _ => 0,
        };

        // ── The reverse axis packs from the far edge ──
        //
        // `arrange` used to ignore `is_reverse()` entirely: the loop below always packed from
        // `origin_main` upward, so a `RowReverse`/`ColumnReverse` layout was placed exactly as if it
        // were forward. `justify_positions` (the other entry point) has always handled it, so the two
        // paths disagreed about what a reverse direction means -- and `arrange` is the path
        // `CompositeBuilder` takes, which is why every assembled row in the crate was silently
        // forward-only. This is the same form `justify_positions` uses: the cursor starts at the far
        // edge and each item is placed by *subtracting* its extent, so the first child ends at the
        // band's end and the last child lands nearest the start.
        //
        // The first child's `first_offset` is mirrored too: `FlexEnd` puts its gutter at the
        // *leading* edge on a reversed axis, which is what keeps the justification meaning "from the
        // end the children are packed toward" rather than "from the left, always".
        let reverse = self.is_reverse();
        let mut cursor = if reverse {
            origin_main + available_main - first_offset
        } else {
            origin_main + first_offset
        };
        for index in 0..sizes.len() {
            let (left, top, right, bottom) = inset(index);
            // The solver reports the *whole* box, margins included, so the child's drawn extent
            // is that minus its own margins. Nothing grows here: a child that should absorb room
            // said so through `fill`, and `update`'s solver already paid it.
            let solved = solved_main.get(index).copied().unwrap_or(0);
            let main_len = (solved - left - right).max(0);
            let cross_len = (outer_cross(index) - top - bottom).min(available_cross).max(0);
            // Cross-axis alignment inside the child's own inset box.
            //
            // # Why `Stretch` is "grow to the band, unless the child asked for less"
            //
            // `Stretch` is the crate's default alignment and was unconditionally "the full band",
            // which is right for a child that has no opinion (a row of labels, a `fill` column) and
            // wrong for one that declares its own cross extent: a 2 px-inset toolbar item wants a
            // 52 px row inside a 56 px strip, and stretching it to 56 drew a hover fill that bled
            // over the inset the strip reserves. `outer_cross` is `hints.height.pref` (plus
            // margins) — the child's own statement of what it needs — so honouring a value *below*
            // the band is the same rule every other alignment already follows, while a child that
            // asked for more than the band gets the band (nothing clips at this layer, so painting
            // outside the parent would be a layout violation rather than a graceful degradation).
            //
            // A child with no opinion reports `0` here, which is also what it did before: the
            // `min(available_cross)` collapses it to the band exactly as the old line did.
            let declared_cross = (outer_cross(index) - top - bottom).min(available_cross).max(0);
            let stretch_cross = if declared_cross == 0 { available_cross } else { declared_cross };
            let (cross_start, cross_len) =
                match self.items[index].align_self.unwrap_or(self.align_items) {
                    AlignItems::Stretch => (0, stretch_cross),
                    AlignItems::FlexStart => (0, outer_cross(index) - top - bottom),
                    AlignItems::FlexEnd => {
                        (available_cross - cross_len, outer_cross(index) - top - bottom)
                    }
                    AlignItems::Center => {
                        ((available_cross - cross_len) / 2, outer_cross(index) - top - bottom)
                    }
                    AlignItems::Baseline => (0, outer_cross(index) - top - bottom),
                };
            let cross_start = cross_start.max(0);

            // The child's box sits at its cursor plus its own leading margin, so a margin is
            // space the child does not draw in — which is what makes it a *gap* rather than a
            // padding of the child's own chrome.
            // The cursor is the trailing edge in a reverse layout, so the child is placed *behind*
            // it by its own extent plus the margin on that side. `main_len + left + right` is the
            // solved box, so subtracting it and adding back the leading margin gives the child's
            // drawn origin -- the mirror of `cursor + left` below.
            let main_start = if reverse { cursor - solved + left } else { cursor + left };
            let child_rect = if is_row {
                Rect::new(
                    main_start,
                    cross_origin + cross_start + top,
                    main_len.max(0) as u32,
                    cross_len.max(0) as u32,
                )
            } else {
                Rect::new(
                    cross_origin + cross_start + left,
                    main_start,
                    cross_len.max(0) as u32,
                    main_len.max(0) as u32,
                )
            };
            if let Some(widget_id) = self.items[index].widget_id {
                out(widget_id, child_rect);
            }
            // Backward on a reversed axis, forward otherwise -- so the next child is always placed
            // against the one just emitted.
            if reverse {
                cursor -= solved + self.gap + inter_extra;
            } else {
                cursor += solved + self.gap + inter_extra;
            }
        }
    }

    fn update_with_context(
        &self,
        rect: Rect,
        context: &LayoutContext,
        widgets: &mut dyn FnMut(ObjectId, Rect),
    ) {
        // Spacing follows the **larger** of the layout scale and the text scale.
        //
        // `LayoutContext::font_scale` is the device's text-size preference, and the two are
        // separate facts: a HiDPI screen needs more logical spacing, and a device whose text is set
        // larger needs more room between controls even at the same DPI. Taking the maximum is the
        // conservative reading — a control whose font grew but whose padding did not would have its
        // text touching its own border, which is the defect the field exists to let a layout avoid.
        //
        // The field had no reader at all before this, so a 2x text preference grew the glyphs (via
        // the theme's font token) and left every gap at its nominal size.
        let scale = context.layout_scale.max(context.font_scale);
        let scaled_padding = (self.padding as f32 * scale).round() as i32;
        let scaled_gap = (self.gap as f32 * scale).round() as i32;

        let content_rect = Rect::new(
            rect.x + scaled_padding,
            rect.y + scaled_padding,
            rect.width.saturating_sub(2 * scaled_padding as u32),
            rect.height.saturating_sub(2 * scaled_padding as u32),
        );

        let results = self.compute_rects(content_rect, Some(scaled_gap));
        for (widget_id, child_rect) in results {
            if let Some(wid) = widget_id {
                // Every child gets at least the device class's minimum touch area. A flex row of
                // small controls is the case this matters most for: the layout would otherwise
                // place a 20 px control in a 20 px slot on a phone, where the neighbouring
                // control's own expanded hit area overlaps it.
                widgets(
                    wid,
                    crate::layout::types::grow_to_min_touch_size(
                        child_rect,
                        context.min_touch_size,
                    ),
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compat::HashMap;
    use crate::layout::{AxisHints, ChildInfo, Hints, LayoutParams};
    use crate::style::EdgeOffsets;

    #[test]
    fn flex_layout_default_creates_empty() {
        let layout = FlexLayout::new();
        assert_eq!(layout.item_count(), 0);
    }

    #[test]
    fn flex_layout_add_and_remove_widget() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 1);
        layout.add_widget(2, 2);
        assert_eq!(layout.item_count(), 2);
        assert!(layout.has_child(1));
        assert!(layout.has_child(2));

        layout.remove_widget(1);
        assert_eq!(layout.item_count(), 1);
        assert!(!layout.has_child(1));
        assert!(layout.has_child(2));
    }

    #[test]
    fn flex_layout_child_ids() {
        let mut layout = FlexLayout::new();
        layout.add_widget(10, 0);
        layout.add_widget(20, 0);
        let ids = layout.child_ids();
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&10));
        assert!(ids.contains(&20));
    }

    #[test]
    fn flex_layout_clear() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 1);
        layout.add_widget(2, 1);
        assert_eq!(layout.item_count(), 2);
        layout.clear();
        assert_eq!(layout.item_count(), 0);
    }

    #[test]
    fn flex_layout_distributes_evenly_with_equal_grow() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 1);
        layout.add_widget(2, 1);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(0, 0), Size::new(0, 0)]);
        layout.update(Rect::new(0, 0, 200, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Two equal flex-grow items in 200px: each gets 100px.
        assert_eq!(rects.get(&1).map(|r| r.width), Some(100));
        assert_eq!(rects.get(&2).map(|r| r.width), Some(100));
        assert_eq!(rects.get(&1).map(|r| r.height), Some(50));
        assert_eq!(rects.get(&2).map(|r| r.height), Some(50));
    }

    #[test]
    fn flex_layout_uneven_grow() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 1);
        layout.add_widget(2, 3);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(0, 0), Size::new(0, 0)]);
        layout.update(Rect::new(0, 0, 200, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Item 1 gets 1/4 (50px), item 2 gets 3/4 (150px).
        assert_eq!(rects.get(&1).map(|r| r.width), Some(50));
        assert_eq!(rects.get(&2).map(|r| r.width), Some(150));
    }

    #[test]
    fn flex_layout_column_direction() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Column,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 1);
        layout.add_widget(2, 1);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(0, 0), Size::new(0, 0)]);
        layout.update(Rect::new(0, 0, 100, 200), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Column: each gets 100px height.
        assert_eq!(rects.get(&1).map(|r| r.height), Some(100));
        assert_eq!(rects.get(&2).map(|r| r.height), Some(100));
        assert_eq!(rects.get(&1).map(|r| r.width), Some(100));
        assert_eq!(rects.get(&2).map(|r| r.width), Some(100));
    }

    #[test]
    fn flex_layout_justify_center() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::Center,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(30, 20), Size::new(30, 20)]);
        layout.update(Rect::new(0, 0, 100, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Two fixed-size items (30+30=60) in 100px: leftover 40, centered offset 20.
        let r1 = rects.get(&1).unwrap();
        let r2 = rects.get(&2).unwrap();
        assert_eq!(r1.x, 20);
        assert_eq!(r2.x, 50);
    }

    #[test]
    fn flex_layout_justify_space_between() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::SpaceBetween,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(20, 10), Size::new(20, 10)]);
        layout.update(Rect::new(0, 0, 100, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Items width=20 each, total=40, leftover=60, gap=60/1=60
        // Positions: item1 at 0, item2 at 80
        assert_eq!(rects.get(&1).map(|r| r.x), Some(0));
        assert_eq!(rects.get(&2).map(|r| r.x), Some(80));
    }

    #[test]
    fn flex_layout_padding_applied() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            0,
            10,
        );
        layout.add_widget(1, 1);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(0, 0)]);
        layout.update(Rect::new(0, 0, 200, 60), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Padding 10 on each side: content width = 200-20=180, height = 60-20=40.
        // Item starts at (10, 10).
        assert_eq!(rects.get(&1).map(|r| r.x), Some(10));
        assert_eq!(rects.get(&1).map(|r| r.y), Some(10));
        assert_eq!(rects.get(&1).map(|r| r.width), Some(180));
        assert_eq!(rects.get(&1).map(|r| r.height), Some(40));
    }

    #[test]
    fn flex_layout_gap_between_items() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            10,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(30, 20), Size::new(30, 20)]);
        layout.update(Rect::new(0, 0, 100, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Fixed items 30+30=60, gap=10 => total=70
        // Item1 at 0, item2 at 30+10=40
        assert_eq!(rects.get(&1).map(|r| r.x), Some(0));
        assert_eq!(rects.get(&2).map(|r| r.x), Some(40));
    }

    #[test]
    fn flex_layout_wraps_rows_when_main_axis_overflows() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::Wrap,
            JustifyContent::FlexStart,
            AlignItems::FlexStart,
            5,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        layout.add_widget(3, 0);
        layout.set_child_sizes(vec![Size::new(60, 20), Size::new(60, 30), Size::new(40, 10)]);

        let mut rects = HashMap::new();
        layout.update(Rect::new(0, 0, 125, 100), &mut |id, rect| {
            rects.insert(id, rect);
        });

        assert_eq!(rects.get(&1), Some(&Rect::new(0, 0, 60, 20)));
        assert_eq!(rects.get(&2), Some(&Rect::new(65, 0, 60, 30)));
        assert_eq!(rects.get(&3), Some(&Rect::new(0, 35, 40, 10)));
    }

    #[test]
    fn flex_layout_wrap_reverse_starts_lines_at_cross_end() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::WrapReverse,
            JustifyContent::FlexStart,
            AlignItems::FlexStart,
            5,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        layout.add_widget(3, 0);
        layout.set_child_sizes(vec![Size::new(60, 20), Size::new(60, 20), Size::new(40, 10)]);

        let mut rects = HashMap::new();
        layout.update(Rect::new(0, 0, 125, 100), &mut |id, rect| {
            rects.insert(id, rect);
        });

        assert_eq!(rects.get(&1).map(|rect| rect.y), Some(80));
        assert_eq!(rects.get(&2).map(|rect| rect.y), Some(80));
        assert_eq!(rects.get(&3).map(|rect| rect.y), Some(65));
    }

    #[test]
    fn flex_layout_wraps_columns_for_column_direction() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Column,
            FlexWrap::Wrap,
            JustifyContent::FlexStart,
            AlignItems::FlexStart,
            5,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        layout.add_widget(3, 0);
        layout.set_child_sizes(vec![Size::new(20, 60), Size::new(30, 60), Size::new(10, 40)]);

        let mut rects = HashMap::new();
        layout.update(Rect::new(0, 0, 100, 125), &mut |id, rect| {
            rects.insert(id, rect);
        });

        assert_eq!(rects.get(&1), Some(&Rect::new(0, 0, 20, 60)));
        assert_eq!(rects.get(&2), Some(&Rect::new(0, 65, 30, 60)));
        assert_eq!(rects.get(&3), Some(&Rect::new(35, 0, 10, 40)));
    }

    #[test]
    fn flex_layout_min_size_constraint() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 0);
        if let Some(item) = layout.items_mut().last_mut() {
            item.min_size = Size::new(50, 0);
        }

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(10, 20)]);
        layout.update(Rect::new(0, 0, 100, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Min width is 50, intrinsic is 10, so width should be at least 50.
        assert_eq!(rects.get(&1).map(|r| r.width), Some(50));
    }

    #[test]
    fn flex_layout_align_items_flex_end() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::FlexEnd,
            0,
            0,
        );
        layout.add_widget(1, 0);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(30, 20)]);
        layout.update(Rect::new(0, 0, 100, 100), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // FlexEnd: item should be at bottom (y = 100-20 = 80).
        assert_eq!(rects.get(&1).map(|r| r.y), Some(80));
    }

    #[test]
    fn flex_layout_align_items_center() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Center,
            0,
            0,
        );
        layout.add_widget(1, 0);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(30, 20)]);
        layout.update(Rect::new(0, 0, 100, 100), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Center: item should be vertically centered (y = (100-20)/2 = 40).
        assert_eq!(rects.get(&1).map(|r| r.y), Some(40));
    }

    #[test]
    fn flex_layout_align_self_overrides_align_items() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::FlexStart,
            0,
            0,
        );
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        if let Some(item) = layout.items_mut().get_mut(1) {
            item.align_self = Some(AlignItems::Center);
        }

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(30, 20), Size::new(30, 20)]);
        layout.update(Rect::new(0, 0, 100, 100), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Item 1: FlexStart => y = 0
        // Item 2: align_self = Center => y = (100-20)/2 = 40
        assert_eq!(rects.get(&1).map(|r| r.y), Some(0));
        assert_eq!(rects.get(&2).map(|r| r.y), Some(40));
    }

    #[test]
    fn flex_layout_update_with_context_scales_gap_and_padding() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            10,
            10,
        );
        layout.add_widget(1, 1);

        let context = LayoutContext { layout_scale: 2.0, ..LayoutContext::default() };

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(0, 0)]);
        layout.update_with_context(Rect::new(0, 0, 200, 60), &context, &mut |id, rect| {
            rects.insert(id, rect);
        });

        // With scale=2.0: padding=20, content area = (20,20) to (180,40), so the flex item is
        // 160x20. It is then grown to the context's minimum touch height, because a 20 px target is
        // smaller than the desktop class's 32 px minimum — that is what `min_touch_size` is for, and
        // this test previously asserted the un-grown height, which is why the field had no reader.
        assert_eq!(rects.get(&1).map(|r| r.x), Some(20));
        assert_eq!(rects.get(&1).map(|r| r.width), Some(160));
        let grown = rects.get(&1).copied().expect("the flex item was laid out");
        assert_eq!(grown.height, context.min_touch_size.height.max(20));
        // The growth is centred on the space the layout allocated, not anchored at its top.
        assert_eq!(
            grown.y,
            20 - (grown.height as i32 - 20) / 2,
            "a grown child must stay centred on its allocated slot"
        );
    }

    #[test]
    fn flex_layout_row_reverse() {
        let mut layout = FlexLayout::with_params(
            FlexDirection::RowReverse,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::Stretch,
            0,
            0,
        );
        layout.add_widget(1, 1);
        layout.add_widget(2, 1);

        let mut rects = HashMap::new();
        layout.set_child_sizes(vec![Size::new(0, 0), Size::new(0, 0)]);
        layout.update(Rect::new(0, 0, 200, 50), &mut |id, rect| {
            rects.insert(id, rect);
        });

        // RowReverse: item1 at x=100, item2 at x=0 (reversed order)
        assert_eq!(rects.get(&1).map(|r| r.x), Some(100));
        assert_eq!(rects.get(&2).map(|r| r.x), Some(0));
    }

    /// `arrange` — the path `CompositeBuilder` takes — honours the reverse axis too.
    ///
    /// # The defect this pins
    ///
    /// `update` and `arrange` are two entry points onto one layout, and only `update` routed the
    /// main-axis positions through `justify_positions`, which is where `is_reverse()` is handled.
    /// `arrange` packed from `origin_main` upward unconditionally, so a `RowReverse` layout came
    /// back **identical to a forward one**: the direction was read by one path and ignored by the
    /// other. The test above could not catch it because it calls `update`.
    ///
    /// The assertion is the *mirror* relation, not two hardcoded numbers: in a reverse row the first
    /// child ends where the last child would have ended forward, and the children appear in the
    /// opposite order, so the two layouts' x-positions are a reflection of one another. Stating it
    /// that way means a change to the band, the gaps or the sizes cannot make the test agree with a
    /// bug.
    #[test]
    fn arrange_honours_the_reverse_axis() {
        let rect_of = |direction: FlexDirection| -> HashMap<u64, Rect> {
            let mut layout = FlexLayout::with_params(
                direction,
                FlexWrap::NoWrap,
                JustifyContent::FlexStart,
                AlignItems::Stretch,
                0,
                0,
            );
            layout.add_widget(1, 1);
            layout.add_widget(2, 1);
            let children = vec![
                ChildInfo { id: 1, hints: Hints::default(), params: LayoutParams::default() },
                ChildInfo { id: 2, hints: Hints::default(), params: LayoutParams::default() },
            ];
            let mut rects = HashMap::new();
            // Both children ask for half the band, so the forward and reverse placements are exact
            // reflections and no rounding can make a wrong answer look right.
            layout.set_child_sizes(vec![Size::new(100, 50), Size::new(100, 50)]);
            layout.arrange(Rect::new(0, 0, 200, 50), &children, &mut |id, rect| {
                rects.insert(id, rect);
            });
            rects
        };

        let forward = rect_of(FlexDirection::Row);
        let reverse = rect_of(FlexDirection::RowReverse);

        assert_eq!(forward.get(&1).map(|r| r.x), Some(0), "forward packs from the leading edge");
        assert_eq!(forward.get(&2).map(|r| r.x), Some(100), "and the second follows it");
        assert_eq!(
            reverse.get(&1).map(|r| r.x),
            Some(100),
            "reversed, the first child is packed against the far edge"
        );
        assert_eq!(reverse.get(&2).map(|r| r.x), Some(0), "and the second lands beside it");
        // Spelled as the reflection, so the assertion is the property rather than the four numbers.
        for id in [1u64, 2] {
            assert_eq!(
                forward.get(&id).map(|r| r.x),
                reverse.get(&id).map(|r| 200 - r.x - r.width as i32),
                "the reverse placement of child {id} is the forward one reflected about the band's \
                 centre"
            );
        }
    }

    // ── The hints channel (BLUE22 §B.5.2) ───────────────────────────────

    #[test]
    fn justify_content_distributes_the_leftover_it_is_given() {
        // The leftover-absorbing branch used to dump the whole surplus on the *last* child,
        // so a row of fixed-width children could never leave anything for the justification.
        // `FlexEnd` was consequently unreachable: a three-button row in a 240 px band with
        // 20 px of spare room came back flush left with a 20 px wider last button.
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexEnd,
            AlignItems::Stretch,
            0,
            0,
        );
        for id in [1u64, 2, 3] {
            layout.add_widget(id, 0);
        }
        let children = vec![
            ChildInfo::new(1, Hints::fixed(60, 30)),
            ChildInfo::new(2, Hints::fixed(60, 30)),
            ChildInfo::new(3, Hints::fixed(60, 30)),
        ];
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 240, 40), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });

        // The row is 180 px in a 240 px band: 60 px spare, all of it *before* the children.
        assert_eq!(
            rects.get(&1).map(|r| r.x),
            Some(60),
            "FlexEnd pins the row to the trailing edge"
        );
        // The row is 180 px in a 240 px band: 60 px spare, all of it *before* the children.
        assert_eq!(
            rects.get(&1).map(|r| r.x),
            Some(60),
            "FlexEnd pins the row to the trailing edge"
        );
        assert_eq!(rects.get(&3).map(|r| r.x), Some(180));
        assert_eq!(rects.get(&3).map(|r| r.x + r.width as i32), Some(240));
        for id in [1u64, 2, 3] {
            assert_eq!(
                rects.get(&id).map(|r| r.width),
                Some(60),
                "a non-growing child must keep its own width, not absorb the leftover"
            );
        }
    }

    #[test]
    fn justification_measures_the_leftover_including_the_gaps() {
        // The leftover is `band - occupied`, and "occupied" must count each gap **once**. The
        // previous form added each child's leading margin on top of a size that already
        // included it, so every gap was counted twice: 20 px of genuine spare room read as 8,
        // and with a slightly wider gap it read as zero and the justification had nothing to
        // distribute at all. A row of three buttons 6 px apart is the shape this has to hold
        // for, because that is what a dialog's action row is.
        let mut layout = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexEnd,
            AlignItems::Stretch,
            0,
            0,
        );
        for id in [1u64, 2, 3] {
            layout.add_widget(id, 0);
        }
        let gap = 6u32;
        let children: Vec<ChildInfo> = [1u64, 2, 3]
            .iter()
            .enumerate()
            .map(|(index, id)| {
                ChildInfo::new(*id, Hints::fixed(60, 30)).with_params(
                    LayoutParams::new().with_margins(EdgeOffsets::new(
                        0,
                        0,
                        0,
                        if index == 0 { 0 } else { gap },
                    )),
                )
            })
            .collect();
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 240, 40), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });

        // Occupied = 3 x 60 buttons + 2 x 6 gaps = 192, so 48 px of spare room, and FlexEnd
        // puts all of it before the first button.
        assert_eq!(
            rects.get(&1).map(|r| r.x),
            Some(48),
            "the leftover must be measured net of each gap exactly once"
        );
        assert_eq!(rects.get(&3).map(|r| r.x + r.width as i32), Some(240));
        for id in [1u64, 2, 3] {
            assert_eq!(rects.get(&id).map(|r| r.width), Some(60));
        }
    }

    #[test]
    fn a_child_is_never_squeezed_below_its_own_minimum() {
        // The shrink branch applied `max(item.min_size)` and then a "if we couldn't shrink
        // enough, cap at available" pass that cut straight through it, down to zero. Two
        // 100 px children in a 120 px band therefore came back 57 px each — narrower than the
        // labels they were about to draw.
        //
        // # What this pins now that G-1 is resolved
        //
        // The floors are unsatisfiable here (200 px of floor in a 120 px band), so *some* child
        // must end up below its floor — nothing can change that. What the layout owes the caller is
        // that the loss is **shared** rather than paid by whoever happens to be last, so this
        // asserts the two children stay equal and that the run fits its band. Before G-1 was
        // resolved the band was ignored: child 1 got its full 100 px and child 2 was packed at
        // `x = 100` in a 120 px band, i.e. 80 px outside the control it belongs to.
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        let children = vec![
            ChildInfo::new(
                1,
                Hints { width: AxisHints::new(100, 100, 200), height: AxisHints::new(30, 30, 30) },
            ),
            ChildInfo::new(
                2,
                Hints { width: AxisHints::new(100, 100, 200), height: AxisHints::new(30, 30, 30) },
            ),
        ];
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 120, 40), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });

        let widths: Vec<u32> = [1u64, 2]
            .iter()
            .map(|id| rects.get(id).map(|r| r.width).expect("both children were placed"))
            .collect();
        assert_eq!(
            widths[0], widths[1],
            "two children with the same floor must be treated the same: {widths:?}"
        );
        assert_eq!(
            widths.iter().sum::<u32>(),
            120,
            "the run must fit its band, whatever the floors say: {widths:?}"
        );
        // Each child keeps a majority of its floor rather than being reduced to nothing: the loss
        // is proportional, so no child collapses while another keeps everything.
        for (index, width) in widths.iter().enumerate() {
            assert!(
                *width >= 60,
                "child {} was reduced to {width}, far past share of the shortfall",
                index + 1
            );
        }
    }

    #[test]
    fn a_margin_is_a_gap_and_not_a_reduction_of_the_childs_own_size() {
        // `min_size` is expressed in the solver's *outer* units, which include the child's
        // margins. A 64 px floor on a child with a 6 px leading margin was previously
        // floored to an outer 64 and then drawn 58 wide — below its own minimum — because
        // the margin was subtracted after the floor was applied.
        //
        // # What this pins now that G-1 is resolved
        //
        // The band below is too narrow for both floors, so the *proportional* pass scales them
        // (see `compute_main_sizes`). What must survive that is the relation this test is named
        // for: the margin is a **gap between two boxes**, not part of either box. Before G-1 was
        // resolved the overhang hid a second reading of it — the trailing child was pushed out of
        // the picture, so its gap could not be checked at all.
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        let children = vec![
            ChildInfo::new(1, Hints::at_least(64, 30)),
            ChildInfo::new(2, Hints::at_least(64, 30))
                .with_params(LayoutParams::new().with_margins(EdgeOffsets::new(0, 0, 0, 6))),
        ];
        let rects = {
            let mut rects = HashMap::new();
            // A band too narrow for both floors: the children are scaled, not overhung.
            layout.arrange(Rect::new(0, 0, 120, 40), &children, &mut |id, rect| {
                rects.insert(id, rect);
            });
            rects
        };

        let first = rects.get(&1).copied().expect("the first child was placed");
        let second = rects.get(&2).copied().expect("the second child was placed");
        assert_eq!(
            second.x - (first.x + first.width as i32),
            6,
            "the margin must remain the gap between the two boxes: first {first:?}, second {second:?}"
        );
        assert_eq!(
            second.x + second.width as i32,
            120,
            "and the run must fit its band, so the trailing child is inside the control"
        );
        // The margin is room the child does not draw in, so the two boxes *plus the gap* are the
        // band — the margin is neither extra width nor stolen width.
        assert_eq!(
            first.width + 6 + second.width,
            120,
            "the two boxes and the one gap between them must account for the band"
        );
    }

    /// A child that *can* still shrink gives up the room a floored sibling cannot.
    ///
    /// # What this pins
    ///
    /// The proportional shrink pass alone stops as soon as any child reaches its floor, and the
    /// room that child would not release is then simply never taken from anyone else — so a row of
    /// a floored child and a freely-shrinkable one stayed wider than its band for no reason: the
    /// second child was at its comfortable size while the row overhung.
    ///
    /// This is the case a composite hits constantly: a split button's face is a *text-driven*
    /// trigger (plenty of room above its floor) beside a *fixed* arrow column (no room above its
    /// floor at all). Narrowing the face has to compress the trigger, and before the second pass it
    /// did not — the arrow column was pushed out of the control instead.
    ///
    /// # Why this case is not the G-1 case
    ///
    /// Here the floors *do* fit — `60 + 100 = 160` is more than the 140 px band, but the first
    /// child only needs 60 of the room it is claiming, so the second pass can resolve the deficit
    /// without anyone crossing a floor. The proportional scaling that resolves G-1 therefore does
    /// not run: `leftover` reaches zero first. The assertion that the first child keeps its 60 px
    /// *is* the distinction between the two mechanisms.
    #[test]
    fn a_child_that_can_shrink_gives_up_the_room_a_floored_sibling_cannot() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        let children = vec![
            // 100 px wide with a 60 px floor: it can give up 40.
            ChildInfo::new(1, Hints { width: AxisHints::new(60, 100, 200), ..Hints::default() }),
            // 100 px wide with a 100 px floor: it can give up nothing.
            ChildInfo::new(2, Hints::fixed(100, 30)),
        ];
        let mut rects = HashMap::new();
        // A 160 px band: 40 px of deficit, all of which the first child can release and none of
        // which the second can.
        layout.arrange(Rect::new(0, 0, 160, 40), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });

        let first = rects.get(&1).copied().expect("the first child was placed");
        let second = rects.get(&2).copied().expect("the second child was placed");
        assert_eq!(second.width, 100, "the floored child keeps its size");
        assert_eq!(
            first.width, 60,
            "the child with room above its floor gives up exactly what the row needs"
        );
        assert_eq!(first.width + second.width, 160, "and the two of them are the band");
    }

    /// The run never leaves its band, even when the children's floors cannot all be satisfied.
    ///
    /// # The defect this closes (BLUE22 · G-1)
    ///
    /// Two 100 px floors cannot both be honoured in a 140 px band — that is arithmetic, not a bug,
    /// and the shrink pass is explicit that a child is never squeezed below its own floor because a
    /// button narrower than its label is a button whose label elides.
    ///
    /// What *was* a bug is where the 60 px that did not fit went. The positions are packed from the
    /// leading edge, so the whole shortfall was paid by whichever child came last: the second child
    /// was placed at `x = 100` in a 140 px band and, because the SVG backend emits absolute
    /// coordinates and nothing clips at this layer, it was **absent from the picture** rather than
    /// overflowing it. A silently missing control is worse than a compressed one.
    ///
    /// # The resolution, and why not the obvious one
    ///
    /// The sizes are scaled by `available / floors`, so the run fits and every child stays inside
    /// the band while keeping its proportions. The obvious alternative — "give each child at most
    /// the room that is left" — was implemented and **reverted**: the same row came back
    /// `100 + 40`, i.e. the shortfall moved into the *second* child as a 40 px button. That does not
    /// resolve the contradiction either, it just concentrates the loss in one child instead of
    /// spreading it, and 40 px is below the 100 px floor it was supposed to respect.
    ///
    /// Scaling cannot make an unsatisfiable layout satisfiable. What it can do is make the loss
    /// **shared, bounded and contained**, which is the part the layout actually owns.
    ///
    /// # Why the scale is deliberately tiny rather than "identical sizes"
    ///
    /// A child with a larger floor keeps a larger box here, which is what keeps the relation
    /// between a wide and a narrow control readable when a form is squeezed. Forcing every child to
    /// `available / count` would make a 100 px button and a 10 px icon the same width.
    #[test]
    fn a_run_that_cannot_fit_its_floors_still_stays_inside_its_band() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        let children = vec![
            ChildInfo::new(1, Hints::fixed(100, 30)),
            ChildInfo::new(2, Hints::fixed(100, 30)),
        ];
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 140, 40), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });
        let first = rects.get(&1).copied().expect("the first child was placed");
        let second = rects.get(&2).copied().expect("the second child was placed");

        // The property that matters, stated as containment rather than as a number: every child is
        // inside the band it was offered.
        for (label, rect) in [("first", first), ("second", second)] {
            assert!(
                rect.x >= 0 && rect.x + rect.width as i32 <= 140,
                "the {label} child must stay inside the band, got {rect:?}"
            );
        }
        // And the run is the band: the shortfall is spread, not deferred.
        assert_eq!(
            first.width + second.width,
            140,
            "the two children must account for the band: first {first:?}, second {second:?}"
        );
        // Equal floors get equal boxes, so the loss is not concentrated anywhere.
        assert_eq!(first.width, second.width, "the shortfall must be shared, not deferred");
        assert_eq!(second.x, 70, "and the second child begins where the first ends");
    }

    /// A child whose floor is larger keeps a larger box when the band cannot hold both.
    ///
    /// The companion to the test above: the scaling preserves *proportions*, so a form that is
    /// squeezed still reads as the same form rather than as a row of equal slabs. It is also the
    /// property that distinguishes scaling from "give everyone `available / count`".
    #[test]
    fn a_squeezed_run_keeps_its_childrens_proportions() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        let children =
            vec![ChildInfo::new(1, Hints::fixed(120, 30)), ChildInfo::new(2, Hints::fixed(40, 30))];
        let mut rects = HashMap::new();
        // 80 px for 160 px of floor: a half-scale band.
        layout.arrange(Rect::new(0, 0, 80, 40), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });
        let first = rects.get(&1).copied().expect("the first child was placed");
        let second = rects.get(&2).copied().expect("the second child was placed");
        assert_eq!(first.width + second.width, 80, "the run fits its band");
        assert!(
            first.width > second.width,
            "the wider control keeps the wider box: {} vs {}",
            first.width,
            second.width
        );
        // 120:40 is 3:1, and the scale is exact for a band that divides evenly.
        assert_eq!(first.width, 60);
        assert_eq!(second.width, 20);
    }

    /// A child that declares its own cross extent is not stretched past it.
    ///
    /// # What this pins
    ///
    /// `AlignItems::Stretch` used to be "the full band", unconditionally. That is right for a child
    /// with no opinion — a row of labels, a `fill` column — and wrong for a child that states its
    /// own cross size: a toolbar item reserves 2 px of inset at each end of its strip, so a 56 px
    /// strip holds 52 px rows. Stretching the item to the full 56 drew its hover fill over the
    /// inset the strip had reserved.
    ///
    /// The fix reads the child's own `hints.pref` on the cross axis, so "I want to fill the cross
    /// axis" is still expressed by declaring no preference (which reports `0` and is then expanded
    /// to the band, exactly as before).
    #[test]
    fn a_child_that_declares_its_cross_size_is_not_stretched_past_it() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        let children = vec![ChildInfo::new(1, Hints::fixed(40, 30))];
        let mut rects = HashMap::new();
        // A 60 px tall band: the child asked for 30 and the default alignment is `Stretch`.
        layout.arrange(Rect::new(0, 0, 200, 60), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });
        let placed = rects.get(&1).copied().expect("the child was placed");
        assert_eq!(placed.height, 30, "the child's own cross size wins over the band: {placed:?}");
    }

    /// A child with no cross opinion still fills the band.
    ///
    /// The companion to the test above: the crate's default alignment must keep doing what it did
    /// for the overwhelming majority of children, which declare a size on one axis only.
    #[test]
    fn a_child_with_no_cross_opinion_still_fills_the_band() {
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        let children =
            vec![ChildInfo::new(1, Hints { width: AxisHints::fixed(60), ..Default::default() })];
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 200, 60), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });
        let placed = rects.get(&1).copied().expect("the child was placed");
        assert_eq!(
            placed.height, 60,
            "a child that declared no cross size is stretched to the band: {placed:?}"
        );
    }

    #[test]
    fn a_layout_can_size_its_children_without_being_told_in_advance() {
        // BLUE22 §B.10 judgment 2: "a layout that does not know the sizes can lay out from
        // `&[ChildInfo]` alone". This is the whole point of the channel — the old path
        // required `set_child_sizes` *before* `update`, so a caller who forgot got a row of
        // zero-width cells rather than an error.
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);

        // Deliberately no `set_child_sizes` call.
        let children = vec![
            ChildInfo::new(1, Hints::at_least(60, 30)),
            ChildInfo::new(2, Hints::at_least(40, 30)),
        ];
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 200, 50), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });

        assert_eq!(rects.get(&1).map(|r| r.width), Some(60), "child 1 gets its own hint");
        assert_eq!(rects.get(&2).map(|r| r.width), Some(40), "child 2 gets its own hint");
        // And they are actually placed, not stacked at the origin.
        assert_eq!(rects.get(&1).map(|r| r.x), Some(0));
        assert_eq!(rects.get(&2).map(|r| r.x), Some(60));
    }

    #[test]
    fn the_hint_channel_and_the_legacy_path_agree_on_the_same_sizes() {
        // The channel must not be a *different* layout algorithm: given the same sizes, the
        // two entry points have to produce the same geometry, or adopting the channel would
        // silently change every existing layout.
        let mut legacy = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::FlexStart,
            8,
            0,
        );
        legacy.add_widget(1, 0);
        legacy.add_widget(2, 0);
        legacy.set_child_sizes(vec![Size::new(60, 30), Size::new(40, 30)]);

        let mut direct = FlexLayout::with_params(
            FlexDirection::Row,
            FlexWrap::NoWrap,
            JustifyContent::FlexStart,
            AlignItems::FlexStart,
            8,
            0,
        );
        direct.add_widget(1, 0);
        direct.add_widget(2, 0);

        let children = vec![
            ChildInfo::new(1, Hints::at_least(60, 30)),
            ChildInfo::new(2, Hints::at_least(40, 30)),
        ];

        let mut from_legacy = HashMap::new();
        legacy.update(Rect::new(0, 0, 200, 50), &mut |id, rect| {
            from_legacy.insert(id, rect);
        });
        let mut from_hints = HashMap::new();
        direct.arrange(Rect::new(0, 0, 200, 50), &children, &mut |id, rect| {
            from_hints.insert(id, rect);
        });

        assert_eq!(from_legacy, from_hints, "both entry points must agree");
    }

    #[test]
    fn a_child_the_caller_did_not_describe_falls_back_to_its_stored_size() {
        // A caller migrating one child at a time must not lose the children it has not
        // converted yet — the same "incremental migration" property `arrange`'s default
        // gives the fifteen layouts.
        let mut layout = FlexLayout::new();
        layout.add_widget(1, 0);
        layout.add_widget(2, 0);
        layout.set_child_sizes(vec![Size::new(0, 0), Size::new(70, 30)]);

        // Only child 1 is described.
        let children = vec![ChildInfo::new(1, Hints::at_least(30, 30))];
        let mut rects = HashMap::new();
        layout.arrange(Rect::new(0, 0, 200, 50), &children, &mut |id, rect| {
            rects.insert(id, rect);
        });

        assert_eq!(rects.get(&1).map(|r| r.width), Some(30));
        assert_eq!(rects.get(&2).map(|r| r.width), Some(70), "the stored size still applies");
    }
}