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