Skip to main content

nsh_core/
desktop.rs

1//! What only desktops have: windows ([`window`]), the application menu,
2//! context menus and keyboard shortcuts (TS `nsh/desktop`). The platforms
3//! get them as [`DesktopCommand`]s on a window's root node (the main
4//! window's is the root) and report a chosen menu item as
5//! [`crate::EventKind::Menu`]; mobile platforms ignore them. The platforms
6//! report the main window's state in the environment ([`WindowState`]),
7//! the other windows' as [`WindowEvent`]s, and the displays with their own
8//! message ([`Display`]). The app's login item is a backend the runner
9//! gives the core ([`LoginItemBackend`]).
10
11use std::sync::Arc;
12
13use crate::{
14    ImageSource,
15    color::Hsla,
16    element::{JsHost, JsIn, JsKind, JsObject, JsOwned, JsValue, PropEnum, PropError, TsTypes},
17    geometry::{Point, Points},
18    keymap::{self, Keystroke, Modifiers, When},
19    platform::Os,
20};
21
22mod login_item;
23#[cfg(not(target_arch = "wasm32"))]
24pub mod menu_icon;
25pub mod window;
26mod window_state;
27
28pub(crate) use login_item::LoginItems;
29pub use login_item::{LaunchAtLoginError, LoginItemBackend, LoginItemStatus};
30pub use window::{
31    Backdrop, CloseReason, MainWindowOptions, OpenWindow, ProgressState, ResizeEdge, SizeToContent,
32    TitleBarOptions, WindowAttributes, WindowBackend, WindowCloseCause, WindowControl, WindowEvent,
33    WindowKind, WindowMode, WindowOptions, WindowPointerEvents, WindowPosition, WindowProgress,
34    WindowRequest, Workspaces,
35};
36pub use window_state::{Display, DisplayId, WindowPlacement, WindowState, notch};
37
38pub use crate::element::desktop::set_quit_mode;
39
40/// When closing the app's last window quits it: nsh.json's
41/// `application.quitMode`, the runtime's `Application.setQuitMode` and
42/// Rust's [`set_quit_mode`] once the app runs.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44#[non_exhaustive]
45pub enum QuitMode {
46    /// As the platform does: macOS stays, Windows and Linux quit.
47    #[default]
48    Platform,
49    /// Every platform quits when the last window closes.
50    LastWindowClosed,
51    /// Never on its own: the app decides.
52    Explicit,
53}
54
55impl QuitMode {
56    /// Whether closing the last window quits on `os`.
57    pub fn quits(self, os: crate::platform::Os) -> bool {
58        match self {
59            Self::Platform => matches!(
60                os,
61                crate::platform::Os::Windows | crate::platform::Os::Linux
62            ),
63            Self::LastWindowClosed => true,
64            Self::Explicit => false,
65        }
66    }
67
68    /// Reads the option: `"platform"`, `"lastWindowClosed"` or `"explicit"`.
69    pub fn from_json(value: &serde_json::Value) -> Result<Self, String> {
70        match value.as_str() {
71            Some("platform") => Ok(Self::Platform),
72            Some("lastWindowClosed") => Ok(Self::LastWindowClosed),
73            Some("explicit") => Ok(Self::Explicit),
74            _ => Err("expected \"platform\", \"lastWindowClosed\" or \"explicit\"".to_owned()),
75        }
76    }
77}
78
79/// The app's `"application"` block of nsh.json (or `app.json`).
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81#[non_exhaustive]
82pub struct ApplicationOptions {
83    /// When closing the last window quits.
84    pub quit_mode: QuitMode,
85    /// Whether nsh.json set `quitMode` (a plain root's implicit main
86    /// window quits on close unless it did).
87    quit_mode_set: bool,
88}
89
90impl ApplicationOptions {
91    /// Reads `"application"`: an unknown key or a wrong value is an error.
92    pub fn from_json(value: &serde_json::Value) -> Result<Self, String> {
93        let object = value
94            .as_object()
95            .ok_or_else(|| "expected an object".to_owned())?;
96        let mut options = Self::default();
97        for (key, value) in object {
98            match key.as_str() {
99                "quitMode" => {
100                    options.quit_mode =
101                        QuitMode::from_json(value).map_err(|e| format!("quitMode: {e}"))?;
102                    options.quit_mode_set = true;
103                }
104                other => return Err(format!("unknown key `{other}`")),
105            }
106        }
107        Ok(options)
108    }
109
110    /// The quit mode nsh.json set, `None` when it omitted `quitMode`.
111    /// Engine plumbing, not app API.
112    #[doc(hidden)]
113    pub fn __explicit_quit_mode(&self) -> Option<QuitMode> {
114        self.quit_mode_set.then_some(self.quit_mode)
115    }
116}
117
118/// Additional sources of quit requests on standalone apps: `system` on
119/// macOS and Windows, `main_window_close` on macOS. Both options default to
120/// false and require a quit request listener. Other platforms and embedded
121/// views keep their existing lifecycle.
122#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, JsObject)]
123#[non_exhaustive]
124pub struct QuitRequestOptions {
125    /// Asks the app before logout, restart or shutdown. Call `quit()` to
126    /// approve, or `cancel_quit_request()` to cancel the system request.
127    #[prop(default)]
128    pub system: bool,
129    /// Legacy in window model v2: there is no user-closable main window, so
130    /// this asks for nothing. A window with `close_on_press: false` uses its
131    /// close handler; a window kept alive on close still hides.
132    #[prop(default)]
133    pub main_window_close: bool,
134}
135
136impl QuitRequestOptions {
137    /// Whether logout, restart and shutdown ask the quit listener.
138    pub fn system(mut self, system: bool) -> Self {
139        self.system = system;
140        self
141    }
142
143    /// Whether closing the main window asks the quit listener: legacy, and
144    /// no window is the main one in window model v2.
145    pub fn main_window_close(mut self, main_window_close: bool) -> Self {
146        self.main_window_close = main_window_close;
147        self
148    }
149}
150
151/// How a window's title bar looks ([`TitleBarOptions::style`]).
152#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
153pub enum TitleBarStyle {
154    /// The system's title bar, above the app.
155    #[default]
156    Default,
157    /// No system title bar: the app fills the window up to its top edge
158    /// and draws its own title bar, which views with `windowDrag` make
159    /// draggable. The system's window controls stay (macOS's traffic
160    /// lights, Windows' caption buttons, GTK's window buttons) in the area
161    /// the environment's `title_bar` reports.
162    Hidden,
163}
164
165/// When the window's menu bar shows (`Menu.setMenuBar`), where the app's
166/// window draws one (the GPUI backend on Windows and Linux).
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
168pub enum MenuBarMode {
169    /// Always, above the app.
170    #[default]
171    Shown,
172    /// Hidden until Alt is pressed and released alone, which shows it until
173    /// Alt alone hides it again. F10 and Alt with a menu's initial open a
174    /// menu, and the bar shows while it is open.
175    #[prop(rename = "autoHide")]
176    AutoHide,
177}
178
179/// A window's frame (`WindowRef.setBounds`): the part of it to move, in
180/// points, in screen coordinates; a field left out keeps its value. The
181/// origin is the window's top left corner, measured from the top left of
182/// the primary screen (the one with the menu bar on macOS) with `y`
183/// growing down, on every platform. TS gives `origin` (`x`, `y`) and
184/// `size` (`width`, `height`) as `Partial<Point>` and `Partial<Size>`.
185#[derive(Debug, Clone, Copy, Default, PartialEq)]
186pub struct WindowFrame {
187    /// Its left edge.
188    pub x: Option<Points>,
189    /// Its top edge, growing down; changing the height without a `y`
190    /// keeps the top edge where it is (the window grows and shrinks at its
191    /// bottom edge).
192    pub y: Option<Points>,
193    /// Its outer width on macOS / Windows, GTK default width on Linux;
194    /// in GPUI windows, the content's width (at least 1 point).
195    pub width: Option<Points>,
196    /// Its outer height on macOS / Windows, GTK default height on Linux;
197    /// in GPUI windows, the content's height (at least 1 point).
198    pub height: Option<Points>,
199    /// Animates the change on macOS (false by default; GPUI ignores it).
200    pub animated: Option<bool>,
201}
202
203/// TS: `{ origin?: Partial<Point>; size?: Partial<Size>; animated? }`.
204impl JsValue for WindowFrame {
205    fn ts_type(types: &mut TsTypes) -> String {
206        types.declare("WindowFrame", |_| {
207            "/** A window's frame (`WindowRef.setBounds`): the part of it to move, in points, in screen coordinates; a field left out keeps its value. */\n\
208             export interface WindowFrame {\n  \
209             /** Its top left corner, from the primary screen's top left corner, `y` growing down. A height changed without a `y` keeps the top edge where it is: the window grows and shrinks at its bottom edge. */\n  \
210             origin?: Partial<Point>;\n  \
211             /** Its outer size on macOS / Windows, GTK's default size on Linux. */\n  \
212             size?: Partial<Size>;\n  \
213             /** Animates the change on macOS (false by default). */\n  \
214             animated?: boolean;\n}"
215                .into()
216        })
217    }
218
219    fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
220        if value.kind() != JsKind::Object {
221            return Err(value.expected("an object"));
222        }
223        // Field `key` of `object` as `T`, `None` when it is left out.
224        fn get<T: JsValue>(object: JsIn<'_>, key: &str) -> Result<Option<T>, PropError> {
225            let v = object.field(key)?;
226            let v = v.get();
227            if v.is_nullish() {
228                return Ok(None);
229            }
230            T::from_js(v)
231                .map(Some)
232                .map_err(|e| PropError(format!("`{key}`: {e}")))
233        }
234        let mut frame = WindowFrame {
235            animated: get(value, "animated")?,
236            ..WindowFrame::default()
237        };
238        let origin = value.field("origin")?;
239        if !origin.get().is_nullish() {
240            frame.x = get(origin.get(), "x")?;
241            frame.y = get(origin.get(), "y")?;
242        }
243        let size = value.field("size")?;
244        if !size.get().is_nullish() {
245            frame.width = get(size.get(), "width")?;
246            frame.height = get(size.get(), "height")?;
247        }
248        Ok(frame)
249    }
250
251    fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
252        let owned = JsOwned::new(host, host.new_object()?);
253        let object = owned.get().raw();
254        let part = |fields: [(&str, Option<Points>); 2]| -> Result<Option<JsOwned<'a>>, PropError> {
255            if fields.iter().all(|(_, v)| v.is_none()) {
256                return Ok(None);
257            }
258            let part = JsOwned::new(host, host.new_object()?);
259            for (key, value) in fields {
260                if let Some(value) = value {
261                    host.set_field(part.get().raw(), key, value.to_js(host)?.into_raw())?;
262                }
263            }
264            Ok(Some(part))
265        };
266        if let Some(origin) = part([("x", self.x), ("y", self.y)])? {
267            host.set_field(object, "origin", origin.into_raw())?;
268        }
269        if let Some(size) = part([("width", self.width), ("height", self.height)])? {
270            host.set_field(object, "size", size.into_raw())?;
271        }
272        if let Some(v) = self.animated {
273            host.set_field(object, "animated", v.to_js(host)?.into_raw())?;
274        }
275        Ok(owned)
276    }
277}
278
279/// How high a window floats (its `level`).
280#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
281pub enum WindowLevel {
282    /// The normal level.
283    #[default]
284    Normal,
285    /// Above normal windows: a floating palette or a widget.
286    Floating,
287    /// Above the Dock and the taskbar (an overlay, a launcher).
288    #[prop(rename = "aboveDock")]
289    AboveDock,
290    /// macOS's desktop icon level; on Windows, moves to the bottom of
291    /// the current z-order (later activation can raise the window).
292    #[prop(rename = "desktopIcon")]
293    DesktopIcon,
294}
295
296/// Whether a window has the system's frame (its `frame`).
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
298pub enum WindowFrameStyle {
299    /// The system's title bar and border.
300    #[default]
301    Default,
302    /// No title bar or border: the app draws everything.
303    None,
304}
305
306/// A key of a [`Shortcut`].
307#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
308pub enum Key {
309    /// A character key, lowercase (`a`, `1`, `,`, `=`).
310    Char(char),
311    /// Enter / Return.
312    Enter,
313    /// Escape.
314    Escape,
315    /// Tab.
316    Tab,
317    /// Backspace.
318    Backspace,
319    /// Delete (forward).
320    Delete,
321    /// Insert.
322    Insert,
323    /// The space bar.
324    Space,
325    /// Arrow up.
326    Up,
327    /// Arrow down.
328    Down,
329    /// Arrow left.
330    Left,
331    /// Arrow right.
332    Right,
333    /// Home.
334    Home,
335    /// End.
336    End,
337    /// Page up.
338    PageUp,
339    /// Page down.
340    PageDown,
341    /// A function key, F1 to F24.
342    F(u8),
343}
344
345impl Key {
346    /// The key named `name`: a key name (`"enter"`, `"f5"`, `"plus"`) or
347    /// the character the key types on the US layout without Shift (`"n"`,
348    /// `"1"`, `","`), in any case ([`Shortcut::parse`]).
349    pub fn parse(name: &str) -> Option<Key> {
350        parse_key(name, &name.to_ascii_lowercase()).ok()
351    }
352
353    /// Its name in a shortcut's label (`N`, `Enter`, `F5`).
354    pub fn label(self) -> String {
355        match self {
356            Key::Char(c) => c.to_uppercase().collect(),
357            Key::Enter => "Enter".into(),
358            Key::Escape => "Esc".into(),
359            Key::Tab => "Tab".into(),
360            Key::Backspace => "Backspace".into(),
361            Key::Delete => "Del".into(),
362            Key::Insert => "Ins".into(),
363            Key::Space => "Space".into(),
364            Key::Up => "Up".into(),
365            Key::Down => "Down".into(),
366            Key::Left => "Left".into(),
367            Key::Right => "Right".into(),
368            Key::Home => "Home".into(),
369            Key::End => "End".into(),
370            Key::PageUp => "PgUp".into(),
371            Key::PageDown => "PgDn".into(),
372            Key::F(n) => format!("F{n}"),
373        }
374    }
375}
376
377/// A keyboard shortcut of a menu item (`"mod+shift+n"`).
378#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
379pub struct Shortcut {
380    /// The key.
381    pub key: Key,
382    /// Control.
383    pub ctrl: bool,
384    /// Alt / Option.
385    pub alt: bool,
386    /// Shift.
387    pub shift: bool,
388    /// Command (macOS) / the Windows key / Super.
389    pub meta: bool,
390}
391
392impl Shortcut {
393    /// A shortcut of `key` alone.
394    pub const fn key(key: Key) -> Shortcut {
395        Shortcut {
396            key,
397            ctrl: false,
398            alt: false,
399            shift: false,
400            meta: false,
401        }
402    }
403
404    /// Parses `"mod+shift+n"`: modifiers and one key joined by `+`, in any
405    /// case (lowercase is the style; a capital letter is the same key, not
406    /// Shift). `mod` (`cmdorctrl`, `commandorcontrol`) is Command when
407    /// `mod_is_meta` (macOS), else Control; `cmd` (`command`, `meta`,
408    /// `super`, `win`) is Command, the Windows key or Super; then `ctrl`
409    /// (`control`), `alt` (`option`, `opt`) and `shift`. The key is a name
410    /// or the US layout's unshifted character ([`Key::parse`]); `plus` is
411    /// the `=` key. `nsh/keymap` (`crate::keymap`) reads the same
412    /// keystrokes, with the same messages for those that are not.
413    pub fn parse(text: &str, mod_is_meta: bool) -> Result<Shortcut, ShortcutError> {
414        // Case does not matter; messages quote the text as written and
415        // suggest lowercase.
416        let lower = text.to_ascii_lowercase();
417        let (mods, key) = split(text, &lower)?;
418        // Modifiers first, as `nsh/keymap` reads them (so are its errors).
419        let mut shortcut = Shortcut::key(Key::Space);
420        for name in mods {
421            let flag =
422                modifier(&mut shortcut, name, mod_is_meta).map_err(|why| error(text, why))?;
423            if *flag {
424                return Err(error(text, format_args!("{name:?} twice")));
425            }
426            *flag = true;
427        }
428        shortcut.key = parse_key(text, key)?;
429        Ok(shortcut)
430    }
431
432    /// Its label on Windows and Linux (`Ctrl+Shift+N`).
433    pub fn label(&self) -> String {
434        let mut out = String::new();
435        for (on, name) in [
436            (self.ctrl, "Ctrl+"),
437            (self.alt, "Alt+"),
438            (self.shift, "Shift+"),
439            (self.meta, "Win+"),
440        ] {
441            if on {
442                out.push_str(name);
443            }
444        }
445        out.push_str(&self.key.label());
446        out
447    }
448
449    /// Its label on `os`: on macOS as symbols in the order Apple writes
450    /// them (`⌃⌥⇧⌘C`), else [`Shortcut::label`].
451    pub fn label_for(&self, os: Os) -> String {
452        if os != Os::MacOs {
453            return self.label();
454        }
455        self.keystroke().label(os, true)
456    }
457
458    /// Whether a focused text field uses this shortcut itself, as it uses
459    /// the same keystroke of `nsh/keymap` ([`Keystroke::edits_text`]).
460    pub fn edits_text(&self) -> bool {
461        self.keystroke().edits_text()
462    }
463
464    /// The same keystroke as `nsh/keymap` reads it.
465    fn keystroke(&self) -> Keystroke {
466        let key = match self.key {
467            Key::Char(c) => keymap::Key::Char(c),
468            Key::Space => keymap::Key::Char(' '),
469            Key::Enter => keymap::Key::Enter,
470            Key::Escape => keymap::Key::Escape,
471            Key::Tab => keymap::Key::Tab,
472            Key::Backspace => keymap::Key::Backspace,
473            Key::Delete => keymap::Key::Delete,
474            Key::Insert => keymap::Key::Insert,
475            Key::Up => keymap::Key::Up,
476            Key::Down => keymap::Key::Down,
477            Key::Left => keymap::Key::Left,
478            Key::Right => keymap::Key::Right,
479            Key::Home => keymap::Key::Home,
480            Key::End => keymap::Key::End,
481            Key::PageUp => keymap::Key::PageUp,
482            Key::PageDown => keymap::Key::PageDown,
483            Key::F(n) => keymap::Key::F(n),
484        };
485        let modifiers = Modifiers {
486            ctrl: self.ctrl,
487            alt: self.alt,
488            shift: self.shift,
489            cmd: self.meta,
490            alt_graph: false,
491        };
492        Keystroke { modifiers, key }
493    }
494}
495
496/// Why a shortcut's text is not one.
497#[derive(Debug, Clone, PartialEq, Eq)]
498pub struct ShortcutError(pub String);
499
500impl std::fmt::Display for ShortcutError {
501    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
502        f.write_str(&self.0)
503    }
504}
505
506impl std::error::Error for ShortcutError {}
507
508fn error(text: &str, reason: impl std::fmt::Display) -> ShortcutError {
509    ShortcutError(format!("invalid keystroke {text:?}: {reason}"))
510}
511
512/// Characters typed with Shift on the US layout, and the key typing them.
513const SHIFTED: &[(char, char)] = &[
514    ('~', '`'),
515    ('!', '1'),
516    ('@', '2'),
517    ('#', '3'),
518    ('$', '4'),
519    ('%', '5'),
520    ('^', '6'),
521    ('&', '7'),
522    ('*', '8'),
523    ('(', '9'),
524    (')', '0'),
525    ('_', '-'),
526    ('+', '='),
527    ('{', '['),
528    ('}', ']'),
529    ('|', '\\'),
530    (':', ';'),
531    ('"', '\''),
532    ('<', ','),
533    ('>', '.'),
534    ('?', '/'),
535];
536
537/// Named keys, by their (lowercase) names.
538const NAMED: &[(&str, Key)] = &[
539    ("enter", Key::Enter),
540    ("return", Key::Enter),
541    ("escape", Key::Escape),
542    ("esc", Key::Escape),
543    ("tab", Key::Tab),
544    ("space", Key::Space),
545    ("backspace", Key::Backspace),
546    ("delete", Key::Delete),
547    ("del", Key::Delete),
548    ("insert", Key::Insert),
549    ("up", Key::Up),
550    ("arrowup", Key::Up),
551    ("down", Key::Down),
552    ("arrowdown", Key::Down),
553    ("left", Key::Left),
554    ("arrowleft", Key::Left),
555    ("right", Key::Right),
556    ("arrowright", Key::Right),
557    ("home", Key::Home),
558    ("end", Key::End),
559    ("pageup", Key::PageUp),
560    ("pagedown", Key::PageDown),
561    // The plus key is the one typing `=`, as on the US layout.
562    ("plus", Key::Char('=')),
563    ("minus", Key::Char('-')),
564];
565
566/// The modifiers and the key of `text` (`"mod+shift+n"`).
567fn split<'a>(text: &str, lower: &'a str) -> Result<(Vec<&'a str>, &'a str), ShortcutError> {
568    if text.is_empty() {
569        return Err(error(text, "empty"));
570    }
571    if text.contains(char::is_whitespace) {
572        return Err(error(
573            text,
574            "one keystroke per binding (key sequences such as \"mod+k mod+s\" are not supported)",
575        ));
576    }
577    if lower == "+" || lower.ends_with("++") {
578        let mods = lower.strip_suffix("++").unwrap_or("");
579        let plus = if mods.is_empty() {
580            "plus".to_owned()
581        } else {
582            format!("{mods}+plus")
583        };
584        return Err(error(
585            text,
586            format_args!("write the plus key as \"plus\": {plus:?}"),
587        ));
588    }
589    let (mods, key) = match lower.rsplit_once('+') {
590        Some((mods, key)) => (mods.split('+').collect(), key),
591        None => (Vec::new(), lower),
592    };
593    if key.is_empty() {
594        return Err(error(text, "no key after the modifiers"));
595    }
596    Ok((mods, key))
597}
598
599/// The flag of modifier `name` in `shortcut`, or why it is none.
600fn modifier<'a>(
601    shortcut: &'a mut Shortcut,
602    name: &str,
603    mod_is_meta: bool,
604) -> Result<&'a mut bool, String> {
605    Ok(match name {
606        "ctrl" | "control" => &mut shortcut.ctrl,
607        "alt" | "option" | "opt" => &mut shortcut.alt,
608        "shift" => &mut shortcut.shift,
609        "cmd" | "command" | "meta" | "super" | "win" => &mut shortcut.meta,
610        "mod" | "cmdorctrl" | "commandorcontrol" if mod_is_meta => &mut shortcut.meta,
611        "mod" | "cmdorctrl" | "commandorcontrol" => &mut shortcut.ctrl,
612        "" => return Err("an empty modifier".into()),
613        other => {
614            return Err(format!(
615                "unknown modifier {other:?} (ctrl, alt, shift, cmd or mod)"
616            ));
617        }
618    })
619}
620
621fn parse_key(text: &str, key: &str) -> Result<Key, ShortcutError> {
622    if let Some(&(_, named)) = NAMED.iter().find(|(name, _)| *name == key) {
623        return Ok(named);
624    }
625    if let Some(n) = key
626        .strip_prefix('f')
627        .filter(|n| !n.starts_with('0'))
628        .and_then(|n| n.parse::<u8>().ok())
629        && (1..=24).contains(&n)
630    {
631        return Ok(Key::F(n));
632    }
633    let mut chars = key.chars();
634    let (Some(c), None) = (chars.next(), chars.next()) else {
635        let hint = if let Some((first, _)) = key.split_once('-')
636            && modifier(&mut Shortcut::key(Key::Space), first, false).is_ok()
637        {
638            // `mod--` is `mod+-`.
639            let joined = match key.strip_suffix("--") {
640                Some(mods) => format!("{}+-", mods.replace('-', "+")),
641                None => key.replace('-', "+"),
642            };
643            format!(" (join modifiers and the key with \"+\": {joined:?})")
644        } else {
645            String::new()
646        };
647        return Err(error(text, format_args!("unknown key {key:?}{hint}")));
648    };
649    if let Some(&(_, base)) = SHIFTED.iter().find(|(shifted, _)| *shifted == c) {
650        return Err(error(
651            text,
652            format_args!("{c:?} is typed with Shift: write \"shift+{base}\""),
653        ));
654    }
655    if !c.is_ascii_graphic() {
656        return Err(error(
657            text,
658            "keys are named by the US layout's characters (they match on any layout)",
659        ));
660    }
661    Ok(Key::Char(c))
662}
663
664/// A standard menu item: the platform carries it out (and labels it when
665/// the item has no label of its own).
666#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
667pub enum MenuRole {
668    /// The about panel (macOS); elsewhere the app hears it and shows its own.
669    About,
670    /// Hides the app (macOS); minimizes the window on Windows and Linux.
671    Hide,
672    /// Hides the other apps (macOS only; left out elsewhere, with a warning).
673    HideOthers,
674    /// Shows all apps (macOS only; left out elsewhere, with a warning).
675    ShowAll,
676    /// Quits the app.
677    Quit,
678    /// Undo in the focused text field.
679    Undo,
680    /// Redo in the focused text field.
681    Redo,
682    /// Cut the focused text field's selection.
683    Cut,
684    /// Copy the selection.
685    Copy,
686    /// Paste into the focused text field.
687    Paste,
688    /// Select all of the focused text field.
689    SelectAll,
690    /// Minimizes the window.
691    Minimize,
692    /// Maximizes (zooms) or restores the window.
693    Zoom,
694    /// Enters or leaves full screen.
695    ToggleFullScreen,
696    /// Closes the window.
697    Close,
698}
699
700impl MenuRole {
701    /// Every role.
702    pub const ALL: &[MenuRole] = &[
703        MenuRole::About,
704        MenuRole::Hide,
705        MenuRole::HideOthers,
706        MenuRole::ShowAll,
707        MenuRole::Quit,
708        MenuRole::Undo,
709        MenuRole::Redo,
710        MenuRole::Cut,
711        MenuRole::Copy,
712        MenuRole::Paste,
713        MenuRole::SelectAll,
714        MenuRole::Minimize,
715        MenuRole::Zoom,
716        MenuRole::ToggleFullScreen,
717        MenuRole::Close,
718    ];
719
720    /// The label of an item with this role and no label of its own.
721    pub fn label(self) -> &'static str {
722        match self {
723            MenuRole::About => "About",
724            MenuRole::Hide => "Hide",
725            MenuRole::HideOthers => "Hide Others",
726            MenuRole::ShowAll => "Show All",
727            MenuRole::Quit => "Quit",
728            MenuRole::Undo => "Undo",
729            MenuRole::Redo => "Redo",
730            MenuRole::Cut => "Cut",
731            MenuRole::Copy => "Copy",
732            MenuRole::Paste => "Paste",
733            MenuRole::SelectAll => "Select All",
734            MenuRole::Minimize => "Minimize",
735            MenuRole::Zoom => "Zoom",
736            MenuRole::ToggleFullScreen => "Toggle Full Screen",
737            MenuRole::Close => "Close",
738        }
739    }
740
741    /// The shortcut of an item with this role and no shortcut of its own,
742    /// on a Mac (`mac`) or elsewhere.
743    pub fn shortcut(self, mac: bool) -> Option<Shortcut> {
744        let primary = |key: char| Shortcut {
745            ctrl: !mac,
746            meta: mac,
747            ..Shortcut::key(Key::Char(key))
748        };
749        Some(match self {
750            MenuRole::About | MenuRole::ShowAll => return None,
751            MenuRole::Hide if mac => primary('h'),
752            MenuRole::HideOthers if mac => Shortcut {
753                alt: true,
754                ..primary('h')
755            },
756            MenuRole::Hide | MenuRole::HideOthers => return None,
757            MenuRole::Quit if mac => primary('q'),
758            MenuRole::Quit => Shortcut {
759                alt: true,
760                ..Shortcut::key(Key::F(4))
761            },
762            MenuRole::Undo => primary('z'),
763            MenuRole::Redo if mac => Shortcut {
764                shift: true,
765                ..primary('z')
766            },
767            MenuRole::Redo => primary('y'),
768            MenuRole::Cut => primary('x'),
769            MenuRole::Copy => primary('c'),
770            MenuRole::Paste => primary('v'),
771            MenuRole::SelectAll => primary('a'),
772            MenuRole::Minimize if mac => primary('m'),
773            MenuRole::Minimize | MenuRole::Zoom => return None,
774            MenuRole::ToggleFullScreen if mac => Shortcut {
775                ctrl: true,
776                ..primary('f')
777            },
778            MenuRole::ToggleFullScreen => Shortcut::key(Key::F(11)),
779            MenuRole::Close => primary('w'),
780        })
781    }
782
783    /// The role edits the focused text field (its shortcut is the field's
784    /// own: a menu does not take it from the field).
785    pub fn edits_text(self) -> bool {
786        matches!(
787            self,
788            MenuRole::Undo
789                | MenuRole::Redo
790                | MenuRole::Cut
791                | MenuRole::Copy
792                | MenuRole::Paste
793                | MenuRole::SelectAll
794        )
795    }
796}
797
798/// The translated labels sent by the core to desktop backends for the
799/// menus NSH builds. These follow the app's language (`nsh/i18n`); apps
800/// override individual menu items through their existing `label` field.
801#[derive(Debug, Clone, Default, PartialEq)]
802#[non_exhaustive]
803pub struct MenuLabels {
804    /// Role labels; `%{app}` is replaced with the app name on macOS.
805    pub roles: std::collections::HashMap<MenuRole, String>,
806    /// The title of the standard menu bar's Edit menu (`"Edit"`).
807    pub edit_menu: Option<String>,
808    /// The title of the standard menu bar's Window menu (`"Window"`).
809    pub window_menu: Option<String>,
810    /// The Delete item of a text field's edit menu, where NSH shows its own
811    /// (`"Delete"`).
812    pub delete: Option<String>,
813}
814
815impl MenuLabels {
816    pub(crate) fn for_locale(locale: crate::platform::Locale, mac: bool) -> Self {
817        static TEXTS: std::sync::OnceLock<crate::i18n::Translations> = std::sync::OnceLock::new();
818        let texts = TEXTS.get_or_init(|| {
819            crate::i18n::Translations::from_json(include_str!("desktop/menu.json"))
820                .expect("the built-in menu translations are valid")
821        });
822        // Region-only Chinese tags select the traditional script there.
823        let language = match locale.as_str() {
824            "zh-TW" | "zh-HK" | "zh-MO" => "zh-Hant",
825            language => language,
826        };
827        let text = |key: &str| texts.lookup(language, key).map(|text| text.into_owned());
828        Self {
829            roles: MenuRole::ALL
830                .iter()
831                .filter_map(|role| {
832                    let key = match (role, mac) {
833                        (MenuRole::About, true) => "About App",
834                        (MenuRole::Hide, true) => "Hide App",
835                        (MenuRole::Quit, true) => "Quit App",
836                        (MenuRole::ToggleFullScreen, true) => "Enter Full Screen",
837                        _ => role.label(),
838                    };
839                    let label = if mac {
840                        text(key)
841                    } else {
842                        text(&format!("Windows {key}")).or_else(|| text(key))
843                    };
844                    label.map(|label| (*role, label))
845                })
846                .collect(),
847            edit_menu: text("Edit"),
848            window_menu: text("Window"),
849            delete: text("Delete"),
850        }
851    }
852
853    /// The labels for a platform's language identifier (`zh-Hans`), which a
854    /// backend shows before the core sends the app's own
855    /// ([`DesktopCommand::SetMenuLabels`]). Engine plumbing, not app API.
856    #[doc(hidden)]
857    pub fn __for_language(identifier: &str, mac: bool) -> Option<Self> {
858        crate::platform::Locale::parse(identifier).map(|locale| Self::for_locale(locale, mac))
859    }
860
861    /// Titles the menus of `bar` ([`menu_bar`]) that have none: the
862    /// standard Edit and Window menus, in these labels' language.
863    #[doc(hidden)]
864    pub fn title_menus(&self, bar: &mut [MenuItem]) {
865        for item in bar {
866            if let MenuItem::Submenu { label, items, .. } = item
867                && label.is_empty()
868            {
869                let window = items.iter().any(|item| {
870                    matches!(
871                        item,
872                        MenuItem::Action(MenuAction {
873                            role: Some(MenuRole::Minimize | MenuRole::Zoom | MenuRole::Close),
874                            ..
875                        })
876                    )
877                });
878                *label = if window {
879                    self.window_menu.as_deref().unwrap_or("Window")
880                } else {
881                    self.edit_menu.as_deref().unwrap_or("Edit")
882                }
883                .to_owned();
884            }
885        }
886    }
887
888    /// NSH's translated label of `role`, when available.
889    pub fn role(&self, role: MenuRole) -> Option<&str> {
890        self.roles.get(&role).map(String::as_str)
891    }
892
893    /// The label of an item with `role` and no label of its own: the
894    /// translated label, else [`MenuRole::label`].
895    pub fn label(&self, role: MenuRole) -> &str {
896        self.role(role).unwrap_or(role.label())
897    }
898}
899
900/// An item of a menu that does something.
901#[derive(Debug, Clone, PartialEq)]
902pub struct MenuAction {
903    /// Reported as [`crate::EventKind::Menu`] when chosen (0: never
904    /// reported, a role-only item).
905    pub id: u32,
906    /// What it shows.
907    pub label: String,
908    /// Its keyboard shortcut.
909    pub shortcut: Option<Shortcut>,
910    /// It can be chosen.
911    pub enabled: bool,
912    /// A check mark: `Some` makes it a checkable item.
913    pub checked: Option<bool>,
914    /// What the platform does with it (the app is not told).
915    pub role: Option<MenuRole>,
916    /// When its shortcut chooses it while a text field has the keyboard
917    /// focus (`when`); [`When::Always`] unless the app says otherwise.
918    pub when: When,
919    /// What it shows beside its label, the app's own image ([`menu_icon`]).
920    pub icon: Option<ImageSource>,
921    /// An SF Symbol name beside its label in iOS header menus; ignored
922    /// elsewhere (including macOS). Prefer this over putting a symbol name
923    /// in [`Self::icon`], which is an image source.
924    pub symbol: Option<String>,
925    /// Shown as a destructive action on iOS (red); the desktops ignore it.
926    pub destructive: bool,
927}
928
929impl MenuAction {
930    /// Whether its shortcut chooses it while a text field has the keyboard
931    /// focus: with [`When::Auto`], unless the field uses the keystroke
932    /// itself ([`Shortcut::edits_text`]), as `nsh/keymap`'s bindings.
933    pub fn fires_while_editing(&self) -> bool {
934        match self.when {
935            When::Always => true,
936            When::NotEditing => false,
937            When::Auto => !self.shortcut.is_some_and(|s| s.edits_text()),
938        }
939    }
940}
941
942/// An item of a menu.
943#[derive(Debug, Clone, PartialEq)]
944pub enum MenuItem {
945    /// A line between groups of items.
946    Separator,
947    /// An item that does something.
948    Action(MenuAction),
949    /// An item opening a menu of its own (the top-level menus of a menu
950    /// bar), or an inline section when [`inline`](Self::Submenu::inline) is
951    /// set.
952    Submenu {
953        /// What it shows.
954        label: String,
955        /// It can be opened.
956        enabled: bool,
957        /// Its items.
958        items: Vec<MenuItem>,
959        /// What it shows beside its label ([`menu_icon`]), but for the
960        /// top-level menus of a menu bar, which show their titles alone.
961        icon: Option<ImageSource>,
962        /// An SF Symbol name beside its label in iOS header menus; ignored
963        /// elsewhere (including macOS).
964        symbol: Option<String>,
965        /// An inline section: on iOS, `UIMenuOptions.displayInline` with
966        /// `label` as the section title; on the desktops, its items between
967        /// separators, its label not shown ([`Self::with_inline_expanded`]).
968        inline: bool,
969    },
970}
971
972impl MenuItem {
973    /// The items of a selection menu (`selectionMenu`), as the platforms
974    /// show them after the system's own: plain items and separators.
975    /// Inline sections are expanded ([`Self::with_inline_expanded`]);
976    /// submenus, roles (the system's items are there already), shortcuts
977    /// and check marks are left out, as are items with no label and
978    /// separators that separate nothing.
979    pub fn selection_menu(items: &[MenuItem]) -> Vec<MenuItem> {
980        let mut out: Vec<MenuItem> = Vec::new();
981        for item in Self::with_inline_expanded(items) {
982            match item {
983                MenuItem::Separator => {
984                    if matches!(out.last(), Some(MenuItem::Action(_))) {
985                        out.push(MenuItem::Separator);
986                    }
987                }
988                MenuItem::Action(action) if action.role.is_none() && !action.label.is_empty() => {
989                    out.push(MenuItem::Action(MenuAction {
990                        shortcut: None,
991                        checked: None,
992                        when: When::Always,
993                        ..action
994                    }));
995                }
996                MenuItem::Action(_) | MenuItem::Submenu { .. } => {}
997            }
998        }
999        if matches!(out.last(), Some(MenuItem::Separator)) {
1000            out.pop();
1001        }
1002        out
1003    }
1004
1005    /// Expands [`inline`](Self::Submenu::inline) submenus into their items
1006    /// between separators (no leading or trailing separator, label not
1007    /// shown), for the desktops. Nested non-inline submenus are kept;
1008    /// their children are expanded the same way. A disabled inline section
1009    /// disables the items it brings, as iOS disables a disabled section's
1010    /// children. iOS header menus keep inline sections as they are.
1011    #[doc(hidden)]
1012    pub fn with_inline_expanded(items: &[MenuItem]) -> Vec<MenuItem> {
1013        let mut out = Vec::new();
1014        for item in items {
1015            match item {
1016                MenuItem::Submenu {
1017                    items,
1018                    enabled,
1019                    inline: true,
1020                    ..
1021                } => {
1022                    if !out.is_empty() && !matches!(out.last(), Some(MenuItem::Separator)) {
1023                        out.push(MenuItem::Separator);
1024                    }
1025                    let expanded = Self::with_inline_expanded(items);
1026                    if *enabled {
1027                        out.extend(expanded);
1028                    } else {
1029                        out.extend(expanded.into_iter().map(MenuItem::disabled));
1030                    }
1031                    if !matches!(out.last(), Some(MenuItem::Separator) | None) {
1032                        out.push(MenuItem::Separator);
1033                    }
1034                }
1035                MenuItem::Submenu {
1036                    label,
1037                    enabled,
1038                    items,
1039                    icon,
1040                    symbol,
1041                    inline: false,
1042                } => out.push(MenuItem::Submenu {
1043                    label: label.clone(),
1044                    enabled: *enabled,
1045                    items: Self::with_inline_expanded(items),
1046                    icon: icon.clone(),
1047                    symbol: symbol.clone(),
1048                    inline: false,
1049                }),
1050                // An explicit separator after an inline section would
1051                // otherwise double the one the expansion already pushed.
1052                MenuItem::Separator if matches!(out.last(), Some(MenuItem::Separator)) => {}
1053                other => out.push(other.clone()),
1054            }
1055        }
1056        while matches!(out.last(), Some(MenuItem::Separator)) {
1057            out.pop();
1058        }
1059        out
1060    }
1061
1062    /// This item, disabled: an action can't be chosen, a submenu can't be
1063    /// opened. A separator stays as it is.
1064    fn disabled(self) -> MenuItem {
1065        match self {
1066            MenuItem::Action(action) => MenuItem::Action(MenuAction {
1067                enabled: false,
1068                ..action
1069            }),
1070            MenuItem::Submenu {
1071                label,
1072                items,
1073                icon,
1074                symbol,
1075                inline,
1076                ..
1077            } => MenuItem::Submenu {
1078                label,
1079                enabled: false,
1080                items,
1081                icon,
1082                symbol,
1083                inline,
1084            },
1085            MenuItem::Separator => MenuItem::Separator,
1086        }
1087    }
1088
1089    /// The index in `items` (a menu bar's top-level items) of its Window
1090    /// menu: the first submenu holding a window role (`Minimize`, `Zoom` or
1091    /// `Close`), at any depth; failing that, the first holding
1092    /// `ToggleFullScreen`, which macOS menus usually put under View. macOS
1093    /// lists the app's open windows at its end.
1094    #[doc(hidden)]
1095    pub fn window_menu(items: &[MenuItem]) -> Option<usize> {
1096        fn has_role(items: &[MenuItem], role: &impl Fn(MenuRole) -> bool) -> bool {
1097            items.iter().any(|item| match item {
1098                MenuItem::Action(action) => action.role.is_some_and(role),
1099                MenuItem::Submenu { items, .. } => has_role(items, role),
1100                MenuItem::Separator => false,
1101            })
1102        }
1103        let first = |role: &dyn Fn(MenuRole) -> bool| {
1104            items.iter().position(|item| match item {
1105                MenuItem::Submenu { items, .. } => has_role(items, &role),
1106                _ => false,
1107            })
1108        };
1109        first(&|r| matches!(r, MenuRole::Minimize | MenuRole::Zoom | MenuRole::Close))
1110            .or_else(|| first(&|r| r == MenuRole::ToggleFullScreen))
1111    }
1112
1113    /// Calls `f` with the icon of every item of `items`, submenus' too.
1114    pub fn each_icon<'a>(items: &'a [MenuItem], f: &mut impl FnMut(&'a ImageSource)) {
1115        for item in items {
1116            match item {
1117                MenuItem::Action(action) => action.icon.iter().for_each(&mut *f),
1118                MenuItem::Submenu { items, icon, .. } => {
1119                    icon.iter().for_each(&mut *f);
1120                    MenuItem::each_icon(items, f);
1121                }
1122                MenuItem::Separator => {}
1123            }
1124        }
1125    }
1126
1127    /// Calls `f` with every action of `items`, submenus' too.
1128    pub fn each_action<'a>(items: &'a [MenuItem], f: &mut impl FnMut(&'a MenuAction)) {
1129        for item in items {
1130            match item {
1131                MenuItem::Action(action) => f(action),
1132                MenuItem::Submenu { items, .. } => MenuItem::each_action(items, f),
1133                MenuItem::Separator => {}
1134            }
1135        }
1136    }
1137
1138    /// The action of `items` (or their submenus) that `shortcut` chooses:
1139    /// enabled, with an id or a role that is not a text field's own.
1140    pub fn find_shortcut<'a>(items: &'a [MenuItem], shortcut: &Shortcut) -> Option<&'a MenuAction> {
1141        for item in items {
1142            match item {
1143                MenuItem::Action(action)
1144                    if action.enabled
1145                        && action.shortcut.as_ref() == Some(shortcut)
1146                        && !action.role.is_some_and(MenuRole::edits_text) =>
1147                {
1148                    return Some(action);
1149                }
1150                MenuItem::Submenu {
1151                    enabled: true,
1152                    items,
1153                    ..
1154                } => {
1155                    if let Some(found) = MenuItem::find_shortcut(items, shortcut) {
1156                        return Some(found);
1157                    }
1158                }
1159                _ => {}
1160            }
1161        }
1162        None
1163    }
1164}
1165
1166/// The menu bar a platform shows for the application menu `items` (its
1167/// top-level menus): `items` completed with the
1168/// platform's standard menus, so every app's menu bar has what the
1169/// platform's users expect without the app building it per platform:
1170///
1171/// - macOS: the app menu first (About, Hide, Hide Others, Show All,
1172///   Quit) unless the first menu already holds one of those roles but
1173///   Quit;
1174///   then the roles found in the app's other menus (a cross-platform
1175///   File menu's Quit) move there. A Window menu (Minimize, Zoom, Full
1176///   Screen, Close) ends the bar unless one exists
1177///   ([`MenuItem::window_menu`]).
1178/// - Windows and Linux: Quit (Exit) ends the first menu unless the
1179///   menu has it somewhere.
1180/// - Everywhere: an Edit menu (Undo, Redo, Cut, Copy, Paste, Select
1181///   All) follows the app's first menu (its File menu) unless the menu
1182///   holds an editing role, so text fields answer the standard keys
1183///   and the menu bar lists them.
1184///
1185/// An empty menu stays empty. The added items are roles (id 0): the
1186/// platform labels them and carries them out. The added Edit and Window
1187/// menus have no title: the platform gives them theirs in the app's
1188/// language ([`MenuLabels::title_menus`]).
1189#[doc(hidden)]
1190pub fn menu_bar(items: &[MenuItem], mac: bool) -> Vec<MenuItem> {
1191    use MenuRole as R;
1192    const APP: &[MenuRole] = &[R::About, R::Hide, R::HideOthers, R::ShowAll, R::Quit];
1193    const EDIT: &[MenuRole] = &[R::Undo, R::Redo, R::Cut, R::Copy, R::Paste, R::SelectAll];
1194    fn has(items: &[MenuItem], roles: &[MenuRole]) -> bool {
1195        items.iter().any(|item| match item {
1196            MenuItem::Action(action) => action.role.is_some_and(|r| roles.contains(&r)),
1197            MenuItem::Submenu { items, .. } => has(items, roles),
1198            MenuItem::Separator => false,
1199        })
1200    }
1201    /// `items` without the actions of `roles`, and without the
1202    /// separators left leading, trailing or doubled.
1203    fn without(items: &[MenuItem], roles: &[MenuRole]) -> Vec<MenuItem> {
1204        let mut out: Vec<MenuItem> = Vec::new();
1205        for item in items {
1206            match item {
1207                MenuItem::Action(a) if a.role.is_some_and(|r| roles.contains(&r)) => {}
1208                MenuItem::Separator if matches!(out.last(), None | Some(MenuItem::Separator)) => {}
1209                MenuItem::Submenu {
1210                    label,
1211                    enabled,
1212                    items,
1213                    icon,
1214                    symbol,
1215                    inline,
1216                } => out.push(MenuItem::Submenu {
1217                    label: label.clone(),
1218                    enabled: *enabled,
1219                    items: without(items, roles),
1220                    icon: icon.clone(),
1221                    symbol: symbol.clone(),
1222                    inline: *inline,
1223                }),
1224                other => out.push(other.clone()),
1225            }
1226        }
1227        while matches!(out.last(), Some(MenuItem::Separator)) {
1228            out.pop();
1229        }
1230        out
1231    }
1232    let role = |role: MenuRole| {
1233        MenuItem::Action(MenuAction {
1234            id: 0,
1235            label: String::new(),
1236            shortcut: None,
1237            enabled: true,
1238            checked: None,
1239            role: Some(role),
1240            when: When::Always,
1241            icon: None,
1242            symbol: None,
1243            destructive: false,
1244        })
1245    };
1246    let menu = |label: &str, roles: &[Option<MenuRole>]| MenuItem::Submenu {
1247        label: label.to_owned(),
1248        enabled: true,
1249        items: roles
1250            .iter()
1251            .map(|r| r.map_or(MenuItem::Separator, role))
1252            .collect(),
1253        icon: None,
1254        symbol: None,
1255        inline: false,
1256    };
1257    if items.is_empty() {
1258        return Vec::new();
1259    }
1260    let mut out = items.to_vec();
1261    // The index of the app menu (macOS), which the Edit menu follows
1262    // with the app's first menu.
1263    let mut first = 0;
1264    if mac {
1265        // Quit alone does not make an app menu: a cross-platform File
1266        // menu ends with it.
1267        const MAC_ONLY: &[MenuRole] = &[R::About, R::Hide, R::HideOthers, R::ShowAll];
1268        let leads =
1269            matches!(out.first(), Some(MenuItem::Submenu { items, .. }) if has(items, MAC_ONLY));
1270        if !leads {
1271            // A menu left empty by the move (a File menu that held
1272            // only Quit) goes.
1273            out = without(&out, APP)
1274                .into_iter()
1275                .filter(|item| !matches!(item, MenuItem::Submenu { items, inline: false, .. } if items.is_empty()))
1276                .collect();
1277            // AppKit titles the first menu with the app's name.
1278            out.insert(
1279                0,
1280                menu(
1281                    "App",
1282                    &[
1283                        Some(R::About),
1284                        None,
1285                        Some(R::Hide),
1286                        Some(R::HideOthers),
1287                        Some(R::ShowAll),
1288                        None,
1289                        Some(R::Quit),
1290                    ],
1291                ),
1292            );
1293        }
1294        first = 1;
1295    } else if !has(&out, &[R::Quit])
1296        && let Some(MenuItem::Submenu { items, .. }) = out
1297            .iter_mut()
1298            .find(|item| matches!(item, MenuItem::Submenu { inline: false, .. }))
1299    {
1300        if !items.is_empty() {
1301            items.push(MenuItem::Separator);
1302        }
1303        items.push(role(R::Quit));
1304    }
1305    if !has(&out, EDIT) {
1306        let at = if out.len() > first {
1307            first + 1
1308        } else {
1309            out.len()
1310        };
1311        // Titled by the platform in the app's language
1312        // ([`MenuLabels::title_menus`]).
1313        let edit = "";
1314        out.insert(
1315            at,
1316            menu(
1317                edit,
1318                &[
1319                    Some(R::Undo),
1320                    Some(R::Redo),
1321                    None,
1322                    Some(R::Cut),
1323                    Some(R::Copy),
1324                    Some(R::Paste),
1325                    Some(R::SelectAll),
1326                ],
1327            ),
1328        );
1329    }
1330    if mac && MenuItem::window_menu(&out).is_none() {
1331        let window = "";
1332        out.push(menu(
1333            window,
1334            &[
1335                Some(R::Minimize),
1336                Some(R::Zoom),
1337                Some(R::ToggleFullScreen),
1338                None,
1339                Some(R::Close),
1340            ],
1341        ));
1342    }
1343    out
1344}
1345
1346impl MenuRole {
1347    /// The role named `name` as TS writes it (`"copy"`, `"selectAll"`,
1348    /// `"toggleFullScreen"`, …).
1349    #[doc(hidden)]
1350    pub fn from_name(name: &str) -> Option<Self> {
1351        Some(match name {
1352            "about" => Self::About,
1353            "hide" => Self::Hide,
1354            "hideOthers" => Self::HideOthers,
1355            "showAll" => Self::ShowAll,
1356            "quit" => Self::Quit,
1357            "undo" => Self::Undo,
1358            "redo" => Self::Redo,
1359            "cut" => Self::Cut,
1360            "copy" => Self::Copy,
1361            "paste" => Self::Paste,
1362            "selectAll" => Self::SelectAll,
1363            "minimize" => Self::Minimize,
1364            "zoom" => Self::Zoom,
1365            "toggleFullScreen" => Self::ToggleFullScreen,
1366            "close" => Self::Close,
1367            _ => return None,
1368        })
1369    }
1370}
1371
1372/// A desktop command, on a window's root node (the root for the main
1373/// window and what is the app's: menus, the tray, global shortcuts).
1374#[derive(Debug, Clone, PartialEq)]
1375pub enum DesktopCommand {
1376    /// Shows the dialog root the command is addressed to in a window of its
1377    /// own, until the node is removed. Sent before the node is inserted; a
1378    /// platform without windows of its own ignores it (the runtime does not
1379    /// send it there).
1380    OpenWindow(Box<OpenWindow>),
1381    /// The window's attributes that changed since the last commit (the
1382    /// fields set; one command per window and commit).
1383    SetAttributes(Box<WindowAttributes>),
1384    /// A request to the window.
1385    Request(WindowRequest),
1386    /// Quits the app, as its `quit` menu role does: the app ends without a
1387    /// per-window close path, also when closing the window would leave it
1388    /// running (a window kept hidden, a tray icon). A view embedded in
1389    /// another app leaves the app's lifecycle to that app.
1390    Quit,
1391    /// Quits the app as [`DesktopCommand::Quit`] does, then starts it again
1392    /// with the same arguments once this process has exited
1393    /// ([`crate::restart`]). A view embedded in another app leaves the
1394    /// app's lifecycle to that app: nothing happens there.
1395    Restart,
1396    /// When the app quits if its last window closes (the mode
1397    /// `Application.setQuitMode` sets; `"platform"` defaults to it on
1398    /// Windows and Linux, not macOS). The core sends
1399    /// [`DesktopCommand::Quit`] on the root when the last window goes and
1400    /// the mode quits there.
1401    SetQuitMode(QuitMode),
1402    /// Whether the user's quit requests quit the app: its Quit item and
1403    /// the platform's quit key (Command-Q, Ctrl+Q). `false` while the app
1404    /// listens to them ([`crate::element::desktop::on_quit_request`]): the
1405    /// platform reports them on the root ([`WindowEvent::QuitRequest`])
1406    /// instead, and the app sends [`DesktopCommand::Quit`] when it is
1407    /// ready. The system ending the app quits either way by default;
1408    /// macOS and Windows can include it with
1409    /// [`DesktopCommand::SetQuitRequestOptions`].
1410    /// Sent when it changes; `true` until the first. On the
1411    /// web, while it is `false`, the user leaving the page is the request.
1412    SetQuitOnRequest(bool),
1413    /// Sets the additional quit request sources (macOS; `system` on
1414    /// Windows and, with a session manager, Linux too). Both default to false. Other platforms ignore this
1415    /// command.
1416    SetQuitRequestOptions(QuitRequestOptions),
1417    /// Cancels a pending quit request on macOS, Windows and Linux, including the
1418    /// system's logout or shutdown. Nothing happens without a pending
1419    /// request.
1420    CancelQuitRequest,
1421    /// The application menu (macOS's menu bar, the window's menu bar on
1422    /// Windows and Linux; not shown there while the title bar is hidden,
1423    /// its shortcuts still work); `None` restores the platform's default.
1424    SetMenu(Option<Arc<[MenuItem]>>),
1425    /// When the menu bar the window draws for the application menu shows.
1426    SetMenuBar(MenuBarMode),
1427    /// Performs a menu role as the application menu's item of that role
1428    /// does (`Menu.perform`): an edit role acts on the focused view, a
1429    /// window role on the focused window. For menus the app draws itself.
1430    PerformMenuRole(MenuRole),
1431    /// The core translated the labels of NSH's menus for the language
1432    /// the app shows. Native backends update their menus at once.
1433    SetMenuLabels(Box<MenuLabels>),
1434    /// Shows a context menu at `at` (root coordinates, points) or at the
1435    /// pointer.
1436    PopupMenu {
1437        /// Its items.
1438        items: Arc<[MenuItem]>,
1439        /// Where its top left corner goes.
1440        at: Option<Point<Points>>,
1441    },
1442    /// Shows the app's icon in the system tray (the notification area on
1443    /// Windows, the menu bar's status items on macOS, a StatusNotifierItem
1444    /// on Linux), or changes it; `None` removes it. One per app: the last
1445    /// window's wins.
1446    SetTray(Option<Tray>),
1447    /// Registers `shortcut` system-wide, whichever app has the keyboard: the
1448    /// root's [`crate::EventKind::Menu`] reports `id` with `registered`
1449    /// (whether the system took it), then `id` alone at each press.
1450    RegisterGlobalShortcut {
1451        /// Reported at each press (not 0).
1452        id: u32,
1453        /// The keystroke.
1454        shortcut: Shortcut,
1455    },
1456    /// Gives back the global shortcut registered as `id`.
1457    UnregisterGlobalShortcut(u32),
1458}
1459
1460impl DesktopCommand {
1461    /// A command about a window that the core keeps a record of or adjusts
1462    /// (opening one, its attributes, a placement to fit).
1463    /// It is addressed to one window: opening it, its attributes or a
1464    /// request.
1465    pub(crate) fn is_window_command(&self) -> bool {
1466        matches!(
1467            self,
1468            DesktopCommand::OpenWindow(_)
1469                | DesktopCommand::SetAttributes(_)
1470                | DesktopCommand::Request(_)
1471        )
1472    }
1473
1474    /// Whether the core carries the command out itself (the windows it
1475    /// keeps records of, the app-wide quit mode) instead of handing it
1476    /// to the platform.
1477    pub(crate) fn is_core_handled(&self) -> bool {
1478        matches!(
1479            self,
1480            DesktopCommand::OpenWindow(_)
1481                | DesktopCommand::SetAttributes(_)
1482                | DesktopCommand::Request(WindowRequest::SetPlacement(_))
1483                | DesktopCommand::SetQuitMode(_)
1484        )
1485    }
1486}
1487
1488/// A run of a tray's title ([`Tray::title`]): text in one color, as GPUI's
1489/// `TextRun`s are.
1490#[derive(Debug, Clone, Default, PartialEq)]
1491#[non_exhaustive]
1492pub struct TrayTitleRun {
1493    /// The text.
1494    pub text: String,
1495    /// Its color; `None`: the panel's text color (on macOS the menu bar's,
1496    /// which follows its appearance).
1497    pub color: Option<Hsla>,
1498}
1499
1500impl TrayTitleRun {
1501    /// A run of `text` in the panel's text color.
1502    pub fn new(text: impl Into<String>) -> Self {
1503        Self {
1504            text: text.into(),
1505            color: None,
1506        }
1507    }
1508
1509    /// The run in `color`.
1510    pub fn color(mut self, color: impl Into<Hsla>) -> Self {
1511        self.color = Some(color.into());
1512        self
1513    }
1514}
1515
1516/// Which side of the tray's icon its title shows on ([`Tray::title_placement`]).
1517#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1518pub enum TrayTitlePlacement {
1519    /// Right of the icon, as menu bar apps usually show it.
1520    #[default]
1521    Right,
1522    /// Left of the icon. macOS only: Linux's panels draw the title right of
1523    /// the icon.
1524    Left,
1525}
1526
1527/// The app's icon in the system tray ([`DesktopCommand::SetTray`]).
1528#[derive(Debug, Clone, Default, PartialEq)]
1529#[non_exhaustive]
1530pub struct Tray {
1531    /// The icon, the app's own image (an SVG is a template, drawn in the
1532    /// panel's text color where the platform has such icons: macOS);
1533    /// `None`: the app's icon where the platform has one.
1534    pub icon: Option<ImageSource>,
1535    /// Shown when the pointer rests on it; `""` for the app's name.
1536    pub tooltip: String,
1537    /// Text beside the icon, in runs each of its own color: what the app
1538    /// keeps in sight (a price, a count). macOS's menu bar shows it in its
1539    /// colors; Linux's panels that show AppIndicator labels (GNOME's
1540    /// AppIndicator extension, Unity, MATE, Budgie) show its text right of
1541    /// the icon; Windows' notification area shows the icon alone. Empty: the
1542    /// icon alone.
1543    pub title: Vec<TrayTitleRun>,
1544    /// Which side of the icon the title shows on.
1545    pub title_placement: TrayTitlePlacement,
1546    /// Its menu: opened by a secondary click (a primary one too when
1547    /// [`Self::click`] is 0); empty for none.
1548    pub menu: Arc<[MenuItem]>,
1549    /// Reported as [`crate::EventKind::Menu`] when the icon is clicked
1550    /// (primary button), with `bounds`: the icon's frame in screen points
1551    /// (as [`WindowState::bounds`]), left out where the platform does not
1552    /// know it; 0: the click opens the menu.
1553    pub click: u32,
1554}
1555
1556pub(crate) fn title_bar_height(height: Option<Points>) -> Option<Points> {
1557    height
1558        .filter(|h| h.is_finite() && h.0 > 0.0)
1559        .map(|h| Points(h.0.min(200.0)))
1560}
1561
1562#[cfg(test)]
1563mod tests {
1564    /// The bar's menus as (title, roles), a separator as `None`.
1565    fn outline(items: &[super::MenuItem]) -> Vec<(String, Vec<Option<super::MenuRole>>)> {
1566        use super::MenuItem;
1567        items
1568            .iter()
1569            .filter_map(|item| match item {
1570                MenuItem::Submenu { label, items, .. } => Some((
1571                    label.clone(),
1572                    items
1573                        .iter()
1574                        .map(|i| match i {
1575                            MenuItem::Action(a) => a.role,
1576                            _ => None,
1577                        })
1578                        .collect(),
1579                )),
1580                _ => None,
1581            })
1582            .collect()
1583    }
1584
1585    fn titled(mut bar: Vec<super::MenuItem>, labels: &super::MenuLabels) -> Vec<super::MenuItem> {
1586        labels.title_menus(&mut bar);
1587        bar
1588    }
1589
1590    fn file_menu() -> Vec<super::MenuItem> {
1591        use super::{MenuAction, MenuItem, MenuRole, When};
1592        let action = |label: &str, role| {
1593            MenuItem::Action(MenuAction {
1594                id: 1,
1595                label: label.into(),
1596                shortcut: None,
1597                enabled: true,
1598                checked: None,
1599                role,
1600                when: When::Always,
1601                icon: None,
1602                symbol: None,
1603                destructive: false,
1604            })
1605        };
1606        vec![MenuItem::Submenu {
1607            label: "File".into(),
1608            enabled: true,
1609            items: vec![
1610                action("New", None),
1611                MenuItem::Separator,
1612                action("Exit", Some(MenuRole::Quit)),
1613            ],
1614            icon: None,
1615            symbol: None,
1616            inline: false,
1617        }]
1618    }
1619
1620    #[test]
1621    fn macos_completes_the_menu_with_the_app_edit_and_window_menus() {
1622        use super::{MenuLabels, MenuRole as R};
1623        let out = outline(&titled(
1624            super::menu_bar(&file_menu(), true),
1625            &MenuLabels::default(),
1626        ));
1627        let titles: Vec<&str> = out.iter().map(|(t, _)| t.as_str()).collect();
1628        assert_eq!(titles, ["App", "File", "Edit", "Window"]);
1629        assert!(out[0].1.contains(&Some(R::Quit)));
1630        // The cross-platform Exit moved to the app menu, with its separator.
1631        assert_eq!(out[1].1, [None]);
1632        assert!(out[2].1.contains(&Some(R::Copy)));
1633        assert!(out[3].1.contains(&Some(R::Minimize)));
1634        // Complete already: nothing more.
1635        let done = titled(super::menu_bar(&file_menu(), true), &MenuLabels::default());
1636        assert_eq!(super::menu_bar(&done, true), done);
1637    }
1638
1639    #[test]
1640    fn windows_and_linux_add_the_edit_menu_and_exit() {
1641        use super::{MenuItem, MenuLabels, MenuRole as R};
1642        let labels = MenuLabels {
1643            edit_menu: Some("编辑".into()),
1644            ..MenuLabels::default()
1645        };
1646        let out = outline(&titled(super::menu_bar(&file_menu(), false), &labels));
1647        let titles: Vec<&str> = out.iter().map(|(t, _)| t.as_str()).collect();
1648        assert_eq!(titles, ["File", "编辑"]);
1649        // The app's own Exit stays, once.
1650        assert_eq!(out[0].1.iter().filter(|r| **r == Some(R::Quit)).count(), 1);
1651        let mut bare = file_menu();
1652        if let MenuItem::Submenu { items, .. } = &mut bare[0] {
1653            items.truncate(1);
1654        }
1655        let out = outline(&titled(super::menu_bar(&bare, false), &labels));
1656        assert_eq!(out[0].1.last(), Some(&Some(R::Quit)));
1657        assert!(super::menu_bar(&[], false).is_empty());
1658    }
1659
1660    #[test]
1661    fn the_application_block_reads_the_quit_mode() {
1662        let read = |json: &str| {
1663            ApplicationOptions::from_json(&serde_json::from_str::<crate::JsonValue>(json).unwrap())
1664        };
1665        assert_eq!(read(r#"{}"#).unwrap().__explicit_quit_mode(), None);
1666        assert_eq!(
1667            read(r#"{"quitMode":"platform"}"#).unwrap().quit_mode,
1668            QuitMode::Platform
1669        );
1670        assert_eq!(
1671            read(r#"{"quitMode":"lastWindowClosed"}"#)
1672                .unwrap()
1673                .quit_mode,
1674            QuitMode::LastWindowClosed
1675        );
1676        assert_eq!(
1677            read(r#"{"quitMode":"explicit"}"#).unwrap().quit_mode,
1678            QuitMode::Explicit
1679        );
1680        assert!(read(r#"{"quitMode":"sometimes"}"#).is_err());
1681        assert!(read(r#"{"quitMode":true}"#).is_err());
1682        assert!(read(r#"{"quitOnLastWindowClosed":"platform"}"#).is_err());
1683        assert!(read("[]").is_err());
1684
1685        use crate::platform::Os;
1686        assert!(QuitMode::Platform.quits(Os::Windows));
1687        assert!(QuitMode::Platform.quits(Os::Linux));
1688        assert!(!QuitMode::Platform.quits(Os::MacOs));
1689        assert!(QuitMode::LastWindowClosed.quits(Os::MacOs));
1690        assert!(!QuitMode::Explicit.quits(Os::Windows));
1691    }
1692
1693    #[test]
1694    fn built_in_menu_labels_follow_locale_fallbacks_and_platform_titles() {
1695        for (locale, copy, quit) in [
1696            ("en", "Copy", "Quit"),
1697            ("ja-JP", "コピー", "終了"),
1698            ("zh-CN", "复制", "退出"),
1699            ("zh-Hant-TW", "複製", "結束"),
1700            ("zh-TW", "複製", "結束"),
1701            ("zh-MO", "複製", "結束"),
1702            ("fr-FR", "Copy", "Quit"),
1703        ] {
1704            let locale = crate::platform::Locale::parse(locale).unwrap();
1705            let labels = MenuLabels::for_locale(locale, false);
1706            assert_eq!(labels.label(MenuRole::Copy), copy);
1707            assert_eq!(labels.label(MenuRole::Quit), quit);
1708            for role in MenuRole::ALL {
1709                assert!(!labels.label(*role).contains("%{app}"));
1710            }
1711        }
1712        let japanese = crate::platform::Locale::parse("ja").unwrap();
1713        let labels = MenuLabels::for_locale(japanese, true);
1714        assert_eq!(labels.label(MenuRole::Quit), "%{app}を終了");
1715        assert_eq!(labels.delete.as_deref(), Some("削除"));
1716        assert_eq!(
1717            MenuLabels::for_locale(japanese, false).label(MenuRole::Paste),
1718            "貼り付け"
1719        );
1720    }
1721
1722    use super::*;
1723    use crate::geometry::px;
1724
1725    #[test]
1726    fn window_menu_is_the_submenu_with_a_window_role() {
1727        let action = |role: Option<MenuRole>| {
1728            MenuItem::Action(MenuAction {
1729                id: 0,
1730                label: String::new(),
1731                shortcut: None,
1732                enabled: true,
1733                checked: None,
1734                role,
1735                when: When::default(),
1736                icon: None,
1737                symbol: None,
1738                destructive: false,
1739            })
1740        };
1741        let sub = |items: Vec<MenuItem>| MenuItem::Submenu {
1742            label: String::new(),
1743            enabled: true,
1744            items,
1745            icon: None,
1746            symbol: None,
1747            inline: false,
1748        };
1749        let bar = vec![
1750            sub(vec![action(Some(MenuRole::Quit))]),
1751            sub(vec![action(Some(MenuRole::Copy))]),
1752            sub(vec![action(None), sub(vec![action(Some(MenuRole::Zoom))])]),
1753            sub(vec![action(Some(MenuRole::Minimize))]),
1754        ];
1755        assert_eq!(MenuItem::window_menu(&bar), Some(2));
1756        assert_eq!(MenuItem::window_menu(&bar[..2]), None);
1757        // A top-level role item is not a submenu of the bar.
1758        assert_eq!(
1759            MenuItem::window_menu(&[action(Some(MenuRole::Close))]),
1760            None
1761        );
1762        // Full screen under an earlier View menu: Window is still the one with
1763        // Minimize or Close.
1764        let view_then_window = vec![
1765            sub(vec![action(Some(MenuRole::Copy))]),
1766            sub(vec![action(None), action(Some(MenuRole::ToggleFullScreen))]),
1767            sub(vec![
1768                action(Some(MenuRole::Minimize)),
1769                action(Some(MenuRole::Close)),
1770            ]),
1771        ];
1772        assert_eq!(MenuItem::window_menu(&view_then_window), Some(2));
1773        // With no other window role, the menu holding full screen.
1774        assert_eq!(MenuItem::window_menu(&view_then_window[..2]), Some(1));
1775    }
1776
1777    #[test]
1778    fn custom_title_bar_height_is_finite_positive_and_bounded() {
1779        for height in [
1780            None,
1781            Some(0.0),
1782            Some(-1.0),
1783            Some(f32::NAN),
1784            Some(f32::INFINITY),
1785        ] {
1786            assert_eq!(title_bar_height(height.map(Points)), None);
1787        }
1788        assert_eq!(title_bar_height(Some(px(42.0))), Some(px(42.0)));
1789        assert_eq!(title_bar_height(Some(px(300.0))), Some(px(200.0)));
1790    }
1791
1792    #[test]
1793    fn mac_labels_use_symbols() {
1794        let copy = MenuRole::Copy.shortcut(true).unwrap();
1795        assert_eq!(copy.label_for(Os::MacOs), "⌘C");
1796        assert_eq!(
1797            MenuRole::Redo.shortcut(true).unwrap().label_for(Os::MacOs),
1798            "⇧⌘Z"
1799        );
1800        assert_eq!(
1801            MenuRole::ToggleFullScreen
1802                .shortcut(true)
1803                .unwrap()
1804                .label_for(Os::MacOs),
1805            "⌃⌘F"
1806        );
1807        assert_eq!(
1808            MenuRole::Copy
1809                .shortcut(false)
1810                .unwrap()
1811                .label_for(Os::Windows),
1812            "Ctrl+C"
1813        );
1814        // Off macOS it is `label()` as it was, `Win+` and all.
1815        let win = Shortcut {
1816            meta: true,
1817            ..Shortcut::key(Key::Char('e'))
1818        };
1819        assert_eq!(win.label_for(Os::Linux), win.label());
1820        assert_eq!(win.label_for(Os::Windows), win.label());
1821        assert_eq!(win.label_for(Os::Linux), "Win+E");
1822        let copy = MenuRole::Copy.shortcut(false).unwrap();
1823        assert_eq!(copy.label_for(Os::Linux), copy.label());
1824    }
1825
1826    #[test]
1827    fn shortcuts_parse() {
1828        let s = Shortcut::parse("mod+shift+n", false).unwrap();
1829        assert_eq!(
1830            s,
1831            Shortcut {
1832                ctrl: true,
1833                shift: true,
1834                ..Shortcut::key(Key::Char('n'))
1835            }
1836        );
1837        // Labels stay the platform's style.
1838        assert_eq!(s.label(), "Ctrl+Shift+N");
1839        let mac = Shortcut::parse("cmdorctrl+,", true).unwrap();
1840        assert!(mac.meta && !mac.ctrl);
1841        assert_eq!(mac.key, Key::Char(','));
1842        assert_eq!(
1843            Shortcut::parse("meta+k", false),
1844            Shortcut::parse("cmd+k", false)
1845        );
1846        // Case does not matter, and a capital letter is not Shift.
1847        assert_eq!(Shortcut::parse("Mod+Shift+N", false), Ok(s));
1848        assert_eq!(
1849            Shortcut::parse("CMD+K", false),
1850            Shortcut::parse("cmd+k", false)
1851        );
1852        assert_eq!(
1853            Shortcut::parse("mod+N", false),
1854            Shortcut::parse("mod+n", false)
1855        );
1856        assert_eq!(
1857            Shortcut::parse("Escape", false),
1858            Shortcut::parse("escape", false)
1859        );
1860        assert_eq!(Shortcut::parse("F5", false), Shortcut::parse("f5", false));
1861        assert_eq!(
1862            Shortcut::parse("Ctrl+Plus", false),
1863            Shortcut::parse("ctrl+=", false)
1864        );
1865        assert_eq!(Key::parse("PageUp"), Some(Key::PageUp));
1866        // The plus key is the `=` key.
1867        assert_eq!(
1868            Shortcut::parse("ctrl+plus", false),
1869            Shortcut::parse("ctrl+=", false)
1870        );
1871        assert_eq!(
1872            Shortcut::parse("ctrl+minus", false),
1873            Shortcut::parse("ctrl+-", false)
1874        );
1875        assert_eq!(
1876            Shortcut::parse("arrowup", false),
1877            Shortcut::parse("up", false)
1878        );
1879        assert_eq!(Shortcut::parse("alt+f4", false).unwrap().key, Key::F(4));
1880        assert_eq!(
1881            Shortcut::parse("f11", false).unwrap(),
1882            Shortcut::key(Key::F(11))
1883        );
1884        let win = Shortcut::parse("win+option+pagedown", true).unwrap();
1885        assert!(win.meta && win.alt && win.key == Key::PageDown);
1886    }
1887
1888    #[test]
1889    fn shortcuts_explain_errors() {
1890        // The same messages as `nsh/keymap`'s.
1891        let err = |t| Shortcut::parse(t, false).unwrap_err().0;
1892        assert_eq!(err(""), "invalid keystroke \"\": empty");
1893        assert!(err("mod+k mod+s").contains("one keystroke per binding"));
1894        assert!(err("mod+").contains("no key after the modifiers"));
1895        assert!(err("hyper+k").contains("unknown modifier \"hyper\""));
1896        assert!(err("ctrl+ctrl+k").contains("\"ctrl\" twice"));
1897        assert!(err("mod-k").contains("join modifiers and the key with \"+\": \"mod+k\""));
1898        // Hints suggest lowercase, whatever case the text was written in.
1899        assert!(err("Mod-N").contains("join modifiers and the key with \"+\": \"mod+n\""));
1900        assert!(err("CTRL++").contains("\"ctrl+plus\""));
1901        assert!(err("mod+?").contains("write \"shift+/\""));
1902        assert!(err("ctrl++").contains("write the plus key as \"plus\": \"ctrl+plus\""));
1903        assert!(err("ctrl+f25").contains("unknown key"));
1904    }
1905
1906    #[test]
1907    fn shortcuts_find_items() {
1908        let copy = Shortcut::parse("ctrl+c", false).unwrap();
1909        let new = Shortcut::parse("ctrl+n", false).unwrap();
1910        let action = |id, shortcut, role| {
1911            MenuItem::Action(MenuAction {
1912                id,
1913                label: String::new(),
1914                shortcut: Some(shortcut),
1915                enabled: true,
1916                checked: None,
1917                role,
1918                when: When::Always,
1919                icon: None,
1920                symbol: None,
1921                destructive: false,
1922            })
1923        };
1924        let menu = vec![MenuItem::Submenu {
1925            label: "File".into(),
1926            enabled: true,
1927            items: vec![
1928                action(1, new, None),
1929                MenuItem::Separator,
1930                action(0, copy, Some(MenuRole::Copy)),
1931            ],
1932            icon: None,
1933            symbol: None,
1934            inline: false,
1935        }];
1936        assert_eq!(MenuItem::find_shortcut(&menu, &new).map(|a| a.id), Some(1));
1937        // Text fields keep their own shortcuts.
1938        assert!(MenuItem::find_shortcut(&menu, &copy).is_none());
1939    }
1940
1941    #[test]
1942    fn items_leave_a_focused_field_the_keys_it_uses_when_asked() {
1943        let item = |shortcut: &str, when| MenuAction {
1944            id: 1,
1945            label: String::new(),
1946            shortcut: Some(Shortcut::parse(shortcut, false).unwrap()),
1947            enabled: true,
1948            checked: None,
1949            role: None,
1950            when,
1951            icon: None,
1952            symbol: None,
1953            destructive: false,
1954        };
1955        let fires = |shortcut, when| item(shortcut, when).fires_while_editing();
1956        assert!(fires("ctrl+z", When::Always));
1957        assert!(!fires("ctrl+z", When::Auto));
1958        assert!(!fires("ctrl+y", When::Auto));
1959        assert!(fires("ctrl+y", When::Always));
1960        assert!(!fires("delete", When::Auto));
1961        assert!(!fires("ctrl+enter", When::Auto));
1962        assert!(!fires("space", When::Auto));
1963        assert!(fires("ctrl+shift+n", When::Auto));
1964        assert!(fires("f5", When::Auto));
1965        assert!(!fires("ctrl+shift+n", When::NotEditing));
1966    }
1967
1968    #[test]
1969    fn inline_submenus_expand_between_separators() {
1970        let action = |label: &str| {
1971            MenuItem::Action(MenuAction {
1972                id: 0,
1973                label: label.into(),
1974                shortcut: None,
1975                enabled: true,
1976                checked: None,
1977                role: None,
1978                when: When::Always,
1979                icon: None,
1980                symbol: None,
1981                destructive: false,
1982            })
1983        };
1984        let items = [
1985            action("New"),
1986            MenuItem::Submenu {
1987                label: "Danger".into(),
1988                enabled: true,
1989                items: vec![action("Delete"), action("Wipe")],
1990                icon: None,
1991                symbol: None,
1992                inline: true,
1993            },
1994            action("Quit"),
1995            MenuItem::Submenu {
1996                label: "More".into(),
1997                enabled: true,
1998                items: vec![
1999                    action("Share"),
2000                    MenuItem::Submenu {
2001                        label: "Nested".into(),
2002                        enabled: true,
2003                        items: vec![action("Deep")],
2004                        icon: None,
2005                        symbol: None,
2006                        inline: true,
2007                    },
2008                ],
2009                icon: None,
2010                symbol: None,
2011                inline: false,
2012            },
2013        ];
2014        let expanded = MenuItem::with_inline_expanded(&items);
2015        assert_eq!(
2016            expanded
2017                .iter()
2018                .map(|i| match i {
2019                    MenuItem::Separator => "—".into(),
2020                    MenuItem::Action(a) => a.label.clone(),
2021                    MenuItem::Submenu {
2022                        label,
2023                        items,
2024                        inline,
2025                        ..
2026                    } => {
2027                        assert!(!inline, "nested non-inline kept");
2028                        format!(
2029                            "{label}[{}]",
2030                            items
2031                                .iter()
2032                                .map(|c| match c {
2033                                    MenuItem::Separator => "—",
2034                                    MenuItem::Action(a) => a.label.as_str(),
2035                                    MenuItem::Submenu { .. } => "sub",
2036                                })
2037                                .collect::<Vec<_>>()
2038                                .join(",")
2039                        )
2040                    }
2041                })
2042                .collect::<Vec<String>>(),
2043            [
2044                "New",
2045                "—",
2046                "Delete",
2047                "Wipe",
2048                "—",
2049                "Quit",
2050                "More[Share,—,Deep]",
2051            ]
2052            .map(str::to_owned)
2053        );
2054        // Separators only between groups: none leading or trailing.
2055        assert!(!matches!(expanded.first(), Some(MenuItem::Separator)));
2056        assert!(!matches!(expanded.last(), Some(MenuItem::Separator)));
2057        // A lone inline group: no separators around it.
2058        let alone = MenuItem::with_inline_expanded(&[MenuItem::Submenu {
2059            label: "Only".into(),
2060            enabled: true,
2061            items: vec![action("A"), action("B")],
2062            icon: None,
2063            symbol: None,
2064            inline: true,
2065        }]);
2066        assert_eq!(
2067            alone
2068                .iter()
2069                .map(|i| match i {
2070                    MenuItem::Action(a) => a.label.as_str(),
2071                    _ => "?",
2072                })
2073                .collect::<Vec<_>>(),
2074            ["A", "B"]
2075        );
2076        // An explicit separator after an inline section must not double.
2077        let after_inline = MenuItem::with_inline_expanded(&[
2078            action("A"),
2079            MenuItem::Submenu {
2080                label: "Group".into(),
2081                enabled: true,
2082                items: vec![action("B")],
2083                icon: None,
2084                symbol: None,
2085                inline: true,
2086            },
2087            MenuItem::Separator,
2088            action("C"),
2089        ]);
2090        assert_eq!(
2091            after_inline
2092                .iter()
2093                .map(|i| match i {
2094                    MenuItem::Separator => "—",
2095                    MenuItem::Action(a) => a.label.as_str(),
2096                    _ => "?",
2097                })
2098                .collect::<Vec<_>>(),
2099            ["A", "—", "B", "—", "C"]
2100        );
2101    }
2102
2103    #[test]
2104    fn a_disabled_inline_section_disables_its_items() {
2105        let action = |label: &str| {
2106            MenuItem::Action(MenuAction {
2107                id: 1,
2108                label: label.into(),
2109                shortcut: None,
2110                enabled: true,
2111                checked: None,
2112                role: None,
2113                when: Default::default(),
2114                icon: None,
2115                symbol: None,
2116                destructive: false,
2117            })
2118        };
2119        let section = |enabled: bool| MenuItem::Submenu {
2120            label: "Group".into(),
2121            enabled,
2122            items: vec![
2123                action("B"),
2124                MenuItem::Submenu {
2125                    label: "More".into(),
2126                    enabled: true,
2127                    items: vec![action("C")],
2128                    icon: None,
2129                    symbol: None,
2130                    inline: false,
2131                },
2132            ],
2133            icon: None,
2134            symbol: None,
2135            inline: true,
2136        };
2137        let enabled = |items: &[MenuItem]| {
2138            items
2139                .iter()
2140                .map(|i| match i {
2141                    MenuItem::Action(a) => (a.label.clone(), a.enabled),
2142                    MenuItem::Submenu { label, enabled, .. } => (label.clone(), *enabled),
2143                    MenuItem::Separator => ("—".into(), true),
2144                })
2145                .collect::<Vec<_>>()
2146        };
2147        let off = MenuItem::with_inline_expanded(&[action("A"), section(false)]);
2148        assert_eq!(
2149            enabled(&off),
2150            [
2151                ("A".into(), true),
2152                ("—".into(), true),
2153                ("B".into(), false),
2154                ("More".into(), false)
2155            ]
2156        );
2157        let on = MenuItem::with_inline_expanded(&[action("A"), section(true)]);
2158        assert_eq!(
2159            enabled(&on),
2160            [
2161                ("A".into(), true),
2162                ("—".into(), true),
2163                ("B".into(), true),
2164                ("More".into(), true)
2165            ]
2166        );
2167    }
2168}