muri 0.13.9

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

use std::collections::HashMap;

use crate::geometry::{LogicalPoint, LogicalRect, LogicalSize};
use crate::layout::{resolve_segments, SegmentMetrics};
use crate::menu::{Align, Axis, Content, Icon, Item, MenuId, Row, Segment, Stack};
use crate::render::{SceneDrawer, TextRun};
use std::borrow::Cow;

use crate::style::{Font, FontFamily, Rgba, Weight};
use crate::theme::{MenuOptions, Theme, TrailingGutterPolicy};
use crate::Menu;

/// A scratch memo of `(text, font)` -> measured width, cleared at the start of
/// every [`render_menu`] call, so the same `(text, font)` isn't re-shaped up to
/// 3× per frame across the width pass and the draw pass.
///
/// Keyed by a **hash** of the borrowed `(text, font)` components (mirroring
/// [`FontStore::shape`](crate::render)'s `shaped` design, #4): a hash hit
/// verifies the owned [`MeasureKey`] field-by-field without allocating, and the
/// owned key is built only on a genuine miss (#F12).
type MeasureCache = HashMap<u64, (MeasureKey, f32)>;

#[derive(PartialEq, Eq)]
struct MeasureKey {
    text: String,
    family_tag: u8,
    family_name: String,
    size_bits: u32,
    weight: u16,
    // Tracking is part of the key: a tracked and untracked measurement of the same
    // text have different widths and must not collide (#42).
    spacing_bits: u32,
    // Optical size is part of the key: `measure_text` shapes at `font.optical_size`
    // (#77), which instances a variable face at a different `opsz` master with
    // different advances, so two otherwise-identical fonts measure differently.
    opsz_bits: u32,
}

/// The `(tag, name)` family discriminant of a [`Font`], borrowed (no allocation):
/// `System`/`SystemMono` carry an empty name, a `Named` family borrows its own.
/// Shared by the measure-cache hash and its field-by-field verify so both agree.
fn font_family_parts(font: &Font) -> (u8, &str) {
    match &font.family {
        FontFamily::System => (0u8, ""),
        FontFamily::SystemMono => (1u8, ""),
        FontFamily::Named(name) => (2u8, name.as_str()),
    }
}

impl MeasureKey {
    fn new(text: &str, font: &Font) -> Self {
        let (family_tag, family_name) = font_family_parts(font);
        MeasureKey {
            text: text.to_string(),
            family_tag,
            family_name: family_name.to_string(),
            size_bits: font.size.to_bits(),
            weight: font.weight.ot_weight(),
            spacing_bits: font.letter_spacing.to_bits(),
            opsz_bits: font.optical_size.map(f32::to_bits).unwrap_or(0),
        }
    }

    /// Whether this owned key equals the borrowed `(text, font)`, checked
    /// field-by-field so a hash hit is verified without allocating an owned key
    /// (guards against a hash collision returning the wrong width, #F12).
    fn matches(&self, text: &str, font: &Font) -> bool {
        let (family_tag, family_name) = font_family_parts(font);
        self.text == text
            && self.family_tag == family_tag
            && self.family_name == family_name
            && self.size_bits == font.size.to_bits()
            && self.weight == font.weight.ot_weight()
            && self.spacing_bits == font.letter_spacing.to_bits()
            && self.opsz_bits == font.optical_size.map(f32::to_bits).unwrap_or(0)
    }
}

/// Hash the borrowed `(text, font)` measure-cache components, so the lookup path
/// allocates no owned [`MeasureKey`] on a hit (#F12). Mirrors `shape_key_hash`.
fn measure_key_hash(text: &str, font: &Font) -> u64 {
    use std::hash::{Hash, Hasher};
    let (family_tag, family_name) = font_family_parts(font);
    let mut h = std::collections::hash_map::DefaultHasher::new();
    text.hash(&mut h);
    family_tag.hash(&mut h);
    family_name.hash(&mut h);
    font.size.to_bits().hash(&mut h);
    font.weight.ot_weight().hash(&mut h);
    font.letter_spacing.to_bits().hash(&mut h);
    font.optical_size
        .map(f32::to_bits)
        .unwrap_or(0)
        .hash(&mut h);
    h.finish()
}

/// Measure `text` in `font` through `drawer`, memoizing in `cache` so an
/// identical `(text, font)` pair within the same frame is only shaped once.
/// Output is identical to calling `drawer.measure_text` directly every time.
///
/// A cache HIT hashes the borrowed key, verifies the stored owned key
/// field-by-field, and returns the stored width — allocating nothing. Only a
/// genuine miss builds and inserts the owned [`MeasureKey`] (#F12).
fn measure_cached<D: SceneDrawer>(
    drawer: &D,
    cache: &mut MeasureCache,
    text: &str,
    font: &Font,
) -> f32 {
    let hash = measure_key_hash(text, font);
    if let Some((key, w)) = cache.get(&hash) {
        // Verify the retained owned key really matches (a hash collision must not
        // return another `(text, font)`'s width).
        if key.matches(text, font) {
            return *w;
        }
    }
    let w = drawer.measure_text(text, font);
    // Build the owned key only now, on a genuine miss (never on a hit).
    cache.insert(hash, (MeasureKey::new(text, font), w));
    w
}

/// A resolved, clickable row in a painted menu (window-relative logical coords).
#[derive(Clone, Debug)]
pub struct LaidRow {
    /// Index of the item within the menu's top-level `items`.
    pub index: usize,
    /// The row's bounding rectangle in logical, window-relative coordinates.
    pub rect: LogicalRect,
    /// The row's click id (may be [`MenuId::none`] for inert rows).
    pub id: MenuId,
    /// Whether the row is interactive (clickable / highlightable).
    pub interactive: bool,
}

/// The result of painting a menu: its logical size and the clickable rows.
#[derive(Clone, Debug, Default)]
pub struct LaidMenu {
    /// Total popup size in logical pixels.
    pub size: LogicalSize,
    /// One entry per top-level item, in order (for hit-testing / highlight).
    pub rows: Vec<LaidRow>,
}

impl LaidMenu {
    /// The top-level item index at a window-relative logical point, if any
    /// interactive row contains it.
    pub fn hit(&self, point: LogicalPoint) -> Option<usize> {
        self.rows
            .iter()
            .find(|r| r.interactive && r.rect.contains(point))
            .map(|r| r.index)
    }

    /// The clickable [`MenuId`] at a point, if it lands on an interactive row.
    pub fn id_at(&self, point: LogicalPoint) -> Option<MenuId> {
        self.rows
            .iter()
            .find(|r| r.interactive && r.rect.contains(point))
            .map(|r| r.id.clone())
    }
}

const SEPARATOR_HEIGHT: f32 = 11.0;
const ICON_SIZE: f32 = 16.0;
const TRAILING_COLUMN: f32 = 14.0;
const DEFAULT_MIN_WIDTH: f32 = 200.0;
const DEFAULT_MAX_WIDTH: f32 = 380.0;
/// Vertical padding above/below an [`Item::Content`] row's measured stack
/// height, on top of the theme's `row_height` floor (issue #44). Chosen to
/// roughly match the breathing room a text row gets from its line-height
/// centering within `theme.row_height`.
const CONTENT_ROW_VPAD: f32 = 4.0;

/// Opacity a **disabled** row's icon/checkmark is drawn at (issue E): the row's
/// text already dims via `secondary_label`, but its icon and checkmark are drawn
/// in their own (accent/image) colors and would otherwise stay at full opacity —
/// so they are dimmed here to match.
const DISABLED_ALPHA: f32 = 0.5;

/// `v` if it is finite, else `fallback`. Sanitizes a measurement/option before it
/// feeds a `clamp` or geometry: an empty or degenerate input (a `NaN` min width,
/// a non-finite measured stack) must not produce `NaN` geometry (`f32::clamp`
/// even *panics* when its bounds aren't ordered).
fn finite_or(v: f32, fallback: f32) -> f32 {
    if v.is_finite() {
        v
    } else {
        fallback
    }
}

/// `c` with its alpha scaled by `alpha` (clamped to `[0, 1]`) — the primitive
/// behind [`dim_color`], applied to a checkmark/symbol glyph so a disabled row's
/// glyph dims exactly like a blitted icon does.
fn dim_rgba(c: Rgba, alpha: f32) -> Rgba {
    let alpha = alpha.clamp(0.0, 1.0);
    Rgba::new(c.r, c.g, c.b, (c.a as f32 * alpha).round() as u8)
}

/// `c` unchanged when `enabled`, else dimmed to [`DISABLED_ALPHA`] (issue E).
fn dim_color(c: Rgba, enabled: bool) -> Rgba {
    if enabled {
        c
    } else {
        dim_rgba(c, DISABLED_ALPHA)
    }
}

fn is_submenu(item: &Item) -> bool {
    matches!(item, Item::Submenu { .. })
}

/// The inline leading advance a row consumes for its own icon/checkmark before
/// its text: `ICON_SIZE + gap` when the row carries a leading icon or is checked,
/// else `0`. This is **per-row** and never reserved globally — every row's
/// content starts at the same left x; an icon row simply draws its image first
/// and pushes only *its own* text right (issue #16). A caller wanting a shared
/// checkmark/icon column adds it explicitly.
fn row_leading_width(row: &Row, gap: f32) -> f32 {
    if row.leading.is_some() || row.checked == Some(true) {
        ICON_SIZE + gap
    } else {
        0.0
    }
}

/// Whether the menu reserves a shared leading gutter: true when any row is
/// **checkable** — `checked.is_some()`, per the `Row::checked` contract that
/// "`Some(true/false)` shows a check column" — so checked *and*
/// currently-unchecked-but-checkable rows align their text past the gutter
/// (native `NSMenu` look). Testing only `Some(true)` would leave an
/// all-unchecked-but-checkable menu with no reserved column, so every row's
/// text would jump right the instant one is toggled on (#16 reconciliation).
fn menu_reserves_gutter(menu: &Menu) -> bool {
    menu.items.iter().any(|it| {
        item_row(it)
            .is_some_and(|r| r.checked.is_some() || matches!(r.leading, Some(Icon::Checkmark)))
    })
}

/// Whether the menu reserves a shared trailing column under [`TrailingGutterPolicy::Auto`]:
/// true when any item is a submenu (needs a `›` chevron column) or carries an
/// explicit trailing icon/accessory (issue A). Reserving it menu-wide keeps every
/// row's right edge aligned (native `NSMenu`); a menu with neither lets its
/// right-aligned content reach the true right edge. Mirrors [`menu_reserves_gutter`]
/// for the trailing side (#60).
fn menu_reserves_trailing(menu: &Menu) -> bool {
    menu.items
        .iter()
        .any(|it| is_submenu(it) || item_row(it).is_some_and(|r| row_trailing_width(r) > 0.0))
}

/// The leading advance a row consumes: the shared gutter width when the menu
/// reserves one (every row, so text aligns), else the row's own inline icon
/// advance (0 for icon-less rows).
fn row_lead(row: &Row, gap: f32, reserve_gutter: bool) -> f32 {
    if reserve_gutter {
        ICON_SIZE + gap
    } else {
        row_leading_width(row, gap)
    }
}

/// The trailing column a row reserves for its own trailing icon/accessory:
/// [`TRAILING_COLUMN`] when the row carries a [`Row::trailing`] icon, else `0`.
/// A submenu's chevron reserves the same column via [`is_submenu`] at the menu
/// level — this is the per-row equivalent for an explicit trailing icon (issue A).
fn row_trailing_width(row: &Row) -> f32 {
    if row.trailing.is_some() {
        TRAILING_COLUMN
    } else {
        0.0
    }
}

/// The font a segment renders in: its own override, else the row's base font.
/// Returns a borrow — this is called ~3× per segment per repaint (width pass,
/// draw metrics, draw loop), so cloning the `Font` (a heap `String` for a `Named`
/// family) each time was pure per-frame churn.
fn row_font<'a>(seg: &'a Segment, base: &'a Font) -> &'a Font {
    seg.font.as_ref().unwrap_or(base)
}

/// Measure the intrinsic width a row's segments want (sum of segment widths plus
/// inter-segment gaps), using the drawer's text metrics. Weight-aware and split
/// exactly as the (un-highlighted) draw pass will render the row, so a segment
/// carrying a bolder `StyleRun` is sized at the bold advance — the popup width
/// then never under-fits the text. `base_color` is the row's resolved base color
/// (the highlight overlay is a hover-time repaint that must not resize the
/// popup, so the width pass always measures the un-highlighted split).
fn row_intrinsic<D: SceneDrawer>(
    d: &D,
    cache: &mut MeasureCache,
    row: &Row,
    base: &Font,
    base_color: Rgba,
    theme: &Theme,
    gap: f32,
) -> f32 {
    if row.segments.is_empty() {
        return 0.0;
    }
    let mut w = 0.0;
    for (i, seg) in row.segments.iter().enumerate() {
        let font = row_font(seg, base);
        let seg_base = seg_base_color(seg, theme, base_color, false);
        w += measure_segment(d, cache, seg, font, theme, seg_base, false);
        if i + 1 < row.segments.len() {
            w += gap;
        }
    }
    w
}

fn item_row(item: &Item) -> Option<&Row> {
    match item {
        Item::Row(r) | Item::SectionHeader(r) => Some(r),
        Item::Submenu { label, .. } => Some(label),
        Item::Separator | Item::Content(_) => None,
    }
}

// -----------------------------------------------------------------------------
// Content stacks (issue #44): recursive measure + paint over a `Stack` tree.
// -----------------------------------------------------------------------------

/// The intrinsic (unconstrained) size of one [`Content`] node: text measured
/// through the drawer's shaper at its resolved font, an image at `size`×`size`,
/// a spacer at zero (it only absorbs slack at paint time), and a stack as the
/// recursive sum-along-axis / max-across-axis of its own children.
fn measure_content<D: SceneDrawer>(
    drawer: &D,
    cache: &mut MeasureCache,
    theme: &Theme,
    content: &Content,
) -> LogicalSize {
    match content {
        Content::Text(t) => {
            let font = t.font.clone().unwrap_or_else(|| theme.row_font.clone());
            let w = measure_cached(drawer, cache, &t.text, &font);
            let h = drawer.line_height(&font);
            LogicalSize::new(w, h)
        }
        Content::Image { size, .. } => LogicalSize::new(*size, *size),
        Content::Stack(stack) => measure_stack(drawer, cache, theme, stack),
        Content::Spacer => LogicalSize::new(0.0, 0.0),
    }
}

/// The intrinsic size of a [`Stack`]: children summed (plus inter-child
/// `spacing`) along `axis`, maxed across the cross axis.
fn measure_stack<D: SceneDrawer>(
    drawer: &D,
    cache: &mut MeasureCache,
    theme: &Theme,
    stack: &Stack,
) -> LogicalSize {
    let mut main = 0.0_f32;
    let mut cross = 0.0_f32;
    for (i, child) in stack.children.iter().enumerate() {
        let sz = measure_content(drawer, cache, theme, child);
        let (m, c) = match stack.axis {
            Axis::Horizontal => (sz.width, sz.height),
            Axis::Vertical => (sz.height, sz.width),
        };
        main += m;
        if i + 1 < stack.children.len() {
            main += stack.spacing;
        }
        cross = cross.max(c);
    }
    match stack.axis {
        Axis::Horizontal => LogicalSize::new(main, cross),
        Axis::Vertical => LogicalSize::new(cross, main),
    }
}

/// Paint one [`Content`] node into `rect` (already resolved by the parent
/// stack's layout pass). `base_color` is the row's default text color (used
/// when a [`crate::menu::TextContent`] carries no explicit color override).
fn paint_content<D: SceneDrawer>(
    drawer: &mut D,
    cache: &mut MeasureCache,
    theme: &Theme,
    content: &Content,
    rect: LogicalRect,
    base_color: Rgba,
) {
    match content {
        Content::Text(t) => {
            let font = t.font.clone().unwrap_or_else(|| theme.row_font.clone());
            let color = t.color.map(|c| theme.resolve(c)).unwrap_or(base_color);
            let w = measure_cached(drawer, cache, &t.text, &font);
            let lh = drawer.line_height(&font);
            let x = match t.align {
                Align::Left => rect.origin.x,
                Align::Center => rect.origin.x + (rect.size.width - w) / 2.0,
                Align::Right => rect.origin.x + (rect.size.width - w),
            };
            let y = rect.origin.y + (rect.size.height - lh) / 2.0;
            drawer.draw_text(&TextRun {
                text: &t.text,
                origin: LogicalPoint::new(x, y),
                font: &font,
                color,
                weight: font.weight,
            });
        }
        Content::Image { icon, size } => {
            let x = rect.origin.x + (rect.size.width - size) / 2.0;
            let y = rect.origin.y + (rect.size.height - size) / 2.0;
            let dest = LogicalRect::new(LogicalPoint::new(x, y), LogicalSize::new(*size, *size));
            // Route through the single icon funnel (a content image is enabled and
            // uses the row's base color for a checkmark/symbol glyph).
            draw_icon(drawer, cache, &theme.row_font, icon, dest, base_color, true);
        }
        Content::Stack(s) => paint_stack(drawer, cache, theme, s, rect, base_color),
        Content::Spacer => {}
    }
}

/// Lay out and paint a [`Stack`]'s children into `rect`: each child gets its
/// intrinsic main-axis size (measured via [`measure_content`]) except a
/// [`Content::Spacer`], which receives an equal share of whatever main-axis
/// space is left over after fixed children and `spacing` are subtracted
/// (clamped to zero — an over-full stack simply overflows `rect`, it is never
/// negative-sized). Cross-axis position honors `stack.align`.
fn paint_stack<D: SceneDrawer>(
    drawer: &mut D,
    cache: &mut MeasureCache,
    theme: &Theme,
    stack: &Stack,
    rect: LogicalRect,
    base_color: Rgba,
) {
    if stack.children.is_empty() {
        return;
    }
    let sizes: Vec<LogicalSize> = stack
        .children
        .iter()
        .map(|c| measure_content(drawer, cache, theme, c))
        .collect();

    let n = stack.children.len();
    let spacing_total = stack.spacing * (n.saturating_sub(1)) as f32;
    let main_avail = match stack.axis {
        Axis::Horizontal => rect.size.width,
        Axis::Vertical => rect.size.height,
    } - spacing_total;
    let cross_avail = match stack.axis {
        Axis::Horizontal => rect.size.height,
        Axis::Vertical => rect.size.width,
    };

    let mut fixed_main_sum = 0.0_f32;
    let mut spacer_count = 0usize;
    for (child, sz) in stack.children.iter().zip(&sizes) {
        if matches!(child, Content::Spacer) {
            spacer_count += 1;
        } else {
            fixed_main_sum += match stack.axis {
                Axis::Horizontal => sz.width,
                Axis::Vertical => sz.height,
            };
        }
    }
    let leftover = (main_avail - fixed_main_sum).max(0.0);
    let spacer_share = if spacer_count > 0 {
        leftover / spacer_count as f32
    } else {
        0.0
    };

    let cross_origin = match stack.axis {
        Axis::Horizontal => rect.origin.y,
        Axis::Vertical => rect.origin.x,
    };
    let mut main_pos = match stack.axis {
        Axis::Horizontal => rect.origin.x,
        Axis::Vertical => rect.origin.y,
    };

    for (child, sz) in stack.children.iter().zip(&sizes) {
        let (m, c) = match stack.axis {
            Axis::Horizontal => (sz.width, sz.height),
            Axis::Vertical => (sz.height, sz.width),
        };
        let this_main = if matches!(child, Content::Spacer) {
            spacer_share
        } else {
            m
        };
        let cross_pos = match stack.align {
            Align::Left => cross_origin,
            Align::Center => cross_origin + (cross_avail - c) / 2.0,
            Align::Right => cross_origin + (cross_avail - c),
        };
        let child_rect = match stack.axis {
            Axis::Horizontal => LogicalRect::new(
                LogicalPoint::new(main_pos, cross_pos),
                LogicalSize::new(this_main, c),
            ),
            Axis::Vertical => LogicalRect::new(
                LogicalPoint::new(cross_pos, main_pos),
                LogicalSize::new(c, this_main),
            ),
        };
        paint_content(drawer, cache, theme, child, child_rect, base_color);
        main_pos += this_main + stack.spacing;
    }
}

/// Split a segment's text into consecutive styled pieces by its UTF-16
/// [`StyleRun`](crate::StyleRun) spans, falling back to `base_color`/`base_weight`.
///
/// `StyleRun` colors resolve against the **live** `theme` so a semantic run color
/// is correct in dark mode, not baked against a hard-coded light palette (spec
/// §7.3). When `highlighted` (row filled with accent, every glyph forced to
/// `base_color`), a run's semantic color is **suppressed** so it inverts with
/// the rest of the row instead of e.g. rendering red on accent blue; per-run
/// *weight* overrides still apply in both states.
fn style_pieces<'a>(
    seg: &'a Segment,
    base_color: Rgba,
    base_weight: Weight,
    theme: &Theme,
    highlighted: bool,
) -> Vec<(&'a str, Rgba, Weight)> {
    if seg.runs.is_empty() {
        return vec![(seg.text.as_str(), base_color, base_weight)];
    }
    // Walk chars, coalescing a maximal run of same-(color, weight) chars into ONE
    // borrowed sub-slice of `seg.text` (byte-range) rather than allocating a
    // `String` per piece — piece boundaries are byte offsets into the original.
    let mut pieces: Vec<(&str, Rgba, Weight)> = Vec::new();
    let mut u16_idx = 0usize;
    let mut piece_start = 0usize;
    let mut cur_color = base_color;
    let mut cur_weight = base_weight;
    let mut open = false;
    for (byte_idx, ch) in seg.text.char_indices() {
        let mut color = base_color;
        let mut weight = base_weight;
        // Walk ALL runs (no early `break`): overlapping runs composite with the
        // LATER RUN WINS (issue D) — a run later in `seg.runs` overrides an earlier
        // one on the chars they share, instead of the first match silently
        // suppressing every later overlapping run.
        for run in &seg.runs {
            // `start`/`len` are public `StyleRun` fields set by the caller;
            // saturating add so a pathological `start + len` can't overflow
            // `usize` and panic under debug overflow checks.
            if u16_idx >= run.start && u16_idx < run.start.saturating_add(run.len) {
                if !highlighted {
                    color = theme.resolve(run.color);
                }
                if let Some(w) = run.weight {
                    weight = w;
                }
            }
        }
        if open && color == cur_color && weight == cur_weight {
            // Same style — the current piece just extends to include this char.
        } else {
            if open {
                pieces.push((&seg.text[piece_start..byte_idx], cur_color, cur_weight));
            }
            piece_start = byte_idx;
            cur_color = color;
            cur_weight = weight;
            open = true;
        }
        u16_idx += ch.len_utf16();
    }
    if open {
        pieces.push((&seg.text[piece_start..], cur_color, cur_weight));
    }
    pieces
}

/// The effective base color for a segment's un-styled chars, matching what the
/// draw pass uses: the highlight override (white) wins; otherwise an explicit
/// per-segment color; else the row's base color. Shared by the width pass, the
/// draw-pass metrics, and the draw loop so all three split into *identical*
/// pieces (piece boundaries depend on this color, and a different split changes
/// the summed width via cross-piece kerning).
fn seg_base_color(seg: &Segment, theme: &Theme, base_color: Rgba, highlighted: bool) -> Rgba {
    if highlighted {
        Rgba::WHITE
    } else if let Some(c) = seg.color {
        theme.resolve(c)
    } else {
        base_color
    }
}

/// The rendered width of a segment, measured the *same way it is drawn*: each
/// `StyleRun` weight override changes glyph advances, so the width is the sum of
/// the per-piece advances at each piece's weight — not the whole string measured
/// once at the base weight (which under-sizes a segment containing a bolder run
/// and lets a right-aligned / flex run overflow its box). `base_color` and
/// `highlighted` must be the same values the draw pass will use for this segment
/// so the piece split — and hence the summed width — is identical to the drawn
/// advance.
fn measure_segment<D: SceneDrawer>(
    drawer: &D,
    cache: &mut MeasureCache,
    seg: &Segment,
    font: &Font,
    theme: &Theme,
    base_color: Rgba,
    highlighted: bool,
) -> f32 {
    style_pieces(seg, base_color, font.weight, theme, highlighted)
        .into_iter()
        .map(|(text, _color, weight)| {
            // Only clone the font when a `StyleRun` actually changes the weight
            // (the common no-run piece keeps the base font, zero clone).
            if weight == font.weight {
                measure_cached(drawer, cache, text, font)
            } else {
                let pf = font.clone().with_weight(weight);
                measure_cached(drawer, cache, text, &pf)
            }
        })
        .sum()
}

/// Lay out and paint `menu` through `drawer`, highlighting the top-level item at
/// `highlight` (usually the row under the cursor). Returns the popup size and
/// clickable row rectangles for hit-testing.
pub fn render_menu<D: SceneDrawer>(
    drawer: &mut D,
    menu: &Menu,
    theme: &Theme,
    opts: &MenuOptions,
    highlight: Option<usize>,
) -> LaidMenu {
    let pad = theme.padding;
    let gap = theme.column_gap;
    let base_font = theme.row_font.clone();
    // Reserve a shared leading gutter per the caller's policy (#43): `Auto` (the
    // OEM default) reserves it only when the menu has checkmarks so checked and
    // unchecked rows align (#16 reconciliation); `Always`/`Never` force it.
    let reserve_gutter = match opts.gutter {
        crate::theme::GutterPolicy::Always => true,
        crate::theme::GutterPolicy::Never => false,
        crate::theme::GutterPolicy::Auto => menu_reserves_gutter(menu),
    };

    // Reserve the trailing column per the caller's policy (#60), symmetric to the
    // leading gutter above: `Auto` reserves it menu-wide only when some item
    // needs it (a submenu chevron or an explicit trailing icon, issue A), so
    // every row's segment band ends at the same right edge. `Always`/`Never`
    // force it; under `Never` a chevron/accessory still draws but overlays the
    // content area instead of getting its own column.
    let reserve_trailing = match opts.trailing_gutter {
        TrailingGutterPolicy::Always => true,
        TrailingGutterPolicy::Never => false,
        TrailingGutterPolicy::Auto => menu_reserves_trailing(menu),
    };
    let trailing_w = if reserve_trailing {
        TRAILING_COLUMN
    } else {
        0.0
    };

    // Scratch text-measurement memo, cleared every call (see `MeasureCache`).
    let mut measure_cache: MeasureCache = HashMap::new();

    // ---- Pass 1: width & height ----
    let mut max_content = 0.0_f32;
    for item in &menu.items {
        if let Some(row) = item_row(item) {
            let is_header = matches!(item, Item::SectionHeader(_));
            let font = if is_header {
                &theme.header_font
            } else {
                &base_font
            };
            // The row's un-highlighted base color, matching draw_row_content so
            // the width pass splits into the same pieces the draw pass advances.
            let base_color = if is_header || !row.enabled {
                theme.resolve(theme.secondary_label)
            } else {
                theme.resolve(theme.label)
            };
            // The row's content width: its leading advance (the shared gutter
            // when reserved, else its own inline icon) plus its segments.
            let content = row_lead(row, gap, reserve_gutter)
                + row_intrinsic(
                    drawer,
                    &mut measure_cache,
                    row,
                    font,
                    base_color,
                    theme,
                    gap,
                );
            max_content = max_content.max(content);
        } else if let Item::Content(stack) = item {
            let stack_size = measure_stack(drawer, &mut measure_cache, theme, stack);
            max_content = max_content.max(stack_size.width);
        }
    }

    // Sanitize every input to the width `clamp` (HIGH): a `NaN`/`inf` `min_width`,
    // `max_width`, or measured `max_content` (a degenerate/empty measurement) must
    // not reach `f32::clamp` — a non-finite bound produces `NaN` geometry, and an
    // out-of-order (`min > max`) bound makes `clamp` *panic*.
    let min_w = finite_or(
        opts.min_width.unwrap_or(DEFAULT_MIN_WIDTH),
        DEFAULT_MIN_WIDTH,
    );
    // `f32::clamp` panics if `min > max`; a consumer can set `min_width >
    // max_width`, so normalize by letting the floor win (#36).
    let max_w = finite_or(
        opts.max_width.unwrap_or(DEFAULT_MAX_WIDTH),
        DEFAULT_MAX_WIDTH,
    )
    .max(min_w);
    let max_content = finite_or(max_content, 0.0);
    let desired = finite_or(pad.left + max_content + trailing_w + pad.right, min_w);
    let width = desired.clamp(min_w, max_w);

    // Every row's content starts at the same left x (`content_left`); a row with a
    // leading icon draws it here and offsets only its own text. `band_right` is
    // the shared right edge segments right-align to (before the submenu column).
    let content_left = pad.left;
    let band_right = width - pad.right - trailing_w;

    let mut y = pad.top;
    let mut rows: Vec<LaidRow> = Vec::new();
    let mut plan: Vec<(usize, f32, f32)> = Vec::new(); // (item index, y, height)
    for (i, item) in menu.items.iter().enumerate() {
        let h = match item {
            Item::Separator => SEPARATOR_HEIGHT,
            Item::SectionHeader(_) => theme.row_height,
            Item::Row(r) | Item::Submenu { label: r, .. } => {
                // Sanitize a caller-supplied `min_height` before the `max` so a
                // `NaN` can't poison the row height (HIGH).
                theme
                    .row_height
                    .max(finite_or(r.min_height.unwrap_or(0.0), 0.0))
            }
            Item::Content(stack) => {
                let stack_size = measure_stack(drawer, &mut measure_cache, theme, stack);
                theme
                    .row_height
                    .max(finite_or(stack_size.height, 0.0) + CONTENT_ROW_VPAD * 2.0)
            }
        };
        plan.push((i, y, h));
        y += h;
    }
    let height = y + pad.bottom;
    let size = LogicalSize::new(width, height);

    // ---- Pass 2: draw ----
    drawer.begin_frame(size);
    let bg = theme.resolve(theme.background);
    drawer.fill_round_rect(
        LogicalRect::new(LogicalPoint::new(0.0, 0.0), size),
        theme.corner_radius,
        bg,
    );

    for (i, ry, rh) in plan {
        let item = &menu.items[i];
        match item {
            Item::Separator => {
                let sep = LogicalRect::new(
                    LogicalPoint::new(pad.left, ry + rh / 2.0),
                    LogicalSize::new(width - pad.horizontal(), 1.0),
                );
                drawer.draw_separator(sep, theme.resolve(theme.separator));
            }
            Item::SectionHeader(row) => {
                draw_row_content(
                    drawer,
                    &mut measure_cache,
                    row,
                    theme,
                    &theme.header_font,
                    content_left,
                    band_right,
                    reserve_gutter,
                    reserve_trailing,
                    ry,
                    rh,
                    false, // submenu
                    true,  // is_header: never paints a `checked` checkmark
                    false, // highlighted
                    theme.resolve(theme.secondary_label),
                );
            }
            Item::Content(stack) => {
                if let Some(bg) = stack.background {
                    let band =
                        LogicalRect::new(LogicalPoint::new(0.0, ry), LogicalSize::new(width, rh));
                    drawer.fill_round_rect(band, 0.0, theme.resolve(bg));
                }
                let content_rect = LogicalRect::new(
                    LogicalPoint::new(content_left, ry + CONTENT_ROW_VPAD),
                    LogicalSize::new(
                        (band_right - content_left).max(1.0),
                        (rh - CONTENT_ROW_VPAD * 2.0).max(1.0),
                    ),
                );
                paint_stack(
                    drawer,
                    &mut measure_cache,
                    theme,
                    stack,
                    content_rect,
                    theme.resolve(theme.label),
                );
            }
            Item::Row(row) | Item::Submenu { label: row, .. } => {
                let submenu = is_submenu(item);
                let interactive = if submenu {
                    row.enabled
                } else {
                    row.enabled && !row.id.is_none()
                };
                let highlighted = interactive && highlight == Some(i);
                let rect =
                    LogicalRect::new(LogicalPoint::new(0.0, ry), LogicalSize::new(width, rh));
                // A row whose model requests an explicit background gets it painted
                // first (issue B), underneath any hover highlight.
                fill_row_background(drawer, theme, row, rect);
                if highlighted {
                    let hl = LogicalRect::new(
                        LogicalPoint::new(pad.left - 2.0, ry + 1.0),
                        LogicalSize::new(width - pad.horizontal() + 4.0, rh - 2.0),
                    );
                    // The hover fill reads `theme.row_highlight` (resolved) rather
                    // than a hard-coded `theme.accent`: the dedicated theme field
                    // exists for exactly this and every preset sets it = Accent, so
                    // the pixels are identical today but a theme can now diverge.
                    drawer.fill_round_rect(hl, 5.0, theme.resolve(theme.row_highlight));
                }
                let base_color = if highlighted {
                    Rgba::WHITE
                } else if !row.enabled {
                    theme.resolve(theme.secondary_label)
                } else {
                    theme.resolve(theme.label)
                };
                draw_row_content(
                    drawer,
                    &mut measure_cache,
                    row,
                    theme,
                    &base_font,
                    content_left,
                    band_right,
                    reserve_gutter,
                    reserve_trailing,
                    ry,
                    rh,
                    submenu,
                    false, // is_header
                    highlighted,
                    base_color,
                );
                rows.push(LaidRow {
                    index: i,
                    rect,
                    id: row.id.clone(),
                    interactive,
                });
            }
        }
    }

    LaidMenu { size, rows }
}

#[allow(clippy::too_many_arguments)]
fn draw_row_content<D: SceneDrawer>(
    drawer: &mut D,
    cache: &mut MeasureCache,
    row: &Row,
    theme: &Theme,
    base_font: &Font,
    content_left: f32,
    band_right: f32,
    reserve_gutter: bool,
    reserve_trailing: bool,
    ry: f32,
    rh: f32,
    submenu: bool,
    is_header: bool,
    highlighted: bool,
    base_color: Rgba,
) {
    // A disabled row dims its icon/checkmark (issue E); its text already dims via
    // `secondary_label`. Headers/highlighted rows are always drawn "enabled".
    let icon_enabled = highlighted || is_header || row.enabled;
    // The color a checkmark/symbol glyph is drawn in: white on a highlighted row,
    // else the theme accent (dimmed later for a disabled row inside the funnel).
    let glyph_color = if highlighted {
        Rgba::WHITE
    } else {
        theme.resolve(theme.accent)
    };

    // Leading advance: the shared gutter width when the menu reserves one (so
    // checked + unchecked rows align, native look), else this row's own inline
    // icon advance (#16). The icon/checkmark still draws at `content_left`.
    let lead = row_lead(row, theme.column_gap, reserve_gutter);
    let band_x = content_left + lead;
    let band_w = (band_right - band_x).max(1.0);
    if lead > 0.0 {
        let icon_rect = LogicalRect::new(
            LogicalPoint::new(content_left, ry + (rh - ICON_SIZE) / 2.0),
            LogicalSize::new(ICON_SIZE, ICON_SIZE),
        );
        if let Some(icon) = &row.leading {
            // Every leading icon — Png, Svg, Checkmark, Symbol — draws through the
            // single funnel, so an `Icon::Svg`/`Icon::Symbol` in the leading slot
            // renders instead of being swallowed by a wildcard (HIGH, issue: Svg
            // leading icon).
            draw_icon(
                drawer,
                cache,
                base_font,
                icon,
                icon_rect,
                glyph_color,
                icon_enabled,
            );
        } else if row.checked == Some(true) && !is_header {
            // A checked row with no explicit leading icon paints the check glyph in
            // the gutter. Section headers never do (their `checked` is ignored, per
            // `Menu::section_header`); a submenu-parent row does.
            draw_icon(
                drawer,
                cache,
                base_font,
                &Icon::Checkmark,
                icon_rect,
                glyph_color,
                icon_enabled,
            );
        }
    }

    // Segment band.
    if !row.segments.is_empty() {
        let metrics: Vec<SegmentMetrics> = row
            .segments
            .iter()
            .map(|seg| {
                let font = row_font(seg, base_font);
                let seg_base = seg_base_color(seg, theme, base_color, highlighted);
                SegmentMetrics::new(
                    measure_segment(drawer, cache, seg, font, theme, seg_base, highlighted),
                    seg.flex,
                    seg.align,
                )
            })
            .collect();
        let boxes = resolve_segments(&metrics, band_w);
        for (seg, bx) in row.segments.iter().zip(boxes.iter()) {
            let font = row_font(seg, base_font);
            let lh = drawer.line_height(font);
            let text_top = ry + (rh - lh) / 2.0;
            let seg_base = seg_base_color(seg, theme, base_color, highlighted);
            let pieces = style_pieces(seg, seg_base, font.weight, theme, highlighted);
            let mut px = band_x + bx.text_x;
            for (text, color, weight) in pieces {
                // Borrow the base font unless a run overrode the weight (then clone
                // once for this piece) — avoids a per-piece `Font` clone per frame.
                let pf: Cow<Font> = if weight == font.weight {
                    Cow::Borrowed(font)
                } else {
                    Cow::Owned(font.clone().with_weight(weight))
                };
                let w = measure_cached(drawer, cache, text, &pf);
                drawer.draw_text(&TextRun {
                    text,
                    origin: LogicalPoint::new(px, text_top),
                    font: &pf,
                    color,
                    weight,
                });
                px += w;
            }
        }
    }

    // The left x of the trailing column: just past the segment band when the
    // menu reserves it (#60); otherwise the band already reaches the inner right
    // edge, so a chevron/accessory overlays the tail of the content area instead.
    let trailing_col_x = if reserve_trailing {
        band_x + band_w
    } else {
        band_x + band_w - TRAILING_COLUMN
    };

    // Trailing icon/accessory (issue A): a row carrying `Row::trailing` draws it in
    // the trailing column, through the same funnel as every other icon.
    if let Some(icon) = &row.trailing {
        let trailing_rect = LogicalRect::new(
            LogicalPoint::new(
                trailing_col_x + (TRAILING_COLUMN - ICON_SIZE) / 2.0,
                ry + (rh - ICON_SIZE) / 2.0,
            ),
            LogicalSize::new(ICON_SIZE, ICON_SIZE),
        );
        draw_icon(
            drawer,
            cache,
            base_font,
            icon,
            trailing_rect,
            glyph_color,
            icon_enabled,
        );
    }

    // Trailing submenu chevron.
    if submenu {
        let chev_rect = LogicalRect::new(
            LogicalPoint::new(trailing_col_x, ry),
            LogicalSize::new(TRAILING_COLUMN, rh),
        );
        draw_glyph_centered(
            drawer,
            cache,
            "\u{203A}", //            base_font,
            Weight::Regular,
            if highlighted {
                Rgba::WHITE
            } else {
                theme.resolve(theme.secondary_label)
            },
            chev_rect,
        );
    }
}

/// The single funnel every icon-drawing site routes through (leading slot,
/// trailing slot, standalone checkmark, content-stack image). It matches
/// **every** [`Icon`] variant exhaustively — no `_` arm — so a future `Icon`
/// variant is a compile error here rather than a silently-undrawn icon.
///
/// `glyph_color` is the color a glyph-based icon draws in (ignored for images);
/// `enabled` dims the whole icon to [`DISABLED_ALPHA`] when `false` (issue E).
#[allow(clippy::too_many_arguments)]
fn draw_icon<D: SceneDrawer>(
    drawer: &mut D,
    cache: &mut MeasureCache,
    base_font: &Font,
    icon: &Icon,
    rect: LogicalRect,
    glyph_color: Rgba,
    enabled: bool,
) {
    let alpha = if enabled { 1.0 } else { DISABLED_ALPHA };
    match icon {
        // Both raster and SVG icon bytes converge on the same decoded-icon blit
        // path (`decode_icon` tries PNG then falls back to the SVG rasterizer; see
        // `crate::render::decode_icon_bytes`).
        Icon::Png(bytes) | Icon::Svg(bytes) => {
            if let Some(decoded) = drawer.decode_icon(bytes) {
                let (rgba, w, h) = &*decoded;
                drawer.draw_image_alpha(rgba, *w, *h, rect, alpha);
            }
        }
        Icon::Checkmark => draw_glyph_centered(
            drawer,
            cache,
            "\u{2713}",
            base_font,
            Weight::Bold,
            dim_color(glyph_color, enabled),
            rect,
        ),
        // No bundled per-name glyph yet (SF Symbols are macOS-only), but it must
        // NOT be a silent no-op — draw a neutral placeholder until a real symbol
        // face is wired up.
        Icon::Symbol(_) => draw_glyph_centered(
            drawer,
            cache,
            "\u{25AA}", // ▪ small filled square placeholder
            base_font,
            Weight::Regular,
            dim_color(glyph_color, enabled),
            rect,
        ),
    }
}

/// Fill a row's explicit background (issue B): a row whose model carries a
/// [`Row::background`] gets that color painted across its full band before its
/// content (and before any hover highlight). A row with no background is a no-op.
fn fill_row_background<D: SceneDrawer>(
    drawer: &mut D,
    theme: &Theme,
    row: &Row,
    rect: LogicalRect,
) {
    if let Some(bg) = row.background {
        drawer.fill_round_rect(rect, 0.0, theme.resolve(bg));
    }
}

#[allow(clippy::too_many_arguments)]
fn draw_glyph_centered<D: SceneDrawer>(
    drawer: &mut D,
    cache: &mut MeasureCache,
    glyph: &str,
    base_font: &Font,
    weight: Weight,
    color: Rgba,
    rect: LogicalRect,
) {
    let font = base_font.clone().with_weight(weight);
    let w = measure_cached(drawer, cache, glyph, &font);
    let lh = drawer.line_height(&font);
    let origin = LogicalPoint::new(
        rect.origin.x + (rect.size.width - w) / 2.0,
        rect.origin.y + (rect.size.height - lh) / 2.0,
    );
    drawer.draw_text(&TextRun {
        text: glyph,
        origin,
        font: &font,
        color,
        weight,
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::Insets;
    use crate::menu::{Align, Flex, StyleRun, TextContent};
    use crate::style::Color;
    use std::sync::Arc;

    fn demo_menu() -> Menu {
        Menu::new()
            .section_header(Row::label_only("Claude"))
            .row(
                Row::new("switch:claude:me")
                    .leading(Icon::Checkmark)
                    .checked(true)
                    .segments(vec![
                        Segment::new("me@example.com")
                            .flex(Flex::Grow)
                            .font(Font::system(13.0, Weight::Bold)),
                        Segment::new("47% / 89%")
                            .align(Align::Right)
                            .runs(vec![StyleRun::new(6, 3, Color::SystemRed)]),
                    ]),
            )
            .separator()
            .submenu(Row::new("settings").label("Settings"), Menu::new())
            .row(Row::new("quit").segments(vec![
                Segment::new("Quit").flex(Flex::Grow),
                Segment::new("usagio v1")
                    .align(Align::Right)
                    .color(Color::SecondaryLabel),
            ]))
    }

    #[test]
    fn repeated_render_reuses_shaped_runs_no_reshaping() {
        // A hover-highlight repaints unchanged text; after the first render, a
        // second identical render must re-shape nothing (all runs served from the
        // shaped cache) — the fix for the ~0.5s hover latency. Instruments the
        // real shape() miss counter rather than wall-clock (non-flaky).
        let mut d = crate::render::RasterDrawer::new(2.0);
        let menu = demo_menu();
        let _ = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        let after_first = d.shape_miss_count();
        assert!(after_first > 0, "the first render shapes its runs");
        // Re-render the same menu with a different highlight (a hover change).
        let _ = render_menu(
            &mut d,
            &menu,
            &Theme::dark(),
            &MenuOptions::default(),
            Some(0),
        );
        assert_eq!(
            d.shape_miss_count(),
            after_first,
            "a repaint of unchanged text must not re-shape any run"
        );
    }

    #[test]
    fn render_produces_nonempty_size_and_hits() {
        let mut d = crate::render::RasterDrawer::new(2.0);
        let laid = render_menu(
            &mut d,
            &demo_menu(),
            &Theme::dark(),
            &MenuOptions::default(),
            None,
        );
        assert!(laid.size.width > 100.0 && laid.size.height > 60.0);
        // Interactive rows: the account, the submenu, and quit (not header/sep).
        assert_eq!(laid.rows.iter().filter(|r| r.interactive).count(), 3);
        // Device pixmap matches logical size * scale, and is non-blank.
        let (dw, dh) = d.device_size();
        assert_eq!(dw, (laid.size.width * 2.0).round() as u32);
        assert_eq!(dh, (laid.size.height * 2.0).round() as u32);
        let any_opaque = d.framebuffer().pixels().chunks_exact(4).any(|p| p[3] > 0);
        assert!(
            any_opaque,
            "rendered pixmap should not be fully transparent"
        );
    }

    /// Regression for spec §7.3: a `StyleRun` carrying a **semantic** color must
    /// resolve against the *active* theme, not a hard-coded `Theme::light()`, so
    /// a themed run reads correctly in dark mode. `Color::Label` is white on dark
    /// and black on light; the old seam returned black in both.
    #[test]
    fn style_run_semantic_color_follows_active_theme() {
        // A two-char segment whose second char is a `Color::Label` style run.
        let seg = Segment::new("ab").runs(vec![StyleRun::new(1, 1, Color::Label)]);
        let base = Rgba::opaque(1, 2, 3);

        let dark = style_pieces(&seg, base, Weight::Regular, &Theme::dark(), false);
        let light = style_pieces(&seg, base, Weight::Regular, &Theme::light(), false);

        // The styled piece ("b") resolves Label against each theme.
        let dark_b = dark.iter().find(|(s, ..)| *s == "b").expect("styled piece");
        let light_b = light
            .iter()
            .find(|(s, ..)| *s == "b")
            .expect("styled piece");
        assert_eq!(dark_b.1, Theme::dark().resolve(Color::Label));
        assert_eq!(light_b.1, Theme::light().resolve(Color::Label));
        // And they actually differ (white vs black), proving the theme is live.
        assert_ne!(dark_b.1, light_b.1);
    }

    /// On a highlighted (accent-filled) row every glyph inverts to the base
    /// color; a `StyleRun`'s semantic color must be suppressed so it doesn't
    /// render, e.g., saturated red on accent blue — but weight overrides stay.
    #[test]
    fn style_run_color_is_suppressed_when_highlighted_but_weight_is_kept() {
        let seg = Segment::new("ab").runs(vec![
            StyleRun::new(1, 1, Color::SystemRed).weight(Weight::Bold)
        ]);
        let white = Rgba::WHITE;

        let hot = style_pieces(&seg, white, Weight::Regular, &Theme::light(), true);
        for (_s, c, _w) in &hot {
            assert_eq!(
                *c, white,
                "highlighted row keeps every piece at the base color"
            );
        }
        let hot_b = hot.iter().find(|(s, ..)| *s == "b").expect("styled piece");
        assert_eq!(hot_b.2, Weight::Bold, "weight override survives highlight");

        // Un-highlighted, the semantic color resolves as before.
        let cold = style_pieces(&seg, white, Weight::Regular, &Theme::light(), false);
        let cold_b = cold.iter().find(|(s, ..)| *s == "b").expect("styled piece");
        assert_eq!(cold_b.1, Theme::light().resolve(Color::SystemRed));
    }

    /// A segment carrying a bolder `StyleRun` must be measured at the run's
    /// weight, not the base weight, so its box matches what `draw_row_content`
    /// actually advances (else a right-aligned run overflows). The measured
    /// width equals the sum of the per-piece advances the draw path uses.
    #[test]
    fn measure_segment_accounts_for_per_run_weight() {
        let d = crate::render::RasterDrawer::new_headless(1.0);
        let mut cache = MeasureCache::new();
        let font = Font::default();
        let theme = Theme::light();

        let seg =
            Segment::new("Quit").runs(vec![StyleRun::new(0, 4, Color::Label).weight(Weight::Bold)]);
        let measured = measure_segment(&d, &mut cache, &seg, &font, &theme, Rgba::WHITE, false);

        // Same computation the draw loop performs, piece by piece.
        let drawn: f32 = style_pieces(&seg, Rgba::WHITE, font.weight, &theme, false)
            .iter()
            .map(|(t, _c, w)| measure_cached(&d, &mut cache, t, &font.clone().with_weight(*w)))
            .sum();
        assert_eq!(measured, drawn);

        // And it is never narrower than the naive base-weight measure the old
        // code used (bold advances are >= regular for the vendored face).
        let naive = measure_cached(&d, &mut cache, &seg.text, &font);
        assert!(measured >= naive);
    }

    #[test]
    fn hit_testing_maps_points_to_rows() {
        let mut d = crate::render::RasterDrawer::new(1.0);
        let laid = render_menu(
            &mut d,
            &demo_menu(),
            &Theme::light(),
            &MenuOptions::default(),
            None,
        );
        let account = &laid.rows[0];
        let center = LogicalPoint::new(
            account.rect.origin.x + account.rect.size.width / 2.0,
            account.rect.origin.y + account.rect.size.height / 2.0,
        );
        assert_eq!(laid.hit(center), Some(account.index));
        assert_eq!(laid.id_at(center).unwrap().as_str(), "switch:claude:me");
    }

    /// `measure_cached`'s doc promise ("output is identical to calling
    /// `drawer.measure_text` directly every time") is what makes the
    /// per-frame memo safe: prove both the cold path (first call, a miss)
    /// and the warm path (second call, a hit) return exactly what a direct,
    /// uncached `measure_text` call would — i.e. the memoization can't drift
    /// from the ground truth it's short-circuiting.
    #[test]
    fn measure_cached_matches_a_direct_measure_text_call() {
        let d = crate::render::RasterDrawer::new_headless(1.0);
        let font = Font::system(13.0, Weight::Regular);
        let text = "Settings";

        let direct = d.measure_text(text, &font);

        let mut cache: MeasureCache = HashMap::new();
        let cold = measure_cached(&d, &mut cache, text, &font);
        assert_eq!(
            cold, direct,
            "first (cache-miss) call must match measure_text"
        );
        assert_eq!(cache.len(), 1);

        let warm = measure_cached(&d, &mut cache, text, &font);
        assert_eq!(
            warm, direct,
            "second (cache-hit) call must still match measure_text"
        );
        assert_eq!(
            cache.len(),
            1,
            "a repeat (text, font) must not grow the cache"
        );
    }

    /// Distinct `(text, font)` keys must not collide in the cache — a
    /// different font size for the same text is a different measurement and
    /// must get its own entry and its own (independently correct) value.
    #[test]
    fn measure_cached_distinguishes_different_fonts_for_the_same_text() {
        let d = crate::render::RasterDrawer::new_headless(1.0);
        let text = "Settings";
        let small = Font::system(11.0, Weight::Regular);
        let large = Font::system(22.0, Weight::Regular);

        let mut cache: MeasureCache = HashMap::new();
        let w_small = measure_cached(&d, &mut cache, text, &small);
        let w_large = measure_cached(&d, &mut cache, text, &large);

        assert_eq!(w_small, d.measure_text(text, &small));
        assert_eq!(w_large, d.measure_text(text, &large));
        assert!(w_large > w_small, "a larger font must measure wider");
        assert_eq!(cache.len(), 2);
    }

    /// A drawer that records the geometry of every draw op, with deterministic
    /// monospace metrics (7px/char, 14px line height) so layout is exactly
    /// reproducible in a test. Icons decode to an **opaque** 2x2 stub so a
    /// dimmed-alpha blit is observable.
    ///
    /// The extra `fill_radii`/`separators`/`text_fonts` channels (for the
    /// theme-completeness guard) capture inputs the earlier channels drop —
    /// corner radius, separator color, resolved `Font` — so the full op record
    /// differs whenever *any* `Theme` field reaches the paint layer.
    #[derive(Default, PartialEq)]
    struct RecordingDrawer {
        texts: Vec<(String, f32, f32)>,        // (text, origin.x, origin.y)
        images: Vec<LogicalRect>,              // dest rects of draw_image[_alpha]
        fills: Vec<(LogicalRect, Rgba)>,       // (rect, color) of fill_round_rect
        text_colors: Vec<(String, Rgba)>,      // (text, resolved color) of draw_text
        image_alphas: Vec<(LogicalRect, f32)>, // (dest, alpha) of draw_image_alpha
        fill_radii: Vec<f32>,                  // corner radius per fill_round_rect
        separators: Vec<(LogicalRect, Rgba)>,  // (rect, color) of draw_separator
        text_fonts: Vec<Font>,                 // the Font each draw_text ran in
    }
    impl SceneDrawer for RecordingDrawer {
        fn begin_frame(&mut self, _size: LogicalSize) {}
        fn fill_round_rect(&mut self, r: LogicalRect, cr: f32, c: Rgba) {
            self.fills.push((r, c));
            self.fill_radii.push(cr);
        }
        fn draw_separator(&mut self, r: LogicalRect, c: Rgba) {
            self.separators.push((r, c));
        }
        fn measure_text(&self, text: &str, _font: &Font) -> f32 {
            text.chars().count() as f32 * 7.0
        }
        fn line_height(&self, _font: &Font) -> f32 {
            14.0
        }
        fn draw_text(&mut self, run: &TextRun<'_>) {
            self.texts
                .push((run.text.to_string(), run.origin.x, run.origin.y));
            self.text_colors.push((run.text.to_string(), run.color));
            self.text_fonts.push(run.font.clone());
        }
        fn draw_image(&mut self, rgba: &[u8], w: u32, h: u32, dest: LogicalRect) {
            self.draw_image_alpha(rgba, w, h, dest, 1.0);
        }
        fn draw_image_alpha(
            &mut self,
            _rgba: &[u8],
            _w: u32,
            _h: u32,
            dest: LogicalRect,
            alpha: f32,
        ) {
            self.images.push(dest);
            self.image_alphas.push((dest, alpha));
        }
        fn decode_icon(&self, _bytes: &Arc<[u8]>) -> Option<crate::render::DecodedIcon> {
            // Opaque stub (alpha 255) so a dimmed blit differs from a transparent one.
            Some(std::rc::Rc::new((vec![255u8; 16], 2, 2)))
        }
    }

    /// Right edge (`origin.x + measured width`) of the draw_text op whose text
    /// matches `needle`, using the same 7px/char metric the drawer reports.
    fn text_right_edge(d: &RecordingDrawer, needle: &str) -> f32 {
        let (t, x, _) = d
            .texts
            .iter()
            .find(|(t, ..)| t == needle)
            .unwrap_or_else(|| panic!("no draw_text for {needle:?}; got {:?}", d.texts));
        x + t.chars().count() as f32 * 7.0
    }

    /// #F19: the `min_width > max_width` guard (the `.max(min_w)` on `max_w`) is
    /// correct but was only exercised through the builder path, which itself
    /// normalizes the two. A consumer can also set the **public struct fields**
    /// directly with `min > max`; `f32::clamp` panics when `min > max`, so render
    /// must not panic and must produce a sane, finite width (the floor wins).
    #[test]
    fn struct_literal_min_greater_than_max_does_not_panic() {
        let menu = Menu::new().row(Row::new("q").label("Quit"));
        let opts = MenuOptions {
            min_width: Some(100.0),
            max_width: Some(50.0),
            ..Default::default()
        };
        let mut d = RecordingDrawer::default();
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &opts, None);
        assert!(
            laid.size.width.is_finite(),
            "width must be finite, not NaN, with min > max"
        );
        // The floor wins (max is clamped up to min), so the width settles at 100.
        assert_eq!(
            laid.size.width, 100.0,
            "min>max must normalize to the floor (100), not panic or go degenerate"
        );
    }

    /// Regression for #16: no global leading gutter. A menu mixing an icon row
    /// with plain text rows must start every row's content at the SAME left x —
    /// the icon sits at that x (inline) and plain rows are NOT indented past it.
    #[test]
    fn issue16_no_global_leading_gutter_shared_left_x() {
        use std::sync::Arc;
        let logo: Arc<[u8]> = Arc::from(vec![0u8; 8]);
        let menu = Menu::new()
            .row(
                Row::new("hdr")
                    .leading(Icon::Png(logo.clone()))
                    .label("Claude")
                    .enabled(false),
            )
            .row(Row::new("acct").label("matthew@example.com"))
            .row(Row::new("quit").label("Quit"));

        let mut d = RecordingDrawer::default();
        let _ = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);

        // The icon is drawn at the shared left x.
        assert_eq!(d.images.len(), 1, "one inline icon");
        let icon_x = d.images[0].origin.x;

        // Plain rows' text starts at the same left x as the icon — NOT indented
        // past a reserved gutter.
        let acct_x = d
            .texts
            .iter()
            .find(|(t, ..)| t == "matthew@example.com")
            .map(|(_, x, _)| *x)
            .expect("account row text");
        let quit_x = d
            .texts
            .iter()
            .find(|(t, ..)| t == "Quit")
            .map(|(_, x, _)| *x)
            .expect("quit row text");

        assert!(
            (acct_x - icon_x).abs() < 0.5,
            "plain row must start at the icon's left x, not indented: icon={icon_x} acct={acct_x}"
        );
        assert!(
            (quit_x - icon_x).abs() < 0.5,
            "every plain row shares the same left x: icon={icon_x} quit={quit_x}"
        );

        // The icon row's OWN label is offset past its icon (inline content).
        let hdr_x = d
            .texts
            .iter()
            .find(|(t, ..)| t == "Claude")
            .map(|(_, x, _)| *x)
            .expect("header text");
        assert!(
            hdr_x > icon_x + 8.0,
            "the icon row's text follows its icon inline: icon={icon_x} hdr={hdr_x}"
        );
    }

    /// OEM alignment: when a menu has a checked row, it reserves a shared gutter
    /// so the checked row's text aligns with the *unchecked* rows' text (native
    /// `NSMenu` look), instead of the checkmark pushing only its own row right.
    #[test]
    fn checkable_menu_reserves_gutter_so_rows_align() {
        let menu = Menu::new()
            .row(Row::new("a").checked(true).segments(vec![
                Segment::new("me@example.com").flex(Flex::Grow),
                Segment::new("47%").align(Align::Right),
            ]))
            .row(Row::new("b").segments(vec![
                Segment::new("you@example.com").flex(Flex::Grow),
                Segment::new("20%").align(Align::Right),
            ]));

        let mut d = RecordingDrawer::default();
        let _ = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);

        let x = |needle: &str| {
            d.texts
                .iter()
                .find(|(t, ..)| t == needle)
                .map(|(_, x, _)| *x)
                .unwrap_or_else(|| panic!("no text {needle:?}"))
        };
        // Checked row's email aligns with the unchecked row's email (shared
        // gutter), not indented by the checkmark.
        assert!(
            (x("me@example.com") - x("you@example.com")).abs() < 0.5,
            "checked and unchecked rows must share a text left x: {} vs {}",
            x("me@example.com"),
            x("you@example.com")
        );
        // And that text starts past the gutter (a checkmark glyph was drawn at
        // the left).
        assert!(x("you@example.com") > 6.0);
    }

    /// Regression: a menu whose checkable rows are ALL currently *unchecked*
    /// (`checked(false)`) must still reserve the shared gutter — `Row::checked`'s
    /// contract is "`Some(true/false)` shows a check column". Testing only
    /// `Some(true)` (the pre-fix bug) reserved nothing here, so the rows' text
    /// sat flush-left and every row jumped right the instant one was toggled on.
    #[test]
    fn all_unchecked_checkable_menu_still_reserves_gutter() {
        let text_x = |checked: bool| {
            let menu = Menu::new()
                .row(Row::new("a").checked(checked).label("Alpha"))
                .row(Row::new("b").checked(checked).label("Beta"));
            let mut d = RecordingDrawer::default();
            let _ = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
            d.texts
                .iter()
                .find(|(t, ..)| t == "Alpha")
                .map(|(_, x, _)| *x)
                .expect("Alpha text")
        };
        // The gutter is reserved regardless of the current on/off state, so text
        // starts at the same x whether the checkable rows are on or off — no jump
        // on toggle. (With the bug, the all-unchecked menu reserved nothing and
        // its text x was smaller.)
        let off = text_x(false);
        let on = text_x(true);
        assert!(
            (off - on).abs() < 0.5,
            "checkable rows must reserve the gutter whether checked or not: off={off} on={on}"
        );
        assert!(
            off > 6.0,
            "an all-unchecked checkable menu must still reserve the check column, text x={off}"
        );
    }

    /// Regression for #15: a menu mixing icon-bearing section headers with
    /// `label\tvalue` rows must (1) draw every leading icon at the same left
    /// gutter x (never trailing), and (2) right-align each `\t` value to one
    /// shared column, for both `Row` and `Submenu` items.
    #[test]
    fn issue15_leading_icons_and_tab_values_align_to_shared_columns() {
        let logo: Arc<[u8]> = Arc::from(vec![0u8; 8]);
        let menu = Menu::new()
            .row(
                Row::new("hdr:claude")
                    .leading(Icon::Png(logo.clone()))
                    .label("Claude")
                    .enabled(false),
            )
            .submenu(
                Row::new("acct:short").segments(vec![
                    Segment::new("a@x.com").flex(Flex::Grow),
                    Segment::new("20% / 38%").align(Align::Right),
                ]),
                Menu::new().row(Row::new("d").label("detail")),
            )
            .submenu(
                Row::new("acct:longemail").segments(vec![
                    Segment::new("demo1@example.com").flex(Flex::Grow),
                    Segment::new("47% / 52%").align(Align::Right),
                ]),
                Menu::new().row(Row::new("d2").label("detail")),
            );

        let mut d = RecordingDrawer::default();
        let _ = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);

        // (1) The header's leading icon is drawn in the left gutter, near x≈0,
        //     never at the right edge of the row.
        assert_eq!(d.images.len(), 1, "one leading icon drawn");
        let icon_x = d.images[0].origin.x;
        assert!(
            icon_x < 12.0,
            "leading icon must sit in the left gutter, got x={icon_x}"
        );

        // (2) Both `\t` values right-align to the same column: their right edges
        //     match despite different value/label widths.
        let r_short = text_right_edge(&d, "20% / 38%");
        let r_long = text_right_edge(&d, "47% / 52%");
        assert!(
            (r_short - r_long).abs() < 0.5,
            "tab-stop values must share a right column: short={r_short} long={r_long}"
        );
    }

    // -------------------------------------------------------------------------
    // Trailing gutter policy (#60) — symmetric to the leading gutter above.
    // -------------------------------------------------------------------------

    /// A menu carrying a submenu row plus a plain row with right-aligned content.
    /// The plain row's `pct` value right-aligns to the shared band right edge.
    fn trailing_probe_menu() -> Menu {
        Menu::new()
            .row(Row::new("plain").segments(vec![
                Segment::new("Battery").flex(Flex::Grow),
                Segment::new("47%").align(Align::Right),
            ]))
            .submenu(
                Row::new("more").label("More"),
                Menu::new().row(Row::new("d").label("detail")),
            )
    }

    /// The chevron glyph (`›`) drawn for a submenu row.
    const CHEVRON: &str = "\u{203A}";

    /// Auto (default) + a menu that has a submenu row → the trailing column is
    /// reserved menu-wide, so even the *non-submenu* row's right content stops
    /// short of the inner right edge by exactly one `TRAILING_COLUMN` (native
    /// `NSMenu` alignment). The chevron is drawn.
    #[test]
    fn trailing_auto_with_submenu_reserves_column() {
        let menu = trailing_probe_menu();
        let mut d = RecordingDrawer::default();
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);

        let inner_right = laid.size.width - Theme::dark().padding.right;
        let pct_right = text_right_edge(&d, "47%");
        assert!(
            (inner_right - pct_right - TRAILING_COLUMN).abs() < 0.5,
            "Auto + submenu must inset right content by the trailing column: \
             inner_right={inner_right} pct_right={pct_right} col={TRAILING_COLUMN}"
        );
        assert!(
            d.texts.iter().any(|(t, ..)| t == CHEVRON),
            "the submenu chevron must still be drawn"
        );
    }

    /// Auto (default) + a menu with NO submenu row (and no trailing accessory) →
    /// nothing is reserved, so the right-aligned content reaches the inner right
    /// edge.
    #[test]
    fn trailing_auto_without_submenu_reaches_edge() {
        let menu = Menu::new().row(Row::new("plain").segments(vec![
            Segment::new("Battery").flex(Flex::Grow),
            Segment::new("47%").align(Align::Right),
        ]));
        let mut d = RecordingDrawer::default();
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);

        let inner_right = laid.size.width - Theme::dark().padding.right;
        let pct_right = text_right_edge(&d, "47%");
        assert!(
            (inner_right - pct_right).abs() < 0.5,
            "Auto without a submenu must let right content reach the edge: \
             inner_right={inner_right} pct_right={pct_right}"
        );
    }

    /// Never → right content reaches the inner right edge even when a submenu is
    /// present; the chevron is still drawn (it overlays the content-area tail).
    #[test]
    fn trailing_never_reaches_edge_with_submenu() {
        let menu = trailing_probe_menu();
        let mut d = RecordingDrawer::default();
        let opts = MenuOptions::default().trailing_gutter(TrailingGutterPolicy::Never);
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &opts, None);

        let inner_right = laid.size.width - Theme::dark().padding.right;
        let pct_right = text_right_edge(&d, "47%");
        assert!(
            (inner_right - pct_right).abs() < 0.5,
            "Never must let right content reach the edge despite a submenu: \
             inner_right={inner_right} pct_right={pct_right}"
        );
        assert!(
            d.texts.iter().any(|(t, ..)| t == CHEVRON),
            "the submenu chevron must still be drawn under Never"
        );
    }

    /// Always → the trailing column is reserved even when the menu has no submenu
    /// and no trailing accessory, so right content is inset by one column.
    #[test]
    fn trailing_always_reserves_without_submenu() {
        let menu = Menu::new().row(Row::new("plain").segments(vec![
            Segment::new("Battery").flex(Flex::Grow),
            Segment::new("47%").align(Align::Right),
        ]));
        let mut d = RecordingDrawer::default();
        let opts = MenuOptions::default().trailing_gutter(TrailingGutterPolicy::Always);
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &opts, None);

        let inner_right = laid.size.width - Theme::dark().padding.right;
        let pct_right = text_right_edge(&d, "47%");
        assert!(
            (inner_right - pct_right - TRAILING_COLUMN).abs() < 0.5,
            "Always must reserve the trailing column even with no submenu: \
             inner_right={inner_right} pct_right={pct_right} col={TRAILING_COLUMN}"
        );
    }

    // -------------------------------------------------------------------------
    // Content stacks (issue #44)
    // -------------------------------------------------------------------------

    /// A vertical stack of 3 texts measures to: width = the widest text (the
    /// cross axis, maxed), height = the summed line heights plus inter-child
    /// spacing (the main axis) — using `RecordingDrawer`'s deterministic
    /// 7px/char, 14px-line-height metrics.
    #[test]
    fn measure_vertical_stack_of_three_texts() {
        let d = RecordingDrawer::default();
        let mut cache = MeasureCache::new();
        let theme = Theme::light();
        let stack = Stack::vertical(2.0)
            .child(Content::Text(TextContent::new("a"))) // 1 char -> 7px wide
            .child(Content::Text(TextContent::new("bb"))) // 2 chars -> 14px wide
            .child(Content::Text(TextContent::new("ccc"))); // 3 chars -> 21px wide

        let size = measure_stack(&d, &mut cache, &theme, &stack);

        // Cross axis (width) = widest child = "ccc" at 21px.
        assert_eq!(size.width, 21.0);
        // Main axis (height) = 3 * 14 (line height) + 2 * 2.0 (spacing between
        // the 3 children).
        assert_eq!(size.height, 3.0 * 14.0 + 2.0 * 2.0);
    }

    /// A horizontal strip measures to: width = summed child widths + spacing
    /// (main axis), height = the tallest child (cross axis).
    #[test]
    fn measure_horizontal_strip() {
        let d = RecordingDrawer::default();
        let mut cache = MeasureCache::new();
        let theme = Theme::light();
        let stack = Stack::horizontal(5.0)
            .child(Content::Text(TextContent::new("ab"))) // 14px wide, 14px tall
            .child(Content::Image {
                icon: Icon::Checkmark,
                size: 20.0,
            }) // 20x20
            .child(Content::Text(TextContent::new("c"))); // 7px wide, 14px tall

        let size = measure_stack(&d, &mut cache, &theme, &stack);

        // Main axis (width) = 14 + 20 + 7 + 2 * 5.0 (spacing between 3 children).
        assert_eq!(size.width, 14.0 + 20.0 + 7.0 + 2.0 * 5.0);
        // Cross axis (height) = tallest child = the 20px image.
        assert_eq!(size.height, 20.0);
    }

    /// A `Spacer` has zero intrinsic size and absorbs the leftover main-axis
    /// space at paint time, splitting it equally among sibling spacers — the
    /// same "grow" promise `Flex::Grow` makes for `Segment`s, generalized to
    /// the `Content` tree.
    #[test]
    fn spacer_distributes_leftover_space_equally() {
        let mut d = RecordingDrawer::default();
        let mut cache = MeasureCache::new();
        let theme = Theme::light();
        // "a" (7px) + spacer + "bb" (14px) + spacer, in a 100px-wide row: the
        // two spacers must split (100 - 7 - 14) = 79px evenly (39.5px each).
        let stack = Stack::horizontal(0.0)
            .child(Content::Text(TextContent::new("a")))
            .child(Content::Spacer)
            .child(Content::Text(TextContent::new("bb")))
            .child(Content::Spacer);

        let rect = LogicalRect::new(LogicalPoint::new(0.0, 0.0), LogicalSize::new(100.0, 14.0));
        paint_stack(&mut d, &mut cache, &theme, &stack, rect, Rgba::BLACK);

        let a_x = d
            .texts
            .iter()
            .find(|(t, ..)| t == "a")
            .map(|(_, x, _)| *x)
            .expect("'a' drawn");
        let bb_x = d
            .texts
            .iter()
            .find(|(t, ..)| t == "bb")
            .map(|(_, x, _)| *x)
            .expect("'bb' drawn");

        assert_eq!(a_x, 0.0, "'a' sits flush at the stack's leading edge");
        // "bb" starts after "a" (7px) plus one spacer's share (39.5px).
        assert_eq!(bb_x, 7.0 + 39.5);
        // The trailing spacer pushes the stack's total content to fill the
        // full 100px width: "bb" ends at 100 - 39.5 (its own trailing spacer).
        assert_eq!(bb_x + 2.0 * 7.0, 100.0 - 39.5);
    }

    /// A nested stack's size is the recursive sum: a horizontal strip of
    /// vertical "cells" (time/icon/temp, the Apple-Weather-extra use case)
    /// measures as wide as its cells summed, and as tall as its tallest cell.
    #[test]
    fn nested_stack_size_recurses() {
        let d = RecordingDrawer::default();
        let mut cache = MeasureCache::new();
        let theme = Theme::light();

        let cell = |time: &str, temp: &str| {
            Content::Stack(
                Stack::vertical(1.0)
                    .child(Content::Text(TextContent::new(time)))
                    .child(Content::Image {
                        icon: Icon::Checkmark,
                        size: 16.0,
                    })
                    .child(Content::Text(TextContent::new(temp))),
            )
        };
        // Each cell: width = max(time, 16, temp) widths; height = time_h + 16 +
        // temp_h + 2 * 1.0 spacing = 14 + 16 + 14 + 2 = 46.
        let strip = Stack::horizontal(3.0)
            .child(cell("1PM", "72°"))
            .child(cell("2PM", "70°"));

        let size = measure_stack(&d, &mut cache, &theme, &strip);

        let cell_height = 14.0 + 16.0 + 14.0 + 2.0 * 1.0;
        assert_eq!(size.height, cell_height, "strip height = tallest cell");
        // Each cell's width = widest of its 3 children; "1PM"/"2PM" are 3
        // chars (21px), wider than the 16px icon, so each cell is 21px wide.
        // Strip width = 2 cells + 1 gap of 3.0.
        assert_eq!(size.width, 21.0 * 2.0 + 3.0);
    }

    /// `Item::Content` integrates into `render_menu`: the row's height is
    /// derived from the stack's measured content (plus padding), it paints
    /// through the ordinary `SceneDrawer` text/image path, and it never
    /// appears in `LaidMenu::rows` (non-interactive, like `SectionHeader`).
    #[test]
    fn item_content_sizes_and_paints_through_render_menu() {
        let logo: std::sync::Arc<[u8]> = std::sync::Arc::from(vec![0u8; 8]);
        let mut d = RecordingDrawer::default();
        let menu = Menu::new().content(
            Stack::vertical(2.0)
                .child(Content::Text(TextContent::new("Weather")))
                .child(Content::Image {
                    icon: Icon::Png(logo),
                    size: 16.0,
                }),
        );
        let laid = render_menu(
            &mut d,
            &menu,
            &Theme::light(),
            &MenuOptions::default(),
            None,
        );

        // Non-interactive: no clickable row recorded for a content item.
        assert!(laid.rows.is_empty());
        // The text was actually painted.
        assert!(d.texts.iter().any(|(t, ..)| t == "Weather"));
        assert_eq!(d.images.len(), 1, "the icon image was blitted");
        // The row is tall enough to fit "Weather" (14px) + gap (2px) + the
        // 16px icon, plus the row's own vertical padding.
        let min_expected = 14.0 + 2.0 + 16.0;
        assert!(laid.size.height > min_expected);
    }

    // -------------------------------------------------------------------------
    // Structural paint-layer fixes
    // -------------------------------------------------------------------------

    /// HIGH: a non-finite `min_width` must be sanitized before the width `clamp`
    /// (a `NaN` bound produces `NaN` geometry / panics `f32::clamp`) so the popup
    /// size is always finite.
    #[test]
    fn nan_min_width_is_clamped() {
        let menu = Menu::new().row(Row::new("a").label("Alpha"));
        let opts = MenuOptions::default().min_width(f32::NAN);
        let mut d = RecordingDrawer::default();
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &opts, None);
        assert!(
            laid.size.width.is_finite() && laid.size.height.is_finite(),
            "geometry must be finite despite a NaN min_width: {:?}",
            laid.size
        );
        assert!(laid.size.width > 0.0);
    }

    /// HIGH: an `Icon::Svg` in the LEADING slot must render (via the funnel),
    /// not be swallowed by a wildcard that only handled `Png`/`Checkmark`.
    #[test]
    fn svg_leading_icon_is_rendered() {
        let svg: Arc<[u8]> = Arc::from(vec![1u8, 2, 3]);
        let menu = Menu::new().row(Row::new("a").leading(Icon::Svg(svg)).label("Alpha"));
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        assert_eq!(
            d.images.len(),
            1,
            "an Svg leading icon must blit, not be dropped"
        );
    }

    /// MEDIUM: a section header must NOT paint a `checked` checkmark (its
    /// `checked` is ignored per `Menu::section_header`), but a submenu-parent row
    /// DOES honor `checked`.
    #[test]
    fn header_ignores_checked_but_submenu_parent_honors_it() {
        let menu = Menu::new()
            .section_header(Row::label_only("Header").checked(true))
            .submenu(Row::new("more").label("More").checked(true), Menu::new());
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        let checks = d.texts.iter().filter(|(t, ..)| t == "\u{2713}").count();
        assert_eq!(
            checks, 1,
            "only the submenu-parent row paints a checkmark, not the header; texts={:?}",
            d.texts
        );
    }

    /// Issue A: a row with a trailing icon/accessory must draw it in the reserved
    /// trailing column (right of the segment band), not silently omit it.
    #[test]
    fn issue_a_trailing_icon_is_drawn() {
        let icon: Arc<[u8]> = Arc::from(vec![9u8; 4]);
        let menu = Menu::new().row(Row::new("a").label("Alpha").trailing(Icon::Png(icon)));
        let mut d = RecordingDrawer::default();
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        assert_eq!(d.images.len(), 1, "the trailing icon must be blitted");
        let icon_x = d.images[0].origin.x;
        let label_x = d
            .texts
            .iter()
            .find(|(t, ..)| t == "Alpha")
            .map(|(_, x, _)| *x)
            .expect("label text");
        assert!(
            icon_x > label_x,
            "trailing icon must sit right of the label: icon={icon_x} label={label_x}"
        );
        assert!(
            icon_x + ICON_SIZE <= laid.size.width + 0.5,
            "trailing icon must stay within the popup width"
        );
    }

    /// Issue B: a row whose model requests an explicit background gets it filled.
    #[test]
    fn issue_b_row_background_is_filled() {
        let menu = Menu::new().row(Row::new("a").label("Alpha").background(Color::SystemRed));
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        let want = Theme::dark().resolve(Color::SystemRed);
        assert!(
            d.fills.iter().any(|(_, c)| *c == want),
            "a row with Row::background must be filled with it; fills={:?}",
            d.fills
        );
    }

    /// Issue D: overlapping style runs composite with the LATER RUN WINS — an
    /// early `break` used to stop at the first matching run, dropping later ones.
    #[test]
    fn issue_d_overlapping_style_runs_the_later_run_wins() {
        let seg = Segment::new("ab").runs(vec![
            StyleRun::new(0, 2, Color::SystemRed),   // covers a, b
            StyleRun::new(1, 1, Color::SystemGreen), // overlaps on b — later, wins
        ]);
        let theme = Theme::light();
        let pieces = style_pieces(&seg, Rgba::BLACK, Weight::Regular, &theme, false);
        let a = pieces.iter().find(|(s, ..)| *s == "a").expect("piece a");
        let b = pieces.iter().find(|(s, ..)| *s == "b").expect("piece b");
        assert_eq!(
            a.1,
            theme.resolve(Color::SystemRed),
            "'a' is covered only by the red run"
        );
        assert_eq!(
            b.1,
            theme.resolve(Color::SystemGreen),
            "'b' is covered by both runs; the later (green) run must win"
        );
    }

    /// Issue E: a disabled row dims its checkmark AND its icon (not just text),
    /// applying `DISABLED_ALPHA` to both the glyph color and the image blit.
    #[test]
    fn issue_e_disabled_row_dims_checkmark_and_icon() {
        let icon: Arc<[u8]> = Arc::from(vec![7u8; 4]);
        let menu = Menu::new()
            .row(
                Row::new("i")
                    .label("IconRow")
                    .leading(Icon::Png(icon))
                    .enabled(false),
            )
            .row(Row::new("c").label("CheckRow").checked(true).enabled(false));
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        assert!(
            d.image_alphas
                .iter()
                .any(|(_, a)| (*a - DISABLED_ALPHA).abs() < 1e-6),
            "a disabled row's icon must blit at DISABLED_ALPHA; got {:?}",
            d.image_alphas
        );
        let check = d
            .text_colors
            .iter()
            .find(|(t, _)| t == "\u{2713}")
            .expect("a checkmark glyph was drawn");
        assert!(
            check.1.a < 255,
            "a disabled row's checkmark must be dimmed, got alpha {}",
            check.1.a
        );
    }

    /// The funnel draws SOMETHING for every `Icon` variant — a table-driven guard
    /// against a future variant becoming a silent no-op (the muri bug class).
    #[test]
    fn draw_icon_funnel_draws_every_icon_variant() {
        let png: Arc<[u8]> = Arc::from(vec![1u8; 4]);
        let svg: Arc<[u8]> = Arc::from(vec![2u8; 4]);
        let cases: Vec<(&str, Icon)> = vec![
            ("Png", Icon::Png(png)),
            ("Svg", Icon::Svg(svg)),
            ("Checkmark", Icon::Checkmark),
            ("Symbol", Icon::Symbol("gear")),
        ];
        let font = Font::default();
        let rect = LogicalRect::new(
            LogicalPoint::new(0.0, 0.0),
            LogicalSize::new(ICON_SIZE, ICON_SIZE),
        );
        for (name, icon) in cases {
            let mut d = RecordingDrawer::default();
            let mut cache = MeasureCache::new();
            draw_icon(&mut d, &mut cache, &font, &icon, rect, Rgba::WHITE, true);
            let ops = d.images.len() + d.texts.len();
            assert!(ops > 0, "Icon::{name} must emit at least one draw op");
        }
    }

    /// The hover highlight fill reads `theme.row_highlight`, not `theme.accent`:
    /// a theme whose two fields differ proves the correct one is used.
    #[test]
    fn row_highlight_uses_the_theme_field() {
        let mut theme = Theme::dark();
        theme.accent = Color::Rgba(1, 2, 3, 255);
        theme.row_highlight = Color::Rgba(9, 8, 7, 255);
        let menu = Menu::new().row(Row::new("a").label("Alpha"));
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &theme, &MenuOptions::default(), Some(0));
        let want = theme.resolve(theme.row_highlight);
        let accent = theme.resolve(theme.accent);
        assert!(
            d.fills.iter().any(|(_, c)| *c == want),
            "hover fill must use row_highlight; fills={:?}",
            d.fills
        );
        assert!(
            !d.fills.iter().any(|(_, c)| *c == accent),
            "hover fill must NOT use accent"
        );
    }

    // -------------------------------------------------------------------------
    // Deliverable 1: "no dead visual field" theme completeness.
    //
    // Generalizes `row_highlight_uses_the_theme_field` into a table over EVERY
    // visually-meaningful `Theme` field: render one rich menu twice — once on a
    // base theme, once with a single field bumped to a clearly-different value —
    // and assert the *full* recorded op stream differs. A field that leaves the
    // op stream untouched is either dead (a paint-layer bug of the "attribute set
    // but silently not rendered" class) or legitimately conditional (documented).
    // -------------------------------------------------------------------------

    /// A menu that exercises every field-consuming code path at once: a section
    /// header (`header_font` + `secondary_label`), a checked row (an accent
    /// checkmark in a reserved gutter — `accent` + `column_gap`), a plain enabled
    /// row (`label`; the highlight target — `row_highlight`), a disabled row
    /// (`secondary_label`), a separator (`separator`), and a final plain row
    /// whose un-highlighted text reads `label`. The whole thing paints on the
    /// popup `background` at `corner_radius`, inset by `padding`, at `row_height`.
    fn field_probe_menu() -> Menu {
        Menu::new()
            .section_header(Row::label_only("Header"))
            .row(Row::new("checked").checked(true).label("Checked"))
            .row(Row::new("plain").label("Plain"))
            .row(Row::new("disabled").label("Disabled").enabled(false))
            .separator()
            .row(Row::new("last").label("Last"))
    }

    /// Record every draw op for `field_probe_menu` on `theme`, highlighting the
    /// plain enabled row (index 2) so `row_highlight` is exercised while the
    /// checked row's accent checkmark and the final row's `label` text stay
    /// un-inverted.
    fn probe_ops(theme: &Theme) -> RecordingDrawer {
        let mut d = RecordingDrawer::default();
        render_menu(
            &mut d,
            &field_probe_menu(),
            theme,
            &MenuOptions::default(),
            Some(2),
        );
        d
    }

    #[test]
    fn every_theme_field_reaches_the_paint_layer() {
        // (name, mutator) for each visually-meaningful `Theme` field. Each mutator
        // sets its field to a value clearly distinct from `Theme::light()`'s.
        type Mutator = fn(&mut Theme);
        let fields: &[(&str, Mutator)] = &[
            ("background", |t| t.background = Color::rgb(1, 2, 3)),
            ("label", |t| t.label = Color::rgb(1, 2, 3)),
            ("secondary_label", |t| {
                t.secondary_label = Color::rgb(4, 5, 6)
            }),
            ("accent", |t| t.accent = Color::rgb(7, 8, 9)),
            ("separator", |t| t.separator = Color::rgb(10, 11, 12)),
            ("row_highlight", |t| {
                t.row_highlight = Color::rgb(13, 14, 15)
            }),
            ("row_font", |t| {
                t.row_font = Font::system(30.0, Weight::Bold)
            }),
            ("header_font", |t| {
                t.header_font = Font::system(30.0, Weight::Bold)
            }),
            ("row_font.letter_spacing", |t| {
                t.row_font = t.row_font.clone().with_letter_spacing(5.0)
            }),
            ("row_height", |t| t.row_height += 40.0),
            ("corner_radius", |t| t.corner_radius += 20.0),
            ("padding", |t| t.padding = Insets::symmetric(40.0, 40.0)),
            ("column_gap", |t| t.column_gap += 30.0),
        ];

        let base = Theme::light();
        let base_ops = probe_ops(&base);

        for (name, mutate) in fields {
            let mut variant = base.clone();
            mutate(&mut variant);
            let variant_ops = probe_ops(&variant);
            assert!(
                base_ops != variant_ops,
                "Theme::{name} did not change any recorded draw op — the field is \
                 either dead (set but never rendered) or not exercised by \
                 field_probe_menu(); investigate before assuming it's inert",
            );
        }
    }

    /// Documents a genuine field/consumer nuance the completeness table would
    /// otherwise paper over: `corner_radius`'s doc says it rounds "the popup and
    /// highlight", but the paint layer only feeds it to the popup-background
    /// `fill_round_rect`; the hover highlight uses a fixed 5.0 radius. So
    /// `corner_radius` DOES reach paint (via the panel), but NOT via the
    /// highlight. This is intentional (a fixed selection radius), recorded here so
    /// the discrepancy is a known, asserted fact rather than a silent surprise.
    #[test]
    fn corner_radius_rounds_the_panel_not_the_highlight() {
        let mut theme = Theme::light();
        theme.corner_radius = 17.0;
        let mut d = RecordingDrawer::default();
        render_menu(
            &mut d,
            &Menu::new().row(Row::new("a").label("Alpha")),
            &theme,
            &MenuOptions::default(),
            Some(0),
        );
        // The panel background is the first fill and carries theme.corner_radius.
        assert_eq!(
            d.fill_radii.first().copied(),
            Some(17.0),
            "the popup background must be rounded at theme.corner_radius"
        );
        // No fill uses the theme radius for the highlight; the highlight's 5.0 is
        // present and distinct.
        assert!(
            d.fill_radii.iter().any(|r| (*r - 5.0).abs() < f32::EPSILON),
            "the hover highlight uses a fixed 5.0 radius, not corner_radius; \
             radii={:?}",
            d.fill_radii
        );
    }

    // -------------------------------------------------------------------------
    // Deliverable 2: measure == draw. In no-width-clamp mode the popup is sized
    // exactly to its content + padding, so the max extent of every recorded op
    // must equal `LaidMenu::size` on both axes — nothing may exceed it, and a
    // primitive escaping the measured rect is a real measure/layout mismatch.
    // -------------------------------------------------------------------------

    /// The bottom-right-most extent of every recorded op (text advanced at the
    /// drawer's 7px/char + 14px line-height metric, plus image/fill/separator
    /// rects). Returns `(max_x, max_y, min_x, min_y)`.
    fn op_extents(d: &RecordingDrawer) -> (f32, f32, f32, f32) {
        let mut max_x = f32::MIN;
        let mut max_y = f32::MIN;
        let mut min_x = f32::MAX;
        let mut min_y = f32::MAX;
        let mut acc = |x0: f32, y0: f32, x1: f32, y1: f32| {
            min_x = min_x.min(x0);
            min_y = min_y.min(y0);
            max_x = max_x.max(x1);
            max_y = max_y.max(y1);
        };
        for (t, x, y) in &d.texts {
            acc(*x, *y, x + t.chars().count() as f32 * 7.0, y + 14.0);
        }
        for r in &d.images {
            acc(r.origin.x, r.origin.y, r.max_x(), r.max_y());
        }
        for (r, _) in &d.fills {
            acc(r.origin.x, r.origin.y, r.max_x(), r.max_y());
        }
        for (r, _) in &d.separators {
            acc(r.origin.x, r.origin.y, r.max_x(), r.max_y());
        }
        (max_x, max_y, min_x, min_y)
    }

    #[test]
    fn measured_size_bounds_every_drawn_primitive() {
        let logo: Arc<[u8]> = Arc::from(vec![0u8; 8]);
        let long = "a-very-long-account-label-that-would-overflow@example.com";
        let cases: Vec<(&str, Menu)> = vec![
            ("empty", Menu::new()),
            ("single", Menu::new().row(Row::new("a").label("Alpha"))),
            (
                "many_rows",
                (0..20).fold(Menu::new(), |m, i| {
                    m.row(Row::new(format!("r{i}")).label(format!("Row {i}")))
                }),
            ),
            ("long_label", Menu::new().row(Row::new("a").label(long))),
            (
                "icons_lead_and_trail",
                Menu::new().row(
                    Row::new("a")
                        .leading(Icon::Png(logo.clone()))
                        .label("Withicons")
                        .trailing(Icon::Checkmark),
                ),
            ),
            (
                "headers_seps_submenu_checks",
                Menu::new()
                    .section_header(Row::label_only("Header"))
                    .row(Row::new("c").checked(true).label("Checked").enabled(false))
                    .separator()
                    .submenu(Row::new("more").label("More"), Menu::new())
                    .row(Row::new("d").checked(false).label("Unchecked")),
            ),
            (
                "flush_right",
                Menu::new().row(Row::new("a").segments(vec![
                    Segment::new(long).flex(Flex::Grow),
                    Segment::new("100%").align(Align::Right),
                ])),
            ),
            (
                "unicode",
                Menu::new().row(Row::new("u").label("café 日本語 🎉 Ω")),
            ),
        ];

        // No-clamp width: min tiny, max huge — the popup is sized exactly to its
        // content, so extents must meet the reported size, never merely fit under
        // a min/max floor/ceiling.
        let opts = MenuOptions::default().min_width(1.0).max_width(100_000.0);
        const TOL: f32 = 1.0;

        for (name, menu) in &cases {
            for highlight in [None, Some(0usize)] {
                let mut d = RecordingDrawer::default();
                let laid = render_menu(&mut d, menu, &Theme::light(), &opts, highlight);
                let (w, h) = (laid.size.width, laid.size.height);
                assert!(w.is_finite() && h.is_finite(), "{name}: non-finite size");

                // The popup background fill is the whole measured rect.
                let (bg_rect, _) = d.fills.first().expect("a panel background fill");
                assert!(
                    (bg_rect.origin.x).abs() < TOL
                        && (bg_rect.origin.y).abs() < TOL
                        && (bg_rect.max_x() - w).abs() < TOL
                        && (bg_rect.max_y() - h).abs() < TOL,
                    "{name}: panel background must equal the measured size {:?}, got {bg_rect:?}",
                    laid.size
                );

                let (max_x, max_y, min_x, min_y) = op_extents(&d);
                // Nothing escapes the measured rect (draw fits measure).
                assert!(
                    min_x >= -TOL && min_y >= -TOL,
                    "{name} (hl={highlight:?}): a primitive starts before the popup origin \
                     (min_x={min_x}, min_y={min_y})"
                );
                assert!(
                    max_x <= w + TOL && max_y <= h + TOL,
                    "{name} (hl={highlight:?}): a primitive overflows the measured size \
                     {w}x{h} (max_x={max_x}, max_y={max_y}) — a measure/draw mismatch"
                );
                // ...and the measured size is snug: the drawn ops actually reach
                // both far edges (measure == draw, not measure > draw).
                assert!(
                    (max_x - w).abs() < TOL && (max_y - h).abs() < TOL,
                    "{name} (hl={highlight:?}): measured size {w}x{h} exceeds the drawn extent \
                     (max_x={max_x}, max_y={max_y}) — the popup is larger than what it paints"
                );
            }
        }
    }

    // -------------------------------------------------------------------------
    // Deliverable 3: edge-case + newly-fixed-path coverage (RecordingDrawer).
    // -------------------------------------------------------------------------

    /// Every `Icon` variant renders in BOTH the leading and the trailing slot —
    /// the per-slot generalization of `draw_icon_funnel_draws_every_icon_variant`,
    /// guarding that neither slot silently swallows a variant.
    #[test]
    fn every_icon_variant_renders_in_leading_and_trailing_slots() {
        let png: Arc<[u8]> = Arc::from(vec![1u8; 4]);
        let svg: Arc<[u8]> = Arc::from(vec![2u8; 4]);
        let variants: Vec<(&str, Icon)> = vec![
            ("Png", Icon::Png(png)),
            ("Svg", Icon::Svg(svg)),
            ("Checkmark", Icon::Checkmark),
            ("Symbol", Icon::Symbol("gear")),
        ];
        for (name, icon) in variants {
            for slot in ["leading", "trailing"] {
                let row = if slot == "leading" {
                    Row::new("r").leading(icon.clone()).label("Label")
                } else {
                    Row::new("r").label("Label").trailing(icon.clone())
                };
                let mut d = RecordingDrawer::default();
                render_menu(
                    &mut d,
                    &Menu::new().row(row),
                    &Theme::dark(),
                    &MenuOptions::default(),
                    None,
                );
                let ops = d.images.len() + d.texts.len();
                // An image icon blits; a glyph icon draws text. Either way, the
                // slot must emit strictly more than the bare "Label" text alone.
                assert!(
                    ops > 1,
                    "Icon::{name} in the {slot} slot emitted no icon draw op (only \
                     the label); images={} texts={:?}",
                    d.images.len(),
                    d.texts
                );
            }
        }
    }

    /// A disabled row with BOTH a leading and a trailing image icon dims each blit
    /// to `DISABLED_ALPHA` (issue E, extended to the trailing slot).
    #[test]
    fn disabled_row_dims_both_leading_and_trailing_icons() {
        let lead: Arc<[u8]> = Arc::from(vec![3u8; 4]);
        let trail: Arc<[u8]> = Arc::from(vec![4u8; 4]);
        let menu = Menu::new().row(
            Row::new("a")
                .leading(Icon::Png(lead))
                .label("Both")
                .trailing(Icon::Png(trail))
                .enabled(false),
        );
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        assert_eq!(d.image_alphas.len(), 2, "both icons must blit");
        assert!(
            d.image_alphas
                .iter()
                .all(|(_, a)| (*a - DISABLED_ALPHA).abs() < 1e-6),
            "a disabled row must dim BOTH its leading and trailing icons; got {:?}",
            d.image_alphas
        );
    }

    /// A disabled row carrying a leading icon AND a checkmark column: the icon
    /// wins the gutter (leading takes precedence over `checked`), and it dims. The
    /// row's own text also dims via `secondary_label`. Proves the disabled path is
    /// coherent when both a checkable state and an icon are requested.
    #[test]
    fn disabled_row_with_icon_and_checked_dims_and_prefers_the_icon() {
        let icon: Arc<[u8]> = Arc::from(vec![5u8; 4]);
        let menu = Menu::new().row(
            Row::new("a")
                .leading(Icon::Png(icon))
                .checked(true)
                .label("Item")
                .enabled(false),
        );
        let mut d = RecordingDrawer::default();
        render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);
        // The leading icon occupies the gutter — no checkmark glyph is drawn.
        assert!(
            !d.texts.iter().any(|(t, ..)| t == "\u{2713}"),
            "a leading icon must win the gutter over the checkmark; texts={:?}",
            d.texts
        );
        // The icon blits dimmed.
        assert_eq!(d.image_alphas.len(), 1);
        assert!((d.image_alphas[0].1 - DISABLED_ALPHA).abs() < 1e-6);
        // The label dims to secondary_label (not the enabled label color).
        let label = d
            .text_colors
            .iter()
            .find(|(t, _)| t == "Item")
            .expect("label drawn");
        assert_eq!(
            label.1,
            Theme::dark().resolve(Theme::dark().secondary_label)
        );
    }

    /// Three overlapping style runs composite last-wins across the whole overlap,
    /// not just pairwise — extends `issue_d` to prove the walk-all-runs loop has no
    /// early-out for any depth of overlap.
    #[test]
    fn three_overlapping_style_runs_last_wins() {
        let seg = Segment::new("abc").runs(vec![
            StyleRun::new(0, 3, Color::SystemRed),    // a b c
            StyleRun::new(0, 2, Color::SystemGreen),  // a b
            StyleRun::new(1, 2, Color::SystemYellow), // b c  (latest over b, c)
        ]);
        let theme = Theme::light();
        let pieces = style_pieces(&seg, Rgba::BLACK, Weight::Regular, &theme, false);
        // a: red then green -> green wins. b: red, green, yellow -> yellow.
        // c: red, yellow -> yellow. Adjacent same-color chars merge, so 'b' and
        // 'c' coalesce into one "bc" yellow piece.
        assert_eq!(
            pieces,
            vec![
                ("a", theme.resolve(Color::SystemGreen), Weight::Regular),
                ("bc", theme.resolve(Color::SystemYellow), Weight::Regular),
            ],
            "last-wins across a 3-deep overlap, with same-color chars merged"
        );
    }

    /// An empty menu still lays out to a finite, sane popup (the default min
    /// width, padding-only height) with a single background fill and no rows —
    /// no panic, no degenerate/`NaN` geometry.
    #[test]
    fn empty_menu_lays_out_to_a_finite_padded_popup() {
        let mut d = RecordingDrawer::default();
        let laid = render_menu(
            &mut d,
            &Menu::new(),
            &Theme::light(),
            &MenuOptions::default(),
            None,
        );
        assert!(laid.rows.is_empty());
        assert_eq!(laid.size.width, DEFAULT_MIN_WIDTH);
        let pad = Theme::light().padding;
        assert!((laid.size.height - (pad.top + pad.bottom)).abs() < f32::EPSILON);
        assert_eq!(d.fills.len(), 1, "only the panel background is filled");
    }

    /// A multi-byte / unicode label round-trips through layout and hit-testing:
    /// the exact string is drawn once, and a click at the row center maps back to
    /// its id (no UTF-16/char-index confusion breaks measurement or hit rects).
    #[test]
    fn unicode_label_renders_and_hit_tests() {
        let label = "café 日本語 🎉 Ω";
        let menu = Menu::new().row(Row::new("u").label(label));
        let mut d = RecordingDrawer::default();
        let laid = render_menu(
            &mut d,
            &menu,
            &Theme::light(),
            &MenuOptions::default(),
            None,
        );
        assert!(
            d.texts.iter().any(|(t, ..)| t == label),
            "the unicode label must be drawn verbatim; texts={:?}",
            d.texts
        );
        let row = &laid.rows[0];
        let center = LogicalPoint::new(
            row.rect.origin.x + row.rect.size.width / 2.0,
            row.rect.origin.y + row.rect.size.height / 2.0,
        );
        assert_eq!(laid.id_at(center).unwrap().as_str(), "u");
    }

    /// A "kitchen sink" menu mixing every top-level `Item` kind — header, plain
    /// row, checked+disabled row, row with leading+trailing icons and a background
    /// tint, a separator, a submenu, and a `Content` stack — lays out without
    /// panicking, paints its explicit row background, and reports exactly the
    /// interactive rows (plain row + submenu; the checked row is disabled).
    #[test]
    fn kitchen_sink_menu_paints_all_item_kinds() {
        let logo: Arc<[u8]> = Arc::from(vec![6u8; 8]);
        let menu = Menu::new()
            .section_header(Row::label_only("Section"))
            .row(Row::new("plain").label("Plain"))
            .row(
                Row::new("cd")
                    .checked(true)
                    .enabled(false)
                    .label("CheckedDisabled"),
            )
            .row(
                Row::new("fancy")
                    .leading(Icon::Png(logo.clone()))
                    .label("Fancy")
                    .trailing(Icon::Checkmark)
                    .background(Color::SystemRed),
            )
            .separator()
            .submenu(Row::new("more").label("More"), Menu::new())
            .content(
                Stack::horizontal(2.0)
                    .child(Content::Text(TextContent::new("Extra")))
                    .child(Content::Image {
                        icon: Icon::Png(logo),
                        size: 16.0,
                    }),
            );
        let mut d = RecordingDrawer::default();
        let laid = render_menu(&mut d, &menu, &Theme::dark(), &MenuOptions::default(), None);

        // Interactive rows: "plain", "fancy", and the submenu "more" (the checked
        // row is disabled; header/separator/content are never interactive).
        assert_eq!(laid.rows.iter().filter(|r| r.interactive).count(), 3);
        // The fancy row's explicit background is painted.
        let want = Theme::dark().resolve(Color::SystemRed);
        assert!(
            d.fills.iter().any(|(_, c)| *c == want),
            "the tinted row's background must be filled"
        );
        // The fancy row's leading image and the content stack's image blit; its
        // trailing Checkmark is a glyph, drawn as text, not an image.
        assert_eq!(d.images.len(), 2, "leading and content icons blit");
        assert!(
            d.texts.iter().any(|(t, ..)| t == "\u{2713}"),
            "the trailing checkmark glyph is drawn"
        );
    }
}