Skip to main content

kui_core/
menu.rs

1//! Menus as data: the rows of a context menu or the application menu bar,
2//! what the window has open, and what a host still has to do after a row
3//! is chosen.
4//!
5//! An app meets this module through `Ui::open_menu` / `Core::open_menu`
6//! (a [`Menu`] over a node, usually from a `contextmenu` event), through
7//! `Core::declare_menu_bar` (a [`MenuBar`] of [`BarMenu`]s), and through
8//! the `menu` event a chosen row posts on the node the menu was about. A
9//! host that holds the core drains [`MenuAction`]s with
10//! `Core::take_menu_actions`: the clipboard work the core cannot do itself.
11//! Nothing here draws; the stock renderer builds ordinary nodes into the
12//! frame, and a platform that owns menus (the macOS menu bar) gets the
13//! same list.
14//!
15//! ```rust
16//! use kui_core::{
17//!     Accel, BarMenu, Core, Key, Menu, MenuAction, MenuBar, MenuItem, MenuRole, Vec2,
18//! };
19//!
20//! let bar = MenuBar::new(vec![
21//!     BarMenu::new("File", vec![
22//!         MenuItem::new("Open...").id("open").accel("mod+o"),
23//!         MenuItem::separator(),
24//!         MenuItem::new("Quit").id("quit"),
25//!     ]),
26//!     BarMenu::new("Edit", vec![
27//!         MenuItem::role(MenuRole::Cut),
28//!         MenuItem::role(MenuRole::Copy),
29//!         MenuItem::role(MenuRole::Paste),
30//!     ]),
31//! ]);
32//! let mut core = Core::new();
33//! core.declare_menu_bar(bar);
34//! assert_eq!(core.menu_bar().map(|b| b.menus.len()), Some(2));
35//!
36//! // A context menu over a node, at the point the press landed.
37//! let items = vec![
38//!     MenuItem::new("Inspect").id("inspect"),
39//!     MenuItem::new("Delete").id("delete").enabled(false),
40//! ];
41//! core.open_menu(Menu::new(Key::ROOT, Vec2::new(40.0, 30.0), items));
42//!
43//! // After a row is chosen, the host finishes what the core cannot.
44//! for action in core.take_menu_actions() {
45//!     match action {
46//!         MenuAction::SetClipboard { text, .. } => println!("copy {text}"),
47//!         MenuAction::Paste => println!("read the clipboard"),
48//!         other => println!("{other:?}"),
49//!     }
50//! }
51//!
52//! // Accelerators are display text; `Accel` parses them for a native bar.
53//! let accel = Accel::parse("mod+shift+s").unwrap();
54//! assert!(accel.mods.shift);
55//! ```
56
57use crate::geom::Vec2;
58use crate::key::Key;
59use crate::tree::OriginId;
60use crate::value::Value;
61
62/// What an item *means*, as far as anything outside the app is concerned.
63///
64/// The roles exist for two reasons and neither is decoration. A host with
65/// a native menu maps them onto its own standard items, so Copy is the
66/// platform's Copy — its wording, its accelerator, its position; and the
67/// core acts on the ones it can act on without asking anybody
68/// ([`MenuRole::SelectAll`]) or with one round trip through the host (the
69/// clipboard three). [`MenuRole::Custom`] is an item the app invented,
70/// which only the app can perform.
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub enum MenuRole {
73    /// The app's own item: choosing it posts the item's payload and the
74    /// core does nothing else.
75    #[default]
76    Custom,
77    /// A divider. Never focusable, never chosen, no payload.
78    Separator,
79    Cut,
80    Copy,
81    Paste,
82    SelectAll,
83    /// Show the platform's definition/Look Up panel for the selection.
84    /// The core cannot draw one: with no host to answer it, the item is
85    /// not offered.
86    LookUp,
87}
88
89impl MenuRole {
90    /// Every role, in wire order: the index a binding that spells roles as
91    /// numbers sends (C's `KUI_MENU_*`), pinned there by name. Append-only,
92    /// like every list a C enum restates.
93    pub const ALL: [MenuRole; 7] = [
94        MenuRole::Custom,
95        MenuRole::Separator,
96        MenuRole::Cut,
97        MenuRole::Copy,
98        MenuRole::Paste,
99        MenuRole::SelectAll,
100        MenuRole::LookUp,
101    ];
102
103    /// The role a wire name spells, for the bindings that take roles as
104    /// strings: the inverse of [`Self::name`], so a binding cannot accept
105    /// a spelling the event will not report back. `None` for a name that
106    /// is no role.
107    pub fn from_name(name: &str) -> Option<MenuRole> {
108        Self::ALL.into_iter().find(|r| r.name() == name)
109    }
110
111    /// The wire name, for the bindings and the report.
112    pub fn name(self) -> &'static str {
113        match self {
114            MenuRole::Custom => "custom",
115            MenuRole::Separator => "separator",
116            MenuRole::Cut => "cut",
117            MenuRole::Copy => "copy",
118            MenuRole::Paste => "paste",
119            MenuRole::SelectAll => "selectAll",
120            MenuRole::LookUp => "lookUp",
121        }
122    }
123
124    /// The label the stock renderer draws when the item declares none.
125    /// A native renderer ignores this and uses the platform's wording,
126    /// which is the point of having a role at all.
127    pub fn default_label(self) -> &'static str {
128        match self {
129            MenuRole::Custom | MenuRole::Separator => "",
130            MenuRole::Cut => "Cut",
131            MenuRole::Copy => "Copy",
132            MenuRole::Paste => "Paste",
133            MenuRole::SelectAll => "Select All",
134            MenuRole::LookUp => "Look Up",
135        }
136    }
137
138    /// The shortcut the stock renderer draws beside the row when the item
139    /// declares none, spelled the way the platform spells it — Command on
140    /// macOS, Control elsewhere, the same split [`KeyMods::primary`] makes
141    /// for the key that produces it.
142    ///
143    /// Display only, like every accelerator here: the core binds nothing,
144    /// and the row only names the key the host is already handling. Empty
145    /// for the roles with no standard shortcut — `Custom` above all, since
146    /// an app's own accelerator is the app's to declare
147    /// ([`MenuItem::accel`]) — and empty for `LookUp`, whose shortcut
148    /// belongs to the one platform that has the panel and draws its own
149    /// menu anyway.
150    ///
151    /// [`KeyMods::primary`]: crate::input::KeyMods::primary
152    pub fn default_accel(self) -> &'static str {
153        let mac = cfg!(target_os = "macos");
154        match self {
155            MenuRole::Cut if mac => "⌘X",
156            MenuRole::Copy if mac => "⌘C",
157            MenuRole::Paste if mac => "⌘V",
158            MenuRole::SelectAll if mac => "⌘A",
159            MenuRole::Cut => "Ctrl+X",
160            MenuRole::Copy => "Ctrl+C",
161            MenuRole::Paste => "Ctrl+V",
162            MenuRole::SelectAll => "Ctrl+A",
163            MenuRole::Custom | MenuRole::Separator | MenuRole::LookUp => "",
164        }
165    }
166
167    /// Whether the core performs this itself, or with one hand from the
168    /// host. `false` is an item only the app can carry out.
169    pub fn is_builtin(self) -> bool {
170        !matches!(self, MenuRole::Custom | MenuRole::Separator)
171    }
172}
173
174/// One row of a menu.
175#[derive(Clone, Debug, PartialEq)]
176pub struct MenuItem {
177    /// What the row reads. Empty takes the role's default wording.
178    pub label: String,
179    pub role: MenuRole,
180    /// A disabled row is drawn dimmed, is not focusable, and cannot be
181    /// chosen — Paste with an empty clipboard, Copy with no selection.
182    /// Present rather than absent on purpose: a menu whose rows move
183    /// depending on what is possible is a menu nobody builds muscle
184    /// memory for.
185    pub enabled: bool,
186    /// Posted as the event payload when the row is chosen. A `Custom`
187    /// item without one posts its label.
188    pub id: Option<Value>,
189    /// Drawn with a checkmark, and the platform's own check state where a
190    /// host renders the menu itself. A setting the row *is* rather than a
191    /// command it runs — View ▸ Show Sidebar — and inert for every other
192    /// row, which is why it is a flag beside the label and not a role.
193    pub checked: bool,
194    /// Drawn right-aligned and dimmed; the core binds nothing to it. The
195    /// keyboard shortcut is the app's or the platform's, and an
196    /// accelerator here only says which one it is. A standard row that
197    /// declares none takes its role's ([`MenuRole::default_accel`]), the
198    /// way an empty label takes the role's wording.
199    pub accel: Option<String>,
200    /// The rows of the menu this row opens: empty for an ordinary row. A
201    /// row with a submenu is drawn with a chevron and is never chosen
202    /// itself — hovering it, clicking it, Enter or the Right arrow opens
203    /// its menu beside it, and Left or Escape closes it again — and what
204    /// a chosen row inside posts is that row's own `menu` event, on the
205    /// node the outermost menu is about (backlog F128). Nests to any
206    /// depth. `MenuItem::submenu(label, items)` builds one.
207    pub submenu: Vec<MenuItem>,
208}
209
210impl MenuItem {
211    /// A row from plain data: a map with `label`, `role` (a wire name;
212    /// absent is `custom`), `enabled` (default true), `checked` (default
213    /// false), `id`, `accel` and `items` (a submenu's rows, the same maps).
214    /// A custom row needs a label, since the label is what it posts when it
215    /// has no `id`. Every binding funnels its rows through here —
216    /// `openMenu`'s list and a menu bar's alike — so a row can never mean
217    /// two things.
218    pub fn from_value(v: &Value) -> Result<Self, String> {
219        let Value::Map(_) = v else {
220            return Err("each menu item is an object".into());
221        };
222        let role = match v.get_str("role") {
223            None => MenuRole::Custom,
224            Some(name) => MenuRole::from_name(name)
225                .ok_or_else(|| format!("unknown menu item role {name:?}"))?,
226        };
227        let label = v.get_str("label").unwrap_or_default().to_string();
228        if label.is_empty() && role == MenuRole::Custom {
229            return Err("a custom menu item needs a label".into());
230        }
231        Ok(MenuItem {
232            label,
233            role,
234            enabled: v.get_bool("enabled").unwrap_or(true),
235            checked: v.get_bool("checked").unwrap_or(false),
236            id: v.get("id").filter(|id| **id != Value::Null).cloned(),
237            accel: v.get_str("accel").map(str::to_string),
238            submenu: match v.get("items") {
239                None | Some(Value::Null) => Vec::new(),
240                Some(items) => Self::list_from_value(items)?,
241            },
242        })
243    }
244
245    /// A menu's rows from plain data: a list of [`Self::from_value`] maps.
246    pub fn list_from_value(v: &Value) -> Result<Vec<Self>, String> {
247        let Value::List(rows) = v else {
248            return Err("a menu's items are an array".into());
249        };
250        rows.iter().map(Self::from_value).collect()
251    }
252
253    /// The keys a row map may carry — everything [`Self::from_value`]
254    /// reads. A binding that drops the rest of a map on the floor checks
255    /// against this first and raises [`crate::diag::unknown_menu_item_key`]
256    /// for what it dropped, so `{label, disabled: true}` is not silently a
257    /// row that is enabled.
258    pub const KEYS: [&'static str; 7] = [
259        "label", "role", "enabled", "checked", "id", "accel", "items",
260    ];
261
262    /// The name a binding reports a row's dropped keys under
263    /// (`diag::unknown_prop` routes it to `diag::unknown_menu_item_key`):
264    /// a row is not an element, so it is not in `schema::ELEMENTS`, and
265    /// the spelling is the type's in JSX (`MenuItemInput`).
266    pub const NAME: &'static str = "menuItem";
267
268    /// A select's options from plain data (`widgets::select_items` in the
269    /// bindings): a list whose entries are strings — an option by its
270    /// label, posting it — or [`Self::from_value`] maps, for an option
271    /// that posts an `id` of its own or is disabled. An empty list is
272    /// refused: a select with nothing to choose from is a field that opens
273    /// a menu of no rows, which only Escape leaves.
274    pub fn options_from_value(v: &Value) -> Result<Vec<Self>, String> {
275        let Value::List(rows) = v else {
276            return Err("a select's options are an array".into());
277        };
278        if rows.is_empty() {
279            return Err("a select needs at least one option".into());
280        }
281        rows.iter()
282            .map(|row| match row {
283                Value::Str(label) if !label.is_empty() => Ok(Self::new(label.as_str())),
284                Value::Str(_) => Err("an option needs a label".into()),
285                other => Self::from_value(other),
286            })
287            .collect()
288    }
289
290    /// An item of the app's own, by label.
291    pub fn new(label: impl Into<String>) -> Self {
292        Self {
293            label: label.into(),
294            role: MenuRole::Custom,
295            enabled: true,
296            checked: false,
297            id: None,
298            accel: None,
299            submenu: Vec::new(),
300        }
301    }
302
303    /// One of the standard items, with the role's own wording.
304    pub fn role(role: MenuRole) -> Self {
305        Self {
306            label: String::new(),
307            role,
308            enabled: true,
309            checked: false,
310            id: None,
311            accel: None,
312            submenu: Vec::new(),
313        }
314    }
315
316    /// A row that opens a menu of `items` beside it: "Move to ▸", "Sort
317    /// by ▸". It is chosen through, never itself — see the `submenu`
318    /// field — so it needs no `id`, and an `accel` on it is not drawn (the
319    /// chevron is where it would go). A submenu with no rows is an ordinary
320    /// row ([`Self::has_submenu`]).
321    ///
322    /// ```rust
323    /// use kui_core::MenuItem;
324    ///
325    /// let sort = MenuItem::submenu("Sort by", vec![
326    ///     MenuItem::new("Name").id("sort.name").checked(true),
327    ///     MenuItem::new("Date modified").id("sort.date"),
328    /// ]);
329    /// assert!(sort.has_submenu());
330    /// ```
331    pub fn submenu(label: impl Into<String>, items: Vec<MenuItem>) -> Self {
332        Self {
333            submenu: items,
334            ..Self::new(label)
335        }
336    }
337
338    /// Whether the row opens a menu rather than being chosen (the
339    /// `submenu` field). A row declared with an empty submenu is an
340    /// ordinary row.
341    pub fn has_submenu(&self) -> bool {
342        !self.submenu.is_empty()
343    }
344
345    /// The row at `path` in `items`: `[2]` is the third row, `[2, 0]` the
346    /// first row of the third row's submenu. `None` past the end of any
347    /// level, for an empty path, and through a row with no submenu.
348    pub fn at_path<'a>(items: &'a [MenuItem], path: &[usize]) -> Option<&'a MenuItem> {
349        let (&last, outer) = path.split_last()?;
350        let mut level = items;
351        for &i in outer {
352            level = &level.get(i)?.submenu;
353        }
354        level.get(last)
355    }
356
357    pub fn separator() -> Self {
358        Self::role(MenuRole::Separator)
359    }
360
361    pub fn enabled(mut self, on: bool) -> Self {
362        self.enabled = on;
363        self
364    }
365
366    /// Draws a checkmark beside the row (and sets the platform's check
367    /// state where a host renders the menu).
368    pub fn checked(mut self, on: bool) -> Self {
369        self.checked = on;
370        self
371    }
372
373    pub fn id(mut self, id: impl Into<Value>) -> Self {
374        self.id = Some(id.into());
375        self
376    }
377
378    pub fn accel(mut self, a: impl Into<String>) -> Self {
379        self.accel = Some(a.into());
380        self
381    }
382
383    /// What the row reads: its own label, or the role's.
384    pub fn text(&self) -> &str {
385        if self.label.is_empty() {
386            self.role.default_label()
387        } else {
388            &self.label
389        }
390    }
391
392    /// The accelerator the row declares: its own, or the role's. `None` is
393    /// a row with neither, which is every `Custom` one the app did not
394    /// spell a shortcut for. As declared — [`Self::accel_label`] is what is
395    /// drawn.
396    pub fn accel_text(&self) -> Option<&str> {
397        match &self.accel {
398            Some(accel) => Some(accel),
399            None => Some(self.role.default_accel()).filter(|a| !a.is_empty()),
400        }
401    }
402
403    /// What the row draws on its right: [`Self::accel_text`] in the
404    /// platform's spelling when kui can parse it (`"mod+shift+n"` reads
405    /// `⇧⌘N` on a Mac and `Ctrl+Shift+N` elsewhere), and exactly as
406    /// written when it cannot (`"gd"`, an app's own hint). See
407    /// [`Accel::label`].
408    pub fn accel_label(&self) -> Option<std::borrow::Cow<'_, str>> {
409        self.accel_text().map(Accel::label)
410    }
411
412    /// Whether the row takes focus and can be chosen — or, for a row with
413    /// a submenu, opened.
414    pub fn selectable(&self) -> bool {
415        self.enabled && self.role != MenuRole::Separator
416    }
417
418    /// Whether the row at `path` can be chosen the way the drawn menu
419    /// reaches it: every row on the way enabled, the last one selectable
420    /// and opening nothing. A host's report of a row the menu could not
421    /// have shown it is refused rather than performed.
422    pub(crate) fn choosable_at(items: &[MenuItem], path: &[usize]) -> bool {
423        let mut level = items;
424        for (n, &i) in path.iter().enumerate() {
425            let Some(item) = level.get(i).filter(|item| item.selectable()) else {
426                return false;
427            };
428            if n + 1 == path.len() {
429                return !item.has_submenu();
430            }
431            level = &item.submenu;
432        }
433        false
434    }
435
436    /// Rewrites every accelerator in `items` that kui can parse into the
437    /// platform's own spelling ([`Accel::label`]) and leaves the rest
438    /// exactly as declared. What `declare_menu_bar` and `open_menu` do on
439    /// the way in, so the menu a host reads back (`Core::menu`,
440    /// `Core::menu_bar`) is the one the drawn menu shows, and a platform
441    /// menu parses the same string into the same key.
442    pub(crate) fn normalize_accels(items: &mut [MenuItem]) {
443        for item in items {
444            if let Some(accel) = &item.accel
445                && let std::borrow::Cow::Owned(display) = Accel::label(accel)
446            {
447                item.accel = Some(display);
448            }
449            Self::normalize_accels(&mut item.submenu);
450        }
451    }
452}
453
454/// The menu a window has open: its items, where it opened, and what it is
455/// about. One per window — opening a second closes the first, the way one
456/// selection closes the last.
457#[derive(Clone, Debug, PartialEq)]
458pub struct Menu {
459    /// The node the menu was opened over. Chosen items post their event
460    /// on it, so an app reads a menu the way it reads a click.
461    pub target: Key,
462    /// Where it opens, logical viewport px — the press point, which is
463    /// where every platform puts a context menu.
464    pub at: Vec2,
465    /// Who asked for it: the host, or the extension whose node it is
466    /// about. Carried onto the events the items post.
467    pub origin: OriginId,
468    pub items: Vec<MenuItem>,
469}
470
471impl Menu {
472    pub fn new(target: Key, at: Vec2, items: Vec<MenuItem>) -> Self {
473        Self {
474            target,
475            at,
476            origin: OriginId::HOST,
477            items,
478        }
479    }
480
481    pub fn origin(mut self, origin: OriginId) -> Self {
482        self.origin = origin;
483        self
484    }
485}
486
487/// What choosing an item leaves for the host to do, drained with
488/// [`crate::runtime::Core::take_menu_actions`] the way window and audio
489/// commands are.
490///
491/// The clipboard is the host's in this library — the runner already reads
492/// and writes it for Cmd-C/X/V — and nothing here changes that. The core
493/// works out *what* to copy, which is the half it is uniquely able to do,
494/// and hands over a string.
495#[derive(Clone, Debug, PartialEq)]
496pub enum MenuAction {
497    /// Put this on the system clipboard. Both Copy and Cut produce one;
498    /// Cut has already removed the text by the time it arrives.
499    ///
500    /// `html` is the same selection with the formatting the core knows
501    /// about (bold, italic, a span's declared colour), for a host that can
502    /// offer a second flavour. It is an addition to `text`, never a
503    /// replacement: a clipboard whose only flavour is HTML pastes markup
504    /// into every plain-text field on the machine.
505    SetClipboard { text: String, html: Option<String> },
506    /// Put this secret on the system clipboard the way a password manager
507    /// does: the text, marked concealed and transient —
508    /// `org.nspasteboard.ConcealedType` and `TransientType` on macOS,
509    /// excluded from monitoring, history and the cloud clipboard on
510    /// Windows, `x-kde-passwordManagerHint: secret` on Linux — so a
511    /// clipboard manager neither shows nor keeps it. Queued by
512    /// `Core::set_clipboard_secret`, never by a menu row. Plain text only:
513    /// a secret has no formatting to offer.
514    SetClipboardSecret { text: String },
515    /// Read the clipboard and deliver it as `InputEvent::Paste`: a
516    /// focused editor takes it as typing, the way it takes Cmd-V, and a
517    /// focused key sink hears it as `{kind:"text"}` — which is how an
518    /// app that owns its text gets a paste it asked for with
519    /// `Core::request_paste`. The core cannot read a clipboard, so Paste
520    /// is the one standard item it can only ask for. The answer carries
521    /// the pasteboard's markers ([`crate::input::ClipboardMarks`]), and an
522    /// answer that is a bare `InputEvent::Commit` is one that marked
523    /// nothing.
524    Paste,
525    /// Show the platform's definition panel for `text`, anchored at
526    /// `rect` (logical viewport px — the word's own box, which is what
527    /// macOS's `showDefinitionForAttributedString:atPoint:` wants). Both
528    /// the Look Up row and a force click over text produce one; a host
529    /// that cannot show a panel drops it, and is never offered the row in
530    /// the first place (`Core::set_lookup_available`).
531    LookUp {
532        text: String,
533        /// The **baseline origin of the selection's first line**, logical
534        /// viewport px — the point
535        /// `showDefinitionForAttributedString:atPoint:` takes and draws
536        /// the term back over. Not a box's corner: a box's bottom puts the
537        /// term a line low, and a multi-run selection's union puts it
538        /// under the last line while the panel shows the first.
539        at: crate::geom::Vec2,
540    },
541}
542
543// -- The application menu bar -----------------------------------------------
544// The bar is the same rows one level up: a list of menus, each a label and
545// the `MenuItem`s above, so an Edit menu's Copy is the *same item* the
546// context menu's Copy is and the core performs it the same way.
547
548/// One menu of the bar: what the bar reads, and what drops out of it.
549#[derive(Clone, Debug, Default, PartialEq)]
550pub struct BarMenu {
551    /// What the bar shows. On macOS the first menu is the application menu
552    /// and the platform titles that one with the app's own name, whatever
553    /// this says.
554    pub label: String,
555    pub items: Vec<MenuItem>,
556    /// A disabled menu is dimmed and opens nothing.
557    pub enabled: bool,
558}
559
560impl BarMenu {
561    pub fn new(label: impl Into<String>, items: Vec<MenuItem>) -> Self {
562        Self {
563            label: label.into(),
564            items,
565            enabled: true,
566        }
567    }
568
569    pub fn enabled(mut self, on: bool) -> Self {
570        self.enabled = on;
571        self
572    }
573}
574
575/// The application menu: what a frame declares, in order
576/// (`Core::declare_menu_bar`).
577///
578/// Declared and not commanded, like the window title: a frame that declares
579/// none leaves the last one in force, and a frame that declares an empty
580/// bar takes it away. Where the platform owns a menu bar the driver hands
581/// this over (macOS: `NSApp.mainMenu`); everywhere else
582/// [`crate::widgets::menu_bar`] draws it, and each of its titles opens the
583/// ordinary [`Menu`] machinery — so the dropdown, its keyboard, its
584/// dismissal and its access tree are the ones already built for the context
585/// menu.
586#[derive(Clone, Debug, Default, PartialEq)]
587pub struct MenuBar {
588    pub menus: Vec<BarMenu>,
589}
590
591impl MenuBar {
592    pub fn new(menus: Vec<BarMenu>) -> Self {
593        Self { menus }
594    }
595
596    /// A bar from plain data: a list of `{ label, items, enabled? }`,
597    /// whose `items` are the rows `openMenu` takes. A menu with no `items`
598    /// is a shape error and not an empty menu: the two read the same on
599    /// screen and only one of them was meant.
600    pub fn from_value(v: &Value) -> Result<Self, String> {
601        let Value::List(menus) = v else {
602            return Err("menu is an array of menus".into());
603        };
604        let mut out = Vec::with_capacity(menus.len());
605        for entry in menus {
606            let Value::Map(_) = entry else {
607                return Err("each menu is an object { label, items }".into());
608            };
609            let label = entry
610                .get_str("label")
611                .ok_or("each menu needs a label")?
612                .to_string();
613            let items = entry
614                .get("items")
615                .ok_or_else(|| format!("menu entry `{label}` needs `items` (a list of rows)"))?;
616            out.push(BarMenu {
617                label,
618                items: MenuItem::list_from_value(items)?,
619                enabled: entry.get_bool("enabled").unwrap_or(true),
620            });
621        }
622        Ok(Self::new(out))
623    }
624
625    /// Nothing declared: the bar the platform is asked to take away.
626    pub fn is_empty(&self) -> bool {
627        self.menus.is_empty()
628    }
629
630    /// The item at `(menu, item)`, if it is there.
631    pub fn item(&self, menu: usize, item: usize) -> Option<&MenuItem> {
632        self.menus.get(menu)?.items.get(item)
633    }
634
635    /// The item at `path` inside menu `menu`, through its submenus
636    /// ([`MenuItem::at_path`]).
637    pub fn item_at(&self, menu: usize, path: &[usize]) -> Option<&MenuItem> {
638        MenuItem::at_path(&self.menus.get(menu)?.items, path)
639    }
640}
641
642/// A keyboard shortcut, parsed out of the string an item declares.
643///
644/// The core binds nothing to it and never has ([`MenuItem::accel`] is
645/// display); this exists for the one consumer that needs the parts rather
646/// than the words — a platform menu bar, which sets a real key equivalent
647/// and then matches it before the window ever sees the key.
648///
649/// Both spellings parse, because both are written in the field: the
650/// portable one (`"mod+shift+s"`, where `mod` is Command on macOS and
651/// Control elsewhere) and the platform one a menu is read in (`"⇧⌘S"`,
652/// `"Ctrl+Shift+S"`). [`Accel::display`] is the second, which is what
653/// `declare_menu_bar` normalizes a declaration into so the drawn bar and
654/// the platform's read the same.
655#[derive(Clone, Copy, Debug, PartialEq, Eq)]
656pub struct Accel {
657    pub code: crate::input::KeyCode,
658    pub mods: crate::input::KeyMods,
659}
660
661impl Accel {
662    /// Parses `"mod+s"`, `"ctrl+shift+p"`, `"f5"`, `"⇧⌘S"`. `None` for
663    /// anything this vocabulary cannot name — the caller then leaves the
664    /// string alone and draws it as written, since a shortcut kui cannot
665    /// parse is still a shortcut the app's own keymap runs.
666    pub fn parse(s: &str) -> Option<Accel> {
667        use crate::input::{KeyCode, KeyMods};
668        let mut mods = KeyMods::default();
669        let mut rest = s.trim();
670        // The glyph spelling has no separators: ⌃⌥⇧⌘ in that order, then
671        // the key. Stripped first so `"⌘S"` and `"cmd+s"` land together.
672        loop {
673            let mut chars = rest.chars();
674            match chars.next() {
675                Some('\u{2303}') => mods.ctrl = true,
676                Some('\u{2325}') => mods.alt = true,
677                Some('\u{21e7}') => mods.shift = true,
678                Some('\u{2318}') => mods.super_key = true,
679                _ => break,
680            }
681            rest = chars.as_str();
682        }
683        let mut code = None;
684        for part in rest.split('+') {
685            let part = part.trim();
686            if part.is_empty() {
687                return None;
688            }
689            let lower = part.to_ascii_lowercase();
690            match lower.as_str() {
691                // The one token that is not a key on any keyboard:
692                // whichever modifier this platform puts shortcuts behind.
693                "mod" | "cmdorctrl" => {
694                    if cfg!(target_os = "macos") {
695                        mods.super_key = true;
696                    } else {
697                        mods.ctrl = true;
698                    }
699                }
700                "cmd" | "command" | "super" | "meta" | "win" => mods.super_key = true,
701                "ctrl" | "control" => mods.ctrl = true,
702                "alt" | "option" | "opt" => mods.alt = true,
703                "shift" => mods.shift = true,
704                // The key, and only one of them: `"s+s"` is a typo.
705                _ if code.is_some() => return None,
706                // A key as `display` writes it reads back as that key, so
707                // the menu that normalized `"mod+backspace"` into `⌘⌫`
708                // binds Backspace and not a `⌫` no keyboard types.
709                _ => {
710                    code = Some(if part.chars().count() == 1 {
711                        key_from_label(part).unwrap_or(KeyCode::Char(part.chars().next().unwrap()))
712                    } else {
713                        KeyCode::from_name(&lower).or_else(|| key_from_label(part))?
714                    });
715                }
716            }
717        }
718        let code = code?;
719        // A lock key turns a state rather than being a key a shortcut is
720        // held against: no menu bar takes `ctrl+capslock`.
721        let lock = matches!(
722            code,
723            KeyCode::CapsLock | KeyCode::NumLock | KeyCode::ScrollLock
724        );
725        (code != KeyCode::Unknown && !lock).then_some(Accel { code, mods })
726    }
727
728    /// How the platform writes it: the macOS glyph run (`⇧⌘S`, in AppKit's
729    /// order, no separators) or the spelled form (`Ctrl+Shift+S`).
730    pub fn display(&self) -> String {
731        let key = key_label(self.code);
732        if cfg!(target_os = "macos") {
733            let mut out = String::new();
734            for (on, glyph) in [
735                (self.mods.ctrl, '\u{2303}'),
736                (self.mods.alt, '\u{2325}'),
737                (self.mods.shift, '\u{21e7}'),
738                (self.mods.super_key, '\u{2318}'),
739            ] {
740                if on {
741                    out.push(glyph);
742                }
743            }
744            out.push_str(&key);
745            out
746        } else {
747            let mut parts = Vec::new();
748            for (on, name) in [
749                (self.mods.ctrl, "Ctrl"),
750                (self.mods.super_key, "Super"),
751                (self.mods.alt, "Alt"),
752                (self.mods.shift, "Shift"),
753            ] {
754                if on {
755                    parts.push(name);
756                }
757            }
758            parts.push(&key);
759            parts.join("+")
760        }
761    }
762
763    /// What a menu draws for the accelerator `spelled`: its
764    /// [`Accel::display`] when it parses, and `spelled` itself when it
765    /// does not — a shortcut kui cannot name is still one the app's own
766    /// keymap runs, and its spelling is the app's (ADR 0018, decision 7).
767    /// The drawn menu, the drawn bar and `open_menu` all read an
768    /// accelerator through this, so a portable `"mod+shift+n"` never
769    /// reaches the screen as written (backlog F127).
770    pub fn label(spelled: &str) -> std::borrow::Cow<'_, str> {
771        match Accel::parse(spelled) {
772            Some(a) => std::borrow::Cow::Owned(a.display()),
773            None => std::borrow::Cow::Borrowed(spelled),
774        }
775    }
776
777    /// The portable spelling, the one [`Accel::parse`] reads back to the
778    /// same chord on every platform: the modifiers held as `ctrl`,
779    /// `super`, `alt`, `shift` in that order, then the key by its wire
780    /// name (`"ctrl+shift+i"`, `"super+alt+f12"`). What a binding hands
781    /// out when it reads a chord back; [`Accel::display`] is what a
782    /// person reads.
783    pub fn spelling(&self) -> String {
784        let mut parts = Vec::new();
785        for (on, name) in [
786            (self.mods.ctrl, "ctrl"),
787            (self.mods.super_key, "super"),
788            (self.mods.alt, "alt"),
789            (self.mods.shift, "shift"),
790        ] {
791            if on {
792                parts.push(name.to_string());
793            }
794        }
795        parts.push(match self.code {
796            crate::input::KeyCode::Char(c) => c.to_ascii_lowercase().to_string(),
797            code => code.name(),
798        });
799        parts.join("+")
800    }
801
802    /// The key equivalent an `NSMenuItem` takes: the character, lowercased
803    /// (AppKit reads an uppercase one as Shift being held), or `None` for a
804    /// key AppKit spells with a function-key code this does not carry.
805    pub fn key_equivalent(&self) -> Option<String> {
806        match self.code {
807            crate::input::KeyCode::Char(c) => Some(c.to_lowercase().to_string()),
808            crate::input::KeyCode::Space => Some(" ".into()),
809            crate::input::KeyCode::Enter => Some("\r".into()),
810            crate::input::KeyCode::Tab => Some("\t".into()),
811            crate::input::KeyCode::Backspace => Some("\u{8}".into()),
812            crate::input::KeyCode::Delete => Some("\u{7f}".into()),
813            crate::input::KeyCode::Escape => Some("\u{1b}".into()),
814            _ => None,
815        }
816    }
817}
818
819/// What a menu writes a key as: the macOS glyph a user reads a shortcut by
820/// (`⇧`, `⌫`, `↩`), and the spelled word everywhere else. A key name is
821/// wire vocabulary (`"pageup"`); this is the label beside a row.
822fn key_label(code: crate::input::KeyCode) -> String {
823    key_label_on(code, cfg!(target_os = "macos"))
824}
825
826/// The key [`key_label`] writes as `label`, on either platform's spelling:
827/// what [`Accel::parse`] reads a displayed accelerator back through.
828fn key_from_label(label: &str) -> Option<crate::input::KeyCode> {
829    crate::input::KeyCode::named()
830        .iter()
831        .map(|(k, _)| *k)
832        .find(|&k| {
833            key_label_on(k, true) == label || key_label_on(k, false).eq_ignore_ascii_case(label)
834        })
835}
836
837fn key_label_on(code: crate::input::KeyCode, mac: bool) -> String {
838    use crate::input::KeyCode;
839    match code {
840        KeyCode::Char(c) => return c.to_uppercase().to_string(),
841        KeyCode::F(n) => return format!("F{n}"),
842        _ => {}
843    }
844    let s = match (code, mac) {
845        (KeyCode::Left, true) => "\u{2190}",
846        (KeyCode::Right, true) => "\u{2192}",
847        (KeyCode::Up, true) => "\u{2191}",
848        (KeyCode::Down, true) => "\u{2193}",
849        (KeyCode::Home, true) => "\u{2196}",
850        (KeyCode::End, true) => "\u{2198}",
851        (KeyCode::PageUp, true) => "\u{21de}",
852        (KeyCode::PageDown, true) => "\u{21df}",
853        (KeyCode::Backspace, true) => "\u{232b}",
854        (KeyCode::Delete, true) => "\u{2326}",
855        (KeyCode::Enter, true) => "\u{21a9}",
856        (KeyCode::Tab, true) => "\u{21e5}",
857        (KeyCode::Escape, true) => "\u{238b}",
858        (KeyCode::Space, true) => "\u{2423}",
859        (KeyCode::Left, _) => "Left",
860        (KeyCode::Right, _) => "Right",
861        (KeyCode::Up, _) => "Up",
862        (KeyCode::Down, _) => "Down",
863        (KeyCode::Home, _) => "Home",
864        (KeyCode::End, _) => "End",
865        (KeyCode::PageUp, _) => "Page Up",
866        (KeyCode::PageDown, _) => "Page Down",
867        (KeyCode::Backspace, _) => "Backspace",
868        (KeyCode::Delete, _) => "Delete",
869        (KeyCode::Enter, _) => "Enter",
870        (KeyCode::Tab, _) => "Tab",
871        (KeyCode::Escape, _) => "Esc",
872        (KeyCode::Space, _) => "Space",
873        (KeyCode::Insert, _) => "Insert",
874        (KeyCode::Clear, true) => "\u{2327}",
875        (KeyCode::Shift, true) => "\u{21e7}",
876        (KeyCode::Ctrl, true) => "\u{2303}",
877        (KeyCode::Alt, true) => "\u{2325}",
878        (KeyCode::Super, true) => "\u{2318}",
879        (KeyCode::CapsLock, true) => "\u{21ea}",
880        (KeyCode::PrintScreen, _) => "Print Screen",
881        (KeyCode::Pause, _) => "Pause",
882        (KeyCode::Menu, _) => "Menu",
883        (KeyCode::Clear, _) => "Clear",
884        (KeyCode::Shift, _) => "Shift",
885        (KeyCode::Ctrl, _) => "Ctrl",
886        (KeyCode::Alt, _) => "Alt",
887        (KeyCode::Super, _) => "Super",
888        (KeyCode::CapsLock, _) => "Caps Lock",
889        (KeyCode::NumLock, _) => "Num Lock",
890        (KeyCode::ScrollLock, _) => "Scroll Lock",
891        (KeyCode::MediaPlay, _) => "Play",
892        (KeyCode::MediaPause, _) => "Pause",
893        (KeyCode::MediaPlayPause, _) => "Play/Pause",
894        (KeyCode::MediaStop, _) => "Stop",
895        (KeyCode::MediaNext, _) => "Next Track",
896        (KeyCode::MediaPrev, _) => "Previous Track",
897        (KeyCode::MediaRecord, _) => "Record",
898        (KeyCode::MediaFastForward, _) => "Fast Forward",
899        (KeyCode::MediaRewind, _) => "Rewind",
900        (KeyCode::VolumeUp, _) => "Volume Up",
901        (KeyCode::VolumeDown, _) => "Volume Down",
902        (KeyCode::VolumeMute, _) => "Mute",
903        // Neither reachable from a parsed accelerator nor worth a lie.
904        (KeyCode::Unknown, _) | (KeyCode::Char(_), _) | (KeyCode::F(_), _) => "",
905    };
906    s.to_string()
907}
908
909#[cfg(test)]
910mod tests {
911    use super::*;
912    use crate::input::{KeyCode, KeyMods};
913
914    /// `ALL` is what C indexes, what Node's generated `MenuItemRole` is
915    /// spelled from and what `from_name` searches, so a variant it lacks
916    /// is one no binding can say. The match is exhaustive on purpose: a
917    /// variant added to the enum fails to compile here until it is placed
918    /// in `ALL` too.
919    #[test]
920    fn all_names_every_role_once() {
921        let mut seen = 0;
922        for role in MenuRole::ALL {
923            match role {
924                MenuRole::Custom
925                | MenuRole::Separator
926                | MenuRole::Cut
927                | MenuRole::Copy
928                | MenuRole::Paste
929                | MenuRole::SelectAll
930                | MenuRole::LookUp => seen += 1,
931            }
932            assert_eq!(MenuRole::from_name(role.name()), Some(role));
933            assert_eq!(
934                MenuRole::ALL.iter().filter(|r| **r == role).count(),
935                1,
936                "{role:?} is listed more than once"
937            );
938        }
939        assert_eq!(seen, MenuRole::ALL.len());
940    }
941
942    #[test]
943    fn mod_is_the_platform_primary() {
944        let a = Accel::parse("mod+s").unwrap();
945        assert_eq!(a.mods.super_key, cfg!(target_os = "macos"));
946        assert_eq!(a.mods.ctrl, !cfg!(target_os = "macos"));
947        assert_eq!(a.code, KeyCode::Char('s'));
948    }
949
950    #[test]
951    fn the_glyph_spelling_parses_back() {
952        let a = Accel::parse("\u{21e7}\u{2318}S").unwrap();
953        assert_eq!(
954            a,
955            Accel {
956                code: KeyCode::Char('S'),
957                mods: KeyMods::NONE.with_shift().with_super(),
958            }
959        );
960    }
961
962    #[test]
963    fn a_named_key_parses_and_reads_back_capitalised() {
964        let a = Accel::parse("ctrl+pageup").unwrap();
965        assert_eq!(a.code, KeyCode::PageUp);
966        let expect = if cfg!(target_os = "macos") {
967            "\u{21de}"
968        } else {
969            "Page Up"
970        };
971        assert!(a.display().ends_with(expect), "{}", a.display());
972    }
973
974    /// `spelling` is the readback a binding hands out, so it must parse
975    /// to the chord it came from on every platform — including the one
976    /// modifier `parse` names five ways.
977    #[test]
978    fn the_portable_spelling_parses_back_to_the_same_chord() {
979        for s in [
980            "ctrl+shift+i",
981            "f12",
982            "cmd+alt+d",
983            "⌃⌥⇧⌘s",
984            "mod+pageup",
985            "shift+/",
986        ] {
987            let a = Accel::parse(s).unwrap();
988            assert_eq!(
989                Accel::parse(&a.spelling()),
990                Some(a),
991                "{s} -> {}",
992                a.spelling()
993            );
994        }
995        assert_eq!(
996            Accel::parse("shift+ctrl+I").unwrap().spelling(),
997            "ctrl+shift+i"
998        );
999        assert_eq!(Accel::parse("win+f12").unwrap().spelling(), "super+f12");
1000    }
1001
1002    /// What a menu draws parses back to the chord it was drawn from: the
1003    /// macOS bar binds its key equivalent off the normalized text, and a
1004    /// `⌘⌫` read as the character `⌫` bound a key no keyboard has.
1005    #[test]
1006    fn the_displayed_spelling_parses_back_to_the_same_chord() {
1007        for (code, _) in KeyCode::named() {
1008            let mods = KeyMods::NONE.with_shift().with_super();
1009            let a = Accel { code: *code, mods };
1010            // A modifier is no shortcut's key, and Play/Pause's pause key
1011            // is spelled as Pause's: that one reads back as Pause.
1012            if code.is_modifier() || *code == KeyCode::MediaPause {
1013                continue;
1014            }
1015            assert_eq!(Accel::parse(&a.display()), Some(a), "{}", a.display());
1016            for mac in [true, false] {
1017                let label = key_label_on(*code, mac);
1018                assert_eq!(key_from_label(&label), Some(*code), "{label}");
1019            }
1020        }
1021        let trash = Accel::parse(&Accel::label("mod+backspace")).unwrap();
1022        assert_eq!(trash.code, KeyCode::Backspace);
1023        assert_eq!(trash.key_equivalent().as_deref(), Some("\u{8}"));
1024    }
1025
1026    #[test]
1027    fn a_shortcut_kui_cannot_name_is_not_a_shortcut() {
1028        assert!(Accel::parse("mod+nope").is_none());
1029        // A lock key is no shortcut's key (backlog RG96).
1030        assert!(Accel::parse("ctrl+capslock").is_none());
1031        assert!(Accel::parse("numlock").is_none());
1032        assert!(Accel::parse("shift+scrolllock").is_none());
1033        assert!(Accel::parse("s+s").is_none());
1034        assert!(Accel::parse("").is_none());
1035    }
1036
1037    #[test]
1038    fn a_key_equivalent_is_lowercase() {
1039        // AppKit reads an uppercase key equivalent as Shift being held, so
1040        // ⌘S must be sent as "s" with the Command flag and nothing else.
1041        assert_eq!(
1042            Accel::parse("cmd+S").unwrap().key_equivalent().as_deref(),
1043            Some("s")
1044        );
1045    }
1046}