Skip to main content

mitsuami_core/services/
menu_data.rs

1//! Menus as data, as platforms get them: menu bars, items, shortcuts and
2//! roles.
3
4use std::rc::Rc;
5
6use crate::backend::Key;
7
8/// A keyboard shortcut: a key, and the modifiers held with it. `primary`
9/// is ⌘ on macOS and Ctrl elsewhere; `alt` is ⌥ on macOS.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub struct Shortcut {
12    /// A letter is lower case: Shift is `shift`.
13    pub key: Key,
14    pub primary: bool,
15    pub shift: bool,
16    pub alt: bool,
17}
18
19impl Shortcut {
20    /// The key on its own: `Shortcut::new(Key::F(2))`, or with modifiers
21    /// added, `Shortcut::new(Key::Up).alt()`.
22    pub fn new(key: impl Into<Key>) -> Shortcut {
23        let key = match key.into() {
24            Key::Char(c) => Key::Char(c.to_ascii_lowercase()),
25            key => key,
26        };
27        Shortcut { key, primary: false, shift: false, alt: false }
28    }
29
30    /// ⌘+key on macOS, Ctrl+key elsewhere: `Shortcut::primary('s')`,
31    /// `Shortcut::primary(Key::Backspace)`.
32    pub fn primary(key: impl Into<Key>) -> Shortcut {
33        Shortcut { primary: true, ..Shortcut::new(key) }
34    }
35
36    pub fn shift(mut self) -> Shortcut {
37        self.shift = true;
38        self
39    }
40
41    pub fn alt(mut self) -> Shortcut {
42        self.alt = true;
43        self
44    }
45}
46
47impl From<Key> for Shortcut {
48    fn from(key: Key) -> Shortcut {
49        Shortcut::new(key)
50    }
51}
52
53impl From<char> for Shortcut {
54    fn from(c: char) -> Shortcut {
55        Shortcut::new(c)
56    }
57}
58
59/// A menu bar as data, for [`Services::set_menu`]: the app's menus, or a
60/// window's. Hidden items and menus are left out.
61///
62/// [`Services::set_menu`]: super::Services::set_menu
63#[derive(Clone, Debug, Default, PartialEq)]
64pub struct MenuBarData {
65    pub menus: Vec<MenuData>,
66}
67
68/// A menu of the bar, or a submenu.
69#[derive(Clone, Debug, Default, PartialEq)]
70pub struct MenuData {
71    pub title: String,
72    pub entries: Vec<MenuEntry>,
73}
74
75/// Builds a node's context menu (or a menu button's menu) as the platform
76/// opens it, for menus that depend on what's under the pointer and
77/// selected at that moment (a table's rows). Calling it builds the menu,
78/// makes it the node's [`Prop::ContextMenu`](crate::Prop::ContextMenu)
79/// (or [`Prop::Menu`](crate::Prop::Menu)), and returns it, for the
80/// platform to show. Equal only to itself.
81#[derive(Clone)]
82pub struct MenuOnOpen(Rc<dyn Fn() -> Vec<MenuEntry>>);
83
84impl MenuOnOpen {
85    pub fn new(build: impl Fn() -> Vec<MenuEntry> + 'static) -> MenuOnOpen {
86        MenuOnOpen(Rc::new(build))
87    }
88
89    /// Builds the menu. Called outside any `Ui` call: from the platform's
90    /// own event (a right-click, a press on the button), or by tests
91    /// before they act on it.
92    pub fn build(&self) -> Vec<MenuEntry> {
93        (self.0)()
94    }
95}
96
97impl PartialEq for MenuOnOpen {
98    fn eq(&self, other: &MenuOnOpen) -> bool {
99        Rc::ptr_eq(&self.0, &other.0)
100    }
101}
102
103impl std::fmt::Debug for MenuOnOpen {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.write_str("MenuOnOpen")
106    }
107}
108
109#[derive(Clone, Debug, PartialEq)]
110pub enum MenuEntry {
111    Item(MenuItemData),
112    Submenu(MenuData),
113    Separator,
114}
115
116#[derive(Clone, Debug, PartialEq)]
117pub struct MenuItemData {
118    /// Unique among every menu bar of the app, and the same while the
119    /// bar's structure is.
120    pub id: u32,
121    pub title: String,
122    pub shortcut: Option<Shortcut>,
123    pub enabled: bool,
124    pub check: MenuCheck,
125    pub role: MenuRole,
126}
127
128/// Whether an item shows a check mark, and which kind.
129#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
130pub enum MenuCheck {
131    #[default]
132    None,
133    /// Checked or not, on its own.
134    Check(bool),
135    /// One of a group: the radio items next to each other in a menu.
136    Radio(bool),
137}
138
139/// An item every app has, which some platforms put in a place of their
140/// own (the app menu on macOS) with their own title and shortcut.
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub enum MenuRole {
143    #[default]
144    None,
145    /// `About <app>`.
146    About,
147    /// The app's settings (preferences).
148    Settings,
149    /// Quitting: it replaces the platform's own Quit item, where there is
150    /// one.
151    Quit,
152}
153
154impl MenuBarData {
155    /// The menus of a window that has menus of its own: the app's, then
156    /// the window's. A window menu titled like an app menu joins it, after
157    /// a separator.
158    pub fn merged(&self, window: &MenuBarData) -> MenuBarData {
159        let mut merged = self.clone();
160        for menu in &window.menus {
161            match merged.menus.iter_mut().find(|m| m.title == menu.title) {
162                Some(app) => {
163                    if !app.entries.is_empty() && !menu.entries.is_empty() {
164                        app.entries.push(MenuEntry::Separator);
165                    }
166                    app.entries.extend(menu.entries.iter().cloned());
167                }
168                None => merged.menus.push(menu.clone()),
169            }
170        }
171        merged
172    }
173
174    /// What a window shows on platforms that put menus in each window
175    /// (GTK, WinUI, Kirigami): the app's with its own ([`merged`](Self::merged)).
176    /// A modal window is a dialog, and dialogs there have no app menus, so
177    /// it shows only its own.
178    pub fn for_window(&self, own: Option<&MenuBarData>, modal: bool) -> MenuBarData {
179        match (own, modal) {
180            (Some(own), false) => self.merged(own),
181            (None, false) => self.clone(),
182            (Some(own), true) => own.clone(),
183            (None, true) => MenuBarData::default(),
184        }
185    }
186
187    /// Takes out the first item with this role, for a platform that puts
188    /// it somewhere of its own. Separators it leaves at an edge or doubled
189    /// go too, and so does a menu it leaves empty.
190    pub fn take_role(&mut self, role: MenuRole) -> Option<MenuItemData> {
191        let taken = self.menus.iter_mut().find_map(|menu| menu.take_role(role))?;
192        self.menus.retain(|menu| !menu.entries.is_empty());
193        Some(taken)
194    }
195
196    /// Every item, submenus' included, in order.
197    pub fn items(&self) -> Vec<&MenuItemData> {
198        let mut items = Vec::new();
199        for menu in &self.menus {
200            menu.collect_items(&mut items);
201        }
202        items
203    }
204
205    /// The same menus, submenus, items, titles, shortcuts and roles: only
206    /// enabled and checked states differ, which platforms can update
207    /// without rebuilding (and closing) an open menu.
208    pub fn same_structure(&self, other: &MenuBarData) -> bool {
209        fn strip(menu: &MenuData) -> MenuData {
210            let entries = menu
211                .entries
212                .iter()
213                .map(|entry| match entry {
214                    MenuEntry::Item(item) => MenuEntry::Item(MenuItemData {
215                        enabled: true,
216                        check: match item.check {
217                            MenuCheck::None => MenuCheck::None,
218                            MenuCheck::Check(_) => MenuCheck::Check(false),
219                            MenuCheck::Radio(_) => MenuCheck::Radio(false),
220                        },
221                        ..item.clone()
222                    }),
223                    MenuEntry::Submenu(menu) => MenuEntry::Submenu(strip(menu)),
224                    MenuEntry::Separator => MenuEntry::Separator,
225                })
226                .collect();
227            MenuData { title: menu.title.clone(), entries }
228        }
229        self.menus.len() == other.menus.len() && self.menus.iter().zip(&other.menus).all(|(a, b)| strip(a) == strip(b))
230    }
231}
232
233/// The item at `path` among these entries: the titles of its submenus,
234/// then its own, e.g. `["Sort By", "Name"]`.
235pub fn find_menu_item<'a>(entries: &'a [MenuEntry], path: &[&str]) -> Option<&'a MenuItemData> {
236    let (title, rest) = path.split_first()?;
237    entries.iter().find_map(|entry| match entry {
238        MenuEntry::Item(item) if rest.is_empty() && item.title == *title => Some(item),
239        MenuEntry::Submenu(submenu) if !rest.is_empty() && submenu.title == *title => {
240            find_menu_item(&submenu.entries, rest)
241        }
242        _ => None,
243    })
244}
245
246/// The item with this id among these entries, submenus' included.
247pub fn menu_item_by_id(entries: &[MenuEntry], id: u32) -> Option<&MenuItemData> {
248    entries.iter().find_map(|entry| match entry {
249        MenuEntry::Item(item) if item.id == id => Some(item),
250        MenuEntry::Submenu(submenu) => menu_item_by_id(&submenu.entries, id),
251        _ => None,
252    })
253}
254
255impl MenuData {
256    /// For each entry, the radio group it belongs to, named by the id of
257    /// the group's first item: radio items next to each other form one.
258    pub fn radio_groups(&self) -> Vec<Option<u32>> {
259        let mut group = None;
260        self.entries
261            .iter()
262            .map(|entry| {
263                group = match entry {
264                    MenuEntry::Item(item @ MenuItemData { check: MenuCheck::Radio(_), .. }) => group.or(Some(item.id)),
265                    _ => None,
266                };
267                group
268            })
269            .collect()
270    }
271
272    fn take_role(&mut self, role: MenuRole) -> Option<MenuItemData> {
273        let mut taken = None;
274        for (i, entry) in self.entries.iter_mut().enumerate() {
275            match entry {
276                MenuEntry::Item(item) if item.role == role => {
277                    taken = Some((i, item.clone()));
278                    break;
279                }
280                MenuEntry::Submenu(submenu) => {
281                    if let Some(item) = submenu.take_role(role) {
282                        if submenu.entries.is_empty() {
283                            self.entries.remove(i);
284                        }
285                        self.tidy_separators();
286                        return Some(item);
287                    }
288                }
289                _ => {}
290            }
291        }
292        let (i, item) = taken?;
293        self.entries.remove(i);
294        self.tidy_separators();
295        Some(item)
296    }
297
298    fn tidy_separators(&mut self) {
299        let mut entries: Vec<MenuEntry> = Vec::with_capacity(self.entries.len());
300        for entry in self.entries.drain(..) {
301            let separator = matches!(entry, MenuEntry::Separator);
302            if separator && entries.last().is_none_or(|e| matches!(e, MenuEntry::Separator)) {
303                continue;
304            }
305            entries.push(entry);
306        }
307        if matches!(entries.last(), Some(MenuEntry::Separator)) {
308            entries.pop();
309        }
310        self.entries = entries;
311    }
312
313    fn collect_items<'a>(&'a self, out: &mut Vec<&'a MenuItemData>) {
314        for entry in &self.entries {
315            match entry {
316                MenuEntry::Item(item) => out.push(item),
317                MenuEntry::Submenu(menu) => menu.collect_items(out),
318                MenuEntry::Separator => {}
319            }
320        }
321    }
322}