Guide API
Skip to main content

tvision_rs/menu/
menu_box.rs

1//! The drop-down / pop-up menu box.
2//!
3//! [`MenuBox`] is a framed, shadowed [`MenuView`] that lays its items out
4//! vertically, one per row. The box-specific work is its layout: the static
5//! [`menu_box_rect`] sizing helper, `frame_line`,
6//! [`draw`](MenuBox::draw), and [`get_item_rect`](MenuView::get_item_rect). Its
7//! [`handle_event`](MenuBox::handle_event) delegates to the shared passive
8//! [`menu_view::handle_event`]; the interactive navigation runs in the menu
9//! session that owns the open box.
10//!
11//! ## The inset frame (intentional, **not** a bug)
12//!
13//! `frame_line` writes the corner/edge glyph at columns 1
14//! and `size.x-2`, leaving **column 0 and column `size.x-1` blank**. The menu-box
15//! frame is deliberately inset one column on each side (those outer columns are
16//! spaces in the frame-glyph table), and the snapshot captures it. Do not
17//! "correct" it.
18//!
19//! ## The per-line colour fill
20//!
21//! Each frame row fills the **interior** columns `[2, size.x-2)` with a per-line
22//! colour (its lo style), while the border cells keep the normal box style. A
23//! selected or disabled item row highlights its interior by passing that colour
24//! into the middle frame row, then the name is drawn over it in the same colour.
25//!
26//! As with [`MenuBar`](crate::menu::MenuBar), [`MenuViewState`] embeds a
27//! [`ViewState`] (not a `View`), so the differing [`View`] methods are
28//! hand-written rather than generated.
29//!
30//! # Turbo Vision heritage
31//! Ports `TMenuBox` (`tmenubox.cpp`/`menus.h`). The `TMenuView` base becomes the
32//! [`MenuView`] trait (deviation D2); `TStreamable` persistence is dropped
33//! (deviation D12).
34
35use crate::event::Event;
36use crate::menu::menu_view::{self, MenuColors, MenuView, MenuViewState};
37use crate::menu::{Menu, MenuItem};
38use crate::view::{Context, DrawCtx, Rect, View, ViewState};
39
40/// Display width of a `~`-marked label, ignoring the `~` markers. Per-module copy
41/// mirroring `button.rs` (see [`MenuBar`]).
42///
43/// [`MenuBar`]: crate::menu::MenuBar
44fn cstrlen(s: &str) -> i32 {
45    s.chars()
46        .filter(|&c| c != '~')
47        .map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) as i32)
48        .sum()
49}
50
51/// Compute the box bounds that fit `menu` inside `bounds`.
52///
53/// **Width** starts at a floor of 10 and grows to the widest item. The per-item
54/// column budget is:
55/// - command with shortcut text: `cstrlen(name) + 6 + cstrlen(param) + 2`
56/// - submenu entry: `cstrlen(name) + 6 + 3` (the `+3` reserves a column for `►`)
57/// - command without shortcut: `cstrlen(name) + 6`
58/// - separator: no width contribution (but still adds a row)
59///
60/// **Height** is `2 + item_count` — 2 for the top and bottom borders plus one
61/// row per item, separators included. The computed `(width, height)` is then
62/// clamped into `bounds`: the box prefers its preferred size but is pushed
63/// against the far edge when the available space is smaller.
64///
65/// The menu session calls this to size each submenu box as it opens; you can
66/// also call it directly to pre-compute a popup box's bounds before passing them
67/// to [`popup_menu`](crate::menu::popup_menu).
68///
69/// # Turbo Vision heritage
70/// Ports the static `getRect` sizing helper (`tmenubox.cpp`).
71pub fn menu_box_rect(bounds: Rect, menu: &Menu) -> Rect {
72    let mut w = 10;
73    let mut h = 2;
74    for item in &menu.items {
75        match item {
76            MenuItem::Separator => {} // no width, but still takes a row (h++ below).
77            MenuItem::SubMenu { name, .. } => {
78                // a submenu: + 3 for the "►" marker column.
79                let l = cstrlen(name) + 6 + 3;
80                w = l.max(w);
81            }
82            MenuItem::Command { name, param, .. } => {
83                let mut l = cstrlen(name) + 6;
84                if let Some(p) = param {
85                    // shortcut text: + its width + 2 for the right-aligned shortcut.
86                    l += cstrlen(p) + 2;
87                }
88                w = l.max(w);
89            }
90        }
91        h += 1; // every item takes a row.
92    }
93
94    let mut r = bounds;
95    if r.a.x + w < r.b.x {
96        r.b.x = r.a.x + w;
97    } else {
98        r.a.x = r.b.x - w;
99    }
100    if r.a.y + h < r.b.y {
101        r.b.y = r.a.y + h;
102    } else {
103        r.a.y = r.b.y - h;
104    }
105    r
106}
107
108/// The framed, shadowed vertical menu box. Holds the shared [`MenuViewState`];
109/// the box-specific layout lives in the methods below.
110///
111/// # Turbo Vision heritage
112/// Ports `TMenuBox` (`tmenubox.cpp`/`menus.h`).
113pub struct MenuBox {
114    mv: MenuViewState,
115}
116
117impl MenuBox {
118    /// Construct a menu box presenting `menu`, sized by [`menu_box_rect`] to fit
119    /// inside `bounds`.
120    ///
121    /// `bounds` is the hint rect within which the box must fit — typically the
122    /// remaining desktop area below and to the right of the parent item. The
123    /// actual bounds are computed by [`menu_box_rect`] (the box shrinks to its
124    /// content). The box casts a drop shadow (`state.shadow = true`) and
125    /// pre-processes events (`options.pre_process = true`) so it intercepts
126    /// accelerator keys before the focused view.
127    ///
128    /// Under normal operation the menu session constructs boxes on your behalf
129    /// via `Deferred::OpenMenuBox`; call `MenuBox::new` directly only in tests
130    /// or when building a standalone draw fixture.
131    pub fn new(bounds: Rect, menu: Menu) -> Self {
132        let rect = menu_box_rect(bounds, &menu);
133        let mut state = ViewState::new(rect);
134        state.state.shadow = true; // drop shadow
135        state.options.pre_process = true; // see accelerators before focused view
136        MenuBox {
137            mv: MenuViewState::new(state, menu),
138        }
139    }
140
141    /// Draw one box-frame row of style `kind`, with the interior columns in
142    /// `color` and the border cells in `c_normal`.
143    ///
144    /// The single-line box glyphs (all from [`Glyphs`](crate::theme::Glyphs)):
145    /// ```text
146    /// kind  cols 0,1        cols [2, size.x-2)   cols size.x-2, size.x-1
147    /// Top   ' '  ┌          ─                    ┐  ' '
148    /// Bot   ' '  └          ─                    ┘  ' '
149    /// Mid   ' '  │          ' '                  │  ' '
150    /// Sep   ' '  ├          ─                    ┤  ' '
151    /// ```
152    /// Columns 0 and `size.x-1` are blank — the intentional inset (see the module
153    /// doc).
154    fn frame_line(
155        ctx: &mut DrawCtx,
156        size_x: i32,
157        y: i32,
158        kind: FrameKind,
159        c_normal: crate::color::Style,
160        color: crate::color::Style,
161    ) {
162        let g = ctx.glyphs();
163        let (g0, g1, fill, g3, g4) = match kind {
164            // n=0:  ' ' ┌ ─ ┐ ' '
165            FrameKind::Top => (' ', g.frame_tl, g.frame_h, g.frame_tr, ' '),
166            // n=5:  ' ' └ ─ ┘ ' '
167            FrameKind::Bottom => (' ', g.frame_bl, g.frame_h, g.frame_br, ' '),
168            // n=10: ' ' │ ' ' │ ' '
169            FrameKind::Middle => (' ', g.frame_v, ' ', g.frame_v, ' '),
170            // n=15: ' ' ├ ─ ┤ ' '
171            FrameKind::Separator => (' ', g.frame_tee_l, g.frame_h, g.frame_tee_r, ' '),
172        };
173        // b.moveBuf(0, &frameChars[n], cNormal, 2) — cols 0, 1 in cNormal.
174        ctx.put_char(0, y, g0, c_normal);
175        ctx.put_char(1, y, g1, c_normal);
176        // b.moveChar(2, frameChars[n+2], color, size.x - 4) — interior in `color`.
177        ctx.fill(Rect::new(2, y, size_x - 2, y + 1), fill, color);
178        // b.moveBuf(size.x-2, &frameChars[n+3], cNormal, 2) — last two in cNormal.
179        ctx.put_char(size_x - 2, y, g3, c_normal);
180        ctx.put_char(size_x - 1, y, g4, c_normal);
181    }
182}
183
184/// Which frame row to draw.
185#[derive(Clone, Copy)]
186enum FrameKind {
187    /// The top border.
188    Top,
189    /// The bottom border.
190    Bottom,
191    /// An item row (vertical edges, blank interior).
192    Middle,
193    /// A separator row (a `├──┤` divider).
194    Separator,
195}
196
197impl MenuView for MenuBox {
198    fn mv(&self) -> &MenuViewState {
199        &self.mv
200    }
201
202    fn mv_mut(&mut self) -> &mut MenuViewState {
203        &mut self.mv
204    }
205
206    /// The rect of item `index`, counting rows from `y = 1` (just below the top
207    /// border).
208    ///
209    /// Every item — separators included — occupies exactly one row, so the row is
210    /// the closed form `y = 1 + index`, and the rect spans the interior columns
211    /// `[2, size.x - 2)`. (Unlike the bar's layout, where separators consume no
212    /// horizontal space and a running walk is genuinely needed.)
213    fn get_item_rect(&self, index: usize) -> Rect {
214        let y = 1 + index as i32;
215        let size_x = self.mv.state.size.x;
216        Rect::new(2, y, size_x - 2, y + 1)
217    }
218}
219
220impl View for MenuBox {
221    fn state(&self) -> &ViewState {
222        &self.mv.state
223    }
224
225    fn state_mut(&mut self) -> &mut ViewState {
226        &mut self.mv.state
227    }
228
229    /// Draw the top border, one row per item, then the bottom border.
230    ///
231    /// The colours come from [`MenuColors`] (the same matrix as
232    /// [`MenuBar`](crate::menu::MenuBar)). For each named item the per-line colour
233    /// is set to the selected/disabled lo style (or stays the normal box style),
234    /// the frame row is drawn with its interior filled in that colour, then the
235    /// label is drawn over it. A submenu gets the `►` marker near the right edge; a
236    /// command with shortcut text gets that text right-aligned.
237    fn draw(&mut self, ctx: &mut DrawCtx) {
238        let colors = MenuColors::resolve(ctx);
239        let c_normal = colors.normal.0; // cNormal lo — the border style.
240        let marker = ctx.glyphs().input_right_arrow; // ► (CP437 \x10)
241
242        let size = self.mv.state.size;
243        let mut y = 0;
244
245        // Top border (n = 0), interior in cNormal.
246        MenuBox::frame_line(ctx, size.x, y, FrameKind::Top, c_normal, c_normal);
247        y += 1;
248
249        for (i, item) in self.mv.menu.items.iter().enumerate() {
250            match item {
251                MenuItem::Separator => {
252                    // C++ p->name == 0: a separator row (n = 15), interior in cNormal.
253                    MenuBox::frame_line(ctx, size.x, y, FrameKind::Separator, c_normal, c_normal);
254                }
255                MenuItem::Command {
256                    name,
257                    param,
258                    disabled,
259                    ..
260                } => {
261                    let selected = self.mv.current == Some(i);
262                    // The per-line color/hi (cNormal unless selected/disabled).
263                    let (lo, hi) = colors.item(*disabled, selected);
264                    // frameLine(10): interior filled in `lo`, then the name over it.
265                    MenuBox::frame_line(ctx, size.x, y, FrameKind::Middle, c_normal, lo);
266                    ctx.put_cstr(3, y, name, lo, hi);
267                    if let Some(p) = param {
268                        // b.moveCStr(size.x-3-cstrlen(param), param, color).
269                        ctx.put_cstr(size.x - 3 - cstrlen(p), y, p, lo, hi);
270                    }
271                }
272                MenuItem::SubMenu { name, disabled, .. } => {
273                    let selected = self.mv.current == Some(i);
274                    let (lo, hi) = colors.item(*disabled, selected);
275                    MenuBox::frame_line(ctx, size.x, y, FrameKind::Middle, c_normal, lo);
276                    ctx.put_cstr(3, y, name, lo, hi);
277                    // command == 0 (submenu): b.putChar(size.x-4, ►).
278                    ctx.put_char(size.x - 4, y, marker, lo);
279                }
280            }
281            y += 1;
282        }
283
284        // Bottom border (n = 5), interior in cNormal.
285        MenuBox::frame_line(ctx, size.x, y, FrameKind::Bottom, c_normal, c_normal);
286    }
287
288    /// Delegates to the passive [`menu_view::handle_event`]; the box adds no event
289    /// logic of its own (interactive navigation lives in the menu session).
290    fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
291        menu_view::handle_event(&self.mv, ev, ctx);
292    }
293
294    /// Write the session-owned highlight index — the pump's
295    /// [`Deferred::SetMenuCurrent`](crate::view::Deferred::SetMenuCurrent) broker
296    /// target. A box is never focused; the
297    /// [`MenuSession`](crate::menu::MenuSession) drives its highlight through here.
298    fn set_menu_current(&mut self, current: Option<usize>) {
299        self.mv.current = current;
300    }
301
302    /// Expose the concrete box so the pump / tests can introspect its
303    /// [`MenuViewState`] (the highlight cache the session drives). Mirrors the
304    /// scroller/list broker downcast precedent.
305    fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
306        Some(self)
307    }
308}
309
310impl MenuBox {
311    /// Read the box's current highlight index (test/inspection hook for the
312    /// session-driven highlight cache).
313    pub fn current(&self) -> Option<usize> {
314        self.mv.current
315    }
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321    use crate::backend::{HeadlessBackend, Renderer};
322    use crate::command::Command;
323    use crate::event::{Key, KeyEvent};
324    use crate::menu::alt;
325    use crate::screen::Buffer;
326    use crate::theme::Theme;
327
328    fn render(b: &mut MenuBox, w: u16, h: u16) -> String {
329        let theme = Theme::classic_blue();
330        let (backend, screen) = HeadlessBackend::new(w, h);
331        let mut r = Renderer::new(Box::new(backend));
332        r.render(|buf: &mut Buffer| {
333            let bounds = b.state().get_bounds();
334            let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
335            b.draw(&mut dc);
336        });
337        screen.snapshot()
338    }
339
340    // -- menu_box_rect sizing -----------------------------------------------
341
342    #[test]
343    fn menu_box_rect_sizes_to_longest_item_and_item_count() {
344        // Items:
345        //   "~O~pen" (cstrlen 4) param "F3" (2)   -> 4 + 6 + 2 + 2 = 14
346        //   "~S~ave" (cstrlen 4) no param         -> 4 + 6        = 10
347        //   "~M~ore" submenu (cstrlen 4)          -> 4 + 6 + 3    = 13
348        // w = max(14, 13, 10, 10) = 14; h = 2 + 3 items = 5.
349        let menu = Menu::builder()
350            .command_key("~O~pen", Command::OPEN, KeyEvent::from(Key::F(3)), "F3")
351            .command("~S~ave", Command::SAVE)
352            .submenu("~M~ore", alt('m'), |m| m.command("~X~", Command::QUIT))
353            .build();
354        // A generous bounds so the box is fully sized (not clamped).
355        let r = menu_box_rect(Rect::new(0, 0, 40, 20), &menu);
356        // width = 14 (the "Open ... F3" row wins).
357        // BITE: dropping the param's "+ cstrlen + 2" would give w = max(10,13,10) =
358        // 13; dropping the submenu's "+ 3" would give 12 from Open=14 -> still 14
359        // here, so the param term is the discriminating one.
360        assert_eq!(r.b.x - r.a.x, 14, "width = longest item (Open + F3 param)");
361        // height = 2 (borders) + 3 items.
362        assert_eq!(r.b.y - r.a.y, 5, "height = items + 2 borders");
363    }
364
365    #[test]
366    fn menu_box_rect_counts_separators_in_height() {
367        // 2 commands + 1 separator -> h = 2 + 3 = 5 (the separator takes a row).
368        let menu = Menu::builder()
369            .command("~A~", Command::OPEN)
370            .separator()
371            .command("~B~", Command::SAVE)
372            .build();
373        let r = menu_box_rect(Rect::new(0, 0, 40, 20), &menu);
374        // BITE: a "separators don't take a row" bug would give h = 2 + 2 = 4.
375        assert_eq!(r.b.y - r.a.y, 5, "separator counts toward height");
376    }
377
378    #[test]
379    fn menu_box_rect_clamps_into_bounds() {
380        // A wide menu inside a narrow bounds: w would be > bounds width, so the
381        // box is pushed against the right edge (a.x = b.x - w), and likewise y.
382        let menu = Menu::builder()
383            .command("~A~", Command::OPEN)
384            .command("~B~", Command::SAVE)
385            .build();
386        // w = 10 (both items short -> the w=10 floor), h = 4.
387        // bounds is 8 wide: 0 + 10 < 8 is false -> a.x = b.x - 10 = 8 - 10 = -2.
388        let r = menu_box_rect(Rect::new(0, 0, 8, 3), &menu);
389        assert_eq!(r.a.x, -2, "narrow bounds clamps a.x = b.x - w");
390        assert_eq!(r.b.x, 8);
391        // h = 4, bounds is 3 tall: 0 + 4 < 3 false -> a.y = b.y - 4 = 3 - 4 = -1.
392        assert_eq!(r.a.y, -1, "short bounds clamps a.y = b.y - h");
393        assert_eq!(r.b.y, 3);
394    }
395
396    #[test]
397    fn menu_box_rect_submenu_plus_three_is_discriminating() {
398        // A submenu is the widest row, and no param item is longer, so the
399        // submenu's "+ 3" (the ► marker column) actually decides the width.
400        //   "~S~ettings" submenu (cstrlen 8) -> 8 + 6 + 3 = 17
401        //   "~O~pen"     command (cstrlen 4) -> 4 + 6     = 10
402        // w = max(17, 10, 10) = 17.
403        let menu = Menu::builder()
404            .submenu("~S~ettings", alt('s'), |m| m.command("~X~", Command::QUIT))
405            .command("~O~pen", Command::OPEN)
406            .build();
407        let r = menu_box_rect(Rect::new(0, 0, 40, 20), &menu);
408        // BITE: dropping the submenu's "+ 3" would give w = max(14, 10, 10) = 14.
409        assert_eq!(
410            r.b.x - r.a.x,
411            17,
412            "width = submenu name + 6 + 3 (the ► marker column)"
413        );
414    }
415
416    // -- get_item_rect ------------------------------------------------------
417
418    #[test]
419    fn get_item_rect_counts_rows_from_one_including_separators() {
420        // A separator before the asserted item proves separators still advance y.
421        let menu = Menu::builder()
422            .command("~A~", Command::OPEN) // idx 0 -> y 1
423            .separator() // idx 1 -> y 2
424            .command("~B~", Command::SAVE) // idx 2 -> y 3
425            .build();
426        let b = MenuBox::new(Rect::new(0, 0, 30, 10), menu);
427        let size_x = b.mv.state.size.x;
428
429        let r0 = b.get_item_rect(0);
430        assert_eq!((r0.a.y, r0.b.y), (1, 2), "first item at row 1");
431        assert_eq!((r0.a.x, r0.b.x), (2, size_x - 2), "x span is [2, size.x-2)");
432
433        let r2 = b.get_item_rect(2);
434        // BITE: a "skip separators" bug would put idx 2 at y = 2 (shifted up one).
435        assert_eq!(
436            (r2.a.y, r2.b.y),
437            (3, 4),
438            "third item at row 3 (separator still advanced y)"
439        );
440    }
441
442    // -- handle_event delegation smoke -------------------------------------
443
444    #[test]
445    fn handle_event_posts_accelerator_command() {
446        use crate::view::{Context, Deferred, Group};
447        use std::collections::VecDeque;
448        // A box whose item has an F3 accelerator; an F3 KeyDown posts cmOpen and
449        // clears the event (proves the passive handler is wired in).
450        let menu = Menu::builder()
451            .command_key("~O~pen", Command::OPEN, KeyEvent::from(Key::F(3)), "F3")
452            .build();
453        let mut group = Group::new(Rect::new(0, 0, 30, 10));
454        let id = group.insert(Box::new(MenuBox::new(Rect::new(2, 2, 20, 8), menu)));
455
456        let mut out = VecDeque::new();
457        let mut timers = crate::timer::TimerQueue::new();
458        let mut deferred: Vec<Deferred> = vec![];
459        let mut ev = Event::KeyDown(KeyEvent::from(Key::F(3)));
460        {
461            let mut ctx = Context::new(&mut out, &mut timers, 0, &mut deferred);
462            group.find_mut(id).unwrap().handle_event(&mut ev, &mut ctx);
463        }
464        assert!(ev.is_nothing(), "F3 accelerator consumed");
465        assert!(
466            out.iter()
467                .any(|e| matches!(e, Event::Command(c) if *c == Command::OPEN)),
468            "F3 posts cmOpen"
469        );
470    }
471
472    // -- draw snapshot ------------------------------------------------------
473
474    #[test]
475    fn snapshot_box_frame_highlight_disabled_separator_param_submenu() {
476        // A box exercising every draw path:
477        //   idx 0 "~O~pen"  param "F3"        (a param/shortcut item)
478        //   idx 1 "~S~ave"  disabled          (greyed)
479        //   idx 2 separator                   (├──┤ divider)
480        //   idx 3 "~M~ore"  submenu           (► marker), highlighted (current = 3)
481        let menu = Menu::builder()
482            .command_key("~O~pen", Command::OPEN, KeyEvent::from(Key::F(3)), "F3")
483            .item(MenuItem::Command {
484                name: "~S~ave".to_string(),
485                command: Command::SAVE,
486                key_code: None,
487                param: None,
488                help_ctx: crate::help::HelpCtx::NO_CONTEXT,
489                disabled: true,
490            })
491            .separator()
492            .submenu("~M~ore", alt('m'), |m| m.command("~X~", Command::QUIT))
493            .build();
494        let mut b = MenuBox::new(Rect::new(0, 0, 40, 20), menu);
495        b.mv.current = Some(3); // highlight the submenu row
496        let size = b.mv.state.size;
497        insta::assert_snapshot!(render(&mut b, size.x as u16, size.y as u16));
498    }
499
500    #[test]
501    fn draw_empty_menu_does_not_panic() {
502        // An empty menu: the box draws top + bottom border (h = 2) with no item
503        // rows. Cheapest guard against an index/iter edge case in draw.
504        let mut b = MenuBox::new(Rect::new(0, 0, 12, 10), Menu::builder().build());
505        let size = b.mv.state.size;
506        let _ = render(&mut b, size.x as u16, size.y as u16); // completes, no panic.
507    }
508}