Skip to main content

mitsuami_core/services/
menu.rs

1//! The menu builder: items, separators, menus and menu bars.
2
3use std::rc::Rc;
4
5use mitsuami_reactive::{IntoValue, Signal, Value};
6
7use super::menu_data::{MenuRole, Shortcut};
8
9pub(super) type Handler = Rc<dyn Fn()>;
10
11pub(super) enum Mark {
12    None,
13    Check(Value<bool>),
14    Radio(Value<bool>),
15}
16
17/// A menu item: a title, what choosing it does, and optionally a
18/// shortcut, a check mark and a role. Its title, enabled state, check mark
19/// and visibility take a literal, a signal or a closure.
20///
21/// ```ignore
22/// MenuItem::new("Save").shortcut(Shortcut::primary('s')).on_select(save)
23/// MenuItem::new("Show Sidebar").bind(sidebar)
24/// MenuItem::new("Large").radio((zoom, Zoom::Large))
25/// ```
26///
27/// In `view!`, its text is its title:
28/// `<MenuItem shortcut=Shortcut::primary('s') @select=save>"Save"</MenuItem>`.
29pub struct MenuItem {
30    pub(super) title: Value<String>,
31    pub(super) shortcut: Option<Shortcut>,
32    pub(super) enabled: Value<bool>,
33    pub(super) visible: Value<bool>,
34    pub(super) check: Mark,
35    pub(super) role: MenuRole,
36    /// What `bind` and `radio` do, before the handler.
37    pub(super) bound: Option<Handler>,
38    pub(super) handler: Option<Handler>,
39}
40
41impl MenuItem {
42    pub fn new(title: impl IntoValue<String>) -> MenuItem {
43        MenuItem {
44            title: title.into_value(),
45            shortcut: None,
46            enabled: Value::Static(true),
47            visible: Value::Static(true),
48            check: Mark::None,
49            role: MenuRole::None,
50            bound: None,
51            handler: None,
52        }
53    }
54
55    /// Called when the item is chosen: clicked, or through its shortcut.
56    pub fn on_select(mut self, handler: impl Fn() + 'static) -> MenuItem {
57        self.handler = Some(Rc::new(handler));
58        self
59    }
60
61    /// The item's shortcut, or `None` for none: some items have one only
62    /// on some platforms.
63    pub fn shortcut(mut self, shortcut: impl Into<Option<Shortcut>>) -> MenuItem {
64        self.shortcut = shortcut.into();
65        self
66    }
67
68    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> MenuItem {
69        self.enabled = enabled.into_value();
70        self
71    }
72
73    /// In the menu while true.
74    pub fn visible(mut self, visible: impl IntoValue<bool>) -> MenuItem {
75        self.visible = visible.into_value();
76        self
77    }
78
79    /// Shows a check mark while true. Choosing the item only calls its
80    /// handler: [`bind`](Self::bind) toggles a signal instead.
81    pub fn checked(mut self, checked: impl IntoValue<bool>) -> MenuItem {
82        self.check = Mark::Check(checked.into_value());
83        self
84    }
85
86    /// A check mark showing the signal; choosing the item toggles it.
87    pub fn bind(mut self, signal: Signal<bool>) -> MenuItem {
88        self.check = Mark::Check(signal.into_value());
89        self.bound = Some(Rc::new(move || signal.update(|on| *on = !*on)));
90        self
91    }
92
93    /// One of a group of choices: checked while `signal` holds `value`,
94    /// and choosing it sets it. Radio items next to each other in a menu
95    /// form a group. A pair, so `view!` can write `radio=(zoom, Zoom::Large)`.
96    pub fn radio<T: PartialEq + Clone + 'static>(mut self, (signal, value): (Signal<T>, T)) -> MenuItem {
97        let chosen = value.clone();
98        self.check = Mark::Radio(Value::Dynamic(Rc::new(move || signal.with(|v| *v == chosen))));
99        self.bound = Some(Rc::new(move || signal.set(value.clone())));
100        self
101    }
102
103    /// An item every app has, which platforms may move to a place of their
104    /// own and give their own title and shortcut: see [`MenuRole`].
105    pub fn role(mut self, role: MenuRole) -> MenuItem {
106        self.role = role;
107        self
108    }
109
110    #[doc(hidden)]
111    pub fn __tag() -> MenuItem {
112        MenuItem::new(String::new())
113    }
114
115    /// `<MenuItem>"Save"</MenuItem>`: its text is its title.
116    #[doc(hidden)]
117    pub fn __children<S: IntoValue<String>>(mut self, title: impl FnOnce() -> S) -> MenuItem {
118        self.title = title().into_value();
119        self
120    }
121
122    pub(super) fn select_handler(&self) -> Handler {
123        let (bound, handler) = (self.bound.clone(), self.handler.clone());
124        Rc::new(move || {
125            if let Some(bound) = &bound {
126                bound();
127            }
128            if let Some(handler) = &handler {
129                handler();
130            }
131        })
132    }
133}
134
135/// A line between groups of items.
136#[derive(Clone, Copy, Debug, Default)]
137pub struct MenuSeparator;
138
139impl MenuSeparator {
140    pub fn new() -> MenuSeparator {
141        MenuSeparator
142    }
143
144    #[doc(hidden)]
145    pub fn __tag() -> MenuSeparator {
146        MenuSeparator
147    }
148}
149
150pub(super) enum Entry {
151    Item(MenuItem),
152    Separator,
153    Submenu(Menu),
154    /// Entries built again whenever what they read changes.
155    Dynamic(Rc<dyn Fn() -> Vec<Entry>>),
156}
157
158/// A menu of the bar, or a submenu of another menu.
159///
160/// ```ignore
161/// Menu::new("File")
162///     .item(MenuItem::new("New").shortcut(Shortcut::primary('n')).on_select(new))
163///     .submenu(Menu::new("Open Recent").children_with(move || {
164///         recent.get().into_iter().map(|path| MenuItem::new(path.clone()).on_select(move || open(&path))).collect::<Vec<_>>()
165///     }))
166///     .separator()
167///     .item(MenuItem::new("Settings…").role(MenuRole::Settings).on_select(settings))
168/// ```
169///
170/// In `view!`, `<Menu title="File">…</Menu>` takes items, `<MenuSeparator/>`s
171/// and `Menu`s as children.
172pub struct Menu {
173    pub(super) title: Value<String>,
174    pub(super) visible: Value<bool>,
175    pub(super) entries: Vec<Entry>,
176}
177
178impl Menu {
179    pub fn new(title: impl IntoValue<String>) -> Menu {
180        Menu { title: title.into_value(), visible: Value::Static(true), entries: Vec::new() }
181    }
182
183    pub fn title(mut self, title: impl IntoValue<String>) -> Menu {
184        self.title = title.into_value();
185        self
186    }
187
188    /// In the bar (or its menu) while true.
189    pub fn visible(mut self, visible: impl IntoValue<bool>) -> Menu {
190        self.visible = visible.into_value();
191        self
192    }
193
194    pub fn item(mut self, item: MenuItem) -> Menu {
195        self.entries.push(Entry::Item(item));
196        self
197    }
198
199    pub fn separator(mut self) -> Menu {
200        self.entries.push(Entry::Separator);
201        self
202    }
203
204    pub fn submenu(mut self, menu: Menu) -> Menu {
205        self.entries.push(Entry::Submenu(menu));
206        self
207    }
208
209    /// Items, separators and submenus, in order.
210    pub fn children(self, children: impl MenuEntries) -> Menu {
211        children.add_to(self)
212    }
213
214    /// Entries built by `children`, and built again whenever what it reads
215    /// changes: a list of recent files, say.
216    pub fn children_with<E: MenuEntries>(mut self, children: impl Fn() -> E + 'static) -> Menu {
217        self.entries.push(Entry::Dynamic(Rc::new(move || children().add_to(Menu::new(String::new())).entries)));
218        self
219    }
220
221    #[doc(hidden)]
222    pub fn __tag() -> Menu {
223        Menu::new(String::new())
224    }
225
226    #[doc(hidden)]
227    pub fn __children<E: MenuEntries>(self, children: impl FnOnce() -> E) -> Menu {
228        self.children(children())
229    }
230}
231
232/// What a [`Menu`] takes as children: [`MenuItem`]s, [`MenuSeparator`]s,
233/// [`Menu`]s (as submenus), and tuples, `Vec`s and `Option`s of them.
234pub trait MenuEntries {
235    fn add_to(self, menu: Menu) -> Menu;
236}
237
238impl MenuEntries for MenuItem {
239    fn add_to(self, menu: Menu) -> Menu {
240        menu.item(self)
241    }
242}
243
244impl MenuEntries for MenuSeparator {
245    fn add_to(self, menu: Menu) -> Menu {
246        menu.separator()
247    }
248}
249
250impl MenuEntries for Menu {
251    fn add_to(self, menu: Menu) -> Menu {
252        menu.submenu(self)
253    }
254}
255
256impl<E: MenuEntries> MenuEntries for Vec<E> {
257    fn add_to(self, menu: Menu) -> Menu {
258        self.into_iter().fold(menu, |menu, entry| entry.add_to(menu))
259    }
260}
261
262impl<E: MenuEntries> MenuEntries for Option<E> {
263    fn add_to(self, menu: Menu) -> Menu {
264        match self {
265            Some(entry) => entry.add_to(menu),
266            None => menu,
267        }
268    }
269}
270
271impl MenuEntries for () {
272    fn add_to(self, menu: Menu) -> Menu {
273        menu
274    }
275}
276
277/// The menus of a bar: [`Menu`]s, and tuples, `Vec`s and `Option`s of them.
278pub trait Menus {
279    fn add_to(self, bar: MenuBar) -> MenuBar;
280}
281
282impl Menus for Menu {
283    fn add_to(self, bar: MenuBar) -> MenuBar {
284        bar.menu(self)
285    }
286}
287
288impl<M: Menus> Menus for Vec<M> {
289    fn add_to(self, bar: MenuBar) -> MenuBar {
290        self.into_iter().fold(bar, |bar, menu| menu.add_to(bar))
291    }
292}
293
294impl<M: Menus> Menus for Option<M> {
295    fn add_to(self, bar: MenuBar) -> MenuBar {
296        match self {
297            Some(menu) => menu.add_to(bar),
298            None => bar,
299        }
300    }
301}
302
303impl Menus for () {
304    fn add_to(self, bar: MenuBar) -> MenuBar {
305        bar
306    }
307}
308
309macro_rules! tuple_menus {
310    ($($name:ident),+) => {
311        impl<$($name: MenuEntries),+> MenuEntries for ($($name,)+) {
312            #[allow(non_snake_case)]
313            fn add_to(self, menu: Menu) -> Menu {
314                let ($($name,)+) = self;
315                $(let menu = $name.add_to(menu);)+
316                menu
317            }
318        }
319
320        impl<$($name: Menus),+> Menus for ($($name,)+) {
321            #[allow(non_snake_case)]
322            fn add_to(self, bar: MenuBar) -> MenuBar {
323                let ($($name,)+) = self;
324                $(let bar = $name.add_to(bar);)+
325                bar
326            }
327        }
328    };
329}
330
331tuple_menus!(A);
332tuple_menus!(A, B);
333tuple_menus!(A, B, C);
334tuple_menus!(A, B, C, D);
335tuple_menus!(A, B, C, D, E);
336tuple_menus!(A, B, C, D, E, F);
337tuple_menus!(A, B, C, D, E, F, G);
338tuple_menus!(A, B, C, D, E, F, G, H);
339tuple_menus!(A, B, C, D, E, F, G, H, I);
340tuple_menus!(A, B, C, D, E, F, G, H, I, J);
341tuple_menus!(A, B, C, D, E, F, G, H, I, J, K);
342tuple_menus!(A, B, C, D, E, F, G, H, I, J, K, L);
343
344/// Menus for the app ([`set_menu`]) or for one window: declared anywhere
345/// in a window's content, like a `Toolbar`, a `MenuBar` holds that
346/// window's own menus while it's there. A window
347/// shows the app's menus and its own; on macOS, whose menu bar is the
348/// app's, a window's menus are there while it's the main window.
349/// Platforms add their standard menus around them.
350///
351/// ```ignore
352/// view! {
353///     <MenuBar>
354///         <Menu title="Machine">
355///             <MenuItem shortcut=Shortcut::primary('r') @select=start>"Start"</MenuItem>
356///             <MenuSeparator/>
357///             <MenuItem bind=show_log>"Show Log"</MenuItem>
358///         </Menu>
359///     </MenuBar>
360/// }
361/// ```
362///
363/// [`set_menu`]: super::set_menu
364#[derive(Default)]
365pub struct MenuBar {
366    pub(super) menus: Vec<Menu>,
367}
368
369impl MenuBar {
370    pub fn new() -> MenuBar {
371        MenuBar::default()
372    }
373
374    pub fn menu(mut self, menu: Menu) -> MenuBar {
375        self.menus.push(menu);
376        self
377    }
378
379    pub fn children(self, menus: impl Menus) -> MenuBar {
380        menus.add_to(self)
381    }
382
383    #[doc(hidden)]
384    pub fn __tag() -> MenuBar {
385        MenuBar::new()
386    }
387
388    #[doc(hidden)]
389    pub fn __children<M: Menus>(self, menus: impl FnOnce() -> M) -> MenuBar {
390        self.children(menus())
391    }
392}