kui_core/runtime/menubar_api.rs
1//! `Core`'s application menu bar: the declaration, the one open menu the
2//! drawn bar keeps, and the two doors a chosen item comes back through.
3//!
4//! The declaration is data and sticky, the way the window title is: a frame
5//! that declares none leaves the last one in force and a frame that
6//! declares an empty bar takes it away, so the driver diffs
7//! [`Core::menu_bar_revision`] rather than a tree.
8//!
9//! Where the platform owns a bar the driver hands the declaration over and
10//! reports back through [`Core::activate_menu_bar_item`]. Where it does not,
11//! [`crate::widgets::menu_bar`] draws it: its titles and its rows are
12//! ordinary nodes with ordinary click payloads, and this module *takes
13//! those events back* by key — recorded while building, never guessed at
14//! from a payload — exactly as `menu_api` does for the open context menu's
15//! rows. What reaches the app is one `{kind:"menu", role, item}`, the same
16//! event both menus have always posted.
17
18use crate::input::UiEvent;
19use crate::key::Key;
20use crate::menu::{MenuBar, MenuItem};
21use crate::runtime::Core;
22use crate::tree::OriginId;
23
24impl Core {
25 /// Declares the application menu for this frame.
26 ///
27 /// Sticky, and diffed: declaring the same bar again costs one
28 /// comparison and changes nothing, a different one bumps
29 /// [`Self::menu_bar_revision`] for the driver to notice, and an empty
30 /// [`MenuBar`] is how an app takes the bar away. A frame that says
31 /// nothing leaves the last declaration standing — which is what lets a
32 /// palette window declare no menu and leave the document window's bar
33 /// alone.
34 ///
35 /// Every item's accelerator is normalized on the way in: a portable
36 /// `"mod+s"` becomes the platform's own spelling (`"⌘S"`, `"Ctrl+S"`),
37 /// so the drawn bar and the platform's read the same and the platform's
38 /// can bind the key. A spelling kui cannot parse is left exactly as
39 /// written and drawn as written — an app's own shortcut is the app's.
40 pub fn declare_menu_bar(&mut self, bar: MenuBar) {
41 let bar = normalize(bar);
42 if self.menu_bar.as_ref() == Some(&bar) {
43 return;
44 }
45 // An open menu describes a bar that may no longer exist. Identity
46 // is the label at that index: an item list that changed under an
47 // open menu is ordinary (a row enabling, a setting checking), but a
48 // *different menu* at that index leaves the open index naming
49 // something the user never opened — and the row keys are derived
50 // from the index, so the next click would perform the new menu's
51 // item at that position.
52 let open_moved = self.menu_bar_open.is_some_and(|i| {
53 fn label(b: &MenuBar, i: usize) -> Option<&str> {
54 b.menus.get(i).map(|m| m.label.as_str())
55 }
56 self.menu_bar.as_ref().and_then(|old| label(old, i)) != label(&bar, i)
57 });
58 if open_moved {
59 self.menu_bar_open = None;
60 }
61 self.menu_bar = Some(bar);
62 self.menu_bar_origin = self.origin();
63 self.menu_bar_rev += 1;
64 }
65
66 /// The declaration in force, if any frame has made one.
67 pub fn menu_bar(&self) -> Option<&MenuBar> {
68 self.menu_bar.as_ref()
69 }
70
71 /// Bumped whenever the declaration changes. A driver keeps the number
72 /// it last applied and touches the platform only when they differ —
73 /// the menu-bar analogue of the title diff, and the reason re-declaring
74 /// an unchanged bar every frame costs nothing.
75 pub fn menu_bar_revision(&self) -> u64 {
76 self.menu_bar_rev
77 }
78
79 /// Tells the core that the platform owns the menu bar — macOS's, which
80 /// is not in any window. The drawn bar then
81 /// draws nothing, and the driver is the one that hands the declaration
82 /// over and reports what was chosen.
83 ///
84 /// Off by default, like [`Self::set_native_menus`]: a host that says
85 /// nothing draws its own bar, which is what every headless test and
86 /// every binding without a runner sees.
87 pub fn set_native_menu_bar(&mut self, on: bool) {
88 self.native_menu_bar = on;
89 }
90
91 /// Whether the platform said the menu bar is its.
92 pub fn native_menu_bar(&self) -> bool {
93 self.native_menu_bar
94 }
95
96 /// Which menu of the drawn bar is open, if any. Retained by the core
97 /// because it is the one thing the widget cannot derive from the frame
98 /// — and always `None` while the platform draws
99 /// the bar, since then the open menu is the platform's.
100 pub fn menu_bar_open(&self) -> Option<usize> {
101 self.menu_bar_open
102 }
103
104 /// Opens one of the drawn bar's menus, closes it (`None`), and is what
105 /// a press on a title goes through. Public because a keymap is as good
106 /// a reason to open the File menu as a click is; out of range closes.
107 pub fn set_menu_bar_open(&mut self, menu: Option<usize>) {
108 let menu = menu.filter(|i| {
109 self.menu_bar
110 .as_ref()
111 .and_then(|b| b.menus.get(*i))
112 .is_some_and(|m| m.enabled && !m.items.is_empty())
113 });
114 if menu == self.menu_bar_open {
115 return;
116 }
117 // Which editor the menu is about, remembered as the menu opens for
118 // the reason `open_menu` remembers it: the rows are focusable, so
119 // by the time Copy runs the field the user was in has lost focus.
120 //
121 // Only when there *is* one, and never `None` over an answer already
122 // recorded: a press on a title has moved focus to the title before
123 // this runs (`Core::note_menu_bar_editor` is where the field was
124 // caught), and hovering across to another title runs it again with
125 // focus inside the open menu. Either would otherwise erase the
126 // field the menu is about and leave Cut with nothing to cut.
127 if menu.is_some()
128 && let Some(editor) = self.edit.focused()
129 {
130 self.menu_editor = Some(editor);
131 }
132 self.menu_bar_open = menu;
133 }
134
135 /// The platform's menu bar reports that an item was chosen: the same
136 /// path a press on the drawn bar's row takes. The core performs the
137 /// standard roles it can, queues what the host must do
138 /// (`take_menu_actions`) and returns the events the app hears.
139 ///
140 /// An index past the end does nothing, which is what a host reporting a
141 /// row this build does not have should do.
142 pub fn activate_menu_bar_item(&mut self, menu: usize, item: usize) -> Vec<UiEvent> {
143 let mut out = Vec::new();
144 let Some(item) = self
145 .menu_bar
146 .as_ref()
147 .and_then(|b| b.item(menu, item))
148 .cloned()
149 else {
150 return out;
151 };
152 // Nothing displaced focus — the platform's menu bar is not in this
153 // window and takes none — so the editor is simply whichever one has
154 // it now.
155 self.menu_editor = self.edit.focused();
156 let (target, origin) = (self.menu_bar_target(), self.menu_bar_origin);
157 self.perform_menu_item(&item, target, origin, &mut out);
158 out
159 }
160
161 /// Where a menu-bar event lands: the bar's own root when one is drawn,
162 /// and the frame root when the platform draws it and there is no node.
163 fn menu_bar_target(&self) -> Key {
164 self.menu_bar_root.unwrap_or(Key::ROOT)
165 }
166
167 /// The drawn bar reports its root this frame (`widgets::menu_bar`):
168 /// where a menu-bar event lands (`menu_bar_target`). Its titles and
169 /// rows are known by their origin, not by key.
170 pub(crate) fn set_menu_bar_root(&mut self, root: Key) {
171 self.menu_bar_root = Some(root);
172 }
173
174 /// Filters the events one input produced: anything belonging to the
175 /// drawn bar is consumed and acted on — a title opens or closes its
176 /// menu, a row performs its item, a dismissal closes what is open — and
177 /// what the app hears instead is the item's own payload.
178 ///
179 /// Runs beside `consume_menu_events` on the way out of `handle_input`,
180 /// so a bar the app never declared can leak nothing and an app that
181 /// declared one never sees its plumbing.
182 pub(crate) fn consume_menu_bar_events(&mut self, out: &mut Vec<UiEvent>) {
183 if self.menu_bar_root.is_none() {
184 return;
185 }
186 // A `dismiss` is the bar's own: Escape, or a press outside it while
187 // a menu is open (the bar is the modal scope then, so its titles
188 // stay live and the app below does not).
189 let taken = Self::take_surface_events(out, OriginId::MENU_BAR);
190 let (title, row, dismissed) = (taken.title, taken.row, taken.dismissed);
191 if let Some(i) = title {
192 // A press on the open menu's own title closes it, which is
193 // what every menu bar does and what makes the title a toggle.
194 let next = (self.menu_bar_open != Some(i)).then_some(i);
195 self.set_menu_bar_open(next);
196 } else if let Some(i) = row {
197 let Some(menu) = self.menu_bar_open else {
198 return;
199 };
200 let item = self
201 .menu_bar
202 .as_ref()
203 .and_then(|b| b.item(menu, i))
204 .cloned();
205 self.set_menu_bar_open(None);
206 if let Some(item) = item {
207 let (target, origin) = (self.menu_bar_target(), self.menu_bar_origin);
208 self.perform_menu_item(&item, target, origin, out);
209 }
210 } else if dismissed {
211 self.set_menu_bar_open(None);
212 }
213 }
214
215 /// A press has landed on a node of the drawn bar: remember the editor
216 /// it is about *now*, because the press is what moves focus onto the
217 /// title and the menu does not open until the release.
218 ///
219 /// The truth at press time, `None` included — a menu opened with no
220 /// field focused is about no field, and must not inherit the one an
221 /// earlier menu was about.
222 pub(crate) fn note_menu_bar_editor(&mut self) {
223 self.menu_editor = self.edit.focused();
224 }
225}
226
227/// Rewrites every accelerator kui can parse into the platform's own
228/// spelling, and leaves the rest exactly as declared. Runs once per
229/// changed declaration and not per frame, which is why `declare_menu_bar`
230/// compares after normalizing rather than before.
231fn normalize(mut bar: MenuBar) -> MenuBar {
232 for menu in &mut bar.menus {
233 for item in &mut menu.items {
234 normalize_item(item);
235 }
236 }
237 bar
238}
239
240fn normalize_item(item: &mut MenuItem) {
241 let Some(accel) = &item.accel else { return };
242 if let Some(parsed) = crate::menu::Accel::parse(accel) {
243 item.accel = Some(parsed.display());
244 }
245}