tvision_rs/menu/menu_bar.rs
1//! The horizontal menu bar.
2//!
3//! [`MenuBar`] is a one-row [`MenuView`] that lays its top-level items out
4//! left-to-right. The bar-specific work is its layout — [`draw`](MenuBar::draw)
5//! and [`get_item_rect`](MenuView::get_item_rect). Its
6//! [`handle_event`](MenuBar::handle_event) delegates to the shared passive
7//! [`menu_view::handle_event`], which handles the command-graying broadcast,
8//! posts an accelerator's command, and opens the menu session on a bar hotkey.
9//!
10//! Because [`MenuViewState`] embeds a [`ViewState`] (not a `View`), the differing
11//! [`View`] methods (`state`/`state_mut`/`draw`/`handle_event`) are hand-written,
12//! like [`ListBox`](crate::widgets::ListBox), rather than generated by the
13//! `#[delegate]` macro.
14//!
15//! A menu bar holding a startup-disabled command would draw it enabled until the
16//! first command-set-changed broadcast, which does not fire at startup; so
17//! [`Program::new`](crate::app::Program::new) seeds each inserted bar by calling
18//! [`update_menu_commands`](View::update_menu_commands) directly with the initial
19//! disabled-command set.
20//!
21//! # Turbo Vision heritage
22//! Ports `TMenuBar` (`tmenubar.cpp`/`menus.h`). The `TMenuView` base becomes the
23//! [`MenuView`] trait (deviation D2); the disabled-command set is held as a
24//! denylist (deviation D1) and `TStreamable` persistence is dropped (deviation
25//! D12).
26
27use crate::event::Event;
28use crate::menu::menu_view::{self, MenuColors, MenuView, MenuViewState};
29use crate::view::{Context, DrawCtx, Point, Rect, View, ViewState};
30
31/// Display width of a `~`-marked label, **ignoring** the `~` markers (which are
32/// not printed columns). A per-module copy mirroring `button.rs` / `cluster.rs`
33/// (the established precedent), using the same `UnicodeWidthChar` primitive so
34/// widths match the rest of the renderer.
35fn cstrlen(s: &str) -> i32 {
36 s.chars()
37 .filter(|&c| c != '~')
38 .map(|c| unicode_width::UnicodeWidthChar::width(c).unwrap_or(1) as i32)
39 .sum()
40}
41
42/// Display width of the kebab string (no `~` markers — plain display columns).
43fn kebab_width(s: &str) -> i32 {
44 unicode_width::UnicodeWidthStr::width(s) as i32
45}
46
47/// The horizontal menu bar. Holds the shared [`MenuViewState`]; the bar-specific
48/// layout lives in [`draw`](MenuBar::draw) /
49/// [`get_item_rect`](MenuView::get_item_rect).
50///
51/// # Turbo Vision heritage
52/// Ports `TMenuBar` (`tmenubar.cpp`/`menus.h`).
53pub struct MenuBar {
54 mv: MenuViewState,
55 /// When true the bar is rendered as the themed `menu_kebab` glyph
56 /// (top-right, width derived from the glyph) and activation opens a corner
57 /// popup instead of the in-bar session. Driven by the pump when a
58 /// `Fullscreen::Screen` window covers the menu row.
59 collapsed: bool,
60}
61
62impl MenuBar {
63 /// Construct a menu bar over `bounds` presenting `menu`.
64 ///
65 /// `bounds` is the initial bounding rectangle (typically `Rect::new(0, 0,
66 /// screen_width, 1)` to occupy the top row); the bar's `grow_mode.hi_x` flag
67 /// causes it to stretch automatically when the terminal is resized. The bar
68 /// sets `options.pre_process = true` so it intercepts accelerator keys and
69 /// Alt-shortcuts in the preprocess pass, before the focused view consumes them.
70 ///
71 /// Use `MenuBar` when you want a persistent horizontal strip of top-level menu
72 /// titles in the application frame. For a transient context popup (a right-click
73 /// menu), use [`popup_menu`](crate::menu::popup_menu) instead.
74 pub fn new(bounds: Rect, menu: crate::menu::Menu) -> Self {
75 let mut state = ViewState::new(bounds);
76 state.grow_mode.hi_x = true; // stretch with screen width
77 state.options.pre_process = true; // see accelerators before focused view
78 MenuBar {
79 mv: MenuViewState::new(state, menu),
80 collapsed: false,
81 }
82 }
83}
84
85impl MenuView for MenuBar {
86 fn mv(&self) -> &MenuViewState {
87 &self.mv
88 }
89
90 fn mv_mut(&mut self) -> &mut MenuViewState {
91 &mut self.mv
92 }
93
94 /// The screen rect of item `index`, computed by a left-to-right accumulator.
95 ///
96 /// Starting at column 1, each item's start is carried from the previous item's
97 /// end, then (only for a named item) the end advances by the label width plus a
98 /// leading and trailing space. A separator carries the start but adds nothing,
99 /// so it consumes no horizontal space. Only ever called with an existing index.
100 fn get_item_rect(&self, index: usize) -> Rect {
101 let mut r = Rect::new(1, 0, 1, 1);
102 for (i, item) in self.mv.menu.items.iter().enumerate() {
103 r.a.x = r.b.x;
104 if !matches!(item, crate::menu::MenuItem::Separator) {
105 r.b.x += cstrlen(item_name(item)) + 2;
106 }
107 if i == index {
108 return r;
109 }
110 }
111 // The C++ loop never exits without a match (it is only called with a valid
112 // index); return the last accumulated rect as a defensive fallback.
113 r
114 }
115}
116
117impl View for MenuBar {
118 fn state(&self) -> &ViewState {
119 &self.mv.state
120 }
121
122 fn state_mut(&mut self) -> &mut ViewState {
123 &mut self.mv.state
124 }
125
126 /// Fill the bar then lay the named items out left-to-right, each with a
127 /// leading and trailing space, in the per-item colour resolved via
128 /// [`MenuColors`]. An item that would overflow the bar width is skipped but
129 /// still advances the cursor. Paints directly through the view-local
130 /// [`DrawCtx`].
131 fn draw(&mut self, ctx: &mut DrawCtx) {
132 let colors = MenuColors::resolve(ctx);
133
134 if self.collapsed {
135 // Render the themed kebab at the top-right; width derived from the
136 // glyph so the rest of the row stays transparent (fullscreen window
137 // shows through).
138 let size = self.mv.state.size;
139 let kebab = ctx.glyphs().menu_kebab;
140 let kw = kebab_width(kebab);
141 ctx.put_str(size.x - kw, 0, kebab, colors.normal.0);
142 return;
143 }
144
145 let size = self.mv.state.size;
146 // b.moveChar(0, ' ', cNormal, size.x) — fill the whole bar.
147 ctx.fill(Rect::new(0, 0, size.x, 1), ' ', colors.normal.0);
148
149 let mut x = 1;
150 for (i, item) in self.mv.menu.items.iter().enumerate() {
151 let name = match item {
152 crate::menu::MenuItem::Separator => continue, // C++ p->name == 0 skip
153 other => item_name(other),
154 };
155 let l = cstrlen(name);
156 if x + l < size.x {
157 let disabled = item_disabled(item);
158 let selected = self.mv.current == Some(i);
159 let (lo, hi) = colors.item(disabled, selected);
160 // b.moveChar(x, ' ', color, 1); moveCStr(x+1, name, color);
161 // moveChar(x+l+1, ' ', color, 1).
162 ctx.put_char(x, 0, ' ', lo);
163 ctx.put_cstr(x + 1, 0, name, lo, hi);
164 ctx.put_char(x + l + 1, 0, ' ', lo);
165 }
166 x += l + 2;
167 }
168 }
169
170 /// Delegates to the shared passive [`menu_view::handle_event`]
171 /// (command-graying broadcast, accelerator post, and bar hotkey activation).
172 /// When collapsed, activation (mouse click, F10/`Command::MENU`, or any
173 /// Alt-shortcut) opens a corner popup anchored at the top-right cell instead
174 /// of the in-bar session — the session freezes the bar's bounds at activation,
175 /// so reclaiming width for an in-bar drop is impossible.
176 fn handle_event(&mut self, ev: &mut Event, ctx: &mut Context) {
177 if self.collapsed {
178 // Activation (click the kebab, F10/cmMenu, or any Alt-shortcut) opens a
179 // vertical popup anchored at the top-right corner — the session freezes
180 // the bar's bounds at activation, so reclaiming width is impossible
181 // (see docs/design/fullscreen-window.md). Other events (graying
182 // broadcast, accelerator posts) still delegate.
183 let activate = match *ev {
184 Event::MouseDown(_) => true,
185 Event::Command(c) => c == crate::command::Command::MENU,
186 Event::KeyDown(k) => k.modifiers.alt,
187 _ => false,
188 };
189 if activate {
190 let owner = ctx.owner_size();
191 crate::menu::popup_menu(
192 Point::new(owner.x - 1, 0),
193 self.mv.menu.clone(),
194 owner,
195 ctx,
196 );
197 ev.clear();
198 return;
199 }
200 }
201 menu_view::handle_event(&self.mv, ev, ctx);
202 }
203
204 /// The command-graying broker hook. The pump calls this at apply time (via
205 /// [`Deferred::UpdateMenu`](crate::view::Deferred::UpdateMenu)) with the live **disabled-command set** in hand,
206 /// and [`Program::new`](crate::app::Program::new) calls it once at startup to
207 /// seed the initial graying; it walks the menu tree setting each command
208 /// item's `disabled = disabled_cmds.has(command)` (the shared
209 /// [`menu_view::update_menu_commands`] free function). Without this override
210 /// the broker would silently no-op on the trait default — and both the startup
211 /// seed and the command-set-changed broadcast depend on it.
212 fn update_menu_commands(&mut self, disabled_cmds: &crate::command::CommandSet) {
213 menu_view::update_menu_commands(&mut self.mv.menu, disabled_cmds);
214 }
215
216 /// Write the session-owned highlight index — the pump's
217 /// [`Deferred::SetMenuCurrent`](crate::view::Deferred::SetMenuCurrent) broker
218 /// target. The bar is never focused while a menu session is active, so this is
219 /// the only path that moves its highlight.
220 fn set_menu_current(&mut self, current: Option<usize>) {
221 self.mv.current = current;
222 }
223
224 /// Expose the concrete bar so the pump / tests can introspect its
225 /// [`MenuViewState`] (the highlight cache the session drives).
226 fn as_any_mut(&mut self) -> Option<&mut dyn core::any::Any> {
227 Some(self)
228 }
229}
230
231impl MenuBar {
232 /// Collapse the bar to a `[⋮]` bracketed kebab (or restore the full bar).
233 /// The pump drives this together with a bounds change to the 3-cell kebab rect.
234 pub fn set_collapsed(&mut self, v: bool) {
235 self.collapsed = v;
236 }
237
238 /// Whether the bar is currently collapsed to a `[⋮]` bracketed kebab.
239 pub fn collapsed(&self) -> bool {
240 self.collapsed
241 }
242
243 /// Read the bar's current highlight index (test/inspection hook for the
244 /// session-driven highlight cache).
245 pub fn current(&self) -> Option<usize> {
246 self.mv.current
247 }
248
249 /// Borrow the bar's menu tree (test/inspection hook — lets the program-wiring
250 /// regray tests read a top-level item's `disabled` flag after the broker hook
251 /// runs).
252 #[cfg(test)]
253 pub fn menu(&self) -> &crate::menu::Menu {
254 &self.mv.menu
255 }
256}
257
258/// The display label of a named menu item. Never called on a [`Separator`], which
259/// has no name (the caller skips separators); returns `""` for one defensively.
260///
261/// [`Separator`]: crate::menu::MenuItem::Separator
262fn item_name(item: &crate::menu::MenuItem) -> &str {
263 match item {
264 crate::menu::MenuItem::Command { name, .. }
265 | crate::menu::MenuItem::SubMenu { name, .. } => name,
266 crate::menu::MenuItem::Separator => "",
267 }
268}
269
270/// The `disabled` flag of a menu item (`false` for a [`Separator`], which is never
271/// greyed).
272///
273/// [`Separator`]: crate::menu::MenuItem::Separator
274fn item_disabled(item: &crate::menu::MenuItem) -> bool {
275 match item {
276 crate::menu::MenuItem::Command { disabled, .. }
277 | crate::menu::MenuItem::SubMenu { disabled, .. } => *disabled,
278 crate::menu::MenuItem::Separator => false,
279 }
280}
281
282#[cfg(test)]
283mod tests {
284 use super::*;
285 use crate::backend::{HeadlessBackend, Renderer};
286 use crate::command::Command;
287 use crate::menu::{Menu, alt};
288 use crate::screen::Buffer;
289 use crate::theme::Theme;
290
291 /// A `File`/`Edit`/`Window` bar — three top-level submenus.
292 fn sample_bar(bounds: Rect) -> MenuBar {
293 let menu = Menu::builder()
294 .submenu("~F~ile", alt('f'), |m| m.command("~O~pen", Command::OPEN))
295 .submenu("~E~dit", alt('e'), |m| m.command("~C~ut", Command::CUT))
296 .submenu("~W~indow", alt('w'), |m| m.command("~N~ext", Command::NEXT))
297 .build();
298 MenuBar::new(bounds, menu)
299 }
300
301 fn render(bar: &mut MenuBar, w: u16, h: u16) -> String {
302 let theme = Theme::classic_blue();
303 let (backend, screen) = HeadlessBackend::new(w, h);
304 let mut r = Renderer::new(Box::new(backend));
305 r.render(|buf: &mut Buffer| {
306 let bounds = bar.state().get_bounds();
307 let mut dc = DrawCtx::new(buf, &theme, bounds, bounds.a);
308 bar.draw(&mut dc);
309 });
310 screen.snapshot()
311 }
312
313 // -- ctor ---------------------------------------------------------------
314
315 #[test]
316 fn ctor_sets_grow_and_preprocess() {
317 let bar = sample_bar(Rect::new(0, 0, 30, 1));
318 assert!(bar.mv.state.grow_mode.hi_x, "gfGrowHiX set");
319 assert!(bar.mv.state.options.pre_process, "ofPreProcess set");
320 assert_eq!(bar.mv.current, None, "nothing highlighted at construction");
321 }
322
323 // -- get_item_rect ------------------------------------------------------
324
325 #[test]
326 fn get_item_rect_accumulates_horizontally() {
327 // " File Edit Window " — each item is a leading space + name + trailing
328 // space, so item i occupies [x, x + cstrlen + 2).
329 // File: cstrlen 4 -> [1, 7)
330 // Edit: cstrlen 4 -> [7, 13)
331 // Window: cstrlen 6 -> [13, 21)
332 let bar = sample_bar(Rect::new(0, 0, 30, 1));
333
334 let file = bar.get_item_rect(0);
335 assert_eq!((file.a.x, file.b.x), (1, 7), "File occupies cols [1, 7)");
336
337 let edit = bar.get_item_rect(1);
338 // BITE: forgetting the `r.a.x = r.b.x` carry would yield (1, 13) — b.x
339 // still accumulates (7 -> 13), only a.x stays 1. The correct (7, 13) proves
340 // Edit starts where File ended (7), not at 1.
341 assert_eq!(
342 (edit.a.x, edit.b.x),
343 (7, 13),
344 "Edit starts where File ended"
345 );
346
347 let window = bar.get_item_rect(2);
348 assert_eq!(
349 (window.a.x, window.b.x),
350 (13, 21),
351 "Window starts where Edit ended"
352 );
353 // y span is always the single bar row [0, 1).
354 assert_eq!((window.a.y, window.b.y), (0, 1));
355 }
356
357 #[test]
358 fn get_item_rect_separator_consumes_no_x() {
359 // A bar with a separator between two named items: the separator runs
360 // r.a.x = r.b.x but adds nothing, so the item after it starts where the
361 // item before it ended.
362 let menu = Menu::builder()
363 .submenu("~F~ile", alt('f'), |m| m.command("~O~pen", Command::OPEN))
364 .separator()
365 .submenu("~E~dit", alt('e'), |m| m.command("~C~ut", Command::CUT))
366 .build();
367 let bar = MenuBar::new(Rect::new(0, 0, 30, 1), menu);
368
369 // File (idx 0): [1, 7).
370 assert_eq!((bar.get_item_rect(0).a.x, bar.get_item_rect(0).b.x), (1, 7));
371 // Separator (idx 1): r.a.x = r.b.x = 7, no advance -> [7, 7).
372 let sep = bar.get_item_rect(1);
373 assert_eq!(
374 (sep.a.x, sep.b.x),
375 (7, 7),
376 "separator consumes no horizontal space"
377 );
378 // Edit (idx 2): starts at 7 (NOT pushed by the separator).
379 // BITE: a "separator advances x" bug would put Edit at [9, 15) or similar.
380 let edit = bar.get_item_rect(2);
381 assert_eq!(
382 (edit.a.x, edit.b.x),
383 (7, 13),
384 "item after a separator starts where the previous named item ended"
385 );
386 }
387
388 // -- draw snapshots -----------------------------------------------------
389
390 #[test]
391 fn snapshot_bar_highlight_and_disabled() {
392 // Edit is highlighted (current = 1); Window is disabled (greyed).
393 let mut bar = sample_bar(Rect::new(0, 0, 24, 1));
394 bar.mv.current = Some(1);
395 if let crate::menu::MenuItem::SubMenu { disabled, .. } = &mut bar.mv.menu.items[2] {
396 *disabled = true;
397 }
398 insta::assert_snapshot!(render(&mut bar, 24, 1));
399 }
400
401 #[test]
402 fn snapshot_bar_narrow_drops_overflowing_item() {
403 // Width 8: File occupies [1, 7) (x=1, l=4 -> 1+4 < 8 true, drawn). After
404 // File, x = 7; Edit has l=4 -> 7+4 < 8 is FALSE, so Edit is NOT drawn but
405 // x still advances (the `if x+l < size.x` false branch). This exercises the
406 // clipped-item path the wide bar never hits.
407 let menu = Menu::builder()
408 .submenu("~F~ile", alt('f'), |m| m.command("~O~pen", Command::OPEN))
409 .submenu("~E~dit", alt('e'), |m| m.command("~C~ut", Command::CUT))
410 .build();
411 let mut bar = MenuBar::new(Rect::new(0, 0, 8, 1), menu);
412 insta::assert_snapshot!(render(&mut bar, 8, 1));
413 }
414
415 #[test]
416 fn draw_empty_menu_does_not_panic() {
417 // An empty menu: the bar fills its background and the item loop is a no-op.
418 // Cheapest guard against an index/iter edge case.
419 let mut bar = MenuBar::new(Rect::new(0, 0, 12, 1), Menu::builder().build());
420 let _ = render(&mut bar, 12, 1); // completes without panic.
421 }
422
423 #[test]
424 fn collapsed_bar_draws_only_kebab() {
425 // A collapsed bar paints the [⋮] kebab at the top-right 3 cells and nothing
426 // else; the rest of the row is left transparent.
427 let mut bar = sample_bar(Rect::new(0, 0, 24, 1));
428 bar.set_collapsed(true);
429 assert!(bar.collapsed());
430 let snap = render(&mut bar, 24, 1);
431 assert!(snap.contains("[⋮]"), "bracketed kebab drawn");
432 assert!(
433 !snap.contains("File"),
434 "top-level items NOT drawn when collapsed"
435 );
436 }
437}