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};
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    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 `MenuButton` its menu, as [`Prop::Menu`], as a context menu is
61/// given (see `install_context_menu`). The menu's title isn't shown.
62#[doc(hidden)]
63pub fn install_button_menu(ui: &Ui, id: NodeId, menu: Menu) {
64    install_menu(ui, id, menu, Prop::Menu, |event| match event {
65        UiEvent::MenuItem(item) => Some(*item),
66        _ => None,
67    });
68}
69
70fn install_menu(
71    ui: &Ui,
72    id: NodeId,
73    menu: Menu,
74    prop: fn(Vec<MenuEntry>) -> Prop,
75    chosen_item: fn(&UiEvent) -> Option<u32>,
76) {
77    let handlers: Rc<RefCell<HashMap<u32, Handler>>> = Rc::default();
78    // As menu bars' handlers do, they run in the scope that built the menu.
79    let scope = mitsuami_reactive::Owner::current();
80    let chosen = handlers.clone();
81    ui.on_event(id, move |event| {
82        let Some(item) = chosen_item(event) else { return };
83        let item = &item;
84        let Some(handler) = chosen.borrow().get(item).cloned() else { return };
85        match scope {
86            Some(scope) if scope.is_alive() => scope.with(|| handler()),
87            _ => handler(),
88        }
89    });
90    let ui = ui.clone();
91    let (mut ids, mut next_id) = (Vec::new(), 0);
92    mitsuami_reactive::effect(move || {
93        let (entries, collected) = menu.collect_entries(&mut ids, &mut || {
94            next_id += 1;
95            next_id
96        });
97        *handlers.borrow_mut() = collected.into_iter().collect();
98        ui.set_prop(id, prop(entries));
99    });
100}
101
102/// The context menus of items a node shows as data, as a `Sidebar` shows
103/// its items: each item's menu as data, sent with the item, and the
104/// handlers of all of them, which the node's `ContextMenuItem` runs. Ids
105/// are unique across the items' menus, and stay the same while their
106/// structure does, as a context menu's do.
107#[doc(hidden)]
108#[derive(Clone)]
109pub struct ItemMenus {
110    state: Rc<RefCell<ItemMenusState>>,
111    /// As menu bars' handlers do, they run in the scope that built them.
112    scope: Option<mitsuami_reactive::Owner>,
113}
114
115#[derive(Default)]
116struct ItemMenusState {
117    ids: Vec<u32>,
118    next_id: u32,
119    handlers: HashMap<u32, Handler>,
120}
121
122impl ItemMenus {
123    pub fn new() -> ItemMenus {
124        ItemMenus { state: Rc::default(), scope: mitsuami_reactive::Owner::current() }
125    }
126
127    /// Each menu's entries as data (empty for an item without one),
128    /// reading their reactive parts, in an effect that sends them.
129    pub fn collect(&self, menus: &[Option<&Menu>]) -> Vec<Vec<MenuEntry>> {
130        let mut state = self.state.borrow_mut();
131        let ItemMenusState { ids, next_id, handlers } = &mut *state;
132        let mut new_id = || {
133            *next_id += 1;
134            *next_id
135        };
136        let mut walk = Walk { ids, position: 0, new_id: &mut new_id, handlers: Vec::new() };
137        let entries = menus
138            .iter()
139            .map(|menu| {
140                let mut out = Vec::new();
141                if let Some(menu) = menu {
142                    walk.entries(&menu.entries, &mut out);
143                }
144                out
145            })
146            .collect();
147        *handlers = walk.handlers.into_iter().collect();
148        entries
149    }
150
151    /// Runs the handler of the item `ContextMenuItem` names, if any.
152    pub fn handle(&self, event: &UiEvent) {
153        let UiEvent::ContextMenuItem(item) = event else { return };
154        let Some(handler) = self.state.borrow().handlers.get(item).cloned() else { return };
155        match self.scope {
156            Some(scope) if scope.is_alive() => scope.with(|| handler()),
157            _ => handler(),
158        }
159    }
160}
161
162impl Default for ItemMenus {
163    fn default() -> ItemMenus {
164        ItemMenus::new()
165    }
166}
167
168struct Walk<'a> {
169    ids: &'a mut Vec<u32>,
170    position: usize,
171    new_id: &'a mut dyn FnMut() -> u32,
172    handlers: Vec<(u32, Handler)>,
173}
174
175impl Walk<'_> {
176    fn menu(&mut self, menu: &Menu) -> Option<MenuData> {
177        if !menu.visible.get() {
178            return None;
179        }
180        let mut entries = Vec::new();
181        self.entries(&menu.entries, &mut entries);
182        Some(MenuData { title: menu.title.get(), entries })
183    }
184
185    fn entries(&mut self, entries: &[Entry], out: &mut Vec<MenuEntry>) {
186        for entry in entries {
187            match entry {
188                Entry::Item(item) => {
189                    if !item.visible.get() {
190                        continue;
191                    }
192                    let id = self.next_id();
193                    self.handlers.push((id, item.select_handler()));
194                    out.push(MenuEntry::Item(MenuItemData {
195                        id,
196                        title: item.title.get(),
197                        shortcut: item.shortcut,
198                        enabled: item.enabled.get(),
199                        check: match &item.check {
200                            Mark::None => MenuCheck::None,
201                            Mark::Check(checked) => MenuCheck::Check(checked.get()),
202                            Mark::Radio(checked) => MenuCheck::Radio(checked.get()),
203                        },
204                        role: item.role,
205                    }));
206                }
207                Entry::Separator => out.push(MenuEntry::Separator),
208                Entry::Submenu(menu) => out.extend(self.menu(menu).map(MenuEntry::Submenu)),
209                Entry::Dynamic(children) => self.entries(&children(), out),
210            }
211        }
212    }
213
214    fn next_id(&mut self) -> u32 {
215        if self.position == self.ids.len() {
216            self.ids.push((self.new_id)());
217        }
218        self.position += 1;
219        self.ids[self.position - 1]
220    }
221}
222
223impl View for MenuBar {
224    /// A placeholder in the tree, which takes no room: the menus are the
225    /// window's, or the app's outside any window.
226    fn build(self, ui: &Ui) -> NodeId {
227        let placeholder = ui.create(WidgetKind::Fragment, Vec::new());
228        match inject::<CurrentWindow>() {
229            Some(CurrentWindow(window)) => ui.set_window_menu(window, self),
230            None => ui.set_menu(self),
231        }
232        placeholder
233    }
234}