1use std::cell::{Cell, RefCell};
10use std::collections::HashMap;
11use std::rc::Rc;
12
13day_reactive::tls_slots! {
14 menu;
15 static ACTIONS: RefCell<HashMap<u64, Rc<dyn Fn()>>> = RefCell::new(HashMap::new());
16 static NEXT_ID: Cell<u64> = const { Cell::new(1) };
17 static APP_MENU_MODEL: RefCell<Vec<day_spec::MenuItem>> = const { RefCell::new(Vec::new()) };
20 static APP_MENU_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
24 static DOCK_MENU_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
26 static DOCK_MENU_MODEL: RefCell<Vec<day_spec::MenuItem>> = const { RefCell::new(Vec::new()) };
29 static DOCK_MENU_SHOWN: Cell<bool> = const { Cell::new(false) };
31}
32
33pub fn reset_menus() {
38 ACTIONS.with(|a| a.borrow_mut().clear());
39 APP_MENU_MODEL.with(|m| m.borrow_mut().clear());
40 APP_MENU_IDS.with(|i| i.borrow_mut().clear());
41}
42
43pub fn rebind_action(from: u64, to: u64) {
52 if from == 0 || to == 0 || from == to {
53 return;
54 }
55 ACTIONS.with(|m| {
56 let mut m = m.borrow_mut();
57 if let Some(f) = m.remove(&from) {
58 m.insert(to, f);
59 }
60 });
61}
62
63pub(crate) fn forget_action(id: u64) {
65 ACTIONS.with(|m| {
66 m.borrow_mut().remove(&id);
67 });
68}
69
70pub fn register_menu_action(f: Rc<dyn Fn()>) -> u64 {
71 let id = next_action_id();
72 ACTIONS.with(|m| m.borrow_mut().insert(id, f));
73 id
74}
75
76pub fn register_scoped_menu_action(f: Rc<dyn Fn()>) -> u64 {
86 let id = register_menu_action(f);
87 day_reactive::Scope::current().on_cleanup(move || {
88 ACTIONS.with(|m| {
89 m.borrow_mut().remove(&id);
90 });
91 });
92 id
93}
94
95pub(crate) fn next_action_id() -> u64 {
98 NEXT_ID.with(|c| {
99 let id = c.get();
100 c.set(id.wrapping_add(1).max(1));
101 id
102 })
103}
104
105pub fn dispatch_menu_action(id: u64) {
108 let id = crate::toolbar::resolve_slot(id);
110 let f = ACTIONS.with(|m| m.borrow().get(&id).cloned());
111 if let Some(f) = f {
112 day_reactive::batch(|| f());
113 return;
114 }
115 log::warn!(
120 "menu action {id} has no handler — the build that registered it was disposed and \
121 whatever is still wired to it (an app menu, a context menu, a nav-bar action) was not \
122 updated. The native side needs the NEW id."
123 );
124}
125
126fn same_shape(a: &[day_spec::MenuItem], b: &[day_spec::MenuItem]) -> bool {
133 a.len() == b.len() && a.iter().zip(b).all(|(x, y)| shape_of(x) == shape_of(y))
134}
135
136fn shape_of(item: &day_spec::MenuItem) -> day_spec::MenuItem {
137 let mut i = item.clone();
138 blank_ids(std::slice::from_mut(&mut i));
139 i
140}
141
142fn blank_ids(items: &mut [day_spec::MenuItem]) {
143 for item in items {
144 match item {
145 day_spec::MenuItem::Action { action, .. } => *action = 0,
146 day_spec::MenuItem::Submenu { items, .. } => blank_ids(items),
147 day_spec::MenuItem::Separator => {}
148 }
149 }
150}
151
152fn rebind_menu(next: &mut [day_spec::MenuItem], prev: &[day_spec::MenuItem]) {
154 for (new, old) in next.iter_mut().zip(prev) {
155 match (new, old) {
156 (
157 day_spec::MenuItem::Action { action: new_id, .. },
158 day_spec::MenuItem::Action { action: old_id, .. },
159 ) => {
160 if new_id != old_id {
161 rebind_action(*new_id, *old_id);
162 *new_id = *old_id;
163 }
164 }
165 (
166 day_spec::MenuItem::Submenu { items: n, .. },
167 day_spec::MenuItem::Submenu { items: o, .. },
168 ) => rebind_menu(n, o),
169 _ => {}
170 }
171 }
172}
173
174pub fn set_app_menu(items: Vec<day_spec::MenuItem>) {
175 let items = inject_preferences(items);
176 let mut items = inject_about(items);
177
178 let unchanged = APP_MENU_MODEL.with(|m| same_shape(&m.borrow(), &items));
184 if unchanged {
185 let installed = APP_MENU_MODEL.with(|m| m.borrow().clone());
186 rebind_menu(&mut items, &installed);
187 APP_MENU_MODEL.with(|m| *m.borrow_mut() = items);
188 return;
189 }
190
191 let new_ids = collect_action_ids(&items);
192 let durable = [
195 crate::windows::preferences_action_id(),
196 crate::windows::about_action_id(),
197 crate::windows::check_for_updates_action_id(),
198 crate::windows::new_window_action_id(),
199 crate::undo_action_id(false),
200 crate::undo_action_id(true),
201 crate::edit_action_id(day_spec::EditOp::Cut),
202 crate::edit_action_id(day_spec::EditOp::Copy),
203 crate::edit_action_id(day_spec::EditOp::Paste),
204 crate::edit_action_id(day_spec::EditOp::SelectAll),
205 ];
206 let stale: Vec<u64> = APP_MENU_IDS.with(|ids| {
207 ids.borrow()
208 .iter()
209 .copied()
210 .filter(|id| !new_ids.contains(id) && !durable.contains(id))
211 .collect()
212 });
213 ACTIONS.with(|m| {
214 let mut m = m.borrow_mut();
215 for id in stale {
216 m.remove(&id);
217 }
218 });
219 APP_MENU_IDS.with(|ids| *ids.borrow_mut() = new_ids);
220 APP_MENU_MODEL.with(|m| (*m.borrow_mut()).clone_from(&items));
221 crate::with_tree(|t| t.set_app_menu(items));
222}
223
224pub fn set_dock_menu(items: Vec<day_spec::MenuItem>) {
229 let new_ids = collect_action_ids(&items);
230 let stale: Vec<u64> = DOCK_MENU_IDS.with(|ids| {
231 ids.borrow()
232 .iter()
233 .copied()
234 .filter(|id| !new_ids.contains(id))
235 .collect()
236 });
237 ACTIONS.with(|m| {
238 let mut m = m.borrow_mut();
239 for id in stale {
240 m.remove(&id);
241 }
242 });
243 DOCK_MENU_IDS.with(|ids| *ids.borrow_mut() = new_ids);
244 DOCK_MENU_MODEL.with(|m| *m.borrow_mut() = items);
245 install_dock_menu();
246}
247
248pub(crate) fn install_dock_menu() {
252 let mut items = crate::shortcuts::shortcut_menu_items();
253 let app = DOCK_MENU_MODEL.with(|m| m.borrow().clone());
254 if !items.is_empty() && !app.is_empty() {
255 items.push(day_spec::MenuItem::Separator);
256 }
257 items.extend(app);
258 if items.is_empty() && !DOCK_MENU_SHOWN.with(std::cell::Cell::get) {
260 return;
261 }
262 DOCK_MENU_SHOWN.with(|c| c.set(!items.is_empty()));
263 crate::with_tree(|t| t.set_dock_menu(&items));
264}
265
266#[must_use]
269pub fn app_menu_model() -> Vec<day_spec::MenuItem> {
270 APP_MENU_MODEL.with(|m| m.borrow().clone())
271}
272
273#[must_use]
275pub fn app_menu_installed() -> bool {
276 APP_MENU_MODEL.with(|m| !m.borrow().is_empty())
277}
278
279#[must_use]
286pub fn has_app_menu() -> bool {
287 APP_MENU_MODEL.with(|m| !m.borrow().is_empty())
288}
289
290pub(crate) fn reinstall_app_menu() {
291 let items = APP_MENU_MODEL.with(|m| m.borrow().clone());
292 if !items.is_empty() {
293 set_app_menu(items);
294 }
295}
296
297fn inject_preferences(mut items: Vec<day_spec::MenuItem>) -> Vec<day_spec::MenuItem> {
304 fn rewrite(items: &mut [day_spec::MenuItem], prefs_id: u64) -> bool {
305 use day_spec::MenuItem as M;
306 for it in items.iter_mut() {
307 match it {
308 M::Action { action, role, .. }
309 if *role == Some(day_spec::MenuRole::Preferences) =>
310 {
311 if *action == 0 {
312 *action = prefs_id;
313 }
314 return true;
315 }
316 M::Submenu { items, .. } => {
317 if rewrite(items, prefs_id) {
318 return true;
319 }
320 }
321 _ => {}
322 }
323 }
324 false
325 }
326 let prefs_id = crate::windows::preferences_action_id();
327 if prefs_id == 0 {
328 return items;
329 }
330 if rewrite(&mut items, prefs_id) {
331 return items;
332 }
333 let item = day_spec::MenuItem::Action {
334 id: None,
335 action: prefs_id,
336 label: String::new(),
339 shortcut: Some(day_spec::Shortcut::primary(",")),
340 enabled: true,
341 checked: None,
342 role: Some(day_spec::MenuRole::Preferences),
343 icon: None,
344 };
345 if let Some(day_spec::MenuItem::Submenu { items: first, .. }) = items
346 .iter_mut()
347 .find(|it| matches!(it, day_spec::MenuItem::Submenu { .. }))
348 {
349 first.push(day_spec::MenuItem::Separator);
350 first.push(item);
351 } else {
352 items.push(item);
353 }
354 items
355}
356
357fn inject_about(mut items: Vec<day_spec::MenuItem>) -> Vec<day_spec::MenuItem> {
365 fn rewrite(items: &mut [M], role: R, id: u64) -> bool {
367 let mut found = false;
368 for it in items.iter_mut() {
369 match it {
370 M::Action {
371 action, role: r, ..
372 } if *r == Some(role) => {
373 if *action == 0 {
374 *action = id;
375 }
376 found = true;
377 }
378 M::Submenu { items, .. } => {
379 found |= rewrite(items, role, id);
380 }
381 _ => {}
382 }
383 }
384 found
385 }
386 use day_spec::{MenuItem as M, MenuRole as R};
387 let about_id = crate::windows::about_action_id();
388 let updates_id = crate::windows::check_for_updates_action_id();
389 if about_id == 0 && updates_id == 0 {
390 return items;
391 }
392 let has_about = rewrite(&mut items, R::About, about_id);
393 let has_updates = rewrite(&mut items, R::CheckForUpdates, updates_id);
394 let act = |role: R, action: u64| M::Action {
395 id: None,
396 action,
397 label: String::new(),
399 shortcut: None,
400 enabled: true,
401 checked: None,
402 role: Some(role),
403 icon: None,
404 };
405 let mut missing = Vec::new();
406 if about_id != 0 && !has_about {
407 missing.push(act(R::About, about_id));
408 }
409 if updates_id != 0 && !has_updates {
410 missing.push(act(R::CheckForUpdates, updates_id));
411 }
412 if missing.is_empty() {
413 return items;
414 }
415 if let Some(M::Submenu { items: help, .. }) = items.iter_mut().find(|it| {
417 matches!(it, M::Submenu { role, label, .. }
418 if *role == Some(day_spec::MenuBarRole::Help) || *label == day_localization::t(day_localization::key::day_help))
419 }) {
420 help.extend(missing);
421 }
422 items
423}
424
425pub(crate) fn collect_ids(items: &[day_spec::MenuItem]) -> Vec<u64> {
427 collect_action_ids(items)
428}
429
430pub(crate) fn forget_actions(ids: &[u64]) {
432 ACTIONS.with(|m| {
433 let mut m = m.borrow_mut();
434 for id in ids {
435 m.remove(id);
436 }
437 });
438}
439
440fn collect_action_ids(items: &[day_spec::MenuItem]) -> Vec<u64> {
441 fn walk(items: &[day_spec::MenuItem], ids: &mut Vec<u64>) {
442 for it in items {
443 match it {
444 day_spec::MenuItem::Action { action, .. } if *action != 0 => ids.push(*action),
445 day_spec::MenuItem::Submenu { items, .. } => walk(items, ids),
446 _ => {}
447 }
448 }
449 }
450 let mut ids = Vec::new();
451 walk(items, &mut ids);
452 ids
453}
454
455#[derive(Clone, Copy, Debug, PartialEq, Eq)]
461#[non_exhaustive]
462pub enum MenuBarStyle {
463 Macos,
465 Gnome,
467 Kde,
469 Windows,
471}
472
473impl MenuBarStyle {
474 #[must_use]
476 pub fn bar_order(
477 self,
478 ) -> (
479 &'static [day_spec::MenuBarRole],
480 &'static [day_spec::MenuBarRole],
481 ) {
482 use day_spec::MenuBarRole as B;
483 const LEADING: &[day_spec::MenuBarRole] = &[B::File, B::Edit, B::View];
484 match self {
485 MenuBarStyle::Macos => (LEADING, &[B::Window, B::Help]),
487 MenuBarStyle::Gnome | MenuBarStyle::Windows => (LEADING, &[B::Help]),
488 MenuBarStyle::Kde => (LEADING, &[B::Settings, B::Help]),
489 }
490 }
491
492 #[must_use]
501 pub fn stock(self, role: day_spec::MenuBarRole) -> Option<day_spec::MenuItem> {
502 use day_spec::{MenuBarRole as B, MenuItem as MI, MenuRole as R};
503 let act = |r: R| MI::Action {
507 id: None,
508 action: match r {
509 R::About => crate::windows::about_action_id(),
510 R::CheckForUpdates => crate::windows::check_for_updates_action_id(),
511 _ => 0,
512 },
513 label: String::new(),
514 shortcut: None,
515 enabled: true,
516 checked: None,
517 role: Some(r),
518 icon: None,
519 };
520 let sub = |key: &str, items: Vec<MI>| {
521 Some(MI::Submenu {
522 label: day_localization::t(key),
523 items,
524 role: None,
525 })
526 };
527 match role {
528 B::Edit => sub(
529 "day_edit",
530 vec![
531 act(R::Undo),
532 act(R::Redo),
533 MI::Separator,
534 act(R::Cut),
535 act(R::Copy),
536 act(R::Paste),
537 act(R::Delete),
538 act(R::SelectAll),
539 ],
540 ),
541 B::View => sub("day_view", vec![act(R::Fullscreen)]),
542 B::Help => {
545 if self == MenuBarStyle::Macos {
546 sub("day_help", Vec::new())
547 } else {
548 let mut items = vec![act(R::About)];
549 if crate::windows::check_for_updates_action_id() != 0 {
550 items.push(act(R::CheckForUpdates));
551 }
552 sub("day_help", items)
553 }
554 }
555 _ => None,
556 }
557 }
558}
559
560#[must_use]
563pub fn standard_menu_bar_for(
564 style: MenuBarStyle,
565 app_menus: Vec<day_spec::MenuItem>,
566) -> Vec<day_spec::MenuItem> {
567 let (leading, trailing) = style.bar_order();
568 standard_menu_bar(app_menus, leading, trailing, |r| style.stock(r))
569}
570
571pub fn standard_menu_bar(
578 app_menus: Vec<day_spec::MenuItem>,
579 leading: &[day_spec::MenuBarRole],
580 trailing: &[day_spec::MenuBarRole],
581 stock: impl Fn(day_spec::MenuBarRole) -> Option<day_spec::MenuItem>,
582) -> Vec<day_spec::MenuItem> {
583 use day_spec::MenuBarRole as R;
584 let _ = R::File;
585
586 let mut claimed: Vec<(R, day_spec::MenuItem)> = Vec::new();
587 let mut own: Vec<day_spec::MenuItem> = Vec::new();
588 for item in app_menus {
589 match &item {
590 day_spec::MenuItem::Submenu { role: Some(r), .. } => claimed.push((*r, item)),
591 _ => own.push(item),
592 }
593 }
594 let mut out: Vec<day_spec::MenuItem> = leading
595 .iter()
596 .filter_map(|r| take_slot(*r, &mut claimed, &mut own, &stock))
597 .collect();
598 let trailing_menus: Vec<day_spec::MenuItem> = trailing
599 .iter()
600 .filter_map(|r| take_slot(*r, &mut claimed, &mut own, &stock))
601 .collect();
602 out.append(&mut own);
603 out.extend(trailing_menus);
604 out.extend(claimed.into_iter().map(|(_, m)| m));
606 out
607}
608
609fn take_slot(
618 role: day_spec::MenuBarRole,
619 claimed: &mut Vec<(day_spec::MenuBarRole, day_spec::MenuItem)>,
620 own: &mut Vec<day_spec::MenuItem>,
621 stock: &impl Fn(day_spec::MenuBarRole) -> Option<day_spec::MenuItem>,
622) -> Option<day_spec::MenuItem> {
623 if let Some(i) = claimed.iter().position(|(cr, _)| *cr == role) {
624 return Some(claimed.remove(i).1);
625 }
626 if let Some(title) = role_title(role)
631 && let Some(i) = own
632 .iter()
633 .position(|m| submenu_label(m).is_some_and(|l| menu_titles_match(l, &title)))
634 {
635 return Some(own.remove(i));
636 }
637 stock(role)
638}
639
640fn role_title(role: day_spec::MenuBarRole) -> Option<String> {
643 use day_spec::MenuBarRole as B;
644 let key = match role {
645 B::File => "day_file",
646 B::Edit => "day_edit",
647 B::View => "day_view",
648 B::Window => "day_window",
649 B::Help => "day_help",
650 _ => return None,
651 };
652 Some(day_localization::t(key))
653}
654
655fn submenu_label(item: &day_spec::MenuItem) -> Option<&str> {
656 match item {
657 day_spec::MenuItem::Submenu { label, .. } => Some(label),
658 _ => None,
659 }
660}
661
662fn menu_titles_match(a: &str, b: &str) -> bool {
667 let norm = |s: &str| s.replace('&', "").trim().to_lowercase();
668 norm(a) == norm(b)
669}
670
671#[cfg(test)]
672mod tests {
673 use super::*;
674 use std::cell::Cell;
675
676 use day_spec::MenuBarRole as BR;
677 const MAC_LEADING: &[BR] = &[BR::File, BR::Edit, BR::View];
678 const MAC_TRAILING: &[BR] = &[BR::Window, BR::Help];
679
680 fn sub(label: &str, role: Option<day_spec::MenuBarRole>) -> day_spec::MenuItem {
681 day_spec::MenuItem::Submenu {
682 label: label.into(),
683 items: Vec::new(),
684 role,
685 }
686 }
687
688 fn labels(items: &[day_spec::MenuItem]) -> Vec<String> {
689 items
690 .iter()
691 .map(|i| match i {
692 day_spec::MenuItem::Submenu { label, .. } => label.clone(),
693 _ => String::new(),
694 })
695 .collect()
696 }
697
698 #[test]
700 fn stock_menus_fill_the_slots_an_app_left_open() {
701 use day_spec::MenuBarRole as R;
702 let out = standard_menu_bar(
703 vec![sub("Go", None), sub("Article", None)],
704 MAC_LEADING,
705 MAC_TRAILING,
706 |r| {
707 Some(sub(
708 match r {
709 R::File => "File",
710 R::Edit => "Edit",
711 R::View => "View",
712 R::Window => "Window",
713 R::Help => "Help",
714 _ => "?",
715 },
716 Some(r),
717 ))
718 },
719 );
720 assert_eq!(
721 labels(&out),
722 ["File", "Edit", "View", "Go", "Article", "Window", "Help"]
723 );
724 }
725
726 #[test]
731 fn an_untagged_menu_named_like_a_stock_one_takes_its_slot() {
732 let bar = standard_menu_bar(
733 vec![sub("File", None), sub("Edit", None), sub("View", None)],
734 &[BR::File, BR::Edit, BR::View],
735 &[BR::Window, BR::Help],
736 |r| match r {
737 BR::File => None,
739 BR::Edit => Some(sub("Edit", Some(BR::Edit))),
740 BR::View => Some(sub("View", Some(BR::View))),
741 BR::Window => Some(sub("Window", Some(BR::Window))),
742 _ => Some(sub("Help", Some(BR::Help))),
743 },
744 );
745 assert_eq!(
746 labels(&bar),
747 ["File", "Edit", "View", "Window", "Help"],
748 "a hand-built standard menu must not double the stock one"
749 );
750 }
751
752 #[test]
754 fn menu_titles_match_across_mnemonics_and_case() {
755 assert!(menu_titles_match("&View", "View"));
756 assert!(menu_titles_match("edit ", "Edit"));
757 assert!(menu_titles_match("Ansicht", "ansicht"));
758 assert!(!menu_titles_match("Edit", "View"));
759 }
760
761 #[test]
764 fn a_claimed_slot_replaces_the_stock_menu_in_place() {
765 use day_spec::MenuBarRole as R;
766 let out = standard_menu_bar(
767 vec![sub("My File", Some(R::File)), sub("Go", None)],
768 MAC_LEADING,
769 MAC_TRAILING,
770 |r| Some(sub("stock", Some(r))),
771 );
772 let l = labels(&out);
773 assert_eq!(l[0], "My File", "the app's File sits in the File slot");
774 assert_eq!(l.iter().filter(|s| *s == "My File").count(), 1);
775 assert!(!l.contains(&"File".to_string()));
776 assert_eq!(l[3], "Go", "app menus still follow the leading slots");
777 }
778
779 #[test]
782 fn each_platform_gets_its_own_bar_order() {
783 use day_spec::MenuBarRole as R;
784 let stock = |r: R| {
786 let label = match r {
787 R::Edit => "Edit",
788 R::View => "View",
789 R::Settings => "Settings",
790 R::Help => "Help",
791 R::Window => "Window",
792 _ => return None,
793 };
794 Some(sub(label, Some(r)))
795 };
796 let kde = standard_menu_bar(
797 vec![sub("Go", None)],
798 &[R::File, R::Edit, R::View],
799 &[R::Settings, R::Help],
800 stock,
801 );
802 assert_eq!(labels(&kde), ["Edit", "View", "Go", "Settings", "Help"]);
803
804 let gnome = standard_menu_bar(
805 vec![sub("Go", None)],
806 &[R::File, R::Edit, R::View],
807 &[R::Help],
808 stock,
809 );
810 assert_eq!(labels(&gnome), ["Edit", "View", "Go", "Help"]);
811 assert!(!labels(&gnome).contains(&"Window".to_string()));
812 }
813
814 #[test]
816 fn a_slot_with_no_stock_menu_is_omitted() {
817 use day_spec::MenuBarRole as R;
818 let out = standard_menu_bar(vec![sub("Go", None)], MAC_LEADING, MAC_TRAILING, |r| {
819 (r == R::Edit).then(|| sub("Edit", Some(r)))
820 });
821 assert_eq!(labels(&out), ["Edit", "Go"]);
822 }
823
824 #[test]
825 fn dispatch_runs_the_registered_action_by_id() {
826 thread_local! { static FIRED: Cell<u32> = const { Cell::new(0) }; }
827 let id = register_menu_action(Rc::new(|| FIRED.with(|c| c.set(c.get() + 1))));
828 assert_ne!(
829 id, 0,
830 "ids are nonzero so role-only items (id 0) never dispatch"
831 );
832 assert_eq!(FIRED.with(Cell::get), 0);
833
834 dispatch_menu_action(id);
835 assert_eq!(FIRED.with(Cell::get), 1, "the closure ran exactly once");
836
837 let id2 = register_menu_action(Rc::new(|| {}));
839 assert_ne!(id, id2);
840
841 dispatch_menu_action(0);
843 dispatch_menu_action(u64::MAX);
844 assert_eq!(FIRED.with(Cell::get), 1);
845 }
846
847 #[test]
848 fn scoped_action_is_reclaimed_when_its_scope_dies() {
849 let scope = day_reactive::Scope::child();
850 let id = scope.enter(|| register_scoped_menu_action(Rc::new(|| {})));
851 assert!(
852 ACTIONS.with(|m| m.borrow().contains_key(&id)),
853 "registered while the scope is alive"
854 );
855 scope.dispose();
856 assert!(
857 !ACTIONS.with(|m| m.borrow().contains_key(&id)),
858 "disposal must reclaim the closure — this is the remount leak"
859 );
860 dispatch_menu_action(id); }
862}