saudade 0.4.0

Classic looking retained-mode, cross-platform Rust GUI library
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
use crate::event::{Event, EventCtx, Key, Modifiers, MouseButton, NamedKey};
use crate::geometry::{Color, Point, Rect};
use crate::painter::Painter;
use crate::theme::Theme;
use crate::widget::{PopupKind, PopupRequest, Widget};
use crate::widgets::mnemonic::{draw_label_with_mnemonic, parse_label};

const BAR_PADDING: i32 = 8;
/// Top inset for the label baseline inside the bar. Tight enough that the
/// 13-pt menu font fits in a 20-px bar without growing it.
const BAR_LABEL_INSET_Y: i32 = 1;
const POPUP_PADDING_X: i32 = 18;
const POPUP_PADDING_Y: i32 = 3;
const ITEM_HEIGHT: i32 = 18;
/// Gap between an item's label and its right-aligned accelerator hint.
const ACCEL_GAP: i32 = 24;
const ITEM_TEXT_INSET_Y: i32 = 1;
const SEPARATOR_HEIGHT: i32 = 6;
const SHADOW_SIZE: i32 = 2;
/// L-shape drop shadow color: a dark gray with no alpha trickery so it
/// renders crisply on every backend.
const SHADOW_COLOR: Color = Color::rgb(0x40, 0x40, 0x40);

/// One entry inside a drop-down [`Menu`].
pub enum MenuItem {
    Action {
        /// Raw label as supplied; may contain `&X` to mark the mnemonic.
        label: String,
        /// Optional accelerator hint (e.g. `"Ctrl+Enter"`) shown right-aligned
        /// in the drop-down. Display only — the binding itself is wired by the
        /// application; the menu never acts on it.
        accel: Option<String>,
        callback: Box<dyn FnMut(&mut EventCtx)>,
    },
    Separator,
}

impl MenuItem {
    pub fn action<F>(label: impl Into<String>, callback: F) -> Self
    where
        F: FnMut(&mut EventCtx) + 'static,
    {
        MenuItem::Action {
            label: label.into(),
            accel: None,
            callback: Box::new(callback),
        }
    }

    /// Attach a right-aligned accelerator hint to an action item, advertising
    /// the keyboard shortcut the application binds for it. No-op on separators.
    pub fn with_accel(mut self, accel: impl Into<String>) -> Self {
        if let MenuItem::Action { accel: slot, .. } = &mut self {
            *slot = Some(accel.into());
        }
        self
    }

    pub fn separator() -> Self {
        MenuItem::Separator
    }

    fn is_action(&self) -> bool {
        matches!(self, MenuItem::Action { .. })
    }

    fn height(&self) -> i32 {
        match self {
            MenuItem::Action { .. } => ITEM_HEIGHT,
            MenuItem::Separator => SEPARATOR_HEIGHT,
        }
    }
}

pub struct Menu {
    pub label: String,
    pub items: Vec<MenuItem>,
}

impl Menu {
    pub fn new(label: impl Into<String>, items: Vec<MenuItem>) -> Self {
        Self {
            label: label.into(),
            items,
        }
    }
}

#[derive(Default, Clone)]
struct Cache {
    /// (x, width) per top-level menu label.
    label_rects: Vec<(i32, i32)>,
    /// Popup rect for the currently open menu, if any.
    popup: Option<Rect>,
}

/// A classic Win 3.1 menu bar.
///
/// `MenuBar::new` takes the bounding rect for the bar itself. The bar paints
/// in the normal pass; any open drop-down is rendered in the overlay pass so
/// it floats over every sibling widget.
///
/// Labels may include an `&` immediately before a character to declare a
/// mnemonic: `&File` displays "File" with **F** underlined and binds Alt+F
/// (top-level) or just F (when the menu is already open) to that entry.
/// Escape closes the open menu.
pub struct MenuBar {
    rect: Rect,
    menus: Vec<Menu>,
    open: Option<usize>,
    hovered_item: Option<usize>,
    /// True between the press-on-the-bar that opened the current menu and
    /// the matching release. Lets us implement classic drag-to-pick: press
    /// on `File`, drag down into the popup, release on an item → fire it.
    /// After the first release without a fire, we drop back into click
    /// mode where a separate click fires an item.
    drag_armed: bool,
    cache: Cache,
}

impl MenuBar {
    pub fn new(rect: Rect) -> Self {
        Self {
            rect,
            menus: Vec::new(),
            open: None,
            hovered_item: None,
            drag_armed: false,
            cache: Cache::default(),
        }
    }

    pub fn add_menu(mut self, menu: Menu) -> Self {
        self.menus.push(menu);
        self
    }

    pub fn push_menu(&mut self, menu: Menu) {
        self.menus.push(menu);
    }

    /// Programmatically open the menu at `index` — useful for tests and
    /// for hooking up custom keyboard shortcuts at the application level.
    pub fn open(&mut self, index: usize) {
        if index < self.menus.len() {
            self.open = Some(index);
            self.hovered_item = None;
        }
    }

    fn rebuild_label_rects(&mut self, painter: &Painter, theme: &Theme) {
        // First label butts up against the bar's left edge so its highlight
        // reaches the window edge when active; subsequent labels follow with
        // their own internal padding. Every label still carries `BAR_PADDING`
        // on both sides of its text for visual breathing room.
        self.cache.label_rects.clear();
        let mut x = self.rect.x;
        for menu in &self.menus {
            let parsed = parse_label(&menu.label);
            let w = painter.measure_text(&parsed.display, theme.font_size).w + BAR_PADDING * 2;
            self.cache.label_rects.push((x, w));
            x += w;
        }
    }

    fn compute_popup(&self, menu_idx: usize, painter: &Painter, theme: &Theme) -> Rect {
        let (lx, _lw) = self
            .cache
            .label_rects
            .get(menu_idx)
            .copied()
            .unwrap_or((self.rect.x, 0));
        let menu = &self.menus[menu_idx];

        let mut max_label = 0;
        let mut max_accel = 0;
        for item in &menu.items {
            if let MenuItem::Action { label, accel, .. } = item {
                let parsed = parse_label(label);
                let w = painter.measure_text(&parsed.display, theme.font_size).w;
                if w > max_label {
                    max_label = w;
                }
                if let Some(accel) = accel {
                    let aw = painter.measure_text(accel, theme.font_size).w;
                    if aw > max_accel {
                        max_accel = aw;
                    }
                }
            }
        }
        // The accelerator column only widens the popup when some item carries
        // one, so accelerator-free menus keep their original width.
        let accel_col = if max_accel > 0 {
            ACCEL_GAP + max_accel
        } else {
            0
        };
        let width = max_label + accel_col + POPUP_PADDING_X * 2;
        let mut height = POPUP_PADDING_Y * 2;
        for item in &menu.items {
            height += item.height();
        }
        Rect::new(lx, self.rect.y + self.rect.h, width, height)
    }

    fn hit_label(&self, pos: Point) -> Option<usize> {
        if pos.y < self.rect.y || pos.y >= self.rect.y + self.rect.h {
            return None;
        }
        self.cache
            .label_rects
            .iter()
            .position(|(x, w)| pos.x >= *x && pos.x < *x + *w)
    }

    fn hit_item(&self, pos: Point) -> Option<usize> {
        let popup = self.cache.popup?;
        if !popup.contains(pos) {
            return None;
        }
        let menu_idx = self.open?;
        let mut y = popup.y + POPUP_PADDING_Y;
        for (i, item) in self.menus[menu_idx].items.iter().enumerate() {
            let h = item.height();
            if pos.y >= y && pos.y < y + h {
                return if item.is_action() { Some(i) } else { None };
            }
            y += h;
        }
        None
    }

    fn fire(&mut self, item_idx: usize, ctx: &mut EventCtx) {
        let Some(menu_idx) = self.open else { return };
        if let Some(MenuItem::Action { callback, .. }) =
            self.menus[menu_idx].items.get_mut(item_idx)
        {
            callback(ctx);
        }
    }

    /// Find a top-level menu whose mnemonic matches the typed character.
    fn top_level_mnemonic(&self, ch: char) -> Option<usize> {
        let target = ch.to_ascii_lowercase();
        for (i, menu) in self.menus.iter().enumerate() {
            if parse_label(&menu.label).mnemonic_char == Some(target) {
                return Some(i);
            }
        }
        None
    }

    /// Find an action item in the currently-open menu whose mnemonic matches.
    fn item_mnemonic(&self, ch: char) -> Option<usize> {
        let menu_idx = self.open?;
        let target = ch.to_ascii_lowercase();
        for (i, item) in self.menus[menu_idx].items.iter().enumerate() {
            if let MenuItem::Action { label, .. } = item
                && parse_label(label).mnemonic_char == Some(target)
            {
                return Some(i);
            }
        }
        None
    }
}

impl Widget for MenuBar {
    fn bounds(&self) -> Rect {
        self.rect
    }

    fn paint(&mut self, painter: &mut Painter, theme: &Theme) {
        self.rebuild_label_rects(painter, theme);
        self.cache.popup = self.open.map(|idx| self.compute_popup(idx, painter, theme));

        // Bar background + 1-px shadow line along the bottom. The bar is
        // white to match Win 3.1's program-manager chrome — only the labels
        // and dropdowns carry color.
        painter.fill_rect(self.rect, theme.background);
        painter.h_line(
            self.rect.x,
            self.rect.bottom() - 1,
            self.rect.w,
            theme.shadow,
        );

        for (i, menu) in self.menus.iter().enumerate() {
            let (lx, lw) = self.cache.label_rects[i];
            let label_rect = Rect::new(lx, self.rect.y, lw, self.rect.h - 1);
            let parsed = parse_label(&menu.label);
            let (fg, draw_bg) = if self.open == Some(i) {
                (theme.highlight_text, true)
            } else {
                (theme.text, false)
            };
            if draw_bg {
                painter.fill_rect(label_rect, theme.highlight_bg);
            }
            // Bar labels are nudged down by one physical pixel so the cap
            // height has visible breathing room above without growing the
            // bar by a whole logical pixel.
            draw_label_with_mnemonic(
                painter,
                lx + BAR_PADDING,
                self.rect.y + BAR_LABEL_INSET_Y,
                1,
                &parsed,
                theme.font_size,
                fg,
            );
        }
    }

    fn paint_overlay(&mut self, painter: &mut Painter, theme: &Theme) {
        // The popup lives in a separate top-level window — only draw it when
        // the painter is running *that* popup pass, so neither the main
        // window nor an unrelated popup in the stack (e.g. a dialog) ends up
        // with a duplicate copy in its framebuffer.
        if !painter.is_popup_pass() {
            return;
        }
        let Some(menu_idx) = self.open else { return };
        let popup = match self.cache.popup {
            Some(p) => p,
            None => {
                let p = self.compute_popup(menu_idx, painter, theme);
                self.cache.popup = Some(p);
                p
            }
        };
        // The cache is populated now; the anchor check has to come after so
        // popup_request can report a rect.
        if painter.popup_anchor() != self.popup_request().map(|r| r.rect) {
            return;
        }

        // L-shape drop shadow drawn first so the popup overlays it on the
        // top/left edges.
        painter.fill_rect(
            Rect::new(popup.x + SHADOW_SIZE, popup.bottom(), popup.w, SHADOW_SIZE),
            SHADOW_COLOR,
        );
        painter.fill_rect(
            Rect::new(popup.right(), popup.y + SHADOW_SIZE, SHADOW_SIZE, popup.h),
            SHADOW_COLOR,
        );

        // White interior + thin black border. No raised bevel — Win 3.1
        // drop-downs are flat panels, the bar holds the chrome.
        painter.fill_rect(popup, theme.background);
        painter.stroke_rect(popup, theme.border);

        let mut y = popup.y + POPUP_PADDING_Y;
        for (i, item) in self.menus[menu_idx].items.iter().enumerate() {
            match item {
                MenuItem::Action { label, accel, .. } => {
                    let row = Rect::new(popup.x + 1, y, popup.w - 2, ITEM_HEIGHT);
                    let parsed = parse_label(label);
                    let (bg, fg) = if self.hovered_item == Some(i) {
                        (theme.highlight_bg, theme.highlight_text)
                    } else {
                        (theme.background, theme.text)
                    };
                    painter.fill_rect(row, bg);
                    draw_label_with_mnemonic(
                        painter,
                        row.x + POPUP_PADDING_X - 4,
                        row.y + ITEM_TEXT_INSET_Y,
                        0,
                        &parsed,
                        theme.font_size,
                        fg,
                    );
                    // Accelerator hint, right-aligned with the same inset the
                    // label carries on the left.
                    if let Some(accel) = accel {
                        let aw = painter.measure_text(accel, theme.font_size).w;
                        let ax = row.right() - (POPUP_PADDING_X - 4) - aw;
                        painter.text(ax, row.y + ITEM_TEXT_INSET_Y, accel, theme.font_size, fg);
                    }
                    y += ITEM_HEIGHT;
                }
                MenuItem::Separator => {
                    let mid = y + SEPARATOR_HEIGHT / 2;
                    painter.etched_h_line(popup.x + 4, mid, popup.w - 8, theme);
                    y += SEPARATOR_HEIGHT;
                }
            }
        }
    }

    fn event(&mut self, event: &Event, ctx: &mut EventCtx) {
        match event {
            Event::PointerDown {
                pos,
                button: MouseButton::Left,
                ..
            } => {
                if let Some(menu_idx) = self.open {
                    if let Some(item) = self.hit_item(*pos) {
                        self.fire(item, ctx);
                        self.open = None;
                        self.hovered_item = None;
                        self.drag_armed = false;
                        ctx.request_paint();
                        return;
                    }
                    if let Some(label_idx) = self.hit_label(*pos) {
                        if label_idx == menu_idx {
                            // Press on the open label — close on release.
                            self.open = None;
                            self.hovered_item = None;
                        } else {
                            self.open = Some(label_idx);
                            self.hovered_item = None;
                            self.drag_armed = true;
                        }
                        ctx.request_paint();
                        return;
                    }
                    // Click outside — dismiss.
                    self.open = None;
                    self.hovered_item = None;
                    self.drag_armed = false;
                    ctx.request_paint();
                } else if let Some(label_idx) = self.hit_label(*pos) {
                    self.open = Some(label_idx);
                    self.hovered_item = None;
                    // The press might be the start of a drag-to-pick gesture.
                    self.drag_armed = true;
                    ctx.request_paint();
                }
            }
            Event::PointerUp {
                pos,
                button: MouseButton::Left,
                ..
            } => {
                if !self.drag_armed {
                    return;
                }
                self.drag_armed = false;
                // Released over an item → fire it.
                if let Some(item) = self.hit_item(*pos) {
                    self.fire(item, ctx);
                    self.open = None;
                    self.hovered_item = None;
                    ctx.request_paint();
                    return;
                }
                // Click-without-drag (released back over the bar, no item
                // ever hovered) → pre-highlight the first action so the
                // user can fire it with Enter or keep arrow-navigating.
                if self.hovered_item.is_none() && self.hit_label(*pos).is_some() {
                    self.hovered_item = self.first_action();
                    ctx.request_paint();
                }
                // Released somewhere else (dragged outside, then released):
                // just disarm and leave the menu in its current state.
            }
            Event::PointerMove { pos }
                if self.open.is_some() => {
                    let item = self.hit_item(*pos);
                    if item != self.hovered_item {
                        self.hovered_item = item;
                        ctx.request_paint();
                    }
                    if let Some(label_idx) = self.hit_label(*pos)
                        && self.open != Some(label_idx)
                    {
                        self.open = Some(label_idx);
                        self.hovered_item = None;
                        ctx.request_paint();
                    }
                }
            Event::KeyDown { key, modifiers } => {
                // Whether the menu was already open *before* handling this key.
                // It matters because firing an item (Enter / a mnemonic) closes
                // the menu in this same dispatch — and we must still swallow that
                // keystroke (see the consume below) so it doesn't also reach the
                // focused widget behind the bar.
                let was_open = self.open.is_some();
                match key {
                    Key::Named(NamedKey::Escape) if was_open => {
                        self.open = None;
                        self.hovered_item = None;
                        ctx.request_paint();
                    }
                    Key::Named(NamedKey::Down) if was_open => {
                        self.move_selection(1, ctx);
                    }
                    Key::Named(NamedKey::Up) if was_open => {
                        self.move_selection(-1, ctx);
                    }
                    Key::Named(NamedKey::Right) if was_open => {
                        self.switch_top_level(1, ctx);
                    }
                    Key::Named(NamedKey::Left) if was_open => {
                        self.switch_top_level(-1, ctx);
                    }
                    Key::Named(NamedKey::Home) if was_open => {
                        self.hovered_item = self.first_action();
                        ctx.request_paint();
                    }
                    Key::Named(NamedKey::End) if was_open => {
                        self.hovered_item = self.last_action();
                        ctx.request_paint();
                    }
                    Key::Named(NamedKey::Enter) if was_open => {
                        if let Some(item) = self.hovered_item {
                            self.fire(item, ctx);
                            self.open = None;
                            self.hovered_item = None;
                            // Don't let the Enter that fired the item leak into
                            // whatever it opened (its release / trailing text).
                            ctx.swallow_key_until_release();
                            ctx.request_paint();
                        }
                    }
                    Key::Char(ch) => {
                        self.handle_mnemonic(*ch, *modifiers, ctx);
                    }
                    _ => {}
                }
                // An open menu owns the keyboard: swallow the keystroke so it
                // can't *also* act on the focused widget behind the bar — the
                // bug where Enter both fired the menu item and activated the
                // control underneath. We consume when the menu was already open
                // (it captures every key while up, even ones it ignores) or when
                // this key just opened one (a top-level mnemonic). A key pressed
                // against a closed bar that opens nothing falls through.
                if was_open || self.open.is_some() {
                    ctx.consume_event();
                }
            }
            Event::Char { ch, modifiers }
                // Some platforms route mnemonic characters through Char with
                // Alt held; treat the same way. AltGr is excluded so composed
                // characters still reach the focused text widget.
                if modifiers.mnemonic_alt() =>
            {
                let was_open = self.open.is_some();
                self.handle_mnemonic(*ch, *modifiers, ctx);
                if was_open || self.open.is_some() {
                    ctx.consume_event();
                }
            }
            _ => {}
        }
    }

    fn captures_pointer(&self) -> bool {
        self.open.is_some()
    }

    fn accepts_accelerators(&self) -> bool {
        true
    }

    fn layout(&mut self, bounds: Rect) {
        self.rect = bounds;
        // Force the cached label rects to be rebuilt on the next paint —
        // they were measured against the previous width.
        self.cache = Cache::default();
    }

    fn popup_request(&self) -> Option<PopupRequest> {
        // Cache.popup is populated during paint; until the first paint
        // completes after the menu opens, we have nothing to anchor.
        let _ = self.open?;
        let popup = self.cache.popup?;
        // Include the L-shape drop shadow inside the popup window's bounds
        // so it doesn't clip at the right/bottom edges.
        Some(PopupRequest {
            rect: Rect::new(
                popup.x,
                popup.y,
                popup.w + SHADOW_SIZE,
                popup.h + SHADOW_SIZE,
            ),
            kind: PopupKind::Popup,
            title: None,
        })
    }
}

impl MenuBar {
    /// Index of the first action item in the currently open menu (skipping
    /// separators); `None` if no menu is open or it has no actions.
    fn first_action(&self) -> Option<usize> {
        let menu_idx = self.open?;
        self.menus[menu_idx]
            .items
            .iter()
            .position(|item| item.is_action())
    }

    fn last_action(&self) -> Option<usize> {
        let menu_idx = self.open?;
        self.menus[menu_idx]
            .items
            .iter()
            .enumerate()
            .rev()
            .find_map(|(i, item)| item.is_action().then_some(i))
    }

    /// Step hovered_item by ±1, skipping separators, wrapping at the ends.
    /// `delta` should be +1 (Down) or -1 (Up).
    fn move_selection(&mut self, delta: i32, ctx: &mut EventCtx) {
        let Some(menu_idx) = self.open else { return };
        let n = self.menus[menu_idx].items.len();
        if n == 0 {
            return;
        }
        let actions: Vec<usize> = self.menus[menu_idx]
            .items
            .iter()
            .enumerate()
            .filter(|(_, item)| item.is_action())
            .map(|(i, _)| i)
            .collect();
        if actions.is_empty() {
            return;
        }
        let current = self
            .hovered_item
            .and_then(|h| actions.iter().position(|&a| a == h));
        let next = match (current, delta) {
            (None, 1) => 0,
            (None, _) => actions.len() - 1,
            (Some(i), d) => {
                let len = actions.len() as i32;
                ((i as i32 + d).rem_euclid(len)) as usize
            }
        };
        self.hovered_item = Some(actions[next]);
        ctx.request_paint();
    }

    /// Move to the previous / next top-level menu, keeping a dropdown open.
    /// Always pre-highlights the first action of the newly opened menu — the
    /// previous highlight position doesn't carry over.
    fn switch_top_level(&mut self, delta: i32, ctx: &mut EventCtx) {
        let Some(current) = self.open else { return };
        let n = self.menus.len() as i32;
        if n == 0 {
            return;
        }
        let next = ((current as i32 + delta).rem_euclid(n)) as usize;
        if next != current {
            self.open = Some(next);
            self.hovered_item = self.first_action();
            ctx.request_paint();
        }
    }

    /// Translate a typed character into a menu-open or item-fire action. Returns
    /// `true` if the keystroke was consumed.
    fn handle_mnemonic(&mut self, ch: char, modifiers: Modifiers, ctx: &mut EventCtx) -> bool {
        if self.open.is_some() {
            // No modifier required while a menu is open — typing a letter
            // fires its mnemonic item.
            if let Some(item) = self.item_mnemonic(ch) {
                self.fire(item, ctx);
                self.open = None;
                self.hovered_item = None;
                // The letter that fired the item must not also reach whatever
                // the item just opened (e.g. a dialog's focused field).
                ctx.swallow_key_until_release();
                ctx.request_paint();
                return true;
            }
            return false;
        }
        // Closed bar: only respond to (left) Alt+letter to open a top-level
        // menu. AltGr is excluded so it stays free for composing characters.
        // Keyboard-opened menus pre-highlight the first action so the user
        // can hit Enter or use arrows immediately.
        if modifiers.mnemonic_alt()
            && let Some(menu_idx) = self.top_level_mnemonic(ch)
        {
            self.open = Some(menu_idx);
            self.hovered_item = self.first_action();
            ctx.request_paint();
            return true;
        }
        false
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;
    use std::rc::Rc;

    fn bar_with_help(fired: Rc<Cell<bool>>) -> MenuBar {
        MenuBar::new(Rect::new(0, 0, 200, 20)).add_menu(Menu::new(
            "&Help",
            vec![MenuItem::action("&About", move |_| fired.set(true))],
        ))
    }

    fn keydown(key: Key) -> Event {
        Event::KeyDown {
            key,
            modifiers: Modifiers::default(),
        }
    }

    #[test]
    fn open_menu_consumes_the_enter_that_fires_an_item() {
        let fired = Rc::new(Cell::new(false));
        let mut bar = bar_with_help(fired.clone());
        bar.open(0);
        // Highlight the first item …
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Named(NamedKey::Down)), &mut ctx);
        // … then Enter fires it.
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Named(NamedKey::Enter)), &mut ctx);
        assert!(fired.get(), "Enter fires the highlighted item");
        assert!(
            ctx.is_consumed(),
            "an open menu must swallow the Enter so it can't also reach the focused widget"
        );
    }

    #[test]
    fn open_menu_swallows_keys_it_ignores() {
        // Space isn't a menu command, but while the menu is up it must not leak
        // to the focused widget behind the bar either.
        let mut bar = bar_with_help(Rc::new(Cell::new(false)));
        bar.open(0);
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Named(NamedKey::Space)), &mut ctx);
        assert!(ctx.is_consumed());
    }

    #[test]
    fn closed_bar_lets_plain_keys_through() {
        let mut bar = bar_with_help(Rc::new(Cell::new(false)));
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Char('x')), &mut ctx);
        assert!(
            !ctx.is_consumed(),
            "a plain key against a closed bar must reach the focused widget"
        );
    }

    #[test]
    fn firing_an_item_by_mnemonic_swallows_the_key_until_release() {
        let fired = Rc::new(Cell::new(false));
        let mut bar = bar_with_help(fired.clone());
        bar.open(0);
        // While the menu is open, the item's letter fires it.
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Char('a')), &mut ctx); // &About
        assert!(fired.get(), "the mnemonic fires the item");
        assert!(
            ctx.swallow_key,
            "the firing keystroke is swallowed through its release so it can't \
             leak into whatever the item opens (e.g. a dialog's focused field)"
        );
    }

    #[test]
    fn firing_an_item_by_enter_swallows_the_key_until_release() {
        let fired = Rc::new(Cell::new(false));
        let mut bar = bar_with_help(fired.clone());
        bar.open(0);
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Named(NamedKey::Down)), &mut ctx); // highlight About
        let mut ctx = EventCtx::new();
        bar.event(&keydown(Key::Named(NamedKey::Enter)), &mut ctx);
        assert!(fired.get());
        assert!(
            ctx.swallow_key,
            "Enter that fires an item is swallowed until release"
        );
    }

    #[test]
    fn merely_opening_a_menu_does_not_swallow_until_release() {
        // Opening (vs. firing) must not swallow: otherwise a held key's
        // autorepeat couldn't drive arrow-key menu navigation.
        let mut bar = bar_with_help(Rc::new(Cell::new(false)));
        let alt = Modifiers {
            alt: true,
            ..Modifiers::default()
        };
        let mut ctx = EventCtx::new();
        bar.event(
            &Event::KeyDown {
                key: Key::Char('h'),
                modifiers: alt,
            },
            &mut ctx,
        );
        assert!(bar.open.is_some(), "Alt+H opens the Help menu");
        assert!(
            !ctx.swallow_key,
            "opening a menu must not swallow the key press"
        );
    }

    #[test]
    fn alt_mnemonic_opening_a_menu_is_consumed() {
        let mut bar = bar_with_help(Rc::new(Cell::new(false)));
        let alt = Modifiers {
            alt: true,
            ..Modifiers::default()
        };
        let mut ctx = EventCtx::new();
        bar.event(
            &Event::KeyDown {
                key: Key::Char('h'),
                modifiers: alt,
            },
            &mut ctx,
        );
        assert!(bar.open.is_some(), "Alt+H opens the Help menu");
        assert!(
            ctx.is_consumed(),
            "and that mnemonic keystroke is swallowed"
        );
    }
}