Guide API
Skip to main content

tvision_rs/menu/
menu_session.rs

1//! The interactive menu layer — opening, navigating, and selecting menus — driven
2//! by one [`MenuSession`] capture handler on the single event loop.
3//!
4//! ## The architecture
5//!
6//! Opening a submenu would normally nest one modal loop per open box. Here there
7//! is a single event loop, so **one** [`MenuSession`] capture handler owns the
8//! WHOLE open stack (bar + every open box) and runs the interaction as one flat
9//! loop rather than recursion. While the session is on the capture stack it
10//! **consumes every menu-directed event**: the bar and boxes only draw and report
11//! item geometry — they are never focused and carry no event logic of their own.
12//!
13//! ## State
14//!
15//! The session holds a **stack of levels** (`MenuLevel`), one per open bar/box,
16//! each carrying its `view_id`, a **clone** of its `menu`, its `current` highlight
17//! index, its `bounds` (cached at open — a box never moves), and an `is_bar` flag
18//! (a bar is one row, a box a vertical column). Cloning the menu at open freezes
19//! its `disabled` flags for the menu's lifetime — the session swallows
20//! command-set-changed broadcasts while active, so regray does not reach an open
21//! menu. The top of the stack is the **active** level; a parent level is
22//! suspended. Cross-level mouse hit-testing gates against the cached per-level
23//! `bounds`.
24//!
25//! **Behavioral note (a consequence of cloning at open):** writing the chosen item
26//! back as the level's default lands on the *level's clone*, which is discarded
27//! when the session closes — so the bar's permanent [`Menu::default`] is NOT
28//! updated, and a later re-activation restarts on the original default rather than
29//! the last-selected item. This is inert within a session (a closed box is only
30//! reopened by re-cloning through the bar), the same trade-off as the
31//! `disabled`-freezing above. Persisting the default would write the chosen index
32//! back to the bar's real menu on close, via a deferred request mirroring the
33//! existing highlight write.
34//!
35//! ## Keyboard
36//!
37//! The keyboard arms cover Up/Down/Left/Right/Home/End/Enter/Esc plus a
38//! character / hotkey arm. Choosing a submenu pushes a level; choosing a command
39//! ends the session and posts the command; Esc or Left close levels.
40//!
41//! ## Mouse
42//!
43//! The mouse arms cover press/release/move plus item tracking and the parent-level
44//! hit gates, with per-level transient flags for the "last opened title", "mouse
45//! has landed on an item", and "first event of this level". Keyboard and mouse
46//! share one re-apply `run` loop tail (set highlight → reset
47//! the last-opened marker → open gate → command result → pop / re-apply). The open
48//! gate re-applies the triggering mouse event into the freshly-opened child; the
49//! child-pop records the parent's last-opened title and default (the "click an
50//! open title to close it" mechanism). The bar's mouse-down activation lives in
51//! [`menu_view::handle_event`](crate::menu::menu_view::handle_event) ([`activate_mouse`]). The per-session
52//! [`put_click_event_on_exit`](MenuSession) flag (`true` for a bar/box, `false`
53//! for a context popup) gates the bottom-level exit-click re-post.
54//!
55//! ## Context popups
56//!
57//! A context popup is a menu box with two observable differences: no default
58//! highlight on open (the level starts with nothing highlighted and clears its
59//! clone's [`Menu::default`]) and no exit-click re-post (the [`popup_menu`]
60//! constructor sets [`put_click_event_on_exit`](MenuSession) to `false`). The
61//! [`popup_menu`] free function builds and runs it (placement via
62//! `auto_place_popup`). A popup needs no extra accelerator handling of its own:
63//! it is run modally the instant it opens, so the session already owns the event
64//! loop and the flat loop's hotkey handling covers it (see [`popup_menu`]).
65//!
66//! Mouse auto-repeat / press-and-hold does not apply to menus.
67//!
68//! # Turbo Vision heritage
69//! Flattens `TMenuView::execute()` and `TMenuPopup` (`tmnuview.cpp`,
70//! `tmenupop.cpp`, `popupmnu.cpp`/`menus.h`). The nested modal loops (one per open
71//! box) become one capture handler on the single event loop (deviation D9).
72
73use crate::capture::{CaptureFlow, CaptureHandler};
74use crate::command::Command;
75use crate::event::{Event, Key, KeyEvent, MouseEvent};
76use crate::help::HelpCtx;
77use crate::menu::menu_box::menu_box_rect;
78use crate::menu::menu_view::hot_key;
79use crate::menu::{Menu, MenuItem};
80use crate::view::{Context, Point, Rect, ViewId};
81
82/// One open bar/box level of the menu stack, made explicit so the single loop can
83/// own every open level at once.
84struct MenuLevel {
85    /// The bar/box view's id in the root group (resolves to a
86    /// [`MenuBar`](crate::menu::MenuBar)/[`MenuBox`](crate::menu::MenuBox) for the
87    /// highlight-write and close brokers). The bar's id is real; each box id is
88    /// **pre-minted** by the session before [`Deferred::OpenMenuBox`].
89    view_id: ViewId,
90    /// A clone of the level's menu. Cloning at open freezes its `disabled` flags
91    /// for the menu's lifetime — the session swallows regray broadcasts while open.
92    menu: Menu,
93    /// The highlighted item index, or `None` for nothing highlighted.
94    current: Option<usize>,
95    /// The level's bounds in the root group's frame, cached at open (a box never
96    /// moves). Used to compute a child box's geometry and to gate mouse
97    /// hit-testing.
98    bounds: Rect,
99    /// Whether this level is the one-row horizontal bar (vs a vertical box).
100    is_bar: bool,
101    /// Whether a no-op step whose highlight names a submenu should open that
102    /// submenu. **Per level**, reset at every level entry so it never leaks from
103    /// the bar into a box's navigation. Set true on this level's Down / Enter /
104    /// hotkey match. This is what makes a Left/Right walk along the bar **re-open**
105    /// the adjacent title's box.
106    auto_select: bool,
107    /// The item whose submenu was most recently opened **from this level**, set
108    /// when the child box pops back. **Per level**, reset at every level entry.
109    /// Drives the "click an open title to close it" behaviour (the mouse-down and
110    /// mouse-up arms read it to decide whether a click on an already-open title
111    /// closes it). The keyboard arms never read it. Mouse-only.
112    last_target_item: Option<usize>,
113    /// Whether the mouse has landed on an item of this level. **Per level**, set by
114    /// [`track_mouse`](MenuSession::track_mouse) and **monotonic** — never reset to
115    /// false within a level's lifetime. Gates the "released outside after
116    /// activating" mouse-up arm and the bar drag-open mouse-move arm. Mouse-only.
117    mouse_active: bool,
118    /// Whether this level has yet to finish processing its first event (the
119    /// re-applied triggering event after an open counts). **Per level**, true at
120    /// level entry, cleared after each loop iteration. Guards exactly one thing: a
121    /// box just opened by a press must NOT be instantly closed by the re-applied
122    /// press. Mouse-only.
123    first_event: bool,
124}
125
126impl MenuLevel {
127    /// The rect of item `index` for this level, in **view-local** coordinates —
128    /// the same contract as
129    /// [`MenuBar::get_item_rect`](crate::menu::MenuView::get_item_rect) /
130    /// [`MenuBox::get_item_rect`](crate::menu::MenuView::get_item_rect), but
131    /// computed from the cached `menu` + `bounds` (the session has no view
132    /// reference). Must agree cell-for-cell with the draw layer.
133    fn item_rect_local(&self, index: usize) -> Rect {
134        if self.is_bar {
135            // TMenuBar::getItemRect (tmenubar.cpp:94): horizontal accumulator.
136            let mut r = Rect::new(1, 0, 1, 1);
137            for (i, item) in self.menu.items.iter().enumerate() {
138                r.a.x = r.b.x;
139                if !matches!(item, MenuItem::Separator) {
140                    r.b.x += cstrlen(item_name(item)) + 2;
141                }
142                if i == index {
143                    return r;
144                }
145            }
146            r
147        } else {
148            // TMenuBox::getItemRect (tmenubox.cpp:125): rows from y = 1.
149            let y = 1 + index as i32;
150            let size_x = self.bounds.b.x - self.bounds.a.x;
151            Rect::new(2, y, size_x - 2, y + 1)
152        }
153    }
154}
155
156/// Display width of a `~`-marked label, ignoring the `~` markers (per-module
157/// copy, as in `menu_bar.rs`/`menu_box.rs`).
158fn cstrlen(s: &str) -> i32 {
159    s.chars()
160        .filter(|&c| c != '~')
161        .map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) as i32)
162        .sum()
163}
164
165/// The display label of a named item (empty for a [`Separator`](MenuItem::Separator)).
166fn item_name(item: &MenuItem) -> &str {
167    match item {
168        MenuItem::Command { name, .. } | MenuItem::SubMenu { name, .. } => name,
169        MenuItem::Separator => "",
170    }
171}
172
173/// The modal menu interaction, run as one capture handler on the single event
174/// loop.
175///
176/// Pushed at activation (via
177/// [`Deferred::PushCapture`](crate::view::Deferred::PushCapture)) alongside the
178/// first [`OpenMenuBox`](crate::view::Deferred::OpenMenuBox) — or, for a bar
179/// activation, with only the bar level on the stack and no box yet (the first key
180/// opens a box). Consumes every event it is offered; pops itself
181/// ([`CaptureFlow::ConsumedPop`]) when the last level closes, restoring the
182/// pre-menu focus.
183///
184/// # Turbo Vision heritage
185/// Flattens `TMenuView::execute()` (`tmnuview.cpp`/`menus.h`). The nested modal
186/// loops (one per open box) become a single capture handler on the one event loop
187/// (deviation D9).
188pub struct MenuSession {
189    /// The open levels, bottom (bar) → top (deepest box). The top is the active
190    /// level.
191    levels: Vec<MenuLevel>,
192    /// The owner (root group) size, used as the bounds hint when sizing a submenu
193    /// box. Captured at activation.
194    owner_size: Point,
195    /// Which arm (press/release/move) the in-flight mouse event selects, set by
196    /// [`run`](Self::run) before each [`step_mouse`](Self::step_mouse) so the three
197    /// arms can branch without re-threading the whole [`Event`] (the
198    /// position/buttons ride on the [`MouseEvent`](crate::event::MouseEvent) passed
199    /// to `step_mouse`). Unused for the keyboard path.
200    mouse_kind: MouseKind,
201    /// Whether an exit-click should be re-posted to the view tree. An exit-click is
202    /// a mouse press outside the menu that ends the session; re-posting it lets the
203    /// view under it recover focus. `true` for a bar/box, `false` for a context
204    /// popup (a popup never re-posts its exit-click). Only the bottom level's value
205    /// matters — an intermediate box's exit-click is carried up by the re-apply
206    /// loop, not re-posted — so this is one session-wide flag, not a per-level
207    /// field.
208    put_click_event_on_exit: bool,
209}
210
211/// Which mouse arm the in-flight event selects.
212#[derive(Clone, Copy)]
213enum MouseKind {
214    /// A button press.
215    Down,
216    /// A button release.
217    Up,
218    /// A move (drag).
219    Move,
220}
221
222/// What a single step decided, used internally to drive the post-step logic.
223#[derive(PartialEq)]
224enum MenuAction {
225    /// Stay open; redraw if the highlight changed.
226    Nothing,
227    /// Try to open the highlighted submenu, or select its command.
228    Select,
229    /// This level returns (close it; if it was the bar, end the session).
230    Return,
231}
232
233impl MenuSession {
234    /// Build a session over an initial level stack. `owner_size` is the root group
235    /// size. Use [`activate`] rather than calling this directly — it assembles the
236    /// level + the first deferred batch.
237    ///
238    /// There is no saved focus: the bar and boxes are **never focused** (the
239    /// session consumes every event on the capture stack, before view-tree
240    /// routing), so the pre-menu highlight is never disturbed and there is nothing
241    /// to restore on close.
242    fn new(levels: Vec<MenuLevel>, owner_size: Point) -> Self {
243        MenuSession {
244            levels,
245            owner_size,
246            mouse_kind: MouseKind::Down,
247            // The bar/box default; `popup_menu` flips it false for a context popup.
248            put_click_event_on_exit: true,
249        }
250    }
251
252    /// The active (top) level. The session is never empty while on the stack
253    /// (popping the last level returns `ConsumedPop`).
254    fn top(&self) -> &MenuLevel {
255        self.levels.last().expect("session has at least one level")
256    }
257
258    fn top_mut(&mut self) -> &mut MenuLevel {
259        self.levels
260            .last_mut()
261            .expect("session has at least one level")
262    }
263
264    // -- mouse geometry + gates (tmnuview.cpp:97-166) -----------------------
265
266    /// The rect of item `index` for `level` in the **root group frame** — the
267    /// view-local [`item_rect_local`](MenuLevel::item_rect_local) offset by the
268    /// level's origin (`level.bounds.a`). The mouse arms compare against
269    /// root-frame positions, and the incoming event is already root-frame, so
270    /// offsetting the rect by the origin is all that is needed.
271    fn item_rect_global(level: &MenuLevel, index: usize) -> Rect {
272        let r = level.item_rect_local(index);
273        let o = level.bounds.a;
274        Rect::new(r.a.x + o.x, r.a.y + o.y, r.b.x + o.x, r.b.y + o.y)
275    }
276
277    /// Whether `level`'s bounds contain the root-frame `pos`.
278    fn mouse_in_view(level: &MenuLevel, pos: Point) -> bool {
279        level.bounds.contains(pos)
280    }
281
282    /// Whether the **parent** level's highlighted-item rect contains `pos`. The
283    /// parent is the level just below the top (a box always has the bar or another
284    /// box above it); with no parent, or a parent with nothing highlighted, the
285    /// result is false.
286    fn mouse_in_owner(&self, pos: Point) -> bool {
287        let n = self.levels.len();
288        if n < 2 {
289            return false; // no parent level
290        }
291        let parent = &self.levels[n - 2];
292        match parent.current {
293            Some(cur) => Self::item_rect_global(parent, cur).contains(pos),
294            None => false,
295        }
296    }
297
298    /// Whether ANY **parent** level (every level except the top) contains `pos` in
299    /// its bounds.
300    fn mouse_in_menus(&self, pos: Point) -> bool {
301        let n = self.levels.len();
302        self.levels[..n - 1]
303            .iter()
304            .any(|l| Self::mouse_in_view(l, pos))
305    }
306
307    /// Set the top level's highlight to the item whose rect contains `pos` (and
308    /// mark the mouse active), or to nothing if no item is hit. All items are
309    /// tested, separators included: in a **box** a separator has a full-width row
310    /// rect and CAN be hit (the up/down arms then treat it as "not a real target"),
311    /// while on the **bar** a separator's rect is zero-width and is never hit.
312    fn track_mouse(&mut self, pos: Point) {
313        let n = self.top().menu.items.len();
314        for i in 0..n {
315            if Self::item_rect_global(self.top(), i).contains(pos) {
316                let top = self.top_mut();
317                top.current = Some(i);
318                top.mouse_active = true;
319                return;
320            }
321        }
322        self.top_mut().current = None; // nothing hit
323    }
324
325    // -- nav primitives -----------------------------------------------------
326
327    /// Advance the active level's highlight, wrapping to the first item at the end.
328    /// Nothing highlighted bootstraps to the first item; an empty menu stays at
329    /// nothing.
330    fn next_item(&mut self) {
331        let n = self.top().menu.items.len();
332        if n == 0 {
333            return;
334        }
335        let cur = self.top().current;
336        let next = match cur {
337            None => 0,
338            Some(i) if i + 1 >= n => 0, // wrap to first
339            Some(i) => i + 1,
340        };
341        self.top_mut().current = Some(next);
342    }
343
344    /// Retreat the active level's highlight by one, wrapping the first item to the
345    /// last. Nothing highlighted bootstraps to the last item.
346    fn prev_item(&mut self) {
347        let n = self.top().menu.items.len();
348        if n == 0 {
349            return;
350        }
351        let cur = self.top().current;
352        let prev = match cur {
353            None => n - 1,
354            Some(0) => n - 1, // first → wrap to last
355            Some(i) => i - 1,
356        };
357        self.top_mut().current = Some(prev);
358    }
359
360    /// Move the active level's highlight to the next or previous **non-separator**
361    /// item.
362    ///
363    /// With nothing highlighted, it bootstraps to the first item (or the last, when
364    /// going backward) and returns immediately if that item is not a separator;
365    /// otherwise it steps in the chosen direction, skipping separators.
366    fn track_key(&mut self, find_next: bool) {
367        if self.top().current.is_none() {
368            self.top_mut().current = Some(0);
369            if !find_next {
370                self.prev_item();
371            }
372            // A named first/last item needs no skip.
373            if !self.current_is_separator() {
374                return;
375            }
376        }
377        // Step until the highlight lands on a non-separator.
378        loop {
379            if find_next {
380                self.next_item();
381            } else {
382                self.prev_item();
383            }
384            if !self.current_is_separator() {
385                break;
386            }
387        }
388    }
389
390    /// Whether the active level's highlight points at a separator. An
391    /// out-of-range / absent highlight is treated as non-separator so the nav loops
392    /// terminate (the menu is assumed non-empty when a nav key arrives).
393    fn current_is_separator(&self) -> bool {
394        match self.top().current {
395            Some(i) => matches!(self.top().menu.items.get(i), Some(MenuItem::Separator)),
396            None => false,
397        }
398    }
399
400    /// The first **enabled, named** item on the active level whose hotkey letter
401    /// matches a plain (no-alt) `ke`. Delegates to the shared
402    /// [`menu_view::matching_item`] walk.
403    fn find_item(&self, ke: &KeyEvent) -> Option<usize> {
404        crate::menu::menu_view::matching_item(&self.top().menu, ke, false)
405    }
406
407    // -- the per-event step = one iteration of execute()'s do/while ---------
408
409    /// One keyboard step on the active level. Returns an `(action, cleared)` pair:
410    /// `cleared` is whether the event is consumed here — when it is `false` and the
411    /// action is Return, the re-apply loop re-delivers the SAME event to the parent
412    /// level (so one press can unwind the whole stack up to the bar). The step may
413    /// mutate the level's highlight and `auto_select`; `pending_command` carries a
414    /// hotkey accelerator result.
415    fn step_keyboard(
416        &mut self,
417        k: KeyEvent,
418        pending_command: &mut Option<Command>,
419    ) -> (MenuAction, bool) {
420        let is_bar = self.top().is_bar;
421        match k.key {
422            // kbUp / kbDown (tmnuview.cpp:280): box navigates; bar's kbDown sets
423            // autoSelect = True (the open-gate then opens the current submenu —
424            // action stays doNothing so the flag PERSISTS for a later Left/Right
425            // walk, Blocker 3). A non-named key consumes (cleared) the event.
426            Key::Up | Key::Down => {
427                if !is_bar {
428                    self.track_key(k.key == Key::Down);
429                } else if k.key == Key::Down {
430                    self.top_mut().auto_select = true;
431                }
432                (MenuAction::Nothing, true)
433            }
434            // kbLeft / kbRight (tmnuview.cpp:287): bar trackKeys to the adjacent
435            // title; a box (parentMenu != 0) returns WITHOUT clearEvent → the
436            // re-apply loop unwinds every open box to the bar, which then walks +
437            // re-opens the neighbour (Blocker 3).
438            Key::Left | Key::Right => {
439                if is_bar {
440                    self.track_key(k.key == Key::Right);
441                    (MenuAction::Nothing, true)
442                } else {
443                    // parentMenu != 0 (always, a box has the bar/another box above)
444                    // → doReturn, NOT cleared.
445                    (MenuAction::Return, false)
446                }
447            }
448            // kbHome / kbEnd (tmnuview.cpp:294): box only.
449            Key::Home | Key::End => {
450                if !is_bar {
451                    self.top_mut().current = Some(0);
452                    if k.key == Key::End {
453                        self.track_key(false);
454                    }
455                }
456                (MenuAction::Nothing, true)
457            }
458            // kbEnter (tmnuview.cpp:303): doSelect; the bar also sets autoSelect.
459            Key::Enter => {
460                if is_bar {
461                    self.top_mut().auto_select = true;
462                }
463                (MenuAction::Select, true)
464            }
465            // kbEsc (tmnuview.cpp:308-312): doReturn. clearEvent runs iff
466            // `parentMenu == 0 || parentMenu->size.y != 1` — i.e. cleared at the
467            // bar OR at a 2nd+-level box (parent is a box), but NOT at a 1st-level
468            // box (parent is the bar, size.y == 1). When not cleared the re-apply
469            // loop carries the Esc up to the bar, closing the whole menu on one
470            // press (Blocker 2). The asymmetry IS this guard, not a mouse concern.
471            Key::Esc => {
472                let cleared = self.esc_clear_event();
473                (MenuAction::Return, cleared)
474            }
475            // default (tmnuview.cpp:313): alt-shortcut on the TOP menu, else a
476            // plain char findItem, else a hotKey accelerator.
477            _ => self.step_default_key(k, pending_command),
478        }
479    }
480
481    /// Whether an Esc press at the active level should be consumed here rather than
482    /// carried up. It is consumed at the bar (no level below) or at a second-or-
483    /// deeper box (whose parent is another box), but NOT at a first-level box
484    /// (whose parent is the bar) — there the Esc is carried up so one press closes
485    /// the whole menu.
486    fn esc_clear_event(&self) -> bool {
487        let depth = self.levels.len();
488        if depth <= 1 {
489            // The bar: no parent → consume here.
490            true
491        } else {
492            // A box: consume iff the parent is NOT the bar (a 2nd+-level box).
493            !self.levels[depth - 2].is_bar
494        }
495    }
496
497    /// The fallthrough key arm: a hotkey on the active level (or an Alt-shortcut on
498    /// the bar), else a bar accelerator. Returns `(action, cleared)`.
499    fn step_default_key(
500        &mut self,
501        k: KeyEvent,
502        pending_command: &mut Option<Command>,
503    ) -> (MenuAction, bool) {
504        // C++: target = this; if Alt-char, target = topMenu(), p = findAltShortcut
505        // on the bar; else p = findItem on THIS level.
506        if k.modifiers.alt {
507            // Alt-shortcut dispatches against the TOP menu (the bar, level 0).
508            if let Some(idx) = self.find_alt_shortcut_bar(&k) {
509                // C++ `tmnuview.cpp:331-340`: if target == this (the active level IS
510                // the bar) → if size.y==1 autoSelect=True; doSelect; current=p.
511                // Otherwise (a box is active) → doReturn (not cleared) so the
512                // re-apply loop unwinds toward the bar, which re-resolves.
513                if self.top().is_bar {
514                    self.top_mut().current = Some(idx);
515                    self.top_mut().auto_select = true;
516                    return (MenuAction::Select, true);
517                } else {
518                    return (MenuAction::Return, false);
519                }
520            }
521        } else if let Some(idx) = self.find_item(&k) {
522            // findItem matched on THIS (active) level → target == this → select it.
523            // (size.y==1 → autoSelect=True, harmless on a box where it is unused.)
524            self.top_mut().current = Some(idx);
525            if self.top().is_bar {
526                self.top_mut().auto_select = true;
527            }
528            return (MenuAction::Select, true);
529        }
530        // No item match: try the bar's hotKey accelerator (topMenu()->hotKey).
531        if let Some(cmd) = hot_key(&self.levels[0].menu, k) {
532            // commandEnabled is backstopped by the pump's drop_disabled filter;
533            // hot_key already skips cached-disabled items. The result
534            // path ends the session (clearEvent runs, tmnuview.cpp:395).
535            *pending_command = Some(cmd);
536            return (MenuAction::Return, true);
537        }
538        // No match at all: consume (a stray key in a modal menu does nothing).
539        (MenuAction::Nothing, true)
540    }
541
542    /// The matched top-level item index for an `Alt`-held `ke`, searched against
543    /// the **bar** (the bottom level). Delegates to the shared
544    /// [`menu_view::matching_item`] walk.
545    fn find_alt_shortcut_bar(&self, ke: &KeyEvent) -> Option<usize> {
546        crate::menu::menu_view::matching_item(&self.levels[0].menu, ke, true)
547    }
548
549    /// One mouse step (press/release/move) on the active level. Mirrors
550    /// [`step_keyboard`](Self::step_keyboard)'s `(action, cleared)` contract,
551    /// widened with a third `exit_click` flag: no mouse step ever consumes a Return
552    /// itself, so a box's Return is always carried up to its parent by the re-apply
553    /// loop; `exit_click` marks the press-outside branch so the loop tail re-posts
554    /// the click to the view tree when the bottom level ends from it AND that
555    /// level's [`put_click_event_on_exit`](MenuSession) is set. Mutates the top
556    /// level's highlight, `auto_select`, `mouse_active`, and `last_target_item`.
557    fn step_mouse(&mut self, m: MouseEvent) -> (MenuAction, bool, bool) {
558        let pos = m.position;
559        let is_bar = self.top().is_bar;
560        let mut action = MenuAction::Nothing;
561        let mut exit_click = false;
562
563        match self.mouse_kind {
564            MouseKind::Down => {
565                // evMouseDown (tmnuview.cpp:201).
566                if Self::mouse_in_view(self.top(), pos) || self.mouse_in_owner(pos) {
567                    self.track_mouse(pos); // sets top.current (maybe None) + mouse_active
568                    if is_bar {
569                        // autoSelect makes a click OPEN the clicked title's box, yet
570                        // CLOSE it on the second click of the same title (after a box
571                        // closed it set last_target_item == that title).
572                        let cur = self.top().current;
573                        self.top_mut().auto_select =
574                            cur.is_none() || self.top().last_target_item != cur;
575                    } else if !self.top().first_event && self.mouse_in_owner(pos) {
576                        // A box closes when the press lands on its parent's title,
577                        // except when the box was just opened (firstEvent guard).
578                        action = MenuAction::Return;
579                    }
580                    // (otherwise action stays doNothing; the open-gate may still fire
581                    // via auto_select for a bar click.)
582                } else {
583                    // Click outside this level's bounds and outside the parent item:
584                    // the menu closes. The exit click is flagged here; the loop tail
585                    // re-posts it to the view tree only when the bottom level ends from
586                    // it AND its `put_click_event_on_exit` is set (the bar/box default;
587                    // a TMenuPopup clears it). An intermediate box just returns and the
588                    // re-apply loop carries the click up to the bottom level.
589                    action = MenuAction::Return;
590                    exit_click = true;
591                }
592            }
593            MouseKind::Up => {
594                // evMouseUp (tmnuview.cpp:225) — always trackMouse first (no gate).
595                self.track_mouse(pos);
596                if self.mouse_in_owner(pos) {
597                    // Released on the parent item → reset to the menu default.
598                    self.top_mut().current = self.top().menu.default;
599                } else if let Some(cur) = self.top().current {
600                    // A named (non-separator) item: select / close / re-arm.
601                    if !matches!(self.top().menu.items.get(cur), Some(MenuItem::Separator)) {
602                        if Some(cur) != self.top().last_target_item {
603                            action = MenuAction::Select;
604                        } else if is_bar {
605                            // A bar entry just closed → exit and stop listening.
606                            action = MenuAction::Return;
607                        } else {
608                            // A box: MouseUp won't reopen a submenu just closed by a
609                            // name-click; but the NEXT one will (clear last_target).
610                            self.top_mut().last_target_item = None;
611                        }
612                    }
613                    // A separator (name == 0): nothing — action stays doNothing.
614                } else if self.top().mouse_active && !Self::mouse_in_view(self.top(), pos) {
615                    // Released outside the view after activating → return.
616                    action = MenuAction::Return;
617                } else if !is_bar {
618                    // Released inside the box but not on a highlightable entry (a
619                    // margin / separator): highlight the default, else the first
620                    // (TV 2.0). Nonsensical in a bar, so bar-only-excluded.
621                    self.top_mut().current = self.top().menu.default.or(Some(0));
622                }
623            }
624            MouseKind::Move => {
625                // evMouseMove (tmnuview.cpp:263) — only while a button is held.
626                if m.buttons.left || m.buttons.right || m.buttons.middle {
627                    self.track_mouse(pos);
628                    if !(Self::mouse_in_view(self.top(), pos) || self.mouse_in_owner(pos))
629                        && self.mouse_in_menus(pos)
630                    {
631                        // Dragged off this box onto an ancestor menu → return.
632                        action = MenuAction::Return;
633                    } else if is_bar
634                        && self.top().mouse_active
635                        && self.top().current != self.top().last_target_item
636                    {
637                        // Drag to a new bar title → open it automatically.
638                        self.top_mut().auto_select = true;
639                    }
640                }
641                // buttons == 0 → no-op (action doNothing).
642            }
643        }
644        (action, false, exit_click)
645    }
646
647    /// The menu-toggle command step on the active level: it resets the level's
648    /// transient mouse flags, then a **box** returns (not consumed — the tail
649    /// carries the command up, unwinding toward the bar) while the **bar** just
650    /// resets and stays open. Mirrors the `(action, cleared)` step contract.
651    fn step_cmd_menu(&mut self) -> (MenuAction, bool) {
652        let is_bar = self.top().is_bar;
653        let top = self.top_mut();
654        top.auto_select = false;
655        top.last_target_item = None;
656        if is_bar {
657            (MenuAction::Nothing, true)
658        } else {
659            // parentMenu != 0 → doReturn, not cleared (the tail re-posts cmMenu up).
660            (MenuAction::Return, false)
661        }
662    }
663
664    /// The flat event loop, **shared** by the keyboard and mouse paths. Steps the
665    /// active level (by event kind), runs the post-step open gate, and on a
666    /// not-consumed Return pops the level and **re-applies the SAME event** to the
667    /// new top level, looping until a level produces a non-Return action (or a
668    /// consumed Return), or the bar ends the whole session. This re-apply-upward is
669    /// what replaces the recursion that would otherwise nest one loop per open box.
670    fn run(&mut self, ev: Event, ctx: &mut Context) -> CaptureFlow {
671        // Cache the event kind for the per-iteration step + the open-gate's
672        // mouse-down/move `continue` divergence (tmnuview.cpp:374).
673        let is_mouse_carry = matches!(ev, Event::MouseDown(_) | Event::MouseMove(_));
674        loop {
675            let mut pending_command = None;
676            let (action, cleared, exit_click) = match ev {
677                Event::KeyDown(k) => {
678                    let (a, c) = self.step_keyboard(k, &mut pending_command);
679                    (a, c, false)
680                }
681                Event::MouseDown(m) => {
682                    self.mouse_kind = MouseKind::Down;
683                    self.step_mouse(m)
684                }
685                Event::MouseUp(m) => {
686                    self.mouse_kind = MouseKind::Up;
687                    self.step_mouse(m)
688                }
689                Event::MouseMove(m) => {
690                    self.mouse_kind = MouseKind::Move;
691                    self.step_mouse(m)
692                }
693                // evCommand cmMenu (tmnuview.cpp:343-350): a box doReturns (re-applies
694                // up, the tail's `putEvent(e)` for an evCommand), the bar resets +
695                // stays. Routed through run() so it shares the doReturn pop/re-apply.
696                Event::Command(Command::MENU) => {
697                    let (a, c) = self.step_cmd_menu();
698                    (a, c, false)
699                }
700                // run() is only entered for the step-bearing kinds.
701                _ => unreachable!("run() dispatches only keyboard/mouse/cmMenu events"),
702            };
703
704            // Post the (possibly changed) highlight of the active level to its view
705            // (execute()'s `if itemShown != current drawView`, tmnuview.cpp:362).
706            let top_id = self.top().view_id;
707            let top_current = self.top().current;
708            ctx.request_set_menu_current(top_id, top_current);
709
710            // Post-switch reset (tmnuview.cpp:359): if a submenu was closed by a
711            // name-click and the mouse is dragged to another entry, the submenu
712            // opens again the next time it is hovered. Runs every iteration, before
713            // the open-gate, on the TOP level (inert for keyboard, which never sets
714            // last_target_item).
715            if self.top().last_target_item != self.top().current {
716                self.top_mut().last_target_item = None;
717            }
718
719            // Post-switch open-gate (tmnuview.cpp:368-390):
720            //   (doSelect || (doNothing && autoSelect)) && current names a NAMED
721            //   item → open its submenu (any of the two), or select its command
722            //   (doSelect only).
723            let auto = self.top().auto_select;
724            let gate = action == MenuAction::Select || (action == MenuAction::Nothing && auto);
725            if gate && let Some(idx) = self.top().current {
726                match self.top().menu.items.get(idx) {
727                    // A submenu, not disabled → open a child box (recurse).
728                    Some(MenuItem::SubMenu { menu, disabled, .. }) if !*disabled => {
729                        let submenu = menu.clone();
730                        self.open_submenu(idx, submenu, ctx);
731                        // C++ putEvent(e) into the child's frame is gated on
732                        // (evMouseDown | evMouseMove) (tmnuview.cpp:374): re-apply the
733                        // SAME mouse-down/move to the freshly-opened child (its
734                        // first_event == true guards the instant-close). Keyboard +
735                        // mouseUp: the child opens and waits.
736                        if is_mouse_carry {
737                            continue;
738                        }
739                        return CaptureFlow::Consumed;
740                    }
741                    // A command item, not disabled → select it ONLY on doSelect
742                    // (the autoSelect branch never selects a command,
743                    // tmnuview.cpp:388). Post + end the whole session.
744                    Some(MenuItem::Command {
745                        command, disabled, ..
746                    }) if !*disabled && action == MenuAction::Select => {
747                        let cmd = *command;
748                        return self.end_session_with(Some(cmd), ctx);
749                    }
750                    _ => {}
751                }
752            }
753
754            // A hotKey accelerator (`topMenu()->hotKey`) is a COMMAND RESULT: it
755            // propagates up through every nested execView and closes the WHOLE
756            // menu, posting the command, regardless of depth (`tmnuview.cpp:392`).
757            // Check it BEFORE the per-level Return-pop, else a deep hotKey would be
758            // dropped (the box-level pop returns Consumed without posting).
759            // Esc/Left/Right/mouse carry no pending_command, so they fall through.
760            if let Some(cmd) = pending_command {
761                return self.end_session_with(Some(cmd), ctx);
762            }
763
764            // doReturn — close the active level; re-apply upward unless cleared.
765            if action == MenuAction::Return {
766                if self.levels.len() > 1 {
767                    // Pop + close the top box; the parent becomes active. C++
768                    // `execView` returns here → set the parent's lastTargetItem /
769                    // menu.default to its current (the "click an open title to close
770                    // it" crux, tmnuview.cpp:385-386) and flip firstEvent
771                    // (tmnuview.cpp:400, runs after execView returns).
772                    let top = self.levels.pop().expect("len > 1");
773                    ctx.request_close(top.view_id);
774                    let parent = self.top_mut();
775                    if let Some(cur) = parent.current {
776                        parent.last_target_item = Some(cur);
777                        parent.menu.default = Some(cur);
778                    }
779                    parent.first_event = false;
780                    if cleared {
781                        // clearEvent → stop; the parent stays open.
782                        return CaptureFlow::Consumed;
783                    }
784                    // Not cleared → re-apply the SAME event to the new top level.
785                    continue;
786                } else {
787                    // The bottom level returned → end the session. For an exit-click
788                    // (a mouse-down outside the menu), re-post the click to the view
789                    // tree so the view under it recovers focus — but ONLY when this
790                    // bottom level's `putClickEventOnExit` is set (the bar/box default;
791                    // a `TMenuPopup` clears it, `tmenupop.cpp:45`, so a popup's
792                    // exit-click is swallowed, `tmnuview.cpp:220-222`). The final-tail
793                    // putEvent does NOT fire (parentMenu == 0 && e.what != evCommand).
794                    let r = self.end_session_with(None, ctx);
795                    if exit_click && self.put_click_event_on_exit {
796                        ctx.put_event(ev);
797                    }
798                    return r;
799                }
800            }
801
802            // doNothing with no open → consume; the active level stays open. Flip
803            // first_event (a level that processed an event without opening a child or
804            // getting popped is no longer on its first event, tmnuview.cpp:400).
805            self.top_mut().first_event = false;
806            return CaptureFlow::Consumed;
807        }
808    }
809
810    /// Open the submenu at `index` of the active level as a new child box level.
811    /// Pre-mints the box id, computes its geometry (just below the parent item),
812    /// and queues [`OpenMenuBox`](crate::view::Deferred::OpenMenuBox). The new level
813    /// starts highlighted on its own default with its transient flags freshly
814    /// initialized.
815    fn open_submenu(&mut self, index: usize, submenu: Menu, ctx: &mut Context) {
816        // Geometry block (tmnuview.cpp:376-381):
817        //   r = getItemRect(current);          // view-local
818        //   r.a.x = r.a.x + origin.x;
819        //   r.a.y = r.b.y + origin.y;          // BELOW the item
820        //   r.b = owner->size;
821        //   if (size.y == 1) r.a.x--;          // bar shift
822        let parent = self.top();
823        let origin = parent.bounds.a;
824        let r = parent.item_rect_local(index);
825        let mut hint = Rect::new(
826            r.a.x + origin.x,
827            r.b.y + origin.y,
828            self.owner_size.x,
829            self.owner_size.y,
830        );
831        if parent.is_bar {
832            hint.a.x -= 1;
833        }
834        // The box sizes itself inside this hint (menu_box_rect clamps).
835        let bounds = menu_box_rect(hint, &submenu);
836
837        // Pre-mint the box id so the session knows it with no callback.
838        let id = ViewId::next();
839        ctx.request_open_menu_box(id, submenu.clone(), bounds);
840
841        // The new box level starts with current = menu->deflt (execute()'s
842        // prologue runs on the freshly entered frame: `current = menu->deflt`) and
843        // its OWN autoSelect = False (per-level; C++ inits it False each frame).
844        let current = submenu.default;
845        self.levels.push(MenuLevel {
846            view_id: id,
847            menu: submenu,
848            current,
849            bounds,
850            is_bar: false,
851            auto_select: false,
852            // The mouse loop-locals, re-init per level (C++ inits them at every
853            // execute() frame entry, so they never leak across levels).
854            last_target_item: None,
855            mouse_active: false,
856            first_event: true,
857        });
858        // Push the new level's initial highlight to its (about-to-exist) box.
859        ctx.request_set_menu_current(id, current);
860    }
861
862    /// The help context of the currently highlighted menu item, as seen by the
863    /// status line while the session is open.
864    ///
865    /// Walks the open levels from the **deepest (top of stack)** toward the bar.
866    /// For the first level whose highlighted item is a named `Command` or `SubMenu`
867    /// with `help_ctx != HelpCtx::NO_CONTEXT`, returns that `help_ctx`. Skips
868    /// `Separator` items and levels with no current highlight. If no level
869    /// qualifies, returns [`HelpCtx::NO_CONTEXT`].
870    ///
871    /// This mirrors `TMenuView::getHelpCtx` (`tmnuview.cpp:453-468`), which walks
872    /// the `parentMenu` chain to find the first active level with a named, non-null
873    /// `helpCtx`. Here the parentMenu chain is the level stack (deviation D9 /
874    /// D3); the walk is equivalent.
875    pub fn help_ctx(&self) -> HelpCtx {
876        for level in self.levels.iter().rev() {
877            let Some(idx) = level.current else {
878                continue;
879            };
880            match level.menu.items.get(idx) {
881                Some(MenuItem::Command { help_ctx, .. })
882                | Some(MenuItem::SubMenu { help_ctx, .. })
883                    if *help_ctx != HelpCtx::NO_CONTEXT =>
884                {
885                    return *help_ctx;
886                }
887                _ => {} // separator, or named item with NO_CONTEXT — keep walking
888            }
889        }
890        HelpCtx::NO_CONTEXT
891    }
892
893    /// End the whole session: close every session-owned box, clear the bar's
894    /// highlight, optionally post `cmd`, and pop the capture handler. Focus was
895    /// never moved, so there is nothing to restore.
896    fn end_session_with(&mut self, cmd: Option<Command>, ctx: &mut Context) -> CaptureFlow {
897        // Tear down every level by kind: a **bar** (`is_bar`) is a permanent frame
898        // child (C++ `TMenuBar`, reset + redrawn on close), so it is only
899        // un-highlighted (execute()'s tail `current = 0; drawView()`), never removed;
900        // every **box** (C++ `TMenuBox`/`TMenuPopup`, `execView`'d then destroyed) is
901        // closed. A bar session has the bar at `levels[0]` + boxes above; a
902        // [`popup_menu`] session has NO bar — its single level IS a box and must be
903        // closed: the popup's level-0-is-a-box teardown needs this kind-keyed
904        // loop, not a `skip(1)`/`first()` bar hard-coding.
905        for level in &self.levels {
906            if level.is_bar {
907                ctx.request_set_menu_current(level.view_id, None);
908            } else {
909                ctx.request_close(level.view_id);
910            }
911        }
912        // Post the selected command, if any (the pump's drop_disabled filter is
913        // the backstop for a stale-enabled command).
914        if let Some(cmd) = cmd {
915            ctx.post(cmd);
916        }
917        // No focus restore: focus was never moved (Clean Architecture A — boxes
918        // and the bar are never current), so the pre-menu current is intact.
919        CaptureFlow::ConsumedPop
920    }
921}
922
923impl CaptureHandler for MenuSession {
924    /// One pass per offered event. Consumes every menu-directed event; keyboard,
925    /// mouse, and the menu-toggle command share the flat re-apply loop, a non-menu
926    /// command ends the session and is re-posted to the view tree, and everything
927    /// else is swallowed to keep the session modal.
928    fn handle(&mut self, ev: &mut Event, ctx: &mut Context) -> CaptureFlow {
929        match *ev {
930            // Keyboard + mouse + cmMenu share the flattened re-apply loop (run); the
931            // per-kind switch arm runs inside it (step_keyboard / step_mouse /
932            // step_cmd_menu). cmMenu is an `execute()` evCommand arm
933            // (tmnuview.cpp:343-350): at a BOX it doReturns (closes + re-applies up,
934            // unwinding to the bar); at the BAR it resets autoSelect/lastTargetItem
935            // and stays open. It MUST go through the same post-switch/doReturn tail as
936            // the other arms (not a top-only reset), else a box stays open on cmMenu.
937            Event::KeyDown(_)
938            | Event::MouseDown(_)
939            | Event::MouseUp(_)
940            | Event::MouseMove(_)
941            | Event::Command(Command::MENU) => self.run(ev.clone(), ctx),
942            // A non-cmMenu command → doReturn (close the whole menu). C++
943            // execute()'s tail re-posts the command (`putEvent(e)` when
944            // `e.what == evCommand`, tmnuview.cpp:403-405) so it still reaches the
945            // view after the menu closes — port that with put_event.
946            Event::Command(cmd) => {
947                let r = self.end_session_with(None, ctx);
948                ctx.put_event(Event::Command(cmd));
949                r
950            }
951            // evBroadcast: SWALLOWED while active (clone-at-open is faithful —
952            // execute() has no evBroadcast case; a cmCommandSetChanged is fetched
953            // and ignored, so disabled stays frozen and boxes never regray
954            // mid-menu). Consume so it does not reach the (idle) menu broker.
955            Event::Broadcast { .. } => CaptureFlow::Consumed,
956            // evMouseAuto: execute() has NO evMouseAuto arm (no auto-repeat /
957            // press-hold in a menu). Consume to keep the session modal.
958            Event::MouseAuto(_) => CaptureFlow::Consumed,
959            // Anything else (Nothing): consume to keep the session modal.
960            // Timer expiries never get here: the pump routes them around the
961            // capture stack, as C++ `idle` delivers them inside execute()'s
962            // `getEvent`.
963            _ => CaptureFlow::Consumed,
964        }
965    }
966
967    fn view(&self) -> Option<ViewId> {
968        // The session is associated with the bar (level 0). Bounds gating uses the
969        // per-level cache, not set_gate_bounds (boxes never move), so this is
970        // informational only.
971        self.levels.first().map(|l| l.view_id)
972    }
973
974    fn menu_help_ctx(&self) -> Option<HelpCtx> {
975        // An open menu preempts the help context of any view behind it —
976        // including when the highlighted item has NO_CONTEXT — matching C++
977        // `TStatusLine::update` calling `TopView()->getHelpCtx()` where
978        // `TopView()` is the active `TMenuView` while a menu is open.
979        // Always returns `Some` so `CaptureStack::active_menu_help_ctx` stops
980        // at this (topmost) handler and does not fall through to views below.
981        Some(self.help_ctx())
982    }
983}
984
985// ---------------------------------------------------------------------------
986// Activation — assemble a MenuSession + its first deferred batch
987// ---------------------------------------------------------------------------
988
989/// Open a menu session from the **bar**.
990///
991/// Two activation kinds, distinguished by `open_index`:
992///
993/// * **Menu key (F10)** (`open_index == None`): the bar is highlighted on its
994///   default title with `auto_select` off, and **no box opens** — the key only
995///   highlights the default title and waits for the next key.
996/// * **Hotkey** (`open_index == Some(idx)`): the bar is highlighted on the matched
997///   title with `auto_select` on, and the matched title's box is opened in the
998///   SAME deferred batch (no dead first event); `auto_select` persists so a later
999///   Left/Right re-opens neighbouring titles.
1000///
1001/// A hotkey that names a top-level **command** (not a submenu) posts that command
1002/// and opens no session at all.
1003///
1004/// `bar_menu` is a clone of the bar's `menu`; `bar_bounds` its bounds in the root
1005/// frame; `owner_size` the root group size.
1006pub fn activate(
1007    bar_id: ViewId,
1008    bar_menu: Menu,
1009    bar_bounds: Rect,
1010    owner_size: Point,
1011    open_index: Option<usize>,
1012    ctx: &mut Context,
1013) {
1014    // The bar's initial highlight: the matched item (Alt-shortcut) or the menu
1015    // default (cmMenu / kbF10).
1016    let initial = open_index.or(bar_menu.default);
1017    // autoSelect is True only for the Alt-shortcut path (it doSelects); cmMenu
1018    // resets it to False (Blocker 1 / 3).
1019    let auto_select = open_index.is_some();
1020
1021    // Alt-shortcut to a top-level COMMAND item (`tmnuview.cpp:388`: doSelect on a
1022    // command → result = command): post it and open NO session (the menu never
1023    // appears, faithful to execView returning the command immediately).
1024    if let Some(idx) = open_index
1025        && let Some(MenuItem::Command {
1026            command, disabled, ..
1027        }) = bar_menu.items.get(idx)
1028        && !*disabled
1029    {
1030        ctx.post(*command);
1031        return;
1032    }
1033
1034    let bar_level = bar_level(bar_id, bar_menu.clone(), initial, bar_bounds, auto_select);
1035    let mut session = MenuSession::new(vec![bar_level], owner_size);
1036
1037    // Push the bar's initial highlight for draw.
1038    ctx.request_set_menu_current(bar_id, initial);
1039
1040    // Open the first box ONLY for the Alt-shortcut path (open_index is Some) — NOT
1041    // for cmMenu, which only highlights the default (Blocker 1). The matched item
1042    // must name a non-disabled submenu.
1043    if let Some(idx) = open_index
1044        && let Some(MenuItem::SubMenu { menu, disabled, .. }) = bar_menu.items.get(idx)
1045        && !*disabled
1046    {
1047        let submenu = menu.clone();
1048        session.open_submenu(idx, submenu, ctx);
1049    }
1050
1051    ctx.push_capture(Box::new(session));
1052}
1053
1054/// Build the bar [`MenuLevel`] with the transient mouse flags freshly initialized
1055/// (`last_target_item: None`, `mouse_active: false`, `first_event: true`). Shared
1056/// by [`activate`] (keyboard) and [`activate_mouse`].
1057fn bar_level(
1058    bar_id: ViewId,
1059    menu: Menu,
1060    current: Option<usize>,
1061    bounds: Rect,
1062    auto_select: bool,
1063) -> MenuLevel {
1064    MenuLevel {
1065        view_id: bar_id,
1066        menu,
1067        current,
1068        bounds,
1069        is_bar: true,
1070        auto_select,
1071        last_target_item: None,
1072        mouse_active: false,
1073        first_event: true,
1074    }
1075}
1076
1077/// Open a menu session from the **bar** on a mouse press: push the session, then
1078/// re-post the click so the session's press arm processes it.
1079///
1080/// Unlike the hotkey [`activate`], this opens **no box up front**: the re-posted
1081/// click drives the session's press arm (track to the clicked title, set
1082/// `auto_select`) and the open gate, which yields the correct
1083/// `auto_select`/`last_target_item` for the second-click-closes behaviour.
1084///
1085/// `bar_menu` is a clone of the bar's `menu`; `bar_bounds` its bounds in the root
1086/// frame (the bar is at `(0,0)`, so the click delivered to `handle_event` is
1087/// already root-frame); `owner_size` the root group size; `mouse` the click to
1088/// re-post.
1089pub fn activate_mouse(
1090    bar_id: ViewId,
1091    bar_menu: Menu,
1092    bar_bounds: Rect,
1093    owner_size: Point,
1094    mouse: MouseEvent,
1095    ctx: &mut Context,
1096) {
1097    // execute()'s prologue sets current = menu->deflt; the re-posted click's
1098    // evMouseDown arm trackMouses to the clicked title and sets auto_select.
1099    let initial = bar_menu.default;
1100    let bar_level = bar_level(bar_id, bar_menu, initial, bar_bounds, false);
1101    let session = MenuSession::new(vec![bar_level], owner_size);
1102
1103    // Initial highlight (the menu default) for draw.
1104    ctx.request_set_menu_current(bar_id, initial);
1105    // Push the session, then re-post the click so the session (now on the stack)
1106    // processes it through its evMouseDown arm on the next pump and opens the
1107    // clicked title's box.
1108    ctx.push_capture(Box::new(session));
1109    ctx.put_event(Event::MouseDown(mouse));
1110}
1111
1112// ---------------------------------------------------------------------------
1113// TMenuPopup — a standalone popup menu (popupMenu, popupmnu.cpp)
1114// ---------------------------------------------------------------------------
1115
1116/// Open a standalone context popup [`MenuBox`](crate::menu::MenuBox) near `where_`, run as a single-box
1117/// [`MenuSession`] on the capture stack.
1118///
1119/// This is a single box level (no bar above it) consuming events on the capture
1120/// stack — the same handler as a bar dropdown, minus the bar. Two popup-specific
1121/// behaviours:
1122///
1123/// * **No default highlight on open**: the level starts with nothing highlighted
1124///   AND its cloned [`Menu::default`] is cleared, so a mouse release on a margin
1125///   highlights the first item.
1126/// * **No exit-click re-post**: a click outside the popup closes it without
1127///   re-posting the click, so the session's
1128///   [`put_click_event_on_exit`](MenuSession) is set `false`.
1129///
1130/// `where_` is in root-group coords (the root group is at `(0,0)`). `owner_size` is
1131/// the root group size.
1132///
1133/// This function returns immediately; the chosen command arrives later via
1134/// [`Context::post`] (in `end_session_with`) when
1135/// the user selects an item, reaching the active routing. A popup needs no separate
1136/// accelerator handling: it is run modally and the session owns the event loop, so
1137/// the flat loop's hotkey handling already covers it.
1138///
1139/// # Turbo Vision heritage
1140/// Ports `popupMenu`/`TMenuPopup` (`popupmnu.cpp`/`tmenupop.cpp`/`menus.h`). The
1141/// blocking modal call becomes an async capture-stack session that posts the
1142/// chosen command (deviation D9); the `receiver` group argument is dropped because
1143/// there is no per-receiver routing seam.
1144pub fn popup_menu(where_: Point, menu: Menu, owner_size: Point, ctx: &mut Context) {
1145    let bounds = auto_place_popup(where_, &menu, owner_size);
1146    let id = ViewId::next();
1147    // The popup box clears its default (`menu->deflt = 0`, tmenupop.cpp:51) — no
1148    // highlight on open, and the margin-release arm picks the first item, not a
1149    // default.
1150    let mut menu = menu;
1151    menu.default = None;
1152    ctx.request_open_menu_box(id, menu.clone(), bounds);
1153    let level = MenuLevel {
1154        view_id: id,
1155        menu,
1156        current: None, // menu->deflt = 0
1157        bounds,
1158        is_bar: false,
1159        auto_select: false,
1160        last_target_item: None,
1161        mouse_active: false,
1162        first_event: true,
1163    };
1164    let mut session = MenuSession::new(vec![level], owner_size);
1165    // (A) TMenuPopup: putClickEventOnExit = False (tmenupop.cpp:45).
1166    session.put_click_event_on_exit = false;
1167    // No initial highlight (menu->deflt == 0).
1168    ctx.request_set_menu_current(id, None);
1169    ctx.push_capture(Box::new(session));
1170}
1171
1172/// Place a freshly-built popup box near the click point `p`.
1173///
1174/// The box is first sized by [`menu_box_rect`] from a zero-size hint at `p`, which
1175/// lands it **above-left** of `p`. It is then moved to sit **below-right** of `p`
1176/// (top-left at `(p.x, p.y + 1)`), each axis clamped so the box stays inside the
1177/// desktop; if it would then cover `p` and there is room above, it is shifted up so
1178/// its bottom edge sits at `p.y`, keeping the click row visible.
1179///
1180/// # Turbo Vision heritage
1181/// Ports `autoPlacePopup` (`popupmnu.cpp`).
1182fn auto_place_popup(p: Point, menu: &Menu, owner_size: Point) -> Rect {
1183    // r = getRect(TRect(p, p), menu) → (p - size)..p (above-left of p).
1184    let mut r = menu_box_rect(Rect::new(p.x, p.y, p.x, p.y), menu);
1185    let size_x = r.b.x - r.a.x; // m->size.x
1186    let size_y = r.b.y - r.a.y; // m->size.y
1187    // d = app->size - p.
1188    let dx = owner_size.x - p.x;
1189    let dy = owner_size.y - p.y;
1190    // r.move(min(size.x, d.x), min(size.y + 1, d.y)) → top-left toward (p.x, p.y+1),
1191    // clamped so the box stays inside the desktop.
1192    r.r#move(size_x.min(dx), (size_y + 1).min(dy));
1193    // If the box still covers p and there is room above it (its height fits above
1194    // p), shift it up so its bottom edge is exactly at p.y.
1195    if r.contains(p) && (r.b.y - r.a.y) < p.y {
1196        r.r#move(0, -(r.b.y - p.y));
1197    }
1198    r
1199}
1200
1201#[cfg(test)]
1202mod tests {
1203    use super::*;
1204    use crate::command::Command;
1205    use crate::help::HelpCtx;
1206
1207    // ---------------------------------------------------------------------------
1208    // MenuSession::help_ctx — mirrors TMenuView::getHelpCtx
1209    // ---------------------------------------------------------------------------
1210
1211    /// Build a bare `MenuLevel` for test purposes (all transient flags at their
1212    /// level-entry defaults).
1213    fn make_level(menu: Menu, current: Option<usize>, is_bar: bool) -> MenuLevel {
1214        let id = ViewId::next();
1215        MenuLevel {
1216            view_id: id,
1217            menu,
1218            current,
1219            bounds: Rect::new(0, 0, 40, 1),
1220            is_bar,
1221            auto_select: false,
1222            last_target_item: None,
1223            mouse_active: false,
1224            first_event: false,
1225        }
1226    }
1227
1228    /// `help_ctx` returns the highlighted item's context when it is non-NO_CONTEXT.
1229    ///
1230    /// Session has a bar level (no highlight) and a box level whose second item
1231    /// (a Command with a distinct HelpCtx) is highlighted. The walk must find the
1232    /// box item and return its context.
1233    #[test]
1234    fn help_ctx_returns_highlighted_item_context() {
1235        const SAVE_CTX: HelpCtx = HelpCtx::custom("test.save");
1236
1237        // Bar level — nothing highlighted.
1238        let bar_menu = Menu::builder()
1239            .submenu("~F~ile", None, |m| {
1240                m.item(MenuItem::Command {
1241                    name: "~S~ave".to_string(),
1242                    command: Command::SAVE,
1243                    key_code: None,
1244                    param: None,
1245                    help_ctx: SAVE_CTX,
1246                    disabled: false,
1247                })
1248            })
1249            .build();
1250        let bar = make_level(bar_menu, None, true);
1251
1252        // Box level — item 0 (Open) has NO_CONTEXT; item 1 (Save) has SAVE_CTX.
1253        let box_menu = Menu::builder()
1254            .item(MenuItem::Command {
1255                name: "~O~pen".to_string(),
1256                command: Command::OPEN,
1257                key_code: None,
1258                param: None,
1259                help_ctx: HelpCtx::NO_CONTEXT,
1260                disabled: false,
1261            })
1262            .item(MenuItem::Command {
1263                name: "~S~ave".to_string(),
1264                command: Command::SAVE,
1265                key_code: None,
1266                param: None,
1267                help_ctx: SAVE_CTX,
1268                disabled: false,
1269            })
1270            .build();
1271        // Highlight item 1 (Save).
1272        let box_level = make_level(box_menu, Some(1), false);
1273
1274        let session = MenuSession::new(vec![bar, box_level], Point::new(80, 25));
1275
1276        assert_eq!(
1277            session.help_ctx(),
1278            SAVE_CTX,
1279            "highlighted Save item's context must be returned"
1280        );
1281    }
1282
1283    /// `help_ctx` falls back to `NO_CONTEXT` when no level has a qualifying item.
1284    ///
1285    /// Cases covered:
1286    /// - `current` is `None` (nothing highlighted)
1287    /// - `current` points at a `NO_CONTEXT` command
1288    /// - `current` points at a `Separator`
1289    #[test]
1290    fn help_ctx_fallback_cases_return_no_context() {
1291        // No current on any level.
1292        let session = MenuSession::new(vec![make_bar()], Point::new(80, 25));
1293        assert_eq!(
1294            session.help_ctx(),
1295            HelpCtx::NO_CONTEXT,
1296            "nothing highlighted → NO_CONTEXT"
1297        );
1298
1299        // Current points at a command with NO_CONTEXT.
1300        let box_menu = Menu::builder()
1301            .command("~O~pen", Command::OPEN) // NO_CONTEXT by default
1302            .build();
1303        let box_level = make_level(box_menu, Some(0), false);
1304        let session2 = MenuSession::new(vec![make_bar(), box_level], Point::new(80, 25));
1305        assert_eq!(
1306            session2.help_ctx(),
1307            HelpCtx::NO_CONTEXT,
1308            "item with NO_CONTEXT → NO_CONTEXT"
1309        );
1310
1311        // Current points at a Separator.
1312        let sep_menu = Menu {
1313            items: vec![MenuItem::Separator],
1314            default: None,
1315        };
1316        let sep_level = make_level(sep_menu, Some(0), false);
1317        let session3 = MenuSession::new(vec![make_bar(), sep_level], Point::new(80, 25));
1318        assert_eq!(
1319            session3.help_ctx(),
1320            HelpCtx::NO_CONTEXT,
1321            "separator highlight → NO_CONTEXT"
1322        );
1323    }
1324
1325    /// `help_ctx` walks from the deepest (top) level toward the bar, stopping at
1326    /// the first qualifying item. Even when the bar has a highlighted title with a
1327    /// context, the box's item wins if it also has a context.
1328    #[test]
1329    fn help_ctx_deepest_level_wins() {
1330        const BAR_CTX: HelpCtx = HelpCtx::custom("test.bar_title");
1331        const BOX_CTX: HelpCtx = HelpCtx::custom("test.box_item");
1332
1333        // Bar level — item 0 is a SubMenu with BAR_CTX, highlighted.
1334        let bar_menu = Menu {
1335            items: vec![MenuItem::SubMenu {
1336                name: "~F~ile".to_string(),
1337                key_code: None,
1338                help_ctx: BAR_CTX,
1339                disabled: false,
1340                menu: Menu::default(),
1341            }],
1342            default: Some(0),
1343        };
1344        let bar = make_level(bar_menu, Some(0), true);
1345
1346        // Box level — a Command with BOX_CTX, highlighted.
1347        let box_menu = Menu {
1348            items: vec![MenuItem::Command {
1349                name: "~S~ave".to_string(),
1350                command: Command::SAVE,
1351                key_code: None,
1352                param: None,
1353                help_ctx: BOX_CTX,
1354                disabled: false,
1355            }],
1356            default: Some(0),
1357        };
1358        let box_level = make_level(box_menu, Some(0), false);
1359
1360        let session = MenuSession::new(vec![bar, box_level], Point::new(80, 25));
1361
1362        // The box (deeper / top of stack) must win.
1363        assert_eq!(
1364            session.help_ctx(),
1365            BOX_CTX,
1366            "deepest level's item context must win over the bar's"
1367        );
1368    }
1369
1370    // ---------------------------------------------------------------------------
1371    // FIX D tests — disabled items, menu_help_ctx / active_menu_help_ctx semantics
1372    // ---------------------------------------------------------------------------
1373
1374    /// Build the "File" bar level used by the fallback test cases (DRYs the three
1375    /// inline repetitions that each needed the same empty bar).
1376    fn make_bar() -> MenuLevel {
1377        make_level(
1378            Menu::builder()
1379                .submenu("~F~ile", None, |m| m.command("Exit", Command::QUIT))
1380                .build(),
1381            None,
1382            true,
1383        )
1384    }
1385
1386    /// `help_ctx` does NOT skip a **disabled** item that has a non-NO_CONTEXT
1387    /// `help_ctx`. The C++ `getHelpCtx` walk (`tmnuview.cpp:453-468`) checks
1388    /// `helpCtx != hcNoContext` — it does not filter by disabled.
1389    #[test]
1390    fn help_ctx_disabled_item_with_context_is_returned() {
1391        const OPEN_CTX: HelpCtx = HelpCtx::custom("test.open_disabled");
1392
1393        let box_menu = Menu {
1394            items: vec![MenuItem::Command {
1395                name: "~O~pen".to_string(),
1396                command: Command::OPEN,
1397                key_code: None,
1398                param: None,
1399                help_ctx: OPEN_CTX,
1400                disabled: true, // disabled, but context still surfaced
1401            }],
1402            default: None,
1403        };
1404        let box_level = make_level(box_menu, Some(0), false);
1405        let session = MenuSession::new(vec![make_bar(), box_level], Point::new(80, 25));
1406
1407        assert_eq!(
1408            session.help_ctx(),
1409            OPEN_CTX,
1410            "disabled item with non-NO_CONTEXT help_ctx must still be returned"
1411        );
1412    }
1413
1414    /// `menu_help_ctx` returns `Some(NO_CONTEXT)` — not `None` — when the
1415    /// highlighted item has `NO_CONTEXT`. This makes an open menu preempt any view
1416    /// behind it, matching C++ `TopView()->getHelpCtx()` semantics.
1417    #[test]
1418    fn menu_help_ctx_yields_some_no_context_when_item_is_no_context() {
1419        let box_menu = Menu::builder()
1420            .command("~O~pen", Command::OPEN) // NO_CONTEXT by default
1421            .build();
1422        let box_level = make_level(box_menu, Some(0), false);
1423        let session = MenuSession::new(vec![make_bar(), box_level], Point::new(80, 25));
1424
1425        // help_ctx() must be NO_CONTEXT …
1426        assert_eq!(session.help_ctx(), HelpCtx::NO_CONTEXT);
1427        // … but menu_help_ctx() must return Some, not None, so it preempts.
1428        assert_eq!(
1429            session.menu_help_ctx(),
1430            Some(HelpCtx::NO_CONTEXT),
1431            "open menu yields Some(NO_CONTEXT) to preempt views below it"
1432        );
1433    }
1434
1435    /// `CaptureStack::active_menu_help_ctx` returns the topmost handler's context
1436    /// (not a lower handler's), and returns `None` when the stack is empty.
1437    #[test]
1438    fn active_menu_help_ctx_uses_topmost_handler_only() {
1439        use crate::capture::CaptureStack;
1440
1441        const ITEM_CTX: HelpCtx = HelpCtx::custom("test.item_ctx");
1442
1443        // A session with a NO_CONTEXT highlighted item on the stack.
1444        let no_ctx_session = {
1445            let box_menu = Menu::builder()
1446                .command("~O~pen", Command::OPEN) // NO_CONTEXT
1447                .build();
1448            let box_level = make_level(box_menu, Some(0), false);
1449            MenuSession::new(vec![make_bar(), box_level], Point::new(80, 25))
1450        };
1451
1452        let mut stack = CaptureStack::new();
1453        // Empty stack → None.
1454        assert_eq!(stack.active_menu_help_ctx(), None, "no handlers → None");
1455
1456        stack.push(Box::new(no_ctx_session));
1457        // Topmost handler has NO_CONTEXT → Some(NO_CONTEXT), not None.
1458        assert_eq!(
1459            stack.active_menu_help_ctx(),
1460            Some(HelpCtx::NO_CONTEXT),
1461            "open menu with NO_CONTEXT item yields Some(NO_CONTEXT)"
1462        );
1463
1464        // Now build a session whose top level has a real context.
1465        let ctx_session = {
1466            let box_menu = Menu {
1467                items: vec![MenuItem::Command {
1468                    name: "~S~ave".to_string(),
1469                    command: Command::SAVE,
1470                    key_code: None,
1471                    param: None,
1472                    help_ctx: ITEM_CTX,
1473                    disabled: false,
1474                }],
1475                default: None,
1476            };
1477            let box_level = make_level(box_menu, Some(0), false);
1478            MenuSession::new(vec![make_bar(), box_level], Point::new(80, 25))
1479        };
1480
1481        // Replace the stack with just this session.
1482        let mut stack2 = CaptureStack::new();
1483        stack2.push(Box::new(ctx_session));
1484        assert_eq!(
1485            stack2.active_menu_help_ctx(),
1486            Some(ITEM_CTX),
1487            "topmost session with real context yields Some(ctx)"
1488        );
1489    }
1490
1491    // ---------------------------------------------------------------------------
1492    // Legacy geometry tests follow
1493    // ---------------------------------------------------------------------------
1494
1495    /// A flat two-command menu sized exactly like the program-test `popup_data`:
1496    /// every label fits the `menu_box_rect` minimum, so the box is 10 wide and
1497    /// `2 + 2 = 4` rows tall (`size_x == 10`, `size_y == 4`).
1498    fn popup_data() -> Menu {
1499        Menu::builder()
1500            .command("~C~ut", Command::CUT)
1501            .command("~C~opy", Command::custom("test.copy"))
1502            .build()
1503    }
1504
1505    /// `auto_place_popup` with room everywhere puts the box below-right of `p`:
1506    /// top-left at `(p.x, p.y + 1)`, and the right edge stays inside the desktop.
1507    #[test]
1508    fn auto_place_popup_below_right_with_room() {
1509        let menu = popup_data();
1510        let p = Point::new(5, 2);
1511        let owner = Point::new(40, 12);
1512        let r = auto_place_popup(p, &menu, owner);
1513
1514        // size_x = 10, size_y = 4 → box = Rect(5,3,15,7).
1515        assert_eq!(r.a, Point::new(p.x, p.y + 1), "top-left at (p.x, p.y+1)");
1516        assert_eq!(r, Rect::new(5, 3, 15, 7), "the full below-right box");
1517        assert!(r.b.x <= owner.x, "right edge clamped inside the desktop");
1518        assert!(
1519            !r.contains(p),
1520            "with room everywhere the box does NOT cover the click point",
1521        );
1522    }
1523
1524    /// `auto_place_popup` near the desktop bottom: the vertical clamp would leave the
1525    /// box covering `p`, so (room above) it is shifted up until its bottom edge sits
1526    /// at `p.y` — the click row stays visible.
1527    ///
1528    /// BITE: drop the `if r.contains(p) ...` shift in [`auto_place_popup`] → the box
1529    /// stays at `Rect(5,8,15,12)`, covering the click row (`r.b.y == 12 != p.y`),
1530    /// failing the `r.b.y == p.y` assert.
1531    #[test]
1532    fn auto_place_popup_bottom_edge_shifts_up() {
1533        let menu = popup_data();
1534        let p = Point::new(5, 10);
1535        let owner = Point::new(40, 12);
1536        let r = auto_place_popup(p, &menu, owner);
1537
1538        // d = (35, 2); move(min(10,35)=10, min(5,2)=2) → Rect(5,8,15,12) covers p
1539        // (y=10 ∈ [8,12)) and height 4 < p.y=10 → shift move(0, -(12-10)) → Rect(5,6,15,10).
1540        assert_eq!(
1541            r,
1542            Rect::new(5, 6, 15, 10),
1543            "shifted up to clear the click row"
1544        );
1545        assert_eq!(
1546            r.b.y, p.y,
1547            "the box's bottom edge sits exactly at the click row"
1548        );
1549        assert!(
1550            !r.contains(p),
1551            "after the shift the box no longer covers the click point",
1552        );
1553        assert!(
1554            r.b.x <= owner.x,
1555            "right edge still clamped inside the desktop"
1556        );
1557    }
1558}