1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44#[non_exhaustive]
45pub enum QuitMode {
46 #[default]
48 Platform,
49 LastWindowClosed,
51 Explicit,
53}
54
55impl QuitMode {
56 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81#[non_exhaustive]
82pub struct ApplicationOptions {
83 pub quit_mode: QuitMode,
85 quit_mode_set: bool,
88}
89
90impl ApplicationOptions {
91 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 #[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, JsObject)]
123#[non_exhaustive]
124pub struct QuitRequestOptions {
125 #[prop(default)]
128 pub system: bool,
129 #[prop(default)]
133 pub main_window_close: bool,
134}
135
136impl QuitRequestOptions {
137 pub fn system(mut self, system: bool) -> Self {
139 self.system = system;
140 self
141 }
142
143 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
153pub enum TitleBarStyle {
154 #[default]
156 Default,
157 Hidden,
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
168pub enum MenuBarMode {
169 #[default]
171 Shown,
172 #[prop(rename = "autoHide")]
176 AutoHide,
177}
178
179#[derive(Debug, Clone, Copy, Default, PartialEq)]
186pub struct WindowFrame {
187 pub x: Option<Points>,
189 pub y: Option<Points>,
193 pub width: Option<Points>,
196 pub height: Option<Points>,
199 pub animated: Option<bool>,
201}
202
203impl 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
281pub enum WindowLevel {
282 #[default]
284 Normal,
285 Floating,
287 #[prop(rename = "aboveDock")]
289 AboveDock,
290 #[prop(rename = "desktopIcon")]
293 DesktopIcon,
294}
295
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PropEnum)]
298pub enum WindowFrameStyle {
299 #[default]
301 Default,
302 None,
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
308pub enum Key {
309 Char(char),
311 Enter,
313 Escape,
315 Tab,
317 Backspace,
319 Delete,
321 Insert,
323 Space,
325 Up,
327 Down,
329 Left,
331 Right,
333 Home,
335 End,
337 PageUp,
339 PageDown,
341 F(u8),
343}
344
345impl Key {
346 pub fn parse(name: &str) -> Option<Key> {
350 parse_key(name, &name.to_ascii_lowercase()).ok()
351 }
352
353 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
379pub struct Shortcut {
380 pub key: Key,
382 pub ctrl: bool,
384 pub alt: bool,
386 pub shift: bool,
388 pub meta: bool,
390}
391
392impl Shortcut {
393 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 pub fn parse(text: &str, mod_is_meta: bool) -> Result<Shortcut, ShortcutError> {
414 let lower = text.to_ascii_lowercase();
417 let (mods, key) = split(text, &lower)?;
418 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 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 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 pub fn edits_text(&self) -> bool {
461 self.keystroke().edits_text()
462 }
463
464 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#[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
512const 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
537const 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 ("plus", Key::Char('=')),
563 ("minus", Key::Char('-')),
564];
565
566fn 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
599fn 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PropEnum)]
667pub enum MenuRole {
668 About,
670 Hide,
672 HideOthers,
674 ShowAll,
676 Quit,
678 Undo,
680 Redo,
682 Cut,
684 Copy,
686 Paste,
688 SelectAll,
690 Minimize,
692 Zoom,
694 ToggleFullScreen,
696 Close,
698}
699
700impl MenuRole {
701 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 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 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 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#[derive(Debug, Clone, Default, PartialEq)]
802#[non_exhaustive]
803pub struct MenuLabels {
804 pub roles: std::collections::HashMap<MenuRole, String>,
806 pub edit_menu: Option<String>,
808 pub window_menu: Option<String>,
810 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 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 #[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 #[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 pub fn role(&self, role: MenuRole) -> Option<&str> {
890 self.roles.get(&role).map(String::as_str)
891 }
892
893 pub fn label(&self, role: MenuRole) -> &str {
896 self.role(role).unwrap_or(role.label())
897 }
898}
899
900#[derive(Debug, Clone, PartialEq)]
902pub struct MenuAction {
903 pub id: u32,
906 pub label: String,
908 pub shortcut: Option<Shortcut>,
910 pub enabled: bool,
912 pub checked: Option<bool>,
914 pub role: Option<MenuRole>,
916 pub when: When,
919 pub icon: Option<ImageSource>,
921 pub symbol: Option<String>,
925 pub destructive: bool,
927}
928
929impl MenuAction {
930 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#[derive(Debug, Clone, PartialEq)]
944pub enum MenuItem {
945 Separator,
947 Action(MenuAction),
949 Submenu {
953 label: String,
955 enabled: bool,
957 items: Vec<MenuItem>,
959 icon: Option<ImageSource>,
962 symbol: Option<String>,
965 inline: bool,
969 },
970}
971
972impl MenuItem {
973 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 #[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 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 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 #[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 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 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 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#[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 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 let mut first = 0;
1264 if mac {
1265 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 out = without(&out, APP)
1274 .into_iter()
1275 .filter(|item| !matches!(item, MenuItem::Submenu { items, inline: false, .. } if items.is_empty()))
1276 .collect();
1277 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 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 #[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#[derive(Debug, Clone, PartialEq)]
1375pub enum DesktopCommand {
1376 OpenWindow(Box<OpenWindow>),
1381 SetAttributes(Box<WindowAttributes>),
1384 Request(WindowRequest),
1386 Quit,
1391 Restart,
1396 SetQuitMode(QuitMode),
1402 SetQuitOnRequest(bool),
1413 SetQuitRequestOptions(QuitRequestOptions),
1417 CancelQuitRequest,
1421 SetMenu(Option<Arc<[MenuItem]>>),
1425 SetMenuBar(MenuBarMode),
1427 PerformMenuRole(MenuRole),
1431 SetMenuLabels(Box<MenuLabels>),
1434 PopupMenu {
1437 items: Arc<[MenuItem]>,
1439 at: Option<Point<Points>>,
1441 },
1442 SetTray(Option<Tray>),
1447 RegisterGlobalShortcut {
1451 id: u32,
1453 shortcut: Shortcut,
1455 },
1456 UnregisterGlobalShortcut(u32),
1458}
1459
1460impl DesktopCommand {
1461 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 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#[derive(Debug, Clone, Default, PartialEq)]
1491#[non_exhaustive]
1492pub struct TrayTitleRun {
1493 pub text: String,
1495 pub color: Option<Hsla>,
1498}
1499
1500impl TrayTitleRun {
1501 pub fn new(text: impl Into<String>) -> Self {
1503 Self {
1504 text: text.into(),
1505 color: None,
1506 }
1507 }
1508
1509 pub fn color(mut self, color: impl Into<Hsla>) -> Self {
1511 self.color = Some(color.into());
1512 self
1513 }
1514}
1515
1516#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PropEnum)]
1518pub enum TrayTitlePlacement {
1519 #[default]
1521 Right,
1522 Left,
1525}
1526
1527#[derive(Debug, Clone, Default, PartialEq)]
1529#[non_exhaustive]
1530pub struct Tray {
1531 pub icon: Option<ImageSource>,
1535 pub tooltip: String,
1537 pub title: Vec<TrayTitleRun>,
1544 pub title_placement: TrayTitlePlacement,
1546 pub menu: Arc<[MenuItem]>,
1549 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 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 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 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 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 assert_eq!(
1759 MenuItem::window_menu(&[action(Some(MenuRole::Close))]),
1760 None
1761 );
1762 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 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 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 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 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 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 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 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 assert!(MenuItem::find_shortcut(&menu, ©).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 assert!(!matches!(expanded.first(), Some(MenuItem::Separator)));
2056 assert!(!matches!(expanded.last(), Some(MenuItem::Separator)));
2057 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 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}