Skip to main content
← rust.krizaka.comkrizaka.com

krizaka_rust/
menu.rs

1//! The native menu bar, described by the page (krizaka-ui ADR-002: « desktop is the web in a window »).
2//!
3//! The page owns the words (its messages, in the person's language) and the shortcuts (the same map `useShortcuts`
4//! answers, turned into accelerators with `acceleratorOf` of `@krizaka/ui`). It sends a [`MenuSpec`]; the kit checks it
5//! here, then builds the macOS menu: the app menu (about, hide, quit), the Edit menu (without it ⌘C and ⌘V do nothing
6//! in a text field), the product's menus, the Window menu. A click on a product item is sent back to the page by its id.
7
8use serde::{Deserialize, Serialize};
9use std::collections::HashSet;
10
11// @fixed: a menu bar a person can read, not a setting
12pub const MAX_MENUS: usize = 6;
13// @fixed: a menu a person can read, not a setting
14pub const MAX_ITEMS: usize = 24;
15// @fixed: the width of a menu label, not a setting
16pub const MAX_LABEL: usize = 60;
17
18/// The labels of the menus macOS expects, in the page's language.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "camelCase")]
21pub struct StandardLabels {
22    pub about: String,
23    pub hide: String,
24    pub hide_others: String,
25    pub show_all: String,
26    pub quit: String,
27    pub edit: String,
28    pub undo: String,
29    pub redo: String,
30    pub cut: String,
31    pub copy: String,
32    pub paste: String,
33    pub select_all: String,
34    pub window: String,
35    pub minimize: String,
36    pub zoom: String,
37    pub close: String,
38}
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41#[serde(rename_all = "camelCase")]
42pub struct MenuItemSpec {
43    /// Sent back to the page when the item is chosen: lowercase letters, digits, `.`, `-` (`library.add-folder`).
44    pub id: String,
45    pub label: String,
46    /// A Tauri accelerator (`CmdOrCtrl+K`), from `acceleratorOf` of `@krizaka/ui`.
47    #[serde(default)]
48    pub accelerator: Option<String>,
49    #[serde(default = "enabled")]
50    pub enabled: bool,
51    /// A separator before this item.
52    #[serde(default)]
53    pub separated: bool,
54}
55
56fn enabled() -> bool {
57    true
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase")]
62pub struct MenuSpec {
63    pub labels: StandardLabels,
64    /// The product's own menus, between Edit and Window (File, View, Go…).
65    pub menus: Vec<MenuGroupSpec>,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(rename_all = "camelCase")]
70pub struct MenuGroupSpec {
71    pub title: String,
72    pub items: Vec<MenuItemSpec>,
73}
74
75/// The shortcuts macOS gives to the standard menus (quit, hide, minimise, close, the Edit menu): never a product's.
76pub const RESERVED: &[&str] = &[
77    "CmdOrCtrl+Q",
78    "CmdOrCtrl+H",
79    "Alt+CmdOrCtrl+H",
80    "CmdOrCtrl+M",
81    "CmdOrCtrl+W",
82    "CmdOrCtrl+Z",
83    "Shift+CmdOrCtrl+Z",
84    "CmdOrCtrl+X",
85    "CmdOrCtrl+C",
86    "CmdOrCtrl+V",
87    "CmdOrCtrl+A",
88];
89
90const MODIFIERS: &[&str] = &["CmdOrCtrl", "Cmd", "Ctrl", "Alt", "Shift", "Super"];
91const NAMED_KEYS: &[&str] = &[
92    "Escape",
93    "Enter",
94    "Space",
95    "Up",
96    "Down",
97    "Left",
98    "Right",
99    "Delete",
100    "Backspace",
101    "Tab",
102    "Plus",
103];
104
105/// What the page sent that the menu refuses. Standard labels are named by their field; anything else the page wrote
106/// (an id, a title, a shortcut) is never repeated.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum MenuError {
109    /// A standard label (the field's name) is empty, too long or holds a control character.
110    BadStandardLabel(&'static str),
111    BadMenuTitle,
112    BadItemLabel,
113    TooManyMenus,
114    /// A menu has no item, or more than [`MAX_ITEMS`].
115    BadItemCount,
116    BadId,
117    DuplicateId,
118    EmptyAccelerator,
119    BadModifier,
120    BadKey,
121    /// The shortcut belongs to a standard menu.
122    ReservedAccelerator,
123    DuplicateAccelerator,
124}
125
126impl MenuError {
127    /// The stable code the page reads.
128    pub fn code(self) -> &'static str {
129        match self {
130            MenuError::BadStandardLabel(_) => "menu_bad_standard_label",
131            MenuError::BadMenuTitle => "menu_bad_menu_title",
132            MenuError::BadItemLabel => "menu_bad_item_label",
133            MenuError::TooManyMenus => "menu_too_many_menus",
134            MenuError::BadItemCount => "menu_bad_item_count",
135            MenuError::BadId => "menu_bad_id",
136            MenuError::DuplicateId => "menu_duplicate_id",
137            MenuError::EmptyAccelerator => "menu_empty_accelerator",
138            MenuError::BadModifier => "menu_bad_modifier",
139            MenuError::BadKey => "menu_bad_key",
140            MenuError::ReservedAccelerator => "menu_reserved_accelerator",
141            MenuError::DuplicateAccelerator => "menu_duplicate_accelerator",
142        }
143    }
144}
145
146impl std::fmt::Display for MenuError {
147    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148        match self {
149            MenuError::BadStandardLabel(what) => {
150                write!(f, "{what}: a label of 1 to {MAX_LABEL} characters")
151            }
152            MenuError::BadMenuTitle => write!(f, "a menu title of 1 to {MAX_LABEL} characters"),
153            MenuError::BadItemLabel => write!(f, "an item label of 1 to {MAX_LABEL} characters"),
154            MenuError::TooManyMenus => write!(f, "at most {MAX_MENUS} menus"),
155            MenuError::BadItemCount => write!(f, "1 to {MAX_ITEMS} items in a menu"),
156            MenuError::BadId => f.write_str("not a menu id"),
157            MenuError::DuplicateId => f.write_str("an id is used twice"),
158            MenuError::EmptyAccelerator => f.write_str("an empty accelerator"),
159            MenuError::BadModifier => f.write_str("not a modifier"),
160            MenuError::BadKey => f.write_str("not a key"),
161            MenuError::ReservedAccelerator => f.write_str("a shortcut belongs to a standard menu"),
162            MenuError::DuplicateAccelerator => f.write_str("a shortcut is used twice"),
163        }
164    }
165}
166
167impl std::error::Error for MenuError {}
168
169/// A label is words a person reads: not empty, not too long, no control character.
170fn is_label(label: &str) -> bool {
171    let n = label.chars().count();
172    !(label.trim().is_empty() || n > MAX_LABEL || label.chars().any(char::is_control))
173}
174
175fn check_label(label: &str, error: MenuError) -> Result<(), MenuError> {
176    if is_label(label) {
177        Ok(())
178    } else {
179        Err(error)
180    }
181}
182
183/// An accelerator as `acceleratorOf` writes it: modifiers, then one key (`CmdOrCtrl+Shift+K`, `CmdOrCtrl+,`, `CmdOrCtrl+1`).
184pub fn check_accelerator(accelerator: &str) -> Result<(), MenuError> {
185    let parts: Vec<&str> = accelerator.split('+').collect();
186    let (key, modifiers) = parts.split_last().ok_or(MenuError::EmptyAccelerator)?;
187    let mut seen = HashSet::new();
188    for m in modifiers {
189        if !MODIFIERS.contains(m) || !seen.insert(*m) {
190            return Err(MenuError::BadModifier);
191        }
192    }
193    let single = key.chars().count() == 1
194        && key
195            .chars()
196            .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || ",./;'[]-=`".contains(c));
197    let function = key.len() >= 2
198        && key.starts_with('F')
199        && key[1..].parse::<u8>().is_ok_and(|n| (1..=12).contains(&n));
200    if !(single || function || NAMED_KEYS.contains(key)) {
201        return Err(MenuError::BadKey);
202    }
203    Ok(())
204}
205
206fn check_id(id: &str) -> Result<(), MenuError> {
207    let ok = !id.is_empty()
208        && id.len() <= 64
209        && id.starts_with(|c: char| c.is_ascii_lowercase())
210        && id
211            .chars()
212            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-');
213    if ok {
214        Ok(())
215    } else {
216        Err(MenuError::BadId)
217    }
218}
219
220impl MenuSpec {
221    /// Everything the page sent, checked before a native menu is built from it.
222    pub fn validate(&self) -> Result<(), MenuError> {
223        let l = &self.labels;
224        for (label, what) in [
225            (&l.about, "about"),
226            (&l.hide, "hide"),
227            (&l.hide_others, "hideOthers"),
228            (&l.show_all, "showAll"),
229            (&l.quit, "quit"),
230            (&l.edit, "edit"),
231            (&l.undo, "undo"),
232            (&l.redo, "redo"),
233            (&l.cut, "cut"),
234            (&l.copy, "copy"),
235            (&l.paste, "paste"),
236            (&l.select_all, "selectAll"),
237            (&l.window, "window"),
238            (&l.minimize, "minimize"),
239            (&l.zoom, "zoom"),
240            (&l.close, "close"),
241        ] {
242            check_label(label, MenuError::BadStandardLabel(what))?;
243        }
244        if self.menus.len() > MAX_MENUS {
245            return Err(MenuError::TooManyMenus);
246        }
247        let mut ids = HashSet::new();
248        let mut accelerators = HashSet::new();
249        for menu in &self.menus {
250            check_label(&menu.title, MenuError::BadMenuTitle)?;
251            if menu.items.is_empty() || menu.items.len() > MAX_ITEMS {
252                return Err(MenuError::BadItemCount);
253            }
254            for item in &menu.items {
255                check_id(&item.id)?;
256                check_label(&item.label, MenuError::BadItemLabel)?;
257                if !ids.insert(item.id.as_str()) {
258                    return Err(MenuError::DuplicateId);
259                }
260                if let Some(a) = &item.accelerator {
261                    check_accelerator(a)?;
262                    if RESERVED.contains(&a.as_str()) {
263                        return Err(MenuError::ReservedAccelerator);
264                    }
265                    if !accelerators.insert(a.as_str()) {
266                        return Err(MenuError::DuplicateAccelerator);
267                    }
268                }
269            }
270        }
271        Ok(())
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    fn labels() -> StandardLabels {
280        let w = |s: &str| s.to_string();
281        StandardLabels {
282            about: w("À propos de Verikora"),
283            hide: w("Masquer Verikora"),
284            hide_others: w("Masquer les autres"),
285            show_all: w("Tout afficher"),
286            quit: w("Quitter Verikora"),
287            edit: w("Édition"),
288            undo: w("Annuler"),
289            redo: w("Rétablir"),
290            cut: w("Couper"),
291            copy: w("Copier"),
292            paste: w("Coller"),
293            select_all: w("Tout sélectionner"),
294            window: w("Fenêtre"),
295            minimize: w("Réduire"),
296            zoom: w("Zoom"),
297            close: w("Fermer"),
298        }
299    }
300
301    fn item(id: &str, accelerator: Option<&str>) -> MenuItemSpec {
302        MenuItemSpec {
303            id: id.into(),
304            label: "Ajouter un dossier…".into(),
305            accelerator: accelerator.map(Into::into),
306            enabled: true,
307            separated: false,
308        }
309    }
310
311    fn spec(items: Vec<MenuItemSpec>) -> MenuSpec {
312        MenuSpec {
313            labels: labels(),
314            menus: vec![MenuGroupSpec {
315                title: "Fichier".into(),
316                items,
317            }],
318        }
319    }
320
321    #[test]
322    fn a_menu_as_the_page_sends_it_is_accepted() {
323        let s = spec(vec![
324            item("library.add-folder", Some("CmdOrCtrl+O")),
325            item("check.new", Some("CmdOrCtrl+N")),
326            item("go.reports", Some("CmdOrCtrl+2")),
327            item("app.settings", Some("CmdOrCtrl+,")),
328            item("app.search", Some("Shift+CmdOrCtrl+K")),
329            item("view.help", None),
330        ]);
331        assert_eq!(s.validate(), Ok(()));
332        let from_page: MenuSpec = serde_json::from_value(serde_json::json!({
333            "labels": serde_json::to_value(labels()).unwrap(),
334            "menus": [{ "title": "Fichier", "items": [{ "id": "check.new", "label": "Nouvelle vérification", "accelerator": "CmdOrCtrl+N" }] }]
335        }))
336        .unwrap();
337        assert!(from_page.menus[0].items[0].enabled);
338        assert_eq!(from_page.validate(), Ok(()));
339    }
340
341    #[test]
342    fn accelerators_are_the_ones_accelerator_of_writes() {
343        for ok in [
344            "CmdOrCtrl+K",
345            "Shift+CmdOrCtrl+/",
346            "Alt+Up",
347            "CmdOrCtrl+Enter",
348            "F5",
349            "CmdOrCtrl+Plus",
350        ] {
351            assert_eq!(check_accelerator(ok), Ok(()), "{ok}");
352        }
353        for bad in [
354            "",
355            "CmdOrCtrl+",
356            "Hyper+K",
357            "CmdOrCtrl+CmdOrCtrl+K",
358            "CmdOrCtrl+k",
359            "CmdOrCtrl+KK",
360            "F13",
361            "CmdOrCtrl+é",
362        ] {
363            assert!(check_accelerator(bad).is_err(), "{bad}");
364        }
365    }
366
367    #[test]
368    fn refuses_bad_ids_twice_used_ids_or_shortcuts_and_unreadable_labels() {
369        assert!(spec(vec![item("Check.New", None)]).validate().is_err());
370        assert!(spec(vec![item("check new", None)]).validate().is_err());
371        assert!(spec(vec![item("a", None), item("a", None)])
372            .validate()
373            .is_err());
374        assert!(spec(vec![
375            item("a", Some("CmdOrCtrl+N")),
376            item("b", Some("CmdOrCtrl+N"))
377        ])
378        .validate()
379        .is_err());
380        assert!(spec(vec![]).validate().is_err());
381        for standard in ["CmdOrCtrl+Q", "CmdOrCtrl+C", "Shift+CmdOrCtrl+Z"] {
382            assert!(
383                spec(vec![item("a", Some(standard))]).validate().is_err(),
384                "{standard}"
385            );
386        }
387        let mut long = item("a", None);
388        long.label = "x".repeat(MAX_LABEL + 1);
389        assert!(spec(vec![long]).validate().is_err());
390        let mut blank = spec(vec![item("a", None)]);
391        blank.labels.copy = " ".into();
392        assert!(blank.validate().is_err());
393        let mut many = spec(vec![item("a", None)]);
394        many.menus = (0..=MAX_MENUS)
395            .map(|i| MenuGroupSpec {
396                title: format!("M{i}"),
397                items: vec![item(&format!("m{i}"), None)],
398            })
399            .collect();
400        assert!(many.validate().is_err());
401    }
402}