quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
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
//! `MenuSystem` — a composed controller for MenuBar + ContextMenu
//! dropdown interaction.
//!
//! Owns the full state machine (open/close, keyboard navigation,
//! hover-to-switch, modal stack coordination) so consumers define
//! their menu structure once and match on [`MenuEvent::Activated`].
//!
//! ```ignore
//! // In handle():
//! match self.menu_system.handle(&event, backend, bar_rect) {
//!     MenuEvent::Activated(id) if id.as_str() == "save" => { /* save */ }
//!     MenuEvent::Activated(id) if id.as_str() == "quit" => return Reaction::Exit,
//!     MenuEvent::StateChanged | MenuEvent::Consumed => return Reaction::Redraw,
//!     _ => { /* handle non-menu events */ }
//! }
//! ```

use crate::backend::{Backend, ResolvedMenuStyle};
use crate::event::{Rect, UiEvent};
use crate::primitives::context_menu::{
    ContextMenu, ContextMenuHit, ContextMenuItem, ContextMenuItemMeasure, ContextMenuLayout,
    ContextMenuPlacement,
};
use crate::primitives::menu_bar::{MenuBar, MenuBarHit, MenuBarItem};
use crate::types::WidgetId;
use crate::{FontRole, Key, Modifiers, MouseButton, NamedKey};

/// Derive a dropdown or submenu's width from its items' real label/detail
/// text via [`Backend::measure_text`]. A flat width guess cannot fit
/// both TUI's fixed grid and a proportional chrome font on GTK/macOS/Win
/// (whose `char_width` isn't meaningful for chrome text — see
/// `Backend::measure_text`'s own doc). Mirrors [`ContextMenu::
/// measure_generic_width`]'s per-item accounting (a leading `✓ ` slot
/// when [`ContextMenuItem::checked`] is `Some(_)`, a trailing gap plus
/// either a `▶` submenu arrow or [`ContextMenuItem::detail`]'s text) but
/// measures the real chrome-font advance instead of counting characters.
/// [`ContextMenuItem::key_equivalent`]-rendered shortcuts aren't counted,
/// same omission `measure_generic_width` documents for itself.
fn dropdown_width(backend: &dyn Backend, items: &[ContextMenuItem], lh: f32) -> f32 {
    let role = FontRole::Chrome;
    let space_w = backend.measure_text(" ", role).0;
    // On a GUI backend, `primitives::context_menu::native_surface_paint`
    // paints the codicon check/chevron glyphs (`codicon::CHECK` /
    // `codicon::CHEVRON_RIGHT`, hardcoded here rather than referencing
    // the `codicon` module directly since that module isn't compiled
    // in a TUI-only build this function also has to run under) instead
    // of the plain `✓`/`▶` text `tui::context_menu` paints — and
    // codicon glyphs are square-advance at the font em, wider than
    // either plain-text glyph's own chrome-font advance. Reserve
    // against whichever glyph the paint path for this backend will
    // actually use, detected the same way every other codicon call
    // site confirms registration: `has_font_family` answers `Some(_)`
    // only on a GUI backend (TUI takes the trait's `None` default),
    // and every GUI backend's own `*Backend::new` self-registers
    // "codicon" unconditionally, so `Some(true)` here means the real
    // paint path really will resolve the codicon glyph.
    let codicon_available = backend.has_font_family("codicon") == Some(true);
    let (check_glyph, arrow_glyph): (&str, &str) = if codicon_available {
        ("\u{eab2}", "\u{eab6}")
    } else {
        ("✓", "▶")
    };
    let checked_w = backend.measure_text(check_glyph, role).0 + space_w;
    let arrow_w = space_w + backend.measure_text(arrow_glyph, role).0;
    let max_content_w = items
        .iter()
        .filter(|item| !item.is_separator())
        .map(|item| {
            let label: String = item.label.spans.iter().map(|s| s.text.as_str()).collect();
            let mut w = backend.measure_text(&label, role).0;
            if item.checked.is_some() {
                w += checked_w;
            }
            if item.submenu.is_some() {
                w += arrow_w;
            } else if let Some(det) = &item.detail {
                let text: String = det.spans.iter().map(|s| s.text.as_str()).collect();
                w += space_w + backend.measure_text(&text, role).0;
            }
            w
        })
        .fold(0.0_f32, f32::max);
    // Interior margin: a budget expressed in line-heights rather than
    // assuming a meaningful relationship between `lh` and the chrome
    // font's space advance.
    (max_content_w + lh * 3.0).max(lh * 8.0)
}

/// One top-level menu and its dropdown items.
#[derive(Debug, Clone)]
pub struct MenuDef {
    pub id: WidgetId,
    pub label: String,
    pub disabled: bool,
    pub items: Vec<ContextMenuItem>,
}

/// What happened after [`MenuSystem::handle`] processed an event.
#[derive(Debug, Clone, PartialEq)]
pub enum MenuEvent {
    /// An action item was activated (clicked or Enter'd).
    Activated(WidgetId),
    /// A menu was opened or closed — the app should redraw.
    StateChanged,
    /// The event was consumed (navigation, highlight) — the app should redraw.
    Consumed,
    /// The event was not relevant to the menu system.
    Ignored,
}

pub struct MenuSystem {
    menus: Vec<MenuDef>,
    open_item: Option<usize>,
    focused_item: Option<usize>,
    /// Selected item index in the root dropdown.
    dropdown_selected: usize,
    dropdown_id: WidgetId,
    /// Depth-first path of open submenus within the current dropdown.
    /// `submenu_path[d]` = `item_idx` in the menu at depth `d` whose child
    /// submenu is open.  Empty ⟹ no submenus open.
    submenu_path: Vec<usize>,
    /// Selected item index at each submenu depth.
    /// `submenu_selected[d]` corresponds to the submenu opened by
    /// `submenu_path[d]`.
    submenu_selected: Vec<usize>,
}

impl MenuSystem {
    pub fn new(menus: Vec<MenuDef>) -> Self {
        Self {
            menus,
            open_item: None,
            focused_item: None,
            dropdown_selected: 0,
            dropdown_id: WidgetId::new("menu-system-dropdown"),
            submenu_path: Vec::new(),
            submenu_selected: Vec::new(),
        }
    }

    pub fn is_open(&self) -> bool {
        self.open_item.is_some()
    }

    pub fn set_menus(&mut self, menus: Vec<MenuDef>) {
        self.menus = menus;
    }

    pub fn close(&mut self, backend: &mut dyn Backend) {
        self.open_item = None;
        self.focused_item = None;
        self.submenu_path.clear();
        self.submenu_selected.clear();
        backend
            .modal_stack_handle()
            .borrow_mut()
            .pop(&self.dropdown_id);
    }

    /// Return the current `MenuBar` descriptor without rendering.
    pub fn menu_bar(&self) -> MenuBar {
        self.build_menu_bar()
    }

    /// Draw the menu bar and any open dropdown (including nested submenus).
    pub fn render(&self, backend: &mut dyn Backend, bar_rect: Rect) {
        let bar = self.build_menu_bar();
        let _ = backend.draw_menu_bar(bar_rect, &bar);

        let stack = self.dropdown_stack(backend, bar_rect);
        for (ctx_menu, layout) in &stack {
            let _ = backend.draw_context_menu(ctx_menu, layout);
        }
    }

    /// Process an event. Call from `handle()` before other UI routing.
    ///
    /// A thin dispatcher over the per-event-shape handlers below.
    /// Each `handle_*` owns one gesture's full state-machine transition
    /// so this stays a readable table of "what shape → which handler".
    pub fn handle(
        &mut self,
        event: &UiEvent,
        backend: &mut dyn Backend,
        bar_rect: Rect,
    ) -> MenuEvent {
        match event {
            // ── Native menu-bar activation ────────────────────────────
            // `Backend::draw_menu_bar` installs a real `NSMenu` instead
            // of painting whenever `effective_menu_style()` resolves
            // `Native` (macOS, by default) — see that method's doc.
            // AppKit then reports a click as a top-level
            // `UiEvent::MenuActivated`, not a hit on this struct's own
            // `bar_rect`-relative dropdown state (there is none; the
            // dropdown is AppKit's own). Translating it to the same
            // `MenuEvent::Activated` the painted path produces means
            // every consumer's existing `match self.menu_system.handle(...)
            // { MenuEvent::Activated(id) => ... }` arm already covers
            // the native path with no separate call site — the same
            // "one call either way" shape
            // [`crate::compose::ContextMenuController::handle`] uses for
            // `ContextMenuItemActivated`.
            UiEvent::MenuActivated(id) => MenuEvent::Activated(*id),

            // ── Keyboard ──────────────────────────────────────────
            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Escape),
                ..
            } if self.open_item.is_some() => self.handle_escape(backend),

            UiEvent::KeyPressed {
                key: Key::Char(c),
                modifiers: Modifiers { alt: true, .. },
                ..
            } => self.handle_alt_char(*c, backend, bar_rect),

            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Down),
                ..
            } if self.open_item.is_some() => {
                self.move_selection(1);
                MenuEvent::Consumed
            }

            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Up),
                ..
            } if self.open_item.is_some() => {
                self.move_selection(-1);
                MenuEvent::Consumed
            }

            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Right),
                ..
            } if self.open_item.is_some() => self.handle_right(backend, bar_rect),

            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Left),
                ..
            } if self.open_item.is_some() => self.handle_left(backend, bar_rect),

            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Enter),
                ..
            } if self.open_item.is_some() => self.handle_enter(backend),

            // ── Mouse click ───────────────────────────────────────
            UiEvent::MouseDown {
                button: MouseButton::Left,
                position,
                ..
            } => self.handle_mouse_down(*position, backend, bar_rect),

            // ── Mouse hover ───────────────────────────────────────
            UiEvent::MouseMoved { position, .. } => {
                self.handle_mouse_moved(*position, backend, bar_rect)
            }

            // ── Mouse release ─────────────────────────────────────
            // Some terminal/multiplexer combinations (Alacritty+tmux,
            // certain gnome-terminal configs) drop `MouseDown(Left)` and
            // only ever deliver `MouseUp(Left)` for a click. Without this
            // arm, an outside click on those terminals never runs the
            // "click outside all open menu levels → close" check the
            // `MouseDown` handler's tail performs, so a dropdown never
            // dismisses on outside click there.
            //
            // On terminals that deliver both `Down` and `Up` normally,
            // `MouseDown` has already fully handled the click by the time
            // `Up` arrives (opened/closed/switched the menu, or activated
            // an item and closed). So this arm only needs to cover the
            // "outside everything" case; it must NOT re-run bar-item
            // toggling or item activation, or it would immediately
            // re-close a menu that `Down` just opened, or double-fire
            // `Activated`.
            UiEvent::MouseUp {
                button: MouseButton::Left,
                position,
                ..
            } => self.handle_mouse_up(*position, backend, bar_rect),

            _ => MenuEvent::Ignored,
        }
    }

    /// Esc: close deepest open submenu; if none, close whole menu.
    /// Caller guarantees `self.open_item.is_some()`.
    fn handle_escape(&mut self, backend: &mut dyn Backend) -> MenuEvent {
        if !self.submenu_path.is_empty() {
            self.close_deepest_submenu();
        } else {
            self.close(backend);
        }
        MenuEvent::StateChanged
    }

    /// Alt+`c`: open/close/switch to the top-level menu whose label's
    /// underlined access key matches `c`.
    ///
    /// Inert whenever [`Backend::effective_menu_style`] resolves
    /// [`ResolvedMenuStyle::Native`]: the menu bar is then the
    /// platform's own (AppKit's `NSMenu`, on macOS), living outside the
    /// window with no mnemonic underlines painted and its own keyboard
    /// activation handled by the OS. There is no in-window strip for a
    /// dropdown to anchor under, so this reports `Ignored` and leaves
    /// the Alt chord to the app.
    fn handle_alt_char(&mut self, c: char, backend: &mut dyn Backend, bar_rect: Rect) -> MenuEvent {
        if backend.effective_menu_style() == ResolvedMenuStyle::Native {
            return MenuEvent::Ignored;
        }
        let bar = self.build_menu_bar();
        if let Some(idx) = bar.find_alt_target(c) {
            if self.open_item == Some(idx) {
                self.close(backend);
            } else {
                self.open_menu(idx, backend, bar_rect);
            }
            MenuEvent::StateChanged
        } else {
            MenuEvent::Ignored
        }
    }

    /// Right: open submenu if selected item has one; otherwise switch
    /// top-level menu (only at root level with no open submenus).
    /// Caller guarantees `self.open_item.is_some()`.
    fn handle_right(&mut self, backend: &mut dyn Backend, bar_rect: Rect) -> MenuEvent {
        let depth = self.submenu_path.len();
        let sel = self.current_selected();
        let has_sub = self
            .items_at_depth(depth)
            .and_then(|items| items.into_iter().nth(sel))
            .map(|item| item.submenu.is_some())
            .unwrap_or(false);

        if has_sub {
            self.open_submenu(sel);
            MenuEvent::StateChanged
        } else if depth == 0 {
            // At root with no submenu open → switch top-level menu.
            let Some(cur) = self.open_item else {
                return MenuEvent::Ignored;
            };
            let next = self.next_enabled_menu(cur, 1);
            self.close(backend);
            self.open_menu(next, backend, bar_rect);
            MenuEvent::StateChanged
        } else {
            // Inside a submenu, non-submenu item → no-op.
            MenuEvent::Ignored
        }
    }

    /// Left: close deepest submenu if one is open; otherwise switch
    /// top-level menu (preserves pre-submenu behaviour).
    /// Caller guarantees `self.open_item.is_some()`.
    fn handle_left(&mut self, backend: &mut dyn Backend, bar_rect: Rect) -> MenuEvent {
        if !self.submenu_path.is_empty() {
            self.close_deepest_submenu();
            MenuEvent::StateChanged
        } else {
            let Some(cur) = self.open_item else {
                return MenuEvent::Ignored;
            };
            let prev = self.next_enabled_menu(cur, -1);
            self.close(backend);
            self.open_menu(prev, backend, bar_rect);
            MenuEvent::StateChanged
        }
    }

    /// Enter: open submenu if item is a submenu parent; otherwise activate.
    /// Caller guarantees `self.open_item.is_some()`.
    fn handle_enter(&mut self, backend: &mut dyn Backend) -> MenuEvent {
        let depth = self.submenu_path.len();
        let sel = self.current_selected();
        let item_opt = self
            .items_at_depth(depth)
            .and_then(|items| items.into_iter().nth(sel));

        match item_opt {
            Some(item) if item.submenu.is_some() => {
                self.open_submenu(sel);
                MenuEvent::StateChanged
            }
            Some(item) => {
                if let Some(id) = item.id {
                    self.close(backend);
                    MenuEvent::Activated(id)
                } else {
                    self.close(backend);
                    MenuEvent::Consumed
                }
            }
            None => {
                self.close(backend);
                MenuEvent::Consumed
            }
        }
    }

    fn handle_mouse_down(
        &mut self,
        position: crate::event::Point,
        backend: &mut dyn Backend,
        bar_rect: Rect,
    ) -> MenuEvent {
        let bar = self.build_menu_bar();
        let bar_layout = backend.menu_bar_layout(bar_rect, &bar);

        match bar_layout.hit_test(position.x, position.y) {
            MenuBarHit::Item(i) => {
                if self.open_item == Some(i) {
                    self.close(backend);
                } else {
                    self.close(backend);
                    self.open_menu(i, backend, bar_rect);
                }
                return MenuEvent::StateChanged;
            }
            MenuBarHit::Bar => {
                if self.open_item.is_some() {
                    self.close(backend);
                    return MenuEvent::StateChanged;
                }
                return MenuEvent::Ignored;
            }
            MenuBarHit::Outside => {}
        }

        if self.open_item.is_some() {
            // Walk the submenu stack deepest-first so that a click on
            // an item in a child popup doesn't fall through to the parent.
            let stack = self.dropdown_stack(backend, bar_rect);
            for (depth_idx, (ref menu, ref layout)) in stack.iter().enumerate().rev() {
                match layout.hit_test(position.x, position.y) {
                    ContextMenuHit::Item(ref id) => {
                        // Resolve item_idx from the id.
                        let item_idx_opt = layout
                            .visible_items
                            .iter()
                            .find(|v| v.clickable && menu.items[v.item_idx].id.as_ref() == Some(id))
                            .map(|v| v.item_idx);

                        if let Some(item_idx) = item_idx_opt {
                            if menu.items[item_idx].submenu.is_some() {
                                // Trim any deeper submenus that were open, then open
                                // this submenu (always open — clicking a submenu parent
                                // re-opens even if already visible).
                                self.submenu_path.truncate(depth_idx);
                                self.submenu_selected.truncate(depth_idx);
                                self.open_submenu(item_idx);
                                return MenuEvent::StateChanged;
                            } else {
                                let id = *id;
                                self.close(backend);
                                return MenuEvent::Activated(id);
                            }
                        }
                        return MenuEvent::Consumed;
                    }
                    ContextMenuHit::Inert => return MenuEvent::Consumed,
                    ContextMenuHit::Empty => {
                        // Click outside this depth — try shallower.
                        continue;
                    }
                }
            }

            // Click outside all open menu levels → close.
            self.close(backend);
            return MenuEvent::StateChanged;
        }
        MenuEvent::Ignored
    }

    fn handle_mouse_moved(
        &mut self,
        position: crate::event::Point,
        backend: &mut dyn Backend,
        bar_rect: Rect,
    ) -> MenuEvent {
        let bar = self.build_menu_bar();
        let bar_layout = backend.menu_bar_layout(bar_rect, &bar);

        if self.open_item.is_some() {
            // Hovering a different top-level menu label → switch.
            if let MenuBarHit::Item(i) = bar_layout.hit_test(position.x, position.y) {
                if !bar.items[i].disabled && self.open_item != Some(i) {
                    self.close(backend);
                    self.open_menu(i, backend, bar_rect);
                    return MenuEvent::StateChanged;
                }
            }

            // Walk the stack shallowest-first to find the deepest level
            // that the cursor is inside. When we find an item:
            //   • Update the selection at that level.
            //   • If it's a submenu parent, open its child (closing any
            //     previously-open sibling submenu at the same depth).
            //   • Close any submenus deeper than the matched level.
            let stack = self.dropdown_stack(backend, bar_rect);
            for (depth_idx, (ref menu, ref layout)) in stack.iter().enumerate() {
                for vis in &layout.visible_items {
                    if !vis.clickable {
                        continue;
                    }
                    if position.x >= vis.bounds.x
                        && position.x < vis.bounds.x + vis.bounds.width
                        && position.y >= vis.bounds.y
                        && position.y < vis.bounds.y + vis.bounds.height
                    {
                        let item_idx = vis.item_idx;
                        let has_sub = menu.items[item_idx].submenu.is_some();

                        // Update selection at this depth.
                        let sel_changed = if depth_idx == 0 {
                            let old = self.dropdown_selected;
                            self.dropdown_selected = item_idx;
                            old != item_idx
                        } else {
                            let sub_d = depth_idx - 1;
                            let old = self.submenu_selected.get(sub_d).copied().unwrap_or(0);
                            if let Some(s) = self.submenu_selected.get_mut(sub_d) {
                                *s = item_idx;
                            }
                            old != item_idx
                        };

                        if has_sub {
                            // Trim any deeper submenus and open this one.
                            self.submenu_path.truncate(depth_idx);
                            self.submenu_selected.truncate(depth_idx);
                            self.open_submenu(item_idx);
                            return MenuEvent::StateChanged;
                        } else if self.submenu_path.len() > depth_idx {
                            // Close deeper submenus when hovering a leaf.
                            self.submenu_path.truncate(depth_idx);
                            self.submenu_selected.truncate(depth_idx);
                            return MenuEvent::StateChanged;
                        } else if sel_changed {
                            return MenuEvent::Consumed;
                        } else {
                            return MenuEvent::Ignored;
                        }
                    }
                }
            }
            MenuEvent::Ignored
        } else {
            let new_focus = match bar_layout.hit_test(position.x, position.y) {
                MenuBarHit::Item(i) if !bar.items[i].disabled => Some(i),
                _ => None,
            };
            if new_focus != self.focused_item {
                self.focused_item = new_focus;
                MenuEvent::Consumed
            } else {
                MenuEvent::Ignored
            }
        }
    }

    fn handle_mouse_up(
        &mut self,
        position: crate::event::Point,
        backend: &mut dyn Backend,
        bar_rect: Rect,
    ) -> MenuEvent {
        if self.open_item.is_none() {
            return MenuEvent::Ignored;
        }

        let bar = self.build_menu_bar();
        let bar_layout = backend.menu_bar_layout(bar_rect, &bar);

        // Clicks landing on the menu bar itself (open/close/switch)
        // are `MouseDown`'s job — leave them alone here.
        if !matches!(
            bar_layout.hit_test(position.x, position.y),
            MenuBarHit::Outside
        ) {
            return MenuEvent::Ignored;
        }

        // Walk the open dropdown stack deepest-first. If the
        // position lands inside any open level (item or inert
        // region), that click was already handled by `MouseDown` —
        // do nothing here to avoid double-activating.
        let stack = self.dropdown_stack(backend, bar_rect);
        for (_, layout) in stack.iter().rev() {
            if !matches!(
                layout.hit_test(position.x, position.y),
                ContextMenuHit::Empty
            ) {
                return MenuEvent::Ignored;
            }
        }

        // Outside the bar and every open dropdown level → close.
        self.close(backend);
        MenuEvent::StateChanged
    }

    // ── Internal helpers ──────────────────────────────────────────────

    fn build_menu_bar(&self) -> MenuBar {
        MenuBar {
            id: WidgetId::new("menu-system-bar"),
            items: self
                .menus
                .iter()
                .map(|m| MenuBarItem {
                    id: m.id,
                    label: m.label.clone(),
                    disabled: m.disabled,
                    // MenuSystem manages dropdowns out-of-band via
                    // build_dropdown(), not through the declarative submenu
                    // field. Leaving this `None` keeps the existing render
                    // path unchanged on TUI/GTK.
                    submenu: None,
                })
                .collect(),
            open_item: self.open_item,
            focused_item: self.focused_item,
        }
    }

    fn build_dropdown(&self, menu_idx: usize) -> ContextMenu {
        ContextMenu {
            id: self.dropdown_id,
            items: self.menus[menu_idx].items.clone(),
            selected_idx: self.dropdown_selected,
            bg: None,
            placement: ContextMenuPlacement::Below,
        }
    }

    fn dropdown_layout(
        &self,
        backend: &dyn Backend,
        bar_rect: Rect,
    ) -> Option<(ContextMenu, ContextMenuLayout)> {
        let open_idx = self.open_item?;
        if self.menus[open_idx].items.is_empty() {
            return None;
        }
        let lh = backend.chrome_line_height();
        let bar = self.build_menu_bar();
        let bar_layout = backend.menu_bar_layout(bar_rect, &bar);
        // A backend that resolves `ResolvedMenuStyle::Native` reports a
        // zero-height layout with no visible items, because its menu bar
        // is the platform's own and lives outside the window. There is
        // then nothing to anchor a dropdown under, so no dropdown.
        let raw_anchor = bar_layout.visible_items.get(open_idx)?.bounds;
        let pad = (lh * 0.15).max(1.0);
        let anchor = Rect::new(
            raw_anchor.x + pad,
            raw_anchor.y,
            raw_anchor.width,
            raw_anchor.height + pad,
        );
        let viewport_rect = backend.context_menu_viewport();
        let ctx_menu = self.build_dropdown(open_idx);
        let menu_width = dropdown_width(backend, &ctx_menu.items, lh);
        let item_h = (lh * 1.4).round().max(lh);
        let sep_h = (lh * 0.5).round().max(1.0);
        let layout = ctx_menu.layout_at(anchor, viewport_rect, menu_width, |i| {
            if ctx_menu.items[i].is_separator() {
                ContextMenuItemMeasure::new(sep_h)
            } else {
                ContextMenuItemMeasure::new(item_h)
            }
        });
        Some((ctx_menu, layout))
    }

    /// Build the full stack of (ContextMenu, ContextMenuLayout) for every
    /// currently-open menu level: index 0 = root dropdown, index 1 = first
    /// open submenu, etc.  Returns an empty vec when no menu is open.
    fn dropdown_stack(
        &self,
        backend: &dyn Backend,
        bar_rect: Rect,
    ) -> Vec<(ContextMenu, ContextMenuLayout)> {
        let mut stack: Vec<(ContextMenu, ContextMenuLayout)> = Vec::new();

        let Some((root_menu, root_layout)) = self.dropdown_layout(backend, bar_rect) else {
            return stack;
        };
        stack.push((root_menu, root_layout));

        let lh = backend.chrome_line_height();
        let item_h = (lh * 1.4).round().max(lh);
        let sep_h = (lh * 0.5).round().max(1.0);
        let vp = backend.context_menu_viewport();

        for (depth, &path_idx) in self.submenu_path.iter().enumerate() {
            // Extract parent data before we push so the borrow checker is happy.
            let sub_items_opt: Option<Vec<ContextMenuItem>> = stack[depth]
                .0
                .items
                .get(path_idx)
                .and_then(|item| item.submenu.clone());
            let parent_bounds = stack[depth].1.bounds;
            let anchor_y = stack[depth]
                .1
                .visible_items
                .iter()
                .find(|v| v.item_idx == path_idx)
                .map(|v| v.bounds.y)
                .unwrap_or(parent_bounds.y);

            let Some(sub_items) = sub_items_opt else {
                break;
            };
            // Each depth is measured from its own items, so a deeper
            // submenu with longer labels than its parent is not clipped
            // to the parent's width.
            let menu_width = dropdown_width(backend, &sub_items, lh);

            // Pull-right anchor with left-flip on overflow.
            let preferred_x = parent_bounds.x + parent_bounds.width + 1.0;
            let flipped_x = parent_bounds.x - menu_width - 1.0;
            let anchor_x = if preferred_x + menu_width <= vp.x + vp.width {
                preferred_x
            } else if flipped_x >= vp.x {
                flipped_x
            } else {
                (vp.x + vp.width - menu_width).max(vp.x)
            };

            let selected = self.submenu_selected.get(depth).copied().unwrap_or(0);

            let sub_menu = ContextMenu {
                id: WidgetId::new("menu-system-submenu"),
                items: sub_items.clone(),
                selected_idx: selected,
                bg: None,
                placement: ContextMenuPlacement::AnchorPoint,
            };

            let sub_layout = sub_menu.layout(anchor_x, anchor_y, vp, menu_width, |i| {
                if sub_items[i].is_separator() {
                    ContextMenuItemMeasure::new(sep_h)
                } else {
                    ContextMenuItemMeasure::new(item_h)
                }
            });

            stack.push((sub_menu, sub_layout));
        }

        stack
    }

    fn open_menu(&mut self, idx: usize, backend: &mut dyn Backend, bar_rect: Rect) {
        self.open_item = Some(idx);
        self.focused_item = Some(idx);
        self.submenu_path.clear();
        self.submenu_selected.clear();
        self.dropdown_selected = self.build_dropdown(idx).first_selectable();
        if let Some((_, layout)) = self.dropdown_layout(backend, bar_rect) {
            backend
                .modal_stack_handle()
                .borrow_mut()
                .push(self.dropdown_id, layout.bounds);
        }
    }

    /// Open the submenu belonging to `item_idx` at the current deepest level.
    /// Sets the initial selection to the first selectable item.
    fn open_submenu(&mut self, item_idx: usize) {
        let depth = self.submenu_path.len();
        let sub_items = match self
            .items_at_depth(depth)
            .and_then(|items| items.into_iter().nth(item_idx))
            .and_then(|item| item.submenu)
        {
            Some(items) => items,
            None => return,
        };
        let first_sel = sub_items
            .iter()
            .position(|i| !i.is_separator() && !i.disabled)
            .unwrap_or(0);
        self.submenu_path.push(item_idx);
        self.submenu_selected.push(first_sel);
    }

    /// Close the deepest open submenu (pop one level).
    fn close_deepest_submenu(&mut self) {
        self.submenu_path.pop();
        self.submenu_selected.pop();
    }

    fn next_enabled_menu(&self, from: usize, delta: isize) -> usize {
        let n = self.menus.len() as isize;
        let mut idx = from as isize;
        for _ in 0..self.menus.len() {
            idx = (idx + delta).rem_euclid(n);
            if !self.menus[idx as usize].disabled {
                return idx as usize;
            }
        }
        from
    }

    /// Return the selected item index at the currently-deepest open level.
    fn current_selected(&self) -> usize {
        if self.submenu_path.is_empty() {
            self.dropdown_selected
        } else {
            *self.submenu_selected.last().unwrap_or(&0)
        }
    }

    /// Return the items at depth `depth` (0 = root dropdown items).
    /// Returns `None` when `open_item` is unset or a submenu is missing.
    fn items_at_depth(&self, depth: usize) -> Option<Vec<ContextMenuItem>> {
        let open_idx = self.open_item?;
        let mut items = self.menus[open_idx].items.clone();
        for &path_idx in self.submenu_path.iter().take(depth) {
            items = items.into_iter().nth(path_idx)?.submenu?;
        }
        Some(items)
    }

    fn move_selection(&mut self, delta: i32) {
        let depth = self.submenu_path.len();
        let current = self.current_selected();

        let Some(items) = self.items_at_depth(depth) else {
            return;
        };

        let temp = ContextMenu {
            id: WidgetId::new("_move"),
            items,
            selected_idx: current,
            bg: None,
            placement: ContextMenuPlacement::AnchorPoint,
        };
        let new_sel = temp.move_selection(current, delta);

        if depth == 0 {
            self.dropdown_selected = new_sel;
        } else if let Some(s) = self.submenu_selected.last_mut() {
            *s = new_sel;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::context_menu::ContextMenuItem;
    use crate::types::StyledText;

    // ── Minimal mock backend for handle()-level tests ─────────────────────────

    struct MockBackend {
        modal_stack: std::rc::Rc<std::cell::RefCell<crate::ModalStack>>,
        drag_state: std::rc::Rc<std::cell::RefCell<crate::DragState>>,
        focus: crate::focus::FocusManager,
        /// Declares `BackendCaps::native_menu`, so the trait's default
        /// `MenuStyle::Auto` resolves `ResolvedMenuStyle::Native` and
        /// the menu-bar layout reports the zero-height, item-less shape
        /// a platform-owned menu bar has in-window (macOS, by default).
        native_menu_bar: bool,
        invalidation_log: crate::backend::InvalidationLog,
    }

    impl MockBackend {
        fn new() -> Self {
            Self {
                modal_stack: std::rc::Rc::new(std::cell::RefCell::new(crate::ModalStack::new())),
                drag_state: std::rc::Rc::new(std::cell::RefCell::new(crate::DragState::new())),
                focus: crate::focus::FocusManager::new(),
                native_menu_bar: false,
                invalidation_log: crate::backend::InvalidationLog::new(),
            }
        }

        /// A backend whose menu bar is the platform's own: `native_menu`
        /// capability, and an in-window layout with nothing in it.
        fn with_native_menu_bar() -> Self {
            Self {
                native_menu_bar: true,
                ..Self::new()
            }
        }

        fn mock_menu_bar_layout(&self, rect: Rect, bar: &crate::MenuBar) -> crate::MenuBarLayout {
            if self.native_menu_bar {
                return crate::MenuBarLayout {
                    bounds: Rect::new(rect.x, rect.y, rect.width, 0.0),
                    visible_items: Vec::new(),
                    hit_regions: Vec::new(),
                };
            }
            bar.layout(rect, |_| crate::MenuBarItemMeasure::new(10.0))
        }
    }

    impl crate::backend::sealed::Sealed for MockBackend {}

    impl crate::backend::Backend for MockBackend {
        fn viewport(&self) -> crate::event::Viewport {
            crate::event::Viewport::new(80.0, 24.0, 1.0)
        }
        fn begin_frame(&mut self, _: crate::event::Viewport) {}
        fn end_frame(&mut self) {}
        fn poll_events(&mut self) -> Vec<UiEvent> {
            Vec::new()
        }
        fn wait_events(&mut self, _: std::time::Duration) -> Vec<UiEvent> {
            Vec::new()
        }
        fn waker(&self) -> std::sync::Arc<dyn Fn(crate::UserPayload) + Send + Sync> {
            // No event loop for a wake to reach — matches `poll_events`/
            // `wait_events` above.
            std::sync::Arc::new(|_payload| {})
        }
        fn request_frame_in(&self, _delay: std::time::Duration) {
            // No event loop to wake, same rationale as `waker` above.
        }
        fn register_accelerator(&mut self, _: &crate::accelerator::Accelerator) {}
        fn unregister_accelerator(&mut self, _: &crate::accelerator::AcceleratorId) {}
        fn invalidate_rect(&mut self, rect: crate::event::Rect) {
            self.invalidation_log.push(rect);
        }
        fn invalidation_log(&self) -> &crate::backend::InvalidationLog {
            &self.invalidation_log
        }
        fn modal_stack_handle(&self) -> std::rc::Rc<std::cell::RefCell<crate::ModalStack>> {
            self.modal_stack.clone()
        }
        fn drag_state_handle(&self) -> std::rc::Rc<std::cell::RefCell<crate::DragState>> {
            self.drag_state.clone()
        }
        fn focus_manager(&self) -> &crate::focus::FocusManager {
            &self.focus
        }
        fn draw_focus_ring(&mut self, _r: Rect) {}
        fn services(&self) -> &dyn crate::backend::PlatformServices {
            unimplemented!()
        }
        fn backend_caps(&self) -> crate::backend::BackendCaps {
            crate::backend::BackendCaps {
                native_menu: self.native_menu_bar,
                ..crate::backend::BackendCaps::empty()
            }
        }
        fn line_height(&self) -> f32 {
            1.0
        }
        fn char_width(&self) -> f32 {
            1.0
        }
        fn list_char_width(&self) -> f32 {
            1.0
        }
        fn measure_text(&self, text: &str, _role: crate::FontRole) -> (f32, f32) {
            (text.chars().count() as f32, 1.0)
        }
        fn default_fonts(&self) -> crate::backend::PlatformFontDefaults {
            crate::backend::PlatformFontDefaults {
                editor_family: String::new(),
                editor_size_pt: 0.0,
                ui_family: String::new(),
                ui_size_pt: 0.0,
            }
        }
        fn menu_bar_layout(&self, rect: Rect, bar: &crate::MenuBar) -> crate::MenuBarLayout {
            self.mock_menu_bar_layout(rect, bar)
        }
        fn draw_menu_bar(&mut self, rect: Rect, bar: &crate::MenuBar) -> crate::MenuBarLayout {
            self.mock_menu_bar_layout(rect, bar)
        }
        fn draw_tree(&mut self, _r: Rect, _t: &crate::TreeView) {}
        fn draw_list(&mut self, _r: Rect, _l: &crate::ListView) {}
        fn draw_data_table(
            &mut self,
            _r: Rect,
            _t: &crate::DataTable,
            _h: Option<usize>,
        ) -> crate::DataTableLayout {
            unimplemented!()
        }
        fn data_table_layout(&self, _r: Rect, _t: &crate::DataTable) -> crate::DataTableLayout {
            unimplemented!()
        }
        fn list_hscrollbar(&self, _r: Rect, _l: &crate::ListView) -> Option<crate::Scrollbar> {
            None
        }
        fn list_vscrollbar(&self, _r: Rect, _l: &crate::ListView) -> Option<crate::Scrollbar> {
            None
        }
        fn list_layout(&self, r: Rect, l: &crate::ListView) -> crate::ListViewLayout {
            l.layout(r.width, r.height, 0.0, |_| {
                crate::primitives::list::ListItemMeasure::new(1.0)
            })
        }
        fn draw_form(&mut self, _r: Rect, _f: &crate::Form) {}
        fn draw_palette(&mut self, _r: Rect, _p: &crate::Palette) {}
        fn palette_layout(&self, r: Rect, p: &crate::Palette) -> crate::PaletteLayout {
            p.layout(r.width, r.height, 0.0, 0.0, 0.0, 1.0, |_| {
                crate::PaletteItemMeasure::new(1.0)
            })
        }
        fn draw_settings_chrome(
            &mut self,
            _r: Rect,
            _header_text: &str,
            _query: &str,
            _placeholder: &str,
            _active: bool,
        ) {
        }
        fn draw_status_bar_interactive(
            &mut self,
            _r: Rect,
            _b: &crate::primitives::status_bar::StatusBar,
            _interaction: &crate::interaction::InteractionState,
        ) -> crate::StatusBarLayout {
            unimplemented!()
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn draw_tab_bar(
            &mut self,
            _r: Rect,
            _b: &crate::TabBar,
            _h: Option<usize>,
        ) -> crate::TabBarHits {
            unimplemented!()
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn draw_tab_bar_icons(
            &mut self,
            _r: Rect,
            _b: &crate::TabBar,
            _icons: &[Option<crate::TabIcon>],
            _h: Option<usize>,
        ) -> crate::TabBarHits {
            unimplemented!()
        }
        fn draw_tab_bar_layout(
            &mut self,
            _r: Rect,
            _b: &crate::TabBar,
            _h: Option<usize>,
        ) -> crate::TabBarLayout {
            unimplemented!()
        }
        fn draw_tab_bar_icons_layout(
            &mut self,
            _r: Rect,
            _b: &crate::TabBar,
            _icons: &[Option<crate::TabIcon>],
            _h: Option<usize>,
        ) -> crate::TabBarLayout {
            unimplemented!()
        }
        fn draw_activity_bar(
            &mut self,
            _r: Rect,
            _b: &crate::primitives::activity_bar::ActivityBar,
            _h: Option<usize>,
        ) -> Vec<crate::primitives::activity_bar::ActivityBarRowHit> {
            unimplemented!()
        }
        fn draw_terminal(&mut self, _r: Rect, _t: &crate::Terminal) {}
        fn draw_terminal_divider(&mut self, _r: Rect) {}
        fn draw_solid_fill(&mut self, _r: Rect, _c: crate::Color) {}
        fn draw_text_display(&mut self, _r: Rect, _t: &crate::TextDisplay) {}
        fn draw_command_line(&mut self, _r: Rect, _c: &crate::CommandLine) {}
        fn draw_command_line_selection(
            &mut self,
            _r: Rect,
            _c: &crate::CommandLine,
            _s: Option<(usize, usize)>,
        ) {
        }
        fn command_line_layout(
            &self,
            _r: Rect,
            _c: &crate::CommandLine,
        ) -> crate::primitives::command_line::CommandLineLayout {
            Default::default()
        }
        fn status_bar_layout(&self, _r: Rect, _b: &crate::StatusBar) -> crate::StatusBarLayout {
            crate::StatusBarLayout {
                bar_width: 0.0,
                bar_height: 0.0,
                visible_segments: Vec::new(),
                hit_regions: Vec::new(),
                resolved_right_start: 0,
            }
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn tab_bar_layout(&self, _r: Rect, _b: &crate::TabBar) -> crate::TabBarHits {
            crate::TabBarHits::default()
        }
        fn resolve_tab_bar_layout(&self, _r: Rect, _b: &crate::TabBar) -> crate::TabBarLayout {
            crate::TabBarLayout {
                bar_width: 0.0,
                bar_height: 0.0,
                visible_tabs: Vec::new(),
                visible_segments: Vec::new(),
                scroll_left: None,
                scroll_right: None,
                hit_regions: Vec::new(),
                resolved_scroll_offset: 0,
            }
        }
        fn resolve_tab_bar_layout_icons(
            &self,
            _r: Rect,
            _b: &crate::TabBar,
            _icons: &[Option<crate::TabIcon>],
        ) -> crate::TabBarLayout {
            crate::TabBarLayout {
                bar_width: 0.0,
                bar_height: 0.0,
                visible_tabs: Vec::new(),
                visible_segments: Vec::new(),
                scroll_left: None,
                scroll_right: None,
                hit_regions: Vec::new(),
                resolved_scroll_offset: 0,
            }
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn tab_bar_layout_icons(
            &self,
            _r: Rect,
            _b: &crate::TabBar,
            _icons: &[Option<crate::TabIcon>],
        ) -> crate::TabBarHits {
            crate::TabBarHits::default()
        }
        fn activity_bar_layout(
            &self,
            _r: Rect,
            _b: &crate::primitives::activity_bar::ActivityBar,
        ) -> Vec<crate::ActivityBarRowHit> {
            Vec::new()
        }
        fn text_display_layout(
            &self,
            _r: Rect,
            _t: &crate::TextDisplay,
        ) -> crate::TextDisplayLayout {
            unimplemented!()
        }
        fn draw_text_input(&mut self, _r: Rect, _t: &crate::TextInput) -> crate::TextInputLayout {
            unimplemented!()
        }
        fn text_input_layout(&self, _r: Rect, _t: &crate::TextInput) -> crate::TextInputLayout {
            unimplemented!()
        }
        fn draw_number_input(&mut self, _n: &crate::NumberInput, _l: &crate::NumberInputLayout) {}
        fn draw_combo_box(&mut self, _c: &crate::ComboBox, _l: &crate::ComboBoxLayout) {}
        fn draw_date_picker(&mut self, _d: &crate::DatePicker, _l: &crate::DatePickerLayout) {}
        fn draw_tooltip(&mut self, _t: &crate::Tooltip, _l: &crate::TooltipLayout) {}
        fn draw_context_menu(
            &mut self,
            _m: &crate::ContextMenu,
            _l: &crate::ContextMenuLayout,
        ) -> Vec<(Rect, WidgetId)> {
            Vec::new()
        }
        fn draw_dialog(&mut self, _d: &crate::Dialog, _l: &crate::DialogLayout) -> Vec<Rect> {
            unimplemented!()
        }
        fn draw_multi_section_view(&mut self, _r: Rect, _v: &crate::MultiSectionView) {}
        fn msv_layout(
            &self,
            _r: Rect,
            _v: &crate::MultiSectionView,
        ) -> crate::MultiSectionViewLayout {
            unimplemented!()
        }
        fn msv_metrics(&self) -> crate::primitives::multi_section_view::MsvLayoutMetrics {
            unimplemented!()
        }
        fn tree_layout(
            &self,
            rect: Rect,
            tree: &crate::TreeView,
        ) -> crate::primitives::tree::TreeViewLayout {
            let lh = self.line_height();
            let indent_cells = tree.style.indent as f32;
            let chevron_w = if tree.style.show_chevrons {
                tree.style.chevron_expanded.chars().count() as f32 + 1.0
            } else {
                0.0
            };
            tree.layout(rect.width, rect.height, |i| {
                let row = &tree.rows[i];
                let chevron_end_x = if row.is_expanded.is_some() && chevron_w > 0.0 {
                    Some(row.indent as f32 * indent_cells + chevron_w)
                } else {
                    None
                };
                crate::primitives::tree::TreeRowMeasure {
                    height: lh,
                    chevron_end_x,
                }
            })
        }
        fn tree_vscrollbar(&self, _r: Rect, _t: &crate::TreeView) -> Option<crate::Scrollbar> {
            None
        }
        fn form_layout(&self, _r: Rect, _f: &crate::Form) -> crate::primitives::form::FormLayout {
            unimplemented!()
        }
        fn draw_editor(
            &mut self,
            _r: Rect,
            _e: &crate::primitives::editor::Editor,
        ) -> crate::backend::EditorPaintResult {
            Default::default()
        }
        fn draw_message_list(
            &mut self,
            _r: Rect,
            _l: &crate::primitives::message_list::MessageList,
        ) {
        }
        fn draw_rich_text_popup(
            &mut self,
            _p: &crate::RichTextPopup,
            _l: &crate::primitives::rich_text_popup::RichTextPopupLayout,
        ) {
        }
        fn draw_find_replace(
            &mut self,
            _r: Rect,
            _p: &crate::primitives::find_replace::FindReplacePanel,
        ) {
        }
        fn draw_completions(
            &mut self,
            _c: &crate::Completions,
            _l: &crate::primitives::completions::CompletionsLayout,
        ) {
        }
        fn draw_scrollbar(&mut self, _r: Rect, _s: &crate::Scrollbar) {}
        fn draw_drop_overlay(&mut self, _o: &crate::primitives::drop_zone::DropOverlay) {}
        fn draw_split(&mut self, _r: Rect, _s: &crate::Split) -> crate::SplitLayout {
            unimplemented!()
        }
        fn split_layout(&self, _r: Rect, _s: &crate::Split) -> crate::SplitLayout {
            unimplemented!()
        }
        fn draw_split_tree(&mut self, _r: Rect, _t: &crate::SplitTree) -> crate::SplitTreeLayout {
            unimplemented!()
        }
        fn split_tree_layout(&self, _r: Rect, _t: &crate::SplitTree) -> crate::SplitTreeLayout {
            unimplemented!()
        }
        fn draw_panel(&mut self, _r: Rect, _p: &crate::Panel) -> crate::PanelLayout {
            unimplemented!()
        }
        fn panel_layout(&self, _r: Rect, _p: &crate::Panel) -> crate::PanelLayout {
            unimplemented!()
        }
        fn draw_canvas(&mut self, _r: Rect, _c: &crate::Canvas) -> crate::CanvasLayout {
            unimplemented!()
        }
        fn draw_float(&mut self, _f: &crate::Float, _l: &crate::FloatLayout) {
            unimplemented!()
        }
        fn draw_toast_overlay(
            &mut self,
            _r: Rect,
            _s: &crate::ToastOverlay,
        ) -> crate::ToastStackLayout {
            unimplemented!()
        }
        fn toast_stack_layout(
            &self,
            _r: Rect,
            _s: &crate::ToastOverlay,
        ) -> crate::ToastStackLayout {
            unimplemented!()
        }
        fn draw_pipeline_view(
            &mut self,
            _r: Rect,
            _v: &crate::PipelineView,
        ) -> crate::PipelineViewLayout {
            unimplemented!()
        }
        fn pipeline_view_layout(
            &self,
            _r: Rect,
            _v: &crate::PipelineView,
        ) -> crate::PipelineViewLayout {
            unimplemented!()
        }
        fn draw_progress(&mut self, _r: Rect, _b: &crate::ProgressBar) -> crate::ProgressBarLayout {
            unimplemented!()
        }
        fn progress_layout(&self, _r: Rect, _b: &crate::ProgressBar) -> crate::ProgressBarLayout {
            unimplemented!()
        }
        fn draw_spinner(&mut self, _r: Rect, _s: &crate::Spinner) -> crate::SpinnerLayout {
            unimplemented!()
        }
        fn spinner_layout(&self, _r: Rect, _s: &crate::Spinner) -> crate::SpinnerLayout {
            unimplemented!()
        }
        fn draw_button(&mut self, _r: Rect, _b: &crate::Button) -> crate::ButtonLayout {
            unimplemented!()
        }
        fn button_layout(&self, _r: Rect, _b: &crate::Button) -> crate::ButtonLayout {
            unimplemented!()
        }
        fn draw_radio_group(
            &mut self,
            _r: Rect,
            _g: &crate::RadioGroup,
        ) -> crate::RadioGroupLayout {
            unimplemented!()
        }
        fn radio_group_layout(&self, _r: Rect, _g: &crate::RadioGroup) -> crate::RadioGroupLayout {
            unimplemented!()
        }
        fn draw_switch(&mut self, _r: Rect, _s: &crate::Switch) -> crate::SwitchLayout {
            unimplemented!()
        }
        fn switch_layout(&self, _r: Rect, _s: &crate::Switch) -> crate::SwitchLayout {
            unimplemented!()
        }
        fn draw_command_center(
            &mut self,
            _r: Rect,
            _c: &crate::CommandCenter,
        ) -> crate::CommandCenterLayout {
            unimplemented!()
        }
        fn command_center_layout(
            &self,
            _r: Rect,
            _c: &crate::CommandCenter,
        ) -> crate::CommandCenterLayout {
            unimplemented!()
        }
        fn draw_toolbar_with_options(
            &mut self,
            _r: Rect,
            _b: &crate::primitives::toolbar::Toolbar,
            _interaction: &crate::interaction::InteractionState,
            _options: crate::primitives::toolbar::ToolbarPaintOptions,
        ) -> crate::primitives::toolbar::ToolbarLayout {
            unimplemented!()
        }
        fn toolbar_layout(
            &self,
            _r: Rect,
            _b: &crate::primitives::toolbar::Toolbar,
        ) -> crate::primitives::toolbar::ToolbarLayout {
            unimplemented!()
        }
        fn draw_sidebar_panel_interactive(
            &mut self,
            _r: Rect,
            _p: &crate::primitives::sidebar_panel::SidebarPanel,
            _interaction: &crate::interaction::InteractionState,
        ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
            unimplemented!()
        }
        fn sidebar_panel_layout(
            &self,
            _r: Rect,
            _p: &crate::primitives::sidebar_panel::SidebarPanel,
        ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
            unimplemented!()
        }
        fn draw_diff_view(
            &mut self,
            _r: Rect,
            view: &crate::primitives::diff_view::DiffView,
        ) -> crate::primitives::diff_view::DiffViewLayout {
            crate::primitives::diff_view::DiffViewLayout {
                visible_rows: 0,
                total_rows: view.total_rows(),
            }
        }
        fn draw_chart(
            &mut self,
            _r: Rect,
            _c: &crate::primitives::chart::Chart,
            _h: Option<(usize, usize)>,
            _x: Option<f64>,
        ) -> crate::primitives::chart::ChartLayout {
            unimplemented!()
        }
        fn chart_layout(
            &self,
            _r: Rect,
            _c: &crate::primitives::chart::Chart,
        ) -> crate::primitives::chart::ChartLayout {
            unimplemented!()
        }

        fn draw_board(
            &mut self,
            _r: Rect,
            _m: &crate::primitives::board::BoardModel,
        ) -> crate::primitives::board::BoardLayout {
            crate::primitives::board::BoardLayout {
                bounds: crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height),
                columns: vec![],
            }
        }

        fn board_layout(
            &self,
            _r: Rect,
            _m: &crate::primitives::board::BoardModel,
        ) -> crate::primitives::board::BoardLayout {
            crate::primitives::board::BoardLayout {
                bounds: crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height),
                columns: vec![],
            }
        }

        fn draw_minimap(
            &mut self,
            _r: Rect,
            _m: &crate::primitives::minimap::Minimap,
        ) -> crate::backend::MinimapPaintResult {
            crate::backend::MinimapPaintResult::default()
        }

        fn minimap_layout(
            &self,
            _r: Rect,
            _m: &crate::primitives::minimap::Minimap,
        ) -> crate::primitives::minimap::MinimapLayout {
            crate::primitives::minimap::MinimapLayout::default()
        }

        fn draw_image(
            &mut self,
            _r: Rect,
            _i: &crate::primitives::image::Image,
        ) -> crate::backend::ImagePaintResult {
            crate::backend::ImagePaintResult::Unsupported
        }
    }

    // Helper: construct a `KeyPressed` event with no modifiers.
    fn key_ev(key: Key) -> UiEvent {
        UiEvent::KeyPressed {
            key,
            modifiers: Modifiers::default(),
            repeat: false,
        }
    }

    // Standard bar rect used by all handle() tests.
    fn bar_rect() -> Rect {
        Rect::new(0.0, 0.0, 80.0, 1.0)
    }

    fn action(id: &str, label: &str) -> ContextMenuItem {
        ContextMenuItem {
            id: Some(WidgetId::new(id)),
            label: StyledText::plain(label),
            ..Default::default()
        }
    }

    fn separator() -> ContextMenuItem {
        ContextMenuItem::default()
    }

    /// `dropdown_width` must track the real content of each item it's
    /// given: a menu with a much longer label must come back wider.
    #[test]
    fn dropdown_width_tracks_the_longest_label() {
        let backend = MockBackend::new();
        let short = [action("a", "Undo")];
        let long = [action("a", "Undo Last 20 Changes")];

        let short_w = dropdown_width(&backend, &short, 1.0);
        let long_w = dropdown_width(&backend, &long, 1.0);
        assert!(
            long_w > short_w,
            "a longer label must widen the dropdown: short={short_w}, long={long_w}"
        );
    }

    /// A `checked` item's leading `✓ ` slot and a submenu item's trailing
    /// `▶` arrow must each widen the result beyond the bare label width —
    /// otherwise the glyph would overlap the label or get clipped.
    #[test]
    fn dropdown_width_reserves_space_for_checked_prefix_and_submenu_arrow() {
        let backend = MockBackend::new();
        let plain = [action("a", "Word Wrap")];
        let mut checked = plain.clone();
        checked[0].checked = Some(true);
        let mut with_submenu = plain.clone();
        with_submenu[0].submenu = Some(vec![action("b", "On")]);

        let plain_w = dropdown_width(&backend, &plain, 1.0);
        let checked_w = dropdown_width(&backend, &checked, 1.0);
        let submenu_w = dropdown_width(&backend, &with_submenu, 1.0);

        assert!(checked_w > plain_w, "checked={checked_w}, plain={plain_w}");
        assert!(submenu_w > plain_w, "submenu={submenu_w}, plain={plain_w}");
    }

    /// Separators never gate the width computation on their own (empty)
    /// label — a menu that is otherwise all separators plus one real item
    /// must size off that one item, not panic or report `0.0`.
    #[test]
    fn dropdown_width_ignores_separators() {
        let backend = MockBackend::new();
        let items = [separator(), action("a", "Save All"), separator()];
        let w = dropdown_width(&backend, &items, 1.0);
        assert!(w > 0.0);
    }

    fn sample_menus() -> Vec<MenuDef> {
        vec![
            MenuDef {
                id: WidgetId::new("file"),
                label: "&File".into(),
                disabled: false,
                items: vec![
                    action("new", "New File"),
                    action("save", "Save"),
                    separator(),
                    action("quit", "Quit"),
                ],
            },
            MenuDef {
                id: WidgetId::new("edit"),
                label: "&Edit".into(),
                disabled: false,
                items: vec![action("undo", "Undo"), action("redo", "Redo")],
            },
            MenuDef {
                id: WidgetId::new("help"),
                label: "&Help".into(),
                disabled: true,
                items: vec![],
            },
        ]
    }

    /// A native `NSMenu` activation (`UiEvent::MenuActivated`,
    /// what AppKit reports once `Backend::draw_menu_bar` installs rather
    /// than paints) must translate to the same `MenuEvent::Activated` the
    /// painted dropdown path produces — same shape as
    /// `ContextMenuController` already uses for its own native event —
    /// so consumer code written against `MenuEvent::Activated` works
    /// unchanged under either `MenuStyle`. The menu need not be "open"
    /// in this struct's own sense at all; the native path has no
    /// in-struct open/dropdown state, only AppKit's own.
    #[test]
    fn handle_routes_native_menu_activated_to_menu_event_activated() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();
        assert!(
            !ms.is_open(),
            "native path never opens the struct's own dropdown state"
        );

        let ev = UiEvent::MenuActivated(WidgetId::new("save"));
        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::Activated(WidgetId::new("save")));
    }

    fn alt_key_ev(c: char) -> UiEvent {
        UiEvent::KeyPressed {
            key: Key::Char(c),
            modifiers: Modifiers {
                alt: true,
                ..Modifiers::default()
            },
            repeat: false,
        }
    }

    /// On a backend that paints its own menu bar, the mnemonic
    /// underlines are real, so Alt+the access key opens that menu's
    /// in-window dropdown.
    #[test]
    fn alt_char_opens_the_painted_menu_bars_dropdown() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();

        let result = ms.handle(&alt_key_ev('f'), &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::StateChanged);
        assert_eq!(ms.open_item, Some(0));
        assert!(
            ms.dropdown_layout(&backend, bar_rect()).is_some(),
            "an opened menu must have a dropdown to paint"
        );
    }

    /// With a platform-owned menu bar there are no painted mnemonic
    /// underlines and no in-window strip to anchor a dropdown under, so
    /// Alt+char is reported `Ignored` and leaves the system closed —
    /// rather than opening an invisible dropdown whose anchor item does
    /// not exist in the layout.
    #[test]
    fn alt_char_is_ignored_when_the_menu_bar_is_native() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::with_native_menu_bar();
        assert_eq!(
            crate::backend::Backend::effective_menu_style(&backend),
            ResolvedMenuStyle::Native,
            "mock must resolve the native style for this to cover anything"
        );

        let result = ms.handle(&alt_key_ev('f'), &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::Ignored);
        assert!(!ms.is_open());
        assert_eq!(ms.open_item, None);
    }

    /// A host may switch menu style at runtime (`Backend::set_menu_style`)
    /// while a painted dropdown is open. The next frame's layout then has
    /// no visible items at all, and both rendering and layout must
    /// degrade to "no dropdown" instead of indexing past that empty list.
    #[test]
    fn menu_bar_turning_native_while_open_paints_no_dropdown() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();
        ms.handle(&alt_key_ev('f'), &mut backend, bar_rect());
        assert!(ms.is_open());

        backend.native_menu_bar = true;

        ms.render(&mut backend, bar_rect());
        assert!(
            ms.dropdown_layout(&backend, bar_rect()).is_none(),
            "no visible bar item to anchor under means no dropdown"
        );
        assert!(
            ms.dropdown_stack(&backend, bar_rect()).is_empty(),
            "an empty root dropdown must not leave submenu levels behind"
        );
    }

    #[test]
    fn new_menu_system_starts_closed() {
        let ms = MenuSystem::new(sample_menus());
        assert!(!ms.is_open());
        assert_eq!(ms.open_item, None);
        assert_eq!(ms.focused_item, None);
    }

    #[test]
    fn set_menus_replaces_definitions() {
        let mut ms = MenuSystem::new(sample_menus());
        assert_eq!(ms.menus.len(), 3);
        ms.set_menus(vec![MenuDef {
            id: WidgetId::new("only"),
            label: "Only".into(),
            disabled: false,
            items: vec![action("a", "A")],
        }]);
        assert_eq!(ms.menus.len(), 1);
    }

    #[test]
    fn next_enabled_menu_skips_disabled() {
        let ms = MenuSystem::new(sample_menus());
        // help (idx 2) is disabled, so from edit (1) forward wraps to file (0)
        assert_eq!(ms.next_enabled_menu(1, 1), 0);
        // from file (0) backward wraps past help to edit (1)
        assert_eq!(ms.next_enabled_menu(0, -1), 1);
    }

    #[test]
    fn build_menu_bar_reflects_state() {
        let mut ms = MenuSystem::new(sample_menus());
        ms.open_item = Some(1);
        ms.focused_item = Some(1);
        let bar = ms.build_menu_bar();
        assert_eq!(bar.items.len(), 3);
        assert_eq!(bar.open_item, Some(1));
        assert_eq!(bar.focused_item, Some(1));
        assert!(bar.items[2].disabled);
    }

    #[test]
    fn build_dropdown_uses_selected_idx() {
        let mut ms = MenuSystem::new(sample_menus());
        ms.dropdown_selected = 2;
        let dd = ms.build_dropdown(0);
        assert_eq!(dd.selected_idx, 2);
        assert_eq!(dd.items.len(), 4);
    }

    // ── Submenu state helpers ─────────────────────────────────────────

    fn menus_with_submenu() -> Vec<MenuDef> {
        vec![MenuDef {
            id: WidgetId::new("view"),
            label: "&View".into(),
            disabled: false,
            items: vec![
                action("sidebar", "Toggle Sidebar"),
                ContextMenuItem {
                    id: Some(WidgetId::new("export")),
                    label: StyledText::plain("Export"),
                    submenu: Some(vec![
                        action("export-png", "PNG"),
                        action("export-svg", "SVG"),
                    ]),
                    ..Default::default()
                },
                action("zoom", "Zoom In"),
            ],
        }]
    }

    #[test]
    fn items_at_depth_zero_returns_root_items() {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        let items = ms.items_at_depth(0).unwrap();
        assert_eq!(items.len(), 3);
        assert_eq!(items[0].id, Some(WidgetId::new("sidebar")));
    }

    #[test]
    fn items_at_depth_one_returns_submenu_items() {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        ms.submenu_path = vec![1]; // item 1 ("Export") has a submenu
        let items = ms.items_at_depth(1).unwrap();
        assert_eq!(items.len(), 2);
        assert_eq!(items[0].id, Some(WidgetId::new("export-png")));
    }

    #[test]
    fn open_submenu_pushes_path_and_first_selectable() {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        ms.dropdown_selected = 1; // "Export" is selected
        ms.open_submenu(1);
        assert_eq!(ms.submenu_path, vec![1]);
        assert_eq!(ms.submenu_selected, vec![0]); // first selectable in PNG/SVG
    }

    #[test]
    fn close_deepest_submenu_pops_one_level() {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        ms.submenu_path = vec![1];
        ms.submenu_selected = vec![0];
        ms.close_deepest_submenu();
        assert!(ms.submenu_path.is_empty());
        assert!(ms.submenu_selected.is_empty());
    }

    #[test]
    fn current_selected_returns_root_when_no_submenus() {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        ms.dropdown_selected = 2;
        assert_eq!(ms.current_selected(), 2);
    }

    #[test]
    fn current_selected_returns_deepest_submenu_selection() {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        ms.dropdown_selected = 1;
        ms.submenu_path = vec![1];
        ms.submenu_selected = vec![1];
        assert_eq!(ms.current_selected(), 1);
    }

    // ── Keyboard-nav interaction tests (flow through handle()) ────────────────

    // Fixture: menus_with_submenu(), but the root dropdown is "open" so that
    // keyboard events are processed.  We set open_item directly (bypassing the
    // modal-stack push that open_menu does) because these tests focus on
    // navigation state, not on rendering.
    fn open_ms() -> MenuSystem {
        let mut ms = MenuSystem::new(menus_with_submenu());
        ms.open_item = Some(0);
        ms.dropdown_selected = 1; // pre-select "Export" (item 1, has submenu)
        ms
    }

    /// `Right` on a submenu-parent item must push the path and return `StateChanged`.
    #[test]
    fn handle_right_on_submenu_parent_opens_submenu() {
        let mut ms = open_ms();
        let mut backend = MockBackend::new();
        let ev = key_ev(Key::Named(NamedKey::Right));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(
            result,
            MenuEvent::StateChanged,
            "Right must return StateChanged"
        );
        assert_eq!(ms.submenu_path, vec![1], "submenu_path must grow to [1]");
        assert!(
            ms.open_item.is_some(),
            "menu must still be open after Right"
        );
    }

    /// `Left` with a submenu open must pop one level and return `StateChanged`.
    #[test]
    fn handle_left_with_submenu_open_closes_deepest() {
        let mut ms = open_ms();
        ms.submenu_path = vec![1];
        ms.submenu_selected = vec![0];
        let mut backend = MockBackend::new();
        let ev = key_ev(Key::Named(NamedKey::Left));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(
            result,
            MenuEvent::StateChanged,
            "Left must return StateChanged"
        );
        assert!(
            ms.submenu_path.is_empty(),
            "submenu_path must shrink back to []"
        );
        assert!(ms.open_item.is_some(), "top-level menu must remain open");
    }

    /// `Esc` with a submenu open must close only the deepest level — NOT the
    /// whole menu.
    #[test]
    fn handle_esc_with_submenu_closes_deepest_not_whole_menu() {
        let mut ms = open_ms();
        ms.submenu_path = vec![1];
        ms.submenu_selected = vec![0];
        let mut backend = MockBackend::new();
        let ev = key_ev(Key::Named(NamedKey::Escape));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::StateChanged);
        assert!(ms.submenu_path.is_empty(), "deepest submenu must be closed");
        assert!(ms.open_item.is_some(), "top-level menu must still be open");
    }

    /// `Esc` with no submenus open must close the whole menu.
    #[test]
    fn handle_esc_with_no_submenu_closes_whole_menu() {
        let mut ms = open_ms();
        // No submenus open — submenu_path is empty.
        let mut backend = MockBackend::new();
        let ev = key_ev(Key::Named(NamedKey::Escape));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::StateChanged);
        assert!(ms.open_item.is_none(), "whole menu must be closed");
        assert!(ms.submenu_path.is_empty());
    }

    /// `Enter` on a submenu-parent must open the child — NOT activate the item.
    #[test]
    fn handle_enter_on_submenu_parent_opens_child() {
        let mut ms = open_ms(); // dropdown_selected = 1 ("Export" with submenu)
        let mut backend = MockBackend::new();
        let ev = key_ev(Key::Named(NamedKey::Enter));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(
            result,
            MenuEvent::StateChanged,
            "Enter on parent must return StateChanged"
        );
        assert_eq!(ms.submenu_path, vec![1], "submenu must open for item 1");
        assert!(ms.open_item.is_some(), "menu must remain open");
    }

    /// `Enter` on a leaf item inside an open submenu must activate it and close
    /// the whole menu.
    #[test]
    fn handle_enter_on_leaf_in_submenu_activates_and_closes() {
        let mut ms = open_ms();
        // Open the submenu for "Export" (item 1) and select "PNG" (item 0 inside).
        ms.submenu_path = vec![1];
        ms.submenu_selected = vec![0]; // "PNG" (id = "export-png")
        let mut backend = MockBackend::new();
        let ev = key_ev(Key::Named(NamedKey::Enter));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(
            result,
            MenuEvent::Activated(WidgetId::new("export-png")),
            "Enter on leaf must return Activated with the item id"
        );
        assert!(ms.open_item.is_none(), "menu must close after activation");
        assert!(
            ms.submenu_path.is_empty(),
            "submenu_path must be cleared on close"
        );
    }

    // ── MouseUp outside-click dismiss ──────────────────────────────────────

    fn mouse_up_ev(position: crate::event::Point) -> UiEvent {
        UiEvent::MouseUp {
            widget: None,
            button: MouseButton::Left,
            position,
        }
    }

    /// `MouseUp(Left)` landing outside the menu bar and outside every open
    /// dropdown level must close the menu — this is the fix for terminals
    /// that drop `MouseDown(Left)` and only deliver `MouseUp(Left)`.
    #[test]
    fn handle_mouse_up_outside_everything_closes_menu() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();
        ms.open_menu(0, &mut backend, bar_rect());
        assert!(ms.open_item.is_some());

        // Far outside the bar (height 1) and outside the viewport-clamped
        // dropdown.
        let ev = mouse_up_ev(crate::event::Point::new(999.0, 999.0));
        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::StateChanged);
        assert!(ms.open_item.is_none(), "menu must close on outside MouseUp");
    }

    /// `MouseUp(Left)` with no menu open must be a no-op `Ignored` — nothing
    /// to close, and no panic touching layout state.
    #[test]
    fn handle_mouse_up_with_no_menu_open_is_ignored() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();
        let ev = mouse_up_ev(crate::event::Point::new(999.0, 999.0));

        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::Ignored);
        assert!(ms.open_item.is_none());
    }

    /// `MouseUp(Left)` on the menu-bar item that `MouseDown` just opened
    /// must NOT immediately re-close the menu — that zone belongs to
    /// `MouseDown`, and closing here would defeat every normal
    /// (Down-then-Up) click-to-open.
    #[test]
    fn handle_mouse_up_on_bar_item_does_not_close() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();
        ms.open_menu(0, &mut backend, bar_rect());

        // Item 0 ("File") occupies x in [0, 10), y in [0, 1) per the mock
        // backend's 10.0-wide, single-row layout.
        let ev = mouse_up_ev(crate::event::Point::new(5.0, 0.0));
        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::Ignored);
        assert!(
            ms.open_item.is_some(),
            "menu must remain open after Up on the bar item that opened it"
        );
    }

    /// `MouseUp(Left)` landing on an actual open dropdown item must be
    /// ignored, not re-activated — `MouseDown` already owns item
    /// activation, so this arm must not double-fire `Activated`.
    #[test]
    fn handle_mouse_up_on_open_dropdown_item_is_ignored() {
        let mut ms = MenuSystem::new(sample_menus());
        let mut backend = MockBackend::new();
        ms.open_menu(0, &mut backend, bar_rect());

        let stack = ms.dropdown_stack(&backend, bar_rect());
        let item_bounds = stack[0].1.visible_items[0].bounds;
        let pos = crate::event::Point::new(
            item_bounds.x + item_bounds.width / 2.0,
            item_bounds.y + item_bounds.height / 2.0,
        );

        let ev = mouse_up_ev(pos);
        let result = ms.handle(&ev, &mut backend, bar_rect());

        assert_eq!(result, MenuEvent::Ignored);
        assert!(
            ms.open_item.is_some(),
            "menu must remain open — MouseUp must not activate or close"
        );
    }
}