tvision_rs/menu/mod.rs
1//! Menus: the data tree and the views that present it.
2//!
3//! [`MenuItem`]/[`Menu`]/[`MenuBuilder`] are the pure data — define a menu tree
4//! fluently with the builder. [`MenuBar`], [`MenuBox`], and the menu session (see
5//! [`menu_view`], [`menu_bar`], [`menu_box`], [`menu_session`]) draw it and run the
6//! interactive open/navigate/select loop.
7//!
8//! ## The item model
9//!
10//! A [`MenuItem`] is one of three things, made explicit and type-safe by the
11//! enum's three variants:
12//!
13//! - a **separator** — a horizontal divider with no label or behaviour;
14//! - a **submenu** — a label that opens a nested [`Menu`];
15//! - a **command item** — a label that emits a [`Command`] when chosen, with an
16//! optional accelerator key and optional shortcut display text such as
17//! `"Alt-X"`.
18//!
19//! A command and a submenu are mutually exclusive: an item can never hold both a
20//! command and a nested menu. The fields common to commands and submenus
21//! (`name`, `key_code`, `help_ctx`, `disabled`) are read uniformly via
22//! or-patterns, e.g. `Command { disabled, .. } | SubMenu { disabled, .. } => …`.
23//!
24//! A [`Menu`] is a [`Vec`] of items plus a `default` selection given as an
25//! *index* into that vector (any valid index, or `None`). The [`MenuBuilder`]
26//! produces the usual convention: `default` is `Some(0)` (the first item) for a
27//! non-empty menu and `None` for an empty one.
28//!
29//! **Guide:** [Menus, status line & help](../../../apps/menus.html).
30//!
31//! # Turbo Vision heritage
32//! Ports `TMenuItem`, `TSubMenu`, and `TMenu` (`menus.h`/`menu.cpp`). The
33//! implicit `name`/`command`-tagged union becomes a 3-variant enum and the
34//! linked list becomes a `Vec` with an index default (deviation D1).
35
36use crate::command::Command;
37use crate::event::{Key, KeyEvent, KeyModifiers};
38use crate::help::HelpCtx;
39
40pub mod menu_bar;
41pub mod menu_box;
42pub mod menu_session;
43pub mod menu_view;
44pub use menu_bar::MenuBar;
45pub use menu_box::MenuBox;
46pub use menu_session::{MenuSession, popup_menu};
47pub use menu_view::{MenuColors, MenuView, MenuViewState};
48
49/// A single menu entry: a [`Separator`], a [`Command`] item, or a [`SubMenu`].
50///
51/// A command item carries the label, the [`Command`] it emits, and its optional
52/// accelerator key and shortcut display text. A submenu carries a label and an
53/// owned nested [`Menu`]. A separator is a divider with no other data. The
54/// command-vs-submenu split is exclusive: an entry holds either a command or a
55/// nested menu, never both.
56///
57/// Use [`MenuBuilder`] for the common case: `.command()`, `.command_key()`,
58/// `.submenu()`, and `.separator()` cover the usual patterns. Construct a
59/// `MenuItem` literal directly when you need fields the builder does not expose
60/// (e.g. a custom `help_ctx` or a pre-disabled item), then pass it via
61/// [`MenuBuilder::item`].
62///
63/// [`Separator`]: MenuItem::Separator
64/// [`Command`]: MenuItem::Command
65/// [`SubMenu`]: MenuItem::SubMenu
66///
67/// # Turbo Vision heritage
68/// Ports `TMenuItem` (`menus.h`), folding in its `TSubMenu` subclass and the
69/// `newLine()` separator. The implicit `union { const char *param; TMenu
70/// *subMenu; }` (tagged by `name`/`command`) becomes the three explicit variants
71/// (deviation D1).
72#[derive(Clone, Debug, PartialEq, Eq)]
73pub enum MenuItem {
74 /// A horizontal divider line with no label or behaviour.
75 ///
76 /// Append one with [`MenuBuilder::separator`].
77 Separator,
78
79 /// A command item: a label that emits a [`Command`] when chosen.
80 ///
81 /// When the user selects this item (via keyboard or mouse) the menu session
82 /// closes and posts the [`command`](MenuItem::Command::command) as a
83 /// [`Event::Command`] broadcast. Use [`MenuBuilder::command`] for items with
84 /// no accelerator, or [`MenuBuilder::command_key`] for items with an
85 /// accelerator key and shortcut display text.
86 ///
87 /// [`Event::Command`]: crate::event::Event::Command
88 Command {
89 /// The menu item label. Wrap one character in tildes (`~X~`) to mark it
90 /// as the single-key hotkey — the menu session will highlight that
91 /// character and let the user press it alone to select the item.
92 name: String,
93 /// The [`Command`] broadcast when this item is chosen.
94 ///
95 /// The menu session posts this as an [`Event::Command`] broadcast after
96 /// closing the menu. The command must be *enabled* in the application's
97 /// command set for the item to be selectable; the menu session
98 /// automatically greys it out (via [`disabled`](MenuItem::Command::disabled))
99 /// when the command is disabled.
100 ///
101 /// [`Event::Command`]: crate::event::Event::Command
102 command: Command,
103 /// The global accelerator key for this item. `None` means no accelerator.
104 ///
105 /// When set, the user can press this key combination from anywhere in
106 /// the application (not just inside an open menu) to trigger the item.
107 /// Use [`alt()`] to build an `Alt`+`<char>` key, or construct a
108 /// [`KeyEvent`] directly for other combinations.
109 key_code: Option<KeyEvent>,
110 /// Right-aligned shortcut hint shown next to the item label, e.g.
111 /// `"Alt-X"`. `None` means no hint is shown. Use `None` (or an empty
112 /// string via the builder) when the item has no accelerator, or when you
113 /// don't want to advertise it in the menu.
114 ///
115 /// This is display text only — the [`key_code`](MenuItem::Command::key_code)
116 /// field is the actual binding.
117 param: Option<String>,
118 /// The help context shown when this item is highlighted.
119 ///
120 /// Set to [`HelpCtx::NO_CONTEXT`] when no context-sensitive help is
121 /// needed. Pass a custom value only if your application ships a help
122 /// system keyed on context ids.
123 help_ctx: HelpCtx,
124 /// Whether this item is greyed out and unselectable.
125 ///
126 /// For a command item this flag is **framework-managed**: each time the
127 /// menu opens, the regray pass (`update_menu_commands`) overwrites it with
128 /// whether `command` is in the program's live disabled-command set
129 /// (`disabled = disabled_cmds.has(command)`). Setting it at menu-build time
130 /// therefore has no lasting effect for a command item — disable the command
131 /// itself instead (e.g. via a [`Deferred`] command-set effect). The public
132 /// [`MenuItem::disabled_mut`] accessor exists for custom graying logic; the
133 /// regray pass writes the field directly rather than through it.
134 ///
135 /// [`Deferred`]: crate::view::Deferred
136 disabled: bool,
137 },
138
139 /// A submenu: a label that opens a nested [`Menu`] in a pop-up box.
140 ///
141 /// When the user navigates to this item the menu session opens [`menu`]
142 /// as a child menu box. Use [`MenuBuilder::submenu`] to build the nested
143 /// menu with a closure; construct this variant directly only when you need to
144 /// set a custom `help_ctx` (the builder always uses [`HelpCtx::NO_CONTEXT`]).
145 ///
146 /// [`menu`]: MenuItem::SubMenu::menu
147 SubMenu {
148 /// The submenu label. Wrap one character in tildes (`~X~`) to mark the
149 /// single-key hotkey, the same as for [`MenuItem::Command::name`].
150 name: String,
151 /// The global accelerator key for this submenu. `None` means no accelerator.
152 ///
153 /// When set the user can press this key to open the submenu from anywhere.
154 /// See [`MenuItem::Command::key_code`] and [`alt()`] for construction.
155 key_code: Option<KeyEvent>,
156 /// The help context shown while this submenu label is highlighted.
157 ///
158 /// The builder always sets this to [`HelpCtx::NO_CONTEXT`]. To attach a
159 /// non-default context, construct the variant directly and pass it to
160 /// [`MenuBuilder::item`].
161 help_ctx: HelpCtx,
162 /// Whether this submenu label is greyed out. Unlike
163 /// [`MenuItem::Command::disabled`], the regray pass does **not** manage a
164 /// submenu's own flag — set it at build time (or via
165 /// [`disabled_mut`](MenuItem::disabled_mut)) to grey a whole submenu.
166 disabled: bool,
167 /// The nested [`Menu`] opened when this item is selected.
168 ///
169 /// The [`Menu`] is owned — the `SubMenu` variant holds the full tree, with
170 /// no raw pointer or manual disposal. Build the nested menu with
171 /// [`Menu::builder()`] or pass a pre-built [`Menu`] value directly.
172 menu: Menu,
173 },
174}
175
176impl MenuItem {
177 /// Returns a mutable reference to the `disabled` flag, or `None` for a
178 /// [`Separator`](MenuItem::Separator), which has no disabled state.
179 ///
180 /// Use this for custom graying logic: call `disabled_mut()`, check for `Some`,
181 /// and set the flag. Note the framework's own regray pass
182 /// (`update_menu_commands`) writes a command item's flag directly from the
183 /// program's disabled-command set rather than through this accessor, so for
184 /// command items prefer disabling the command itself; this handle is most
185 /// useful for greying a whole submenu. Separators are never greyable so they
186 /// yield `None`.
187 pub fn disabled_mut(&mut self) -> Option<&mut bool> {
188 match self {
189 MenuItem::Separator => None,
190 MenuItem::Command { disabled, .. } | MenuItem::SubMenu { disabled, .. } => {
191 Some(disabled)
192 }
193 }
194 }
195}
196
197/// An ordered list of [`MenuItem`]s with an optional default selection.
198///
199/// A `Menu` is the data backing a drop-down or pop-up menu: a flat list of
200/// entries plus the index of the item that is pre-selected when the menu opens.
201/// Use [`Menu::builder()`] to construct one fluently; the builder sets
202/// [`default`](Menu::default) automatically. Construct a `Menu` literal only
203/// when you need precise control over the default index — for example, when you
204/// want to pre-select an item other than the first:
205///
206/// ```rust
207/// use tvision_rs::menu::{Menu, MenuItem};
208/// use tvision_rs::command::Command;
209/// use tvision_rs::help::HelpCtx;
210///
211/// // Pre-built items.
212/// let items = vec![
213/// MenuItem::Command {
214/// name: "~N~ew".into(), command: Command::NEW,
215/// key_code: None, param: None,
216/// help_ctx: HelpCtx::NO_CONTEXT, disabled: false,
217/// },
218/// MenuItem::Command {
219/// name: "~O~pen".into(), command: Command::OPEN,
220/// key_code: None, param: None,
221/// help_ctx: HelpCtx::NO_CONTEXT, disabled: false,
222/// },
223/// ];
224/// // Pre-select "Open" (index 1) rather than "New" (index 0).
225/// let menu = Menu { items, default: Some(1) };
226/// assert_eq!(menu.default, Some(1));
227/// ```
228///
229/// Both fields are public and not invariant-checked: `default` may be any valid
230/// index into `items`, or `None`. [`Default::default()`] gives an empty menu
231/// with no pre-selection.
232///
233/// # Turbo Vision heritage
234/// Ports `TMenu` (`menus.h`): the singly-linked list of items becomes a [`Vec`]
235/// and the `deflt` pointer becomes an index into it.
236#[derive(Clone, Debug, PartialEq, Eq, Default)]
237pub struct Menu {
238 /// The menu entries, in display order.
239 ///
240 /// Iterate with `.iter()` / `.iter_mut()` or index directly. Modify in
241 /// place (e.g. to disable a specific item by index) only between menu
242 /// activations: while a [`MenuSession`] is open it holds a **clone** of the
243 /// menu, so changes to this vec are not visible until the next activation.
244 ///
245 /// [`MenuSession`]: crate::menu::MenuSession
246 pub items: Vec<MenuItem>,
247 /// The index of the item that is highlighted when the menu first opens.
248 ///
249 /// Any valid index into [`items`], or `None` for no initial highlight.
250 /// [`MenuBuilder`] sets this to `Some(0)` for a non-empty menu and `None`
251 /// for an empty one. To pre-select a different item, either set this field
252 /// directly after building (`menu.default = Some(n)`) or construct the
253 /// struct literal. The session clones the whole `Menu` at open and reads
254 /// this field once as the initial highlight; subsequent navigation does not
255 /// write it back to the original, so re-activating the menu always restarts
256 /// on this index.
257 ///
258 /// [`items`]: Menu::items
259 pub default: Option<usize>,
260}
261
262impl Menu {
263 /// Start building a menu with the fluent [`MenuBuilder`].
264 ///
265 /// The returned builder starts empty; chain `.command()`, `.command_key()`,
266 /// `.submenu()`, and `.separator()` calls, then finish with `.build()`.
267 /// The first item appended automatically becomes the default selection
268 /// (`default = Some(0)`). Use this for the common case; if you need a
269 /// non-first default or full control over every field, construct a `Menu`
270 /// struct literal directly (both fields are `pub`).
271 pub fn builder() -> MenuBuilder {
272 MenuBuilder::default()
273 }
274}
275
276/// A fluent builder for a [`Menu`].
277///
278/// Start a builder via [`Menu::builder()`] or `MenuBuilder::default()`, chain
279/// item-appending methods, and finish with [`.build()`](MenuBuilder::build):
280///
281/// ```rust
282/// use tvision_rs::menu::{Menu, alt};
283/// use tvision_rs::command::Command;
284///
285/// let menu = Menu::builder()
286/// .submenu("~F~ile", alt('f'), |m| {
287/// m.command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
288/// })
289/// .build();
290/// ```
291///
292/// Each method appends exactly one [`MenuItem`] and returns `self` for
293/// chaining. The first item appended sets [`Menu::default`] to `Some(0)`,
294/// making the first item pre-selected when the menu opens. **The builder
295/// always uses `Some(0)` as the default** — there is no builder method to
296/// choose a different pre-selected item. If you need a non-first default
297/// (e.g. to match the Turbo Vision two-argument `TMenu(itemList, theDefault)`
298/// constructor), build the item list with the builder, then override the field:
299/// `let mut menu = builder.build(); menu.default = Some(n);`, or construct a
300/// [`Menu`] struct literal directly (both fields are `pub`).
301///
302/// For items that need full field control (custom `help_ctx`, pre-set
303/// `disabled`, etc.) use [`MenuBuilder::item`] with a [`MenuItem`] literal.
304///
305/// # Turbo Vision heritage
306/// Replaces the `operator+` overloads (`menu.cpp`) that chained `TSubMenu` and
307/// `TMenuItem` nodes together, and the `NewItem`/`NewLine`/`NewSubMenu`
308/// constructor functions from the Pascal-era API.
309#[derive(Default)]
310pub struct MenuBuilder {
311 menu: Menu,
312}
313
314impl MenuBuilder {
315 /// Append an already-built [`MenuItem`], giving full control over every field.
316 ///
317 /// Use this when the convenience methods ([`command`](MenuBuilder::command),
318 /// [`command_key`](MenuBuilder::command_key), [`submenu`](MenuBuilder::submenu))
319 /// don't expose what you need — for example, a custom `help_ctx`, a
320 /// pre-disabled item, or a submenu with a non-`NO_CONTEXT` help id:
321 ///
322 /// ```rust
323 /// use tvision_rs::menu::{Menu, MenuItem};
324 /// use tvision_rs::command::Command;
325 /// use tvision_rs::help::HelpCtx;
326 ///
327 /// let menu = Menu::builder()
328 /// .item(MenuItem::Command {
329 /// name: "~S~ave".into(),
330 /// command: Command::SAVE,
331 /// key_code: None,
332 /// param: None,
333 /// help_ctx: HelpCtx::custom("myapp.save"),
334 /// disabled: false,
335 /// })
336 /// .build();
337 /// ```
338 pub fn item(mut self, item: MenuItem) -> Self {
339 self.menu.items.push(item);
340 if self.menu.default.is_none() {
341 self.menu.default = Some(0);
342 }
343 self
344 }
345
346 /// Append a [`MenuItem::Separator`] — a horizontal divider line.
347 ///
348 /// Corresponds to the classic Turbo Vision `NewLine()` helper (`newLine()` in
349 /// magiblot C++).
350 pub fn separator(self) -> Self {
351 self.item(MenuItem::Separator)
352 }
353
354 /// Append a [`MenuItem::Command`] with no accelerator and no shortcut text.
355 ///
356 /// Use this for items that are triggered only by navigating with arrow keys
357 /// or by their hotkey letter, not by a global accelerator. For items with an
358 /// accelerator use [`command_key`](MenuBuilder::command_key) instead.
359 ///
360 /// All convenience builder methods use [`HelpCtx::NO_CONTEXT`] and
361 /// `disabled: false`. To set a custom `help_ctx`, pre-disable the item, or
362 /// control any other non-default field, build the item explicitly with
363 /// [`MenuBuilder::item`] and a [`MenuItem::Command`] literal.
364 ///
365 /// Corresponds to `NewItem(name, "", 0, cmd, hcNoContext, 0)` in the classic
366 /// (Pascal-era) Turbo Vision API; magiblot C++ builds the equivalent
367 /// `TMenuItem` via `operator+`.
368 pub fn command(self, name: impl Into<String>, command: Command) -> Self {
369 self.item(MenuItem::Command {
370 name: name.into(),
371 command,
372 key_code: None,
373 param: None,
374 help_ctx: HelpCtx::NO_CONTEXT,
375 disabled: false,
376 })
377 }
378
379 /// Append a [`MenuItem::Command`] with an accelerator key and shortcut display text.
380 ///
381 /// `key_code` is the global accelerator (use [`alt()`] for `Alt`+`<char>`
382 /// combinations, or pass a [`KeyEvent`] directly for others). `param` is the
383 /// display hint shown right-aligned next to the label (e.g. `"Alt-X"`,
384 /// `"F3"`); an empty string is stored as `None` (no hint shown).
385 ///
386 /// ```rust
387 /// use tvision_rs::menu::{Menu, alt};
388 /// use tvision_rs::command::Command;
389 /// use tvision_rs::event::{Key, KeyEvent};
390 ///
391 /// let menu = Menu::builder()
392 /// .command_key("~O~pen", Command::OPEN, KeyEvent::from(Key::F(3)), "F3")
393 /// .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
394 /// .build();
395 /// ```
396 ///
397 /// See [`MenuBuilder::command`] for the `HelpCtx`/`disabled` escape hatch.
398 ///
399 /// Corresponds to `NewItem(name, param, key, cmd, hcNoContext, 0)` in the
400 /// classic (Pascal-era) Turbo Vision API.
401 pub fn command_key(
402 self,
403 name: impl Into<String>,
404 command: Command,
405 key_code: impl Into<Option<KeyEvent>>,
406 param: impl Into<String>,
407 ) -> Self {
408 let param = param.into();
409 self.item(MenuItem::Command {
410 name: name.into(),
411 command,
412 key_code: key_code.into(),
413 param: if param.is_empty() { None } else { Some(param) },
414 help_ctx: HelpCtx::NO_CONTEXT,
415 disabled: false,
416 })
417 }
418
419 /// Append a [`MenuItem::SubMenu`] whose contents are built by the closure.
420 ///
421 /// `name` is the label (tilde-hotkey syntax applies). `key_code` is the
422 /// optional global accelerator (use [`alt()`] or `None`). The closure
423 /// receives a fresh [`MenuBuilder`] for the nested menu and must return it
424 /// after appending items:
425 ///
426 /// ```rust
427 /// use tvision_rs::menu::{Menu, alt};
428 /// use tvision_rs::command::Command;
429 ///
430 /// let menu = Menu::builder()
431 /// .submenu("~F~ile", alt('f'), |m| {
432 /// m.command("~N~ew", Command::NEW)
433 /// .command("~O~pen", Command::OPEN)
434 /// })
435 /// .build();
436 /// ```
437 ///
438 /// **`help_ctx` limitation:** this method always uses [`HelpCtx::NO_CONTEXT`]
439 /// for the submenu item itself. To attach a custom `help_ctx`, construct the
440 /// [`MenuItem::SubMenu`] variant directly and pass it to [`MenuBuilder::item`].
441 ///
442 /// Corresponds to `NewSubMenu(name, key, subMenu, hcNoContext, 0)` in the
443 /// classic (Pascal-era) Turbo Vision API.
444 pub fn submenu(
445 self,
446 name: impl Into<String>,
447 key_code: impl Into<Option<KeyEvent>>,
448 build: impl FnOnce(MenuBuilder) -> MenuBuilder,
449 ) -> Self {
450 let menu = build(MenuBuilder::default()).build();
451 self.item(MenuItem::SubMenu {
452 name: name.into(),
453 key_code: key_code.into(),
454 help_ctx: HelpCtx::NO_CONTEXT,
455 disabled: false,
456 menu,
457 })
458 }
459
460 /// Finish building and return the completed [`Menu`].
461 pub fn build(self) -> Menu {
462 self.menu
463 }
464}
465
466/// Build an `Alt`+`<char>` [`KeyEvent`] for use as a menu accelerator.
467///
468/// This is the most common accelerator form for menu items. Pass the result
469/// to [`MenuBuilder::command_key`] or [`MenuBuilder::submenu`], or store it
470/// in [`MenuItem::Command::key_code`] / [`MenuItem::SubMenu::key_code`]:
471///
472/// ```rust
473/// use tvision_rs::menu::{Menu, alt};
474/// use tvision_rs::command::Command;
475///
476/// let menu = Menu::builder()
477/// .submenu("~F~ile", alt('f'), |m| {
478/// m.command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
479/// })
480/// .build();
481/// ```
482///
483/// For other key combinations (e.g. function keys) construct a [`KeyEvent`]
484/// directly using [`KeyEvent::from(Key::F(n))`](KeyEvent::from).
485pub fn alt(c: char) -> KeyEvent {
486 KeyEvent::new(
487 Key::Char(c),
488 KeyModifiers {
489 alt: true,
490 ..Default::default()
491 },
492 )
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 /// The builder must reproduce, node for node, the canonical File/Window menu
500 /// tree. The expected tree is hand-built with struct/enum literals (a
501 /// *different* code path from the builder) so a builder bug cannot pass
502 /// silently.
503 #[test]
504 fn builder_reproduces_file_window_menu() {
505 let built = Menu::builder()
506 .submenu("~F~ile", alt('f'), |m| {
507 m.command_key("~O~pen", Command::OPEN, KeyEvent::from(Key::F(3)), "F3")
508 .command("~N~ew", Command::NEW)
509 .separator()
510 .command_key("E~x~it", Command::QUIT, alt('x'), "Alt-X")
511 })
512 .submenu("~W~indow", alt('w'), |m| {
513 m.command_key("~N~ext", Command::NEXT, KeyEvent::from(Key::F(6)), "")
514 })
515 .build();
516
517 let expected = Menu {
518 items: vec![
519 MenuItem::SubMenu {
520 name: "~F~ile".to_string(),
521 key_code: Some(alt('f')),
522 help_ctx: HelpCtx::NO_CONTEXT,
523 disabled: false,
524 menu: Menu {
525 items: vec![
526 MenuItem::Command {
527 name: "~O~pen".to_string(),
528 command: Command::OPEN,
529 key_code: Some(KeyEvent::from(Key::F(3))),
530 param: Some("F3".to_string()),
531 help_ctx: HelpCtx::NO_CONTEXT,
532 disabled: false,
533 },
534 MenuItem::Command {
535 name: "~N~ew".to_string(),
536 command: Command::NEW,
537 key_code: None,
538 param: None,
539 help_ctx: HelpCtx::NO_CONTEXT,
540 disabled: false,
541 },
542 MenuItem::Separator,
543 MenuItem::Command {
544 name: "E~x~it".to_string(),
545 command: Command::QUIT,
546 key_code: Some(alt('x')),
547 param: Some("Alt-X".to_string()),
548 help_ctx: HelpCtx::NO_CONTEXT,
549 disabled: false,
550 },
551 ],
552 default: Some(0),
553 },
554 },
555 MenuItem::SubMenu {
556 name: "~W~indow".to_string(),
557 key_code: Some(alt('w')),
558 help_ctx: HelpCtx::NO_CONTEXT,
559 disabled: false,
560 menu: Menu {
561 items: vec![MenuItem::Command {
562 name: "~N~ext".to_string(),
563 command: Command::NEXT,
564 key_code: Some(KeyEvent::from(Key::F(6))),
565 param: None, // empty "" param → None (C++ param == 0)
566 help_ctx: HelpCtx::NO_CONTEXT,
567 disabled: false,
568 }],
569 default: Some(0),
570 },
571 },
572 ],
573 default: Some(0),
574 };
575
576 assert_eq!(built, expected);
577 }
578
579 #[test]
580 fn empty_builder_has_no_items_and_no_default() {
581 let menu = Menu::builder().build();
582 assert!(menu.items.is_empty());
583 assert_eq!(menu.default, None);
584 }
585
586 #[test]
587 fn command_without_accelerator_has_no_key_code() {
588 let menu = Menu::builder().command("~N~ew", Command::NEW).build();
589 assert_eq!(menu.default, Some(0));
590 match &menu.items[0] {
591 MenuItem::Command {
592 command,
593 key_code,
594 param,
595 ..
596 } => {
597 assert_eq!(*command, Command::NEW);
598 assert_eq!(*key_code, None);
599 assert_eq!(*param, None);
600 }
601 other => panic!("expected a Command item, got {other:?}"),
602 }
603 }
604
605 #[test]
606 fn empty_param_string_is_stored_as_none() {
607 let menu = Menu::builder()
608 .command_key("~N~ext", Command::NEXT, KeyEvent::from(Key::F(6)), "")
609 .build();
610 match &menu.items[0] {
611 MenuItem::Command {
612 param, key_code, ..
613 } => {
614 assert_eq!(*param, None);
615 // The accelerator must still be present — not swallowed.
616 assert_eq!(*key_code, Some(KeyEvent::from(Key::F(6))));
617 }
618 other => panic!("expected a Command item, got {other:?}"),
619 }
620 }
621
622 #[test]
623 fn raw_item_escape_hatch_sets_default_and_carries_full_control() {
624 let menu = Menu::builder()
625 .item(MenuItem::Command {
626 name: "~D~isabled".to_string(),
627 command: Command::SAVE,
628 key_code: None,
629 param: None,
630 help_ctx: HelpCtx::custom("myapp.save"),
631 disabled: true,
632 })
633 .build();
634 assert_eq!(menu.default, Some(0));
635 match &menu.items[0] {
636 MenuItem::Command {
637 help_ctx, disabled, ..
638 } => {
639 assert_eq!(*help_ctx, HelpCtx::custom("myapp.save"));
640 assert!(*disabled);
641 }
642 other => panic!("expected a Command item, got {other:?}"),
643 }
644 }
645
646 #[test]
647 fn disabled_mut_is_none_for_separator_and_live_otherwise() {
648 let mut sep = MenuItem::Separator;
649 assert_eq!(sep.disabled_mut(), None);
650
651 let mut cmd = MenuItem::Command {
652 name: "~X~".to_string(),
653 command: Command::QUIT,
654 key_code: None,
655 param: None,
656 help_ctx: HelpCtx::NO_CONTEXT,
657 disabled: false,
658 };
659 *cmd.disabled_mut().expect("command has a disabled flag") = true;
660 match &cmd {
661 MenuItem::Command { disabled, .. } => assert!(*disabled),
662 _ => unreachable!(),
663 }
664
665 let mut sub = MenuItem::SubMenu {
666 name: "~F~ile".to_string(),
667 key_code: None,
668 help_ctx: HelpCtx::NO_CONTEXT,
669 disabled: false,
670 menu: Menu::default(),
671 };
672 *sub.disabled_mut().expect("submenu has a disabled flag") = true;
673 match &sub {
674 MenuItem::SubMenu { disabled, .. } => assert!(*disabled),
675 _ => unreachable!(),
676 }
677 }
678}