Skip to main content

mitsuami_core/services/
menu_collect.rs

1//! Turning built menus into data and handlers, again whenever what they
2//! read changes: menu bars, context menus and menu buttons' menus.
3
4use std::cell::RefCell;
5use std::collections::HashMap;
6use std::rc::Rc;
7
8use mitsuami_reactive::inject;
9
10use crate::command::UiEvent;
11use crate::ui::Ui;
12use crate::view::View;
13use crate::widget::{CurrentWindow, NodeId, Prop, WidgetKind};
14
15use super::menu::{Entry, Handler, Mark, Menu, MenuBar};
16use super::menu_data::{MenuBarData, MenuCheck, MenuData, MenuEntry, MenuItemData, MenuOnOpen};
17
18impl MenuBar {
19    /// The bar as data, reading reactive values, and each item's handler.
20    /// `ids` holds the id given to each item position, so ids stay the
21    /// same while the structure does; `new_id` makes more.
22    pub(crate) fn collect(
23        &self,
24        ids: &mut Vec<u32>,
25        new_id: &mut dyn FnMut() -> u32,
26    ) -> (MenuBarData, Vec<(u32, Handler)>) {
27        let mut walk = Walk { ids, position: 0, new_id, handlers: Vec::new() };
28        let menus = self.menus.iter().filter_map(|menu| walk.menu(menu)).collect();
29        (MenuBarData { menus }, walk.handlers)
30    }
31}
32
33impl Menu {
34    /// The menu's entries as data, for a context menu (whose title isn't
35    /// shown), and each item's handler; see [`MenuBar::collect`].
36    pub(crate) fn collect_entries(
37        &self,
38        ids: &mut Vec<u32>,
39        new_id: &mut dyn FnMut() -> u32,
40    ) -> (Vec<MenuEntry>, Vec<(u32, Handler)>) {
41        let mut walk = Walk { ids, position: 0, new_id, handlers: Vec::new() };
42        let mut entries = Vec::new();
43        walk.entries(&self.entries, &mut entries);
44        (entries, walk.handlers)
45    }
46}
47
48/// Gives a node the context menu `.context_menu(...)` built: sends it as
49/// [`Prop::ContextMenu`] again whenever its reactive parts change, and runs
50/// an item's handler when the platform reports it chosen. Ids only need to
51/// be unique within the node's menu, since the choice comes as the node's
52/// event.
53pub(crate) fn install_context_menu(ui: &Ui, id: NodeId, menu: Menu) {
54    install_menu(ui, id, menu, Prop::ContextMenu, |event| match event {
55        UiEvent::ContextMenuItem(item) => Some(*item),
56        _ => None,
57    });
58}
59
60/// Gives a node a context menu `build` makes as the platform opens it
61/// (`.context_menu_on_open(...)`): [`Prop::ContextMenuOnOpen`], which
62/// builds the menu, keeps its items' handlers until it's built again, and
63/// makes it the node's [`Prop::ContextMenu`]. Its reactive parts are read
64/// as it opens, not followed.
65pub(crate) fn install_context_menu_on_open(ui: &Ui, id: NodeId, build: Rc<dyn Fn() -> Menu>) {
66    install_menu_on_open(ui, id, build, Prop::ContextMenu, Prop::ContextMenuOnOpen, |event| match event {
67        UiEvent::ContextMenuItem(item) => Some(*item),
68        _ => None,
69    });
70}
71
72/// Gives a `MenuButton` a menu `build` makes as the platform opens it, as
73/// [`Prop::MenuOnOpen`], as a context menu built as it opens is given
74/// (see `install_context_menu_on_open`).
75#[doc(hidden)]
76pub fn install_button_menu_on_open(ui: &Ui, id: NodeId, build: Rc<dyn Fn() -> Menu>) {
77    install_menu_on_open(ui, id, build, Prop::Menu, Prop::MenuOnOpen, |event| match event {
78        UiEvent::MenuItem(item) => Some(*item),
79        _ => None,
80    });
81}
82
83fn install_menu_on_open(
84    ui: &Ui,
85    id: NodeId,
86    build: Rc<dyn Fn() -> Menu>,
87    prop: fn(Vec<MenuEntry>) -> Prop,
88    on_open_prop: fn(Option<MenuOnOpen>) -> Prop,
89    chosen_item: fn(&UiEvent) -> Option<u32>,
90) {
91    let handlers: Rc<RefCell<HashMap<u32, Handler>>> = Rc::default();
92    let scope = mitsuami_reactive::Owner::current();
93    let chosen = handlers.clone();
94    ui.on_event(id, move |event| {
95        let Some(item) = chosen_item(event) else { return };
96        let Some(handler) = chosen.borrow().get(&item).cloned() else { return };
97        match scope {
98            Some(scope) if scope.is_alive() => scope.with(|| handler()),
99            _ => handler(),
100        }
101    });
102    let weak = ui.downgrade();
103    let ids = RefCell::new(Vec::new());
104    let next_id = std::cell::Cell::new(0);
105    let on_open = MenuOnOpen::new(move || {
106        let menu = match scope {
107            Some(scope) if scope.is_alive() => scope.with(|| build()),
108            _ => build(),
109        };
110        let (entries, collected) = mitsuami_reactive::untrack(|| {
111            menu.collect_entries(&mut ids.borrow_mut(), &mut || {
112                next_id.set(next_id.get() + 1);
113                next_id.get()
114            })
115        });
116        *handlers.borrow_mut() = collected.into_iter().collect();
117        if let Some(ui) = weak.upgrade() {
118            ui.set_prop(id, prop(entries.clone()));
119        }
120        entries
121    });
122    ui.set_prop(id, on_open_prop(Some(on_open)));
123}
124
125/// Gives a `MenuButton` or `SplitButton` its menu, as [`Prop::Menu`], as a
126/// context menu is given (see `install_context_menu`). The menu's title isn't shown.
127#[doc(hidden)]
128pub fn install_button_menu(ui: &Ui, id: NodeId, menu: Menu) {
129    install_menu(ui, id, menu, Prop::Menu, |event| match event {
130        UiEvent::MenuItem(item) => Some(*item),
131        _ => None,
132    });
133}
134
135fn install_menu(
136    ui: &Ui,
137    id: NodeId,
138    menu: Menu,
139    prop: fn(Vec<MenuEntry>) -> Prop,
140    chosen_item: fn(&UiEvent) -> Option<u32>,
141) {
142    let handlers: Rc<RefCell<HashMap<u32, Handler>>> = Rc::default();
143    // As menu bars' handlers do, they run in the scope that built the menu.
144    let scope = mitsuami_reactive::Owner::current();
145    let chosen = handlers.clone();
146    ui.on_event(id, move |event| {
147        let Some(item) = chosen_item(event) else { return };
148        let item = &item;
149        let Some(handler) = chosen.borrow().get(item).cloned() else { return };
150        match scope {
151            Some(scope) if scope.is_alive() => scope.with(|| handler()),
152            _ => handler(),
153        }
154    });
155    let ui = ui.clone();
156    let (mut ids, mut next_id) = (Vec::new(), 0);
157    mitsuami_reactive::effect(move || {
158        let (entries, collected) = menu.collect_entries(&mut ids, &mut || {
159            next_id += 1;
160            next_id
161        });
162        *handlers.borrow_mut() = collected.into_iter().collect();
163        ui.set_prop(id, prop(entries));
164    });
165}
166
167/// The context menus of items a node shows as data, as a `Sidebar` shows
168/// its items: each item's menu as data, sent with the item, and the
169/// handlers of all of them, which the node's `ContextMenuItem` runs. Ids
170/// are unique across the items' menus, and stay the same while their
171/// structure does, as a context menu's do.
172#[doc(hidden)]
173#[derive(Clone)]
174pub struct ItemMenus {
175    state: Rc<RefCell<ItemMenusState>>,
176    /// As menu bars' handlers do, they run in the scope that built them.
177    scope: Option<mitsuami_reactive::Owner>,
178}
179
180#[derive(Default)]
181struct ItemMenusState {
182    ids: Vec<u32>,
183    next_id: u32,
184    handlers: HashMap<u32, Handler>,
185}
186
187impl ItemMenus {
188    pub fn new() -> ItemMenus {
189        ItemMenus { state: Rc::default(), scope: mitsuami_reactive::Owner::current() }
190    }
191
192    /// Each menu's entries as data (empty for an item without one),
193    /// reading their reactive parts, in an effect that sends them.
194    pub fn collect(&self, menus: &[Option<&Menu>]) -> Vec<Vec<MenuEntry>> {
195        let mut state = self.state.borrow_mut();
196        let ItemMenusState { ids, next_id, handlers } = &mut *state;
197        let mut new_id = || {
198            *next_id += 1;
199            *next_id
200        };
201        let mut walk = Walk { ids, position: 0, new_id: &mut new_id, handlers: Vec::new() };
202        let entries = menus
203            .iter()
204            .map(|menu| {
205                let mut out = Vec::new();
206                if let Some(menu) = menu {
207                    walk.entries(&menu.entries, &mut out);
208                }
209                out
210            })
211            .collect();
212        *handlers = walk.handlers.into_iter().collect();
213        entries
214    }
215
216    /// Runs the handler of the item `ContextMenuItem` names, if any.
217    pub fn handle(&self, event: &UiEvent) {
218        let UiEvent::ContextMenuItem(item) = event else { return };
219        let Some(handler) = self.state.borrow().handlers.get(item).cloned() else { return };
220        match self.scope {
221            Some(scope) if scope.is_alive() => scope.with(|| handler()),
222            _ => handler(),
223        }
224    }
225}
226
227impl Default for ItemMenus {
228    fn default() -> ItemMenus {
229        ItemMenus::new()
230    }
231}
232
233struct Walk<'a> {
234    ids: &'a mut Vec<u32>,
235    position: usize,
236    new_id: &'a mut dyn FnMut() -> u32,
237    handlers: Vec<(u32, Handler)>,
238}
239
240impl Walk<'_> {
241    fn menu(&mut self, menu: &Menu) -> Option<MenuData> {
242        if !menu.visible.get() {
243            return None;
244        }
245        let mut entries = Vec::new();
246        self.entries(&menu.entries, &mut entries);
247        Some(MenuData { title: menu.title.get(), entries })
248    }
249
250    fn entries(&mut self, entries: &[Entry], out: &mut Vec<MenuEntry>) {
251        for entry in entries {
252            match entry {
253                Entry::Item(item) => {
254                    if !item.visible.get() {
255                        continue;
256                    }
257                    let id = self.next_id();
258                    self.handlers.push((id, item.select_handler()));
259                    out.push(MenuEntry::Item(MenuItemData {
260                        id,
261                        title: item.title.get(),
262                        shortcut: item.shortcut,
263                        enabled: item.enabled.get(),
264                        check: match &item.check {
265                            Mark::None => MenuCheck::None,
266                            Mark::Check(checked) => MenuCheck::Check(checked.get()),
267                            Mark::Radio(checked) => MenuCheck::Radio(checked.get()),
268                        },
269                        role: item.role,
270                    }));
271                }
272                Entry::Separator => out.push(MenuEntry::Separator),
273                Entry::Submenu(menu) => out.extend(self.menu(menu).map(MenuEntry::Submenu)),
274                Entry::Dynamic(children) => self.entries(&children(), out),
275            }
276        }
277    }
278
279    fn next_id(&mut self) -> u32 {
280        if self.position == self.ids.len() {
281            self.ids.push((self.new_id)());
282        }
283        self.position += 1;
284        self.ids[self.position - 1]
285    }
286}
287
288impl View for MenuBar {
289    /// A placeholder in the tree, which takes no room: the menus are the
290    /// window's, or the app's outside any window.
291    fn build(self, ui: &Ui) -> NodeId {
292        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
293        match inject::<CurrentWindow>() {
294            Some(CurrentWindow(window)) => ui.set_window_menu(window, self),
295            None => ui.set_menu(self),
296        }
297        placeholder
298    }
299}
300
301impl View for super::TrayIcon {
302    /// A placeholder in the tree, which takes no room: the icon is the
303    /// app's, in the platform's tray.
304    fn build(self, ui: &Ui) -> NodeId {
305        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
306        ui.set_tray(self);
307        placeholder
308    }
309}