tvision_rs/menu/menu_view.rs
1//! The shared, non-interactive layer behind the menu bar and menu boxes:
2//! [`MenuViewState`] (the data every menu view holds) plus the free functions for
3//! command-graying and passive accelerator dispatch.
4//!
5//! Two responsibilities live here:
6//!
7//! 1. The **command-graying broker** ([`update_menu_commands`]) — driven by the
8//! command-set-changed broadcast, it walks the menu tree and marks each item
9//! enabled/disabled to match the live command set.
10//! 2. **Passive accelerator dispatch** — the key branch of [`handle_event`] that
11//! posts the command of a menu item whose accelerator matches a pressed key,
12//! even when no menu is open (see [`hot_key`]).
13//!
14//! The interactive modal layer (opening, navigating, and selecting) lives in
15//! [`MenuBar`](crate::menu::MenuBar), [`MenuBox`](crate::menu::MenuBox), and the
16//! [`MenuSession`](crate::menu) capture handler. The parent-of relationship
17//! between an open box and the level above it is modeled by that session's level
18//! stack rather than a field on the view, so [`MenuViewState`] carries no
19//! parent pointer.
20//!
21//! # Turbo Vision heritage
22//! Ports the passive half of `TMenuView` (`tmnuview.cpp`/`menus.h`). The
23//! `current`/`parentMenu` up-pointers become an item index plus the session's
24//! level stack (deviation D3); the disabled-command set is held as a denylist
25//! (deviation D1) and `TStreamable` persistence is dropped (deviation D12).
26
27use crate::color::Style;
28use crate::command::{Command, CommandSet};
29use crate::event::{Event, KeyEvent};
30use crate::menu::{Menu, MenuItem};
31use crate::theme::Role;
32use crate::view::{Context, DrawCtx, Rect, View, ViewState};
33
34/// Runtime view state shared by the menu views that
35/// [`MenuBar`](crate::menu::MenuBar) and [`MenuBox`](crate::menu::MenuBox) build
36/// on.
37///
38/// The `current` field (the highlighted item) is an **index** into the menu's
39/// items; the draw layer reads it to pick the selected colour. There is no parent
40/// pointer here — the parent-of relationship between an open box and the level
41/// above it is held by the menu session's level stack instead.
42///
43/// Normally you do not construct this directly: [`MenuBar::new`] and
44/// [`MenuBox::new`] call [`MenuViewState::new`] for you.
45///
46/// [`MenuBar::new`]: crate::menu::MenuBar::new
47/// [`MenuBox::new`]: crate::menu::MenuBox::new
48///
49/// # Turbo Vision heritage
50/// Ports the `TMenuView` data members (`tmnuview.cpp`/`menus.h`).
51pub struct MenuViewState {
52 /// The embedded [`ViewState`] (geometry, flags, id).
53 pub state: ViewState,
54 /// The menu tree this view presents.
55 ///
56 /// The [`MenuSession`] clones this at activation time, so in-place
57 /// mutations during an open session are not visible until the next
58 /// activation. To update items between sessions, modify `menu.items`
59 /// directly or rebuild the tree and replace this field.
60 ///
61 /// [`MenuSession`]: crate::menu::MenuSession
62 pub menu: Menu,
63 /// The highlighted item, an **index** into [`menu`](Self::menu)`.items`, or
64 /// `None` for nothing highlighted. Consistent with [`Menu::default`] (also an
65 /// index). Draw compares `Some(i) == current` to pick the selected colour;
66 /// the [`MenuSession`] writes it through [`View::set_menu_current`] on every
67 /// navigation step — do not write it yourself while a session is active.
68 ///
69 /// [`MenuSession`]: crate::menu::MenuSession
70 /// [`View::set_menu_current`]: crate::view::View::set_menu_current
71 pub current: Option<usize>,
72}
73
74impl MenuViewState {
75 /// Build a menu-view state over `state` and `menu`, with nothing highlighted
76 /// (`current = None`).
77 ///
78 /// Called by [`MenuBar::new`] and [`MenuBox::new`]; you rarely need to call
79 /// this directly. `current` is `pub`, so a caller or test can set it after
80 /// construction. The broadcast mask (`evBroadcast`) that `TMenuView::Init`
81 /// sets in C++ is not ported here — the group fans broadcasts to every child
82 /// unconditionally, so no per-view opt-in is needed.
83 ///
84 /// [`MenuBar::new`]: crate::menu::MenuBar::new
85 /// [`MenuBox::new`]: crate::menu::MenuBox::new
86 pub fn new(state: ViewState, menu: Menu) -> Self {
87 MenuViewState {
88 state,
89 menu,
90 current: None,
91 }
92 }
93}
94
95/// The shared interface a [`MenuBar`](crate::menu::MenuBar) and a
96/// [`MenuBox`](crate::menu::MenuBox) implement so menu navigation can treat them
97/// uniformly.
98///
99/// Item geometry ([`get_item_rect`](MenuView::get_item_rect)) and the draw layout
100/// are the two operations that differ between a horizontal bar and a vertical box;
101/// they must agree cell-for-cell, so they travel together. The passive shared
102/// logic ([`hot_key`]/[`update_menu_commands`]/[`handle_event`]) stays as free
103/// functions over `&Menu`/[`MenuViewState`]. Menu navigation reaches a bar or box
104/// through a `MenuView` reference.
105///
106/// # Turbo Vision heritage
107/// Ports the abstract part of `TMenuView` (`tmnuview.cpp`/`menus.h`). The
108/// `TMenuBar`/`TMenuBox` subclassing becomes this trait the two concrete views
109/// implement (deviation D2).
110pub trait MenuView: View {
111 /// Borrow the embedded [`MenuViewState`].
112 fn mv(&self) -> &MenuViewState;
113 /// Mutably borrow the embedded [`MenuViewState`].
114 fn mv_mut(&mut self) -> &mut MenuViewState;
115
116 /// The screen rect (view-local coordinates) of item `index` within this view.
117 ///
118 /// Every concrete implementor **must** override this — the default returns an
119 /// empty rect, which the session uses as a fallback but which will produce
120 /// invisible hit-testing. [`MenuBar`] overrides it with a horizontal
121 /// left-to-right accumulator; [`MenuBox`] overrides it with a closed-form
122 /// `y = 1 + index` formula. Implement it so the returned rect matches the
123 /// cells drawn by [`View::draw`] cell-for-cell: the session's mouse
124 /// hit-testing reads item rects to track which item the cursor is over.
125 ///
126 /// [`MenuBar`]: crate::menu::MenuBar
127 /// [`MenuBox`]: crate::menu::MenuBox
128 fn get_item_rect(&self, _index: usize) -> Rect {
129 Rect::new(0, 0, 0, 0)
130 }
131}
132
133/// The four `(lo, hi)` style pairs a menu item is drawn in, one per
134/// enabled/disabled × normal/selected combination, resolved once per draw. The
135/// `lo` style paints the label and `hi` the highlighted hotkey character. Shared
136/// by [`MenuBar`](crate::menu::MenuBar) and [`MenuBox`](crate::menu::MenuBox) so
137/// the matrix lives in one place.
138///
139/// # Turbo Vision heritage
140/// Captures the menu `getColor` matrix (`cNormal`/`cSelect`/`cNormDisabled`/
141/// `cSelDisabled`) as a resolved struct.
142#[derive(Clone, Copy)]
143pub struct MenuColors {
144 /// Enabled, not selected: `(MenuNormal, MenuNormalShortcut)`.
145 pub normal: (Style, Style),
146 /// Enabled, selected: `(MenuSelected, MenuSelectedShortcut)`.
147 pub select: (Style, Style),
148 /// Disabled, not selected: `MenuDisabled` for both lo and hi.
149 pub norm_disabled: (Style, Style),
150 /// Disabled, selected: `MenuSelectedDisabled` for both lo and hi.
151 pub sel_disabled: (Style, Style),
152}
153
154impl MenuColors {
155 /// Resolve the six menu colour roles from the draw context's theme into a
156 /// ready-to-use `MenuColors` matrix.
157 ///
158 /// Call this once at the start of `draw` and reuse the result per item —
159 /// it reads six [`Role::Menu*`] entries from the theme and builds the four
160 /// `(lo, hi)` pairs used to paint normal/selected × enabled/disabled items.
161 /// The disabled pair collapses to a single style (no shortcut highlight
162 /// when greyed). The theme's derivation of these roles from the classic
163 /// six-entry `CMenuView` palette is documented in `src/theme.rs`.
164 ///
165 /// [`Role::Menu*`]: crate::theme::Role
166 pub fn resolve(ctx: &DrawCtx) -> Self {
167 let d = ctx.style(Role::MenuDisabled);
168 let sd = ctx.style(Role::MenuSelectedDisabled);
169 MenuColors {
170 normal: (
171 ctx.style(Role::MenuNormal),
172 ctx.style(Role::MenuNormalShortcut),
173 ),
174 select: (
175 ctx.style(Role::MenuSelected),
176 ctx.style(Role::MenuSelectedShortcut),
177 ),
178 // Disabled rows: a single style for both lo and hi (no shortcut
179 // highlight when greyed).
180 norm_disabled: (d, d),
181 sel_disabled: (sd, sd),
182 }
183 }
184
185 /// The `(lo, hi)` pair for an item given its `disabled`/`selected` state,
186 /// shared by command and submenu rows in both the bar and the box.
187 pub fn item(&self, disabled: bool, selected: bool) -> (Style, Style) {
188 match (disabled, selected) {
189 (true, true) => self.sel_disabled,
190 (true, false) => self.norm_disabled,
191 (false, true) => self.select,
192 (false, false) => self.normal,
193 }
194 }
195}
196
197/// Find the menu item whose accelerator matches `key` and return its
198/// [`Command`].
199///
200/// Walks the items in declaration order, **skips separators**, and **recurses
201/// into submenus** regardless of the submenu's own `disabled` flag (a submenu has
202/// no command of its own to match, so only its contents are searched). A
203/// **command item** matches only when it is not `disabled` and its accelerator
204/// equals `Some(key)` — an item with no accelerator (`None`) never matches. The
205/// first match wins (depth-first, in declaration order).
206///
207/// # Turbo Vision heritage
208/// Ports `TMenuView::findHotKey` (via `hotKey`, `tmnuview.cpp`).
209pub fn hot_key(menu: &Menu, key: KeyEvent) -> Option<Command> {
210 for item in &menu.items {
211 match item {
212 // separator, skipped.
213 MenuItem::Separator => {}
214 // submenu — recurse only (do NOT match its own key_code), regardless
215 // of the submenu's `disabled` flag.
216 MenuItem::SubMenu { menu: sub, .. } => {
217 if let Some(cmd) = hot_key(sub, key) {
218 return Some(cmd);
219 }
220 }
221 // command item: matches when enabled and its accelerator equals key.
222 MenuItem::Command {
223 command,
224 key_code,
225 disabled,
226 ..
227 } => {
228 if !*disabled && *key_code == Some(key) {
229 return Some(*command);
230 }
231 }
232 }
233 }
234 None
235}
236
237/// Regray the menu tree against the program's live **disabled-command set**.
238///
239/// `disabled_cmds` is the set of commands currently *disabled*. For each
240/// **command item** this sets `disabled = disabled_cmds.has(command)`; it
241/// **recurses into submenus** (a submenu's own `disabled` flag is never touched —
242/// only command items are regrayed, while the submenu's contents are walked); and
243/// it **skips separators**.
244///
245/// The write is unconditional because the whole tree is repainted each pump, so
246/// there is no need to report whether anything changed.
247///
248/// # Turbo Vision heritage
249/// Ports `TMenuView::updateMenu` (`tmnuview.cpp`); the disabled-command set is a
250/// denylist (deviation D1), and the changed/null-pointer bookkeeping is dropped
251/// because the [`Menu`] is owned and the tree is redrawn every pump.
252pub fn update_menu_commands(menu: &mut Menu, disabled_cmds: &CommandSet) {
253 for item in &mut menu.items {
254 match item {
255 MenuItem::Separator => {}
256 MenuItem::SubMenu { menu: sub, .. } => {
257 update_menu_commands(sub, disabled_cmds);
258 }
259 MenuItem::Command {
260 command, disabled, ..
261 } => {
262 *disabled = disabled_cmds.has(*command);
263 }
264 }
265 }
266}
267
268/// The **passive event layer** of a menu view.
269///
270/// Reads `mv.menu` + `mv.state.id()` and posts / requests through `ctx`; it does
271/// **not** mutate the menu (regray is routed through the command-set broker). The
272/// interactive *activation* branches (opening a menu, navigating it) live in the
273/// menu session, so this function leaves an activation event for the session.
274///
275/// Handled branches:
276/// - a **command-set-changed broadcast** → request the regray broker by the
277/// view's own id ([`Context::request_update_menu`]).
278/// - a **key press** → an accelerator match posts the item's command and clears
279/// the event ([`hot_key`]); a bar hotkey opens the menu session instead.
280///
281/// # Turbo Vision heritage
282/// Ports the passive subset of `TMenuView::handleEvent` (`tmnuview.cpp`); the
283/// interactive subset is flattened into the menu session (deviation D9).
284pub fn handle_event(mv: &MenuViewState, ev: &mut Event, ctx: &mut Context) {
285 match ev {
286 // C++ evBroadcast / cmCommandSetChanged: updateMenu(menu) (the conditional
287 // drawView is moot under whole-tree redraw). The regray runs through the
288 // broker — the menu view cannot read the command set inline, so request
289 // UpdateMenu by our own id; the pump calls back through
290 // View::update_menu_commands at apply time.
291 //
292 // NOTE (deviation): C++ TMenuView sets `eventMask |= evBroadcast` to opt
293 // in to broadcasts. Our Group::handle_event fans broadcasts out to EVERY
294 // child unconditionally (test
295 // `broadcast_reaches_all_children_including_disabled`), so the menu
296 // receives cmCommandSetChanged automatically — no mask/gate is ported.
297 Event::Broadcast {
298 command: Command::COMMAND_SET_CHANGED,
299 ..
300 } => {
301 if let Some(id) = mv.state.id() {
302 ctx.request_update_menu(id);
303 }
304 }
305 // C++ evKeyDown (`TMenuView::handleEvent`). The C++ order is:
306 // findAltShortcut → do_a_select (open the menu at the matched item) FIRST,
307 // then fall back to the hotKey accelerator post.
308 //
309 // Only the **bar** (`size.y == 1`) activates: a box exists only inside an
310 // active session,
311 // which swallows its events on the capture stack, so a box never reaches
312 // here live. The bar runs during group-routed preprocess dispatch
313 // (`ofPreProcess`), so `ctx.owner_size()` is the root group size (C++
314 // `owner->size`) and `mv.state` carries the bar's bounds — what
315 // [`menu_session::activate`] needs.
316 Event::KeyDown(k) => {
317 // 1. Bar alt-shortcut → open the session at the matched item.
318 if mv.state.size.y == 1
319 && let Some(bar_id) = mv.state.id()
320 && let Some(idx) = find_alt_shortcut_index(&mv.menu, k)
321 {
322 crate::menu::menu_session::activate(
323 bar_id,
324 mv.menu.clone(),
325 mv.state.get_bounds(),
326 ctx.owner_size(),
327 Some(idx),
328 ctx,
329 );
330 ev.clear();
331 return;
332 }
333 // 2. Otherwise the hotKey accelerator post (the passive path).
334 if let Some(cmd) = hot_key(&mv.menu, *k) {
335 // C++ posts evCommand with the matched command and clears the
336 // event. The C++ `commandEnabled(p->command)` re-check is NOT
337 // ported: (a) hot_key's `!disabled` filter already excludes
338 // disabled items, and that cached flag is kept current by the
339 // regray broker; (b) even a stale-enabled post is dropped by the
340 // pump's command boundary filter (program.rs: an Event::Command
341 // whose cmd is in the disabled set is cleared before routing). The
342 // only gap is a one-idle-cycle staleness window between a
343 // command-set change and the next cmCommandSetChanged regray —
344 // accepted.
345 ctx.post(cmd);
346 ev.clear();
347 }
348 }
349 // evCommand cmMenu (kbF10 → cmMenu): the bar opens the session at the menu
350 // default (`do_a_select`). Bar only (`size.y == 1`).
351 Event::Command(Command::MENU) if mv.state.size.y == 1 => {
352 if let Some(bar_id) = mv.state.id() {
353 crate::menu::menu_session::activate(
354 bar_id,
355 mv.menu.clone(),
356 mv.state.get_bounds(),
357 ctx.owner_size(),
358 None, // cmMenu → menu->deflt
359 ctx,
360 );
361 ev.clear();
362 }
363 }
364 // evMouseDown activation (`do_a_select`, tmnuview.cpp:505-516, reached from
365 // handleEvent's evMouseDown arm :522-524): a click ON the bar opens the
366 // session, which then (via the re-posted click) opens the clicked title's
367 // box. Bar only (`size.y == 1`) and only when the click lands inside the
368 // bar's bounds (a click elsewhere on the desktop must NOT activate). The
369 // bar is at the root frame's `(0,0)`, so the position delivered here is
370 // already root-frame.
371 Event::MouseDown(m)
372 if mv.state.size.y == 1
373 && mv.state.id().is_some()
374 && mv.state.get_bounds().contains(m.position) =>
375 {
376 let bar_id = mv.state.id().expect("guarded by id().is_some()");
377 crate::menu::menu_session::activate_mouse(
378 bar_id,
379 mv.menu.clone(),
380 mv.state.get_bounds(),
381 ctx.owner_size(),
382 *m,
383 ctx,
384 );
385 ev.clear();
386 }
387 // Other un-handled events are inert (a box's events are owned by the
388 // session on the capture stack; a bar click outside its bounds is not ours).
389 _ => {}
390 }
391}
392
393/// The index of the first **enabled, named** item whose hotkey letter matches
394/// `ke`. Skips separators and disabled items, and compares case-insensitively on
395/// the highlighted letter (the character after the first `~` in the label).
396///
397/// `alt == true` matches an `Alt`-held key
398/// ([`is_alt_hotkey`](crate::event::is_alt_hotkey)); `alt == false` a plain
399/// unmodified press ([`is_plain_hotkey`](crate::event::is_plain_hotkey)). Both
400/// predicates self-gate on the modifier, so no extra `alt` check is needed. This
401/// is the shared body of both the plain-letter selection and the `Alt`-shortcut
402/// activation paths.
403pub(crate) fn matching_item(menu: &Menu, ke: &KeyEvent, alt: bool) -> Option<usize> {
404 for (i, item) in menu.items.iter().enumerate() {
405 let (name, disabled) = match item {
406 MenuItem::Separator => continue,
407 MenuItem::Command { name, disabled, .. } | MenuItem::SubMenu { name, disabled, .. } => {
408 (name.as_str(), *disabled)
409 }
410 };
411 if disabled {
412 continue;
413 }
414 if let Some(letter) = crate::event::hot_key(name) {
415 let hit = if alt {
416 crate::event::is_alt_hotkey(ke, letter)
417 } else {
418 crate::event::is_plain_hotkey(ke, letter)
419 };
420 if hit {
421 return Some(i);
422 }
423 }
424 }
425 None
426}
427
428/// The index of the first **enabled, named** top-level item whose hotkey letter
429/// matches the `Alt`-held `key`. Used by the bar's activation arm to open the
430/// menu session at the matched title.
431///
432/// # Turbo Vision heritage
433/// Ports the keyboard-activation subset of `TMenuView::findAltShortcut`
434/// (`tmnuview.cpp`).
435fn find_alt_shortcut_index(menu: &Menu, key: &KeyEvent) -> Option<usize> {
436 matching_item(menu, key, true)
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442 use crate::command::CommandSet;
443 use crate::event::{Key, KeyEvent};
444 use crate::help::HelpCtx;
445 use crate::menu::{Menu, MenuItem, alt};
446
447 fn f3() -> KeyEvent {
448 KeyEvent::from(Key::F(3))
449 }
450 fn f6() -> KeyEvent {
451 KeyEvent::from(Key::F(6))
452 }
453
454 /// A File/Window menu: File has Open (F3), New (no key), a separator, and a
455 /// disabled-via-key item; Window has a nested Next (F6).
456 fn sample_menu() -> Menu {
457 Menu::builder()
458 .submenu("~F~ile", alt('f'), |m| {
459 m.command_key("~O~pen", Command::OPEN, f3(), "F3")
460 .command("~N~ew", Command::NEW)
461 .separator()
462 })
463 .submenu("~W~indow", alt('w'), |m| {
464 m.command_key("~N~ext", Command::NEXT, f6(), "F6")
465 })
466 .build()
467 }
468
469 // -- hot_key ------------------------------------------------------------
470
471 #[test]
472 fn hot_key_matches_top_level_via_submenu_descent() {
473 // Open (F3) lives one level down in File; findHotKey recurses submenus.
474 let menu = sample_menu();
475 assert_eq!(hot_key(&menu, f3()), Some(Command::OPEN));
476 }
477
478 #[test]
479 fn hot_key_recurses_into_a_second_submenu() {
480 // Next (F6) lives in the Window submenu — proves recursion past the first
481 // submenu into a later sibling submenu.
482 let menu = sample_menu();
483 assert_eq!(hot_key(&menu, f6()), Some(Command::NEXT));
484 }
485
486 #[test]
487 fn hot_key_skips_disabled_item() {
488 // Bite-check: with Open enabled the key matches; flipping `disabled`
489 // makes the match disappear (proving the `!disabled` filter is live).
490 let mut menu = sample_menu();
491 assert_eq!(hot_key(&menu, f3()), Some(Command::OPEN));
492
493 // Flip Open's `disabled` to true.
494 if let MenuItem::SubMenu { menu: file, .. } = &mut menu.items[0] {
495 *file.items[0]
496 .disabled_mut()
497 .expect("Open is a command item") = true;
498 } else {
499 panic!("items[0] should be the File submenu");
500 }
501 assert_eq!(
502 hot_key(&menu, f3()),
503 None,
504 "a disabled item must not match (C++ !p->disabled)"
505 );
506 }
507
508 #[test]
509 fn hot_key_returns_none_for_separator_or_no_key() {
510 // New has no accelerator (key_code None) and there is a separator; a key
511 // that matches nothing returns None — and crucially the separator does
512 // not panic / match.
513 let menu = sample_menu();
514 // A key nobody has.
515 let unknown = KeyEvent::from(Key::F(12));
516 assert_eq!(hot_key(&menu, unknown), None);
517 // New's command must not be reachable by any key (it has key_code None,
518 // which is C++ kbNoKey — never matches). Build a one-item menu to prove
519 // a None key_code never matches a "None == Some" mishap.
520 let only_new = Menu::builder().command("~N~ew", Command::NEW).build();
521 // No KeyEvent equals a missing key_code.
522 assert_eq!(hot_key(&only_new, f3()), None);
523 }
524
525 #[test]
526 fn hot_key_does_not_match_a_submenus_own_key_code() {
527 // The File submenu itself has key_code Alt-F. hot_key must NOT return on
528 // a submenu's own accelerator (submenus carry no command) — it only
529 // recurses. Searching for Alt-F finds nothing.
530 let menu = sample_menu();
531 assert_eq!(
532 hot_key(&menu, alt('f')),
533 None,
534 "a submenu's own key_code is an open-shortcut, not a hot key"
535 );
536 }
537
538 // -- update_menu_commands -----------------------------------------------
539
540 #[test]
541 fn update_menu_commands_regrays_recursively_against_set() {
542 let mut menu = sample_menu();
543 // The DISABLED set (denylist): New + Next disabled, Open left enabled.
544 let mut disabled_cmds = CommandSet::new();
545 disabled_cmds.insert(Command::NEW);
546 disabled_cmds.insert(Command::NEXT);
547
548 update_menu_commands(&mut menu, &disabled_cmds);
549
550 // File > Open: NOT in the disabled set → disabled == false.
551 // File > New: in the disabled set → disabled == true.
552 let file = match &menu.items[0] {
553 MenuItem::SubMenu { menu, .. } => menu,
554 _ => panic!("items[0] is File"),
555 };
556 match &file.items[0] {
557 MenuItem::Command {
558 command, disabled, ..
559 } => {
560 assert_eq!(*command, Command::OPEN);
561 assert!(!*disabled, "Open is not in the disabled set → enabled");
562 }
563 _ => panic!("File[0] is Open"),
564 }
565 match &file.items[1] {
566 MenuItem::Command {
567 command, disabled, ..
568 } => {
569 assert_eq!(*command, Command::NEW);
570 assert!(*disabled, "New is in the disabled set → disabled");
571 }
572 _ => panic!("File[1] is New"),
573 }
574 // Window > Next (a SECOND-level submenu): in the disabled set →
575 // disabled == true. Proves the recursion reaches a later sibling submenu.
576 let window = match &menu.items[1] {
577 MenuItem::SubMenu { menu, .. } => menu,
578 _ => panic!("items[1] is Window"),
579 };
580 match &window.items[0] {
581 MenuItem::Command {
582 command, disabled, ..
583 } => {
584 assert_eq!(*command, Command::NEXT);
585 assert!(*disabled, "Next is in the disabled set → disabled");
586 }
587 _ => panic!("Window[0] is Next"),
588 }
589 }
590
591 #[test]
592 fn update_menu_commands_predicate_is_plain_membership() {
593 // Bite-check against the WRONG (allowlist-era) predicate
594 // `disabled = !cs.has(command)`: with an EMPTY disabled set every item
595 // must come out enabled. Under the negated predicate an item absent from
596 // the set would gray, failing this assertion.
597 let mut menu = Menu::builder()
598 .item(MenuItem::SubMenu {
599 name: "~F~ile".to_string(),
600 key_code: None,
601 help_ctx: HelpCtx::NO_CONTEXT,
602 disabled: false,
603 menu: Menu::builder().command("~S~ave", Command::SAVE).build(),
604 })
605 .build();
606 // Pre-gray the inner item so the regray has to actively UN-gray it.
607 if let MenuItem::SubMenu { menu: sub, .. } = &mut menu.items[0]
608 && let MenuItem::Command { disabled, .. } = &mut sub.items[0]
609 {
610 *disabled = true;
611 }
612 let empty = CommandSet::new(); // nothing disabled
613
614 update_menu_commands(&mut menu, &empty);
615
616 match &menu.items[0] {
617 MenuItem::SubMenu { menu: sub, .. } => match &sub.items[0] {
618 MenuItem::Command { disabled, .. } => assert!(
619 !*disabled,
620 "command absent from the DISABLED set → enabled (plain membership)"
621 ),
622 _ => unreachable!(),
623 },
624 _ => unreachable!(),
625 }
626 }
627
628 #[test]
629 fn update_menu_commands_does_not_touch_submenu_disabled() {
630 // A submenu's own `disabled` is never written (C++ updates only command
631 // items). Start with a submenu marked disabled and assert it stays so
632 // even though its inner command gets regrayed (to disabled, via the
633 // denylist).
634 let mut menu = Menu::builder()
635 .item(MenuItem::SubMenu {
636 name: "~F~ile".to_string(),
637 key_code: None,
638 help_ctx: HelpCtx::NO_CONTEXT,
639 disabled: true, // deliberately set
640 menu: Menu::builder().command("~O~pen", Command::OPEN).build(),
641 })
642 .build();
643 let mut disabled_cmds = CommandSet::new();
644 disabled_cmds.insert(Command::OPEN); // OPEN is disabled
645
646 update_menu_commands(&mut menu, &disabled_cmds);
647
648 match &menu.items[0] {
649 MenuItem::SubMenu { disabled, menu, .. } => {
650 assert!(*disabled, "the submenu's own disabled flag is left alone");
651 match &menu.items[0] {
652 MenuItem::Command { disabled, .. } => {
653 assert!(*disabled, "the inner command WAS regrayed (disabled)")
654 }
655 _ => unreachable!(),
656 }
657 }
658 _ => unreachable!(),
659 }
660 }
661}