Skip to main content

day_core/
menu.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Menu action dispatch (§ menus). The model ([`day_spec::MenuItem`]) is toolkit-neutral and carries
5//! only ids for its actions; the closures live here, keyed by id. A backend fires
6//! `Event::MenuAction(id)` when a native item is chosen; the event pump routes it to
7//! [`dispatch_menu_action`], which runs the app's closure. Ids are process-unique and monotonic.
8
9use 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    /// The app menu as last installed (post-injection). The dayscript `menu:` step
18    /// matches against it, and late `register_preferences` re-forwards it.
19    static APP_MENU_MODEL: RefCell<Vec<day_spec::MenuItem>> = const { RefCell::new(Vec::new()) };
20    /// The action ids the current app menu registered, so replacing the menu (the reactive
21    /// re-lower on a locale change) can drop the stale closures without touching context
22    /// menus, which share the `ACTIONS` map.
23    static APP_MENU_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
24    /// The dispatch ids the installed Dock menu holds, swept on the next install.
25    static DOCK_MENU_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
26    /// The app's own Dock menu entries, kept so a launch-time install can put them back after
27    /// the shortcuts.
28    static DOCK_MENU_MODEL: RefCell<Vec<day_spec::MenuItem>> = const { RefCell::new(Vec::new()) };
29    /// Whether the toolkit currently holds a non-empty Dock menu.
30    static DOCK_MENU_SHOWN: Cell<bool> = const { Cell::new(false) };
31}
32
33/// Forget every menu action and the last-installed app menu: a re-mount (docs/settings.md
34/// "Appearance on Android"). The closures a previous mount registered capture that mount's
35/// reactive graph, which has just been disposed; keeping them would leave the menu bar invoking
36/// a dead tree.
37pub 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
43/// Register an app closure for a menu item and return its dispatch id (nonzero). The `day-pieces`
44/// menu builder calls this while lowering a menu tree to the [`day_spec::MenuItem`] model.
45/// Move the closure registered under `from` onto `to`, dropping `from`.
46///
47/// Used when an app-menu install turns out to be the same menu with new closures: the native
48/// side keeps dispatching the ids it already has, and this points them at the current handlers.
49/// (Toolbars never need it: their items dispatch through stable slot ids, see
50/// `day_core::toolbar`.)
51pub 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
63/// Drop the closure registered under `id`: a toolbar item's, once no contribution carries it.
64pub(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
76/// Register an app closure whose lifetime is tied to the current scope: the id is dropped
77/// from the dispatch map when that scope is disposed. This is the registrar for closures
78/// owned by a piece build (context menus, nav-row menus, nav `bar_action`), which are
79/// re-registered on every rebuild; without the cleanup each remount leaks the previous
80/// build's closure (and whatever app state it captured) for the process lifetime.
81///
82/// The app menu and toolbars stay on plain [`register_menu_action`]: their ids are managed
83/// by shape-rebinding ([`rebind_action`]) and toolbar slots plus explicit sweeps, and a scope cleanup firing
84/// after a rebind would remove an id the platform still dispatches.
85pub 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
95/// The next dispatch id (nonzero, monotonic). Toolbar value callbacks draw from this same
96/// counter (docs/toolbars.md) so a toolbar id can never collide with a menu id.
97pub(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
105/// Run the closure registered for `id` (no-op if none). Called by the event pump on
106/// `Event::MenuAction`. Runs inside a reactive batch so multiple signal writes coalesce.
107pub fn dispatch_menu_action(id: u64) {
108    // A toolbar button or pull-down entry carries its bar's stable slot id (docs/toolbars.md).
109    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    // An id with no closure means something native is still wired to an action whose scope has
116    // been disposed: a menu or a nav-bar button that draws normally and does nothing when
117    // pressed. Silent before, and undiagnosable from the outside: the press produces no event,
118    // no log line, no visible change.
119    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
126/// Set the application menu (menu bar / app-bar overflow / iPad main menu). Retains the
127/// model (post-injection, [`app_menu_model`]), injects the auto Preferences item when one
128/// is registered (docs/windows.md), drops the previous app menu's action closures (context
129/// menus share the map and are untouched), and forwards to the backend.
130/// Whether two menu models describe the same menu (labels, shortcuts, roles, enablement and
131/// nesting), ignoring the action ids, which are re-registered on every build.
132fn 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
152/// Move `next`'s closures onto the ids `prev` already published to the platform.
153fn 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    // The same concern the toolbar has (docs/toolbars.md): an app declares its menu inside the
179    // page build, so every route change
180    // re-installs the same menu with freshly registered closures. Rebuilding the native menu bar
181    // for that is churn at best, and on macOS it closes a menu the user has open, so a menu
182    // that differs only in its action ids rebinds onto the ids the platform already holds.
183    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    // The prefs/new-window/undo dispatch ids are registered outside menu lowering (by
193    // `day::register_*` and `undo_action_id`) and outlive any menu install; never sweep them.
194    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
224/// Install the app's Dock menu (docs/menus.md "Dock menu"): `items` go above the app's
225/// `[[shortcuts]]` and the system's own items when the user right-clicks the Dock icon
226/// (`Cap::DockMenu`, macOS). An empty vec leaves only the shortcuts. Replacing the menu drops the
227/// previous install's action closures.
228pub 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
248/// Send the Dock menu to the toolkit: the app's launcher shortcuts first, as the platform's own
249/// apps list their quick actions, then the app's `dock_menu` entries. Called at launch, so the
250/// shortcuts are there before the app installs anything, and on every `set_dock_menu`.
251pub(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    // Nothing to show and nothing shown: leave the toolkit alone (most apps never have a menu).
259    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/// The app menu as last installed (post-injection). The dayscript `menu:` step walks it to
267/// resolve an item's dispatch id; backends re-read it on late preferences registration.
268#[must_use]
269pub fn app_menu_model() -> Vec<day_spec::MenuItem> {
270    APP_MENU_MODEL.with(|m| m.borrow().clone())
271}
272
273/// Whether any app menu was installed (an empty model = the backend default menu is up).
274#[must_use]
275pub fn app_menu_installed() -> bool {
276    APP_MENU_MODEL.with(|m| !m.borrow().is_empty())
277}
278
279/// Re-forward the retained model through the injection pass: the self-heal for
280/// `register_preferences` running after `app_menu` (docs/menus.md ordering note).
281/// Did the app install a menu model of its own (`app_menu`)? `false` means it is running on the
282/// backend's default menu bar, which the backend builds before `root()` runs, so a backend that
283/// puts registration-dependent items there (Settings…, File ▸ New Window) has to rebuild it once
284/// the app's registrations are in. day-toolkit-appkit does exactly that.
285#[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
297/// Inject the auto Settings…/Preferences item (docs/windows.md): when a preferences piece
298/// is registered and the model carries an inert `role(Preferences)` item (id 0), rewrite
299/// its id to the registered action; when the model has no Preferences item at all, append
300/// `separator + item` to the first top-level submenu (the File menu by convention). An
301/// app-supplied `.action` (nonzero id) always wins. Backends give the item its platform
302/// placement (macOS hoists it into the App menu) and label fallback.
303fn 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        // Empty label: each backend falls back to its localized role label
337        // ("Settings…" on macOS, "Preferences" elsewhere).
338        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
357/// Inject the About and Check for Updates… commands (docs/settings.md): an inert
358/// `role(About)` / `role(CheckForUpdates)` item (id 0) is rewritten to the registered action,
359/// so an app that placed the role itself keeps its placement. When the model has no About at
360/// all but an About is registered, About (and the updater command, when registered) are
361/// appended to the app's Help menu if it has one; otherwise the stock Help menu
362/// ([`MenuBarStyle::stock`]) supplies them, and macOS hoists both into the App menu whichever
363/// way they arrive.
364fn inject_about(mut items: Vec<day_spec::MenuItem>) -> Vec<day_spec::MenuItem> {
365    // Rewrite inert role items in place; report whether each role appears at all.
366    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        // Empty label: each backend falls back to its localized role label.
398        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    // Only an app-owned Help menu takes them here; without one the stock Help menu does.
416    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
425/// The dispatch ids a menu model holds (status items sweep theirs when replaced).
426pub(crate) fn collect_ids(items: &[day_spec::MenuItem]) -> Vec<u64> {
427    collect_action_ids(items)
428}
429
430/// Drop the closures behind `ids`: a menu that held them was replaced or removed.
431pub(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/// Arrange an app's top-level menus into the platform's standard bar, filling every standard
456/// slot the app did not claim with the backend's stock menu.
457///
458/// Which desktop's menu-bar conventions a backend follows. A toolkit picks the style of the
459/// platform it is native to, not the one it happens to be compiled on.
460#[derive(Clone, Copy, Debug, PartialEq, Eq)]
461#[non_exhaustive]
462pub enum MenuBarStyle {
463    /// macOS: an app menu, and a Window menu the toolkit installs natively.
464    Macos,
465    /// GNOME / GTK on Linux.
466    Gnome,
467    /// KDE Plasma / Qt on Linux.
468    Kde,
469    /// Windows.
470    Windows,
471}
472
473impl MenuBarStyle {
474    /// The standard slots before and after the app's own menus on this desktop.
475    #[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            // Only macOS has a Window menu; the Linux and Windows shells own window management.
486            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    /// This desktop's stock menu for a slot, as a pure model: every entry is a `MenuRole`, so
493    /// each backend renders it with its own native command and localized label and nothing here
494    /// is toolkit- or app-specific.
495    ///
496    /// `File` is always the app's own. `Window` is `None` even on macOS because the toolkit
497    /// installs it natively (only AppKit can append the live window list). `Settings` is `None`
498    /// for now everywhere: Preferences is placed before a backend sees the model
499    /// (`inject_preferences`), so a stock Settings menu would be a second copy of it.
500    #[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        // About and Check for Updates… dispatch to the registered Day actions when the app
504        // registered them (docs/settings.md); every other role keeps the backend's native
505        // command (action 0).
506        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            // macOS keeps About in the app menu; the other desktops keep it in Help. An empty
543            // Help menu still earns its place on macOS, where AppKit fills it with the help search.
544            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/// Assemble the bar for a desktop's conventions: [`standard_menu_bar`] with that style's slot
561/// order and stock menus.
562#[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
571/// `leading` are the slots before the app's own menus and `trailing` the ones after; each
572/// backend passes its platform's bar (macOS trails Window and Help; KDE trails Settings and
573/// Help; GNOME and Windows trail Help alone). `stock` returns the backend's house version of a
574/// slot, or `None` where that platform has no such menu. Menus the app tagged with
575/// [`day_spec::MenuBarRole`] replace the stock one in place, so an app customizes a standard menu by
576/// claiming it rather than by rebuilding the whole bar.
577pub 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    // A role the platform does not know about still belongs on the bar rather than vanishing.
605    out.extend(claimed.into_iter().map(|(_, m)| m));
606    out
607}
608
609/// Fill one bar slot: the app's role-tagged menu if it claimed the slot, else its own menu that
610/// IS this standard menu by title, else the platform's stock one.
611///
612/// The title fallback is what keeps a bar from showing the same menu twice. Tagging a submenu
613/// with a [`day_spec::MenuBarRole`] is how an app claims a slot, but an app that builds
614/// its own "Edit" (the natural thing to write, and what the showcase did) would otherwise get
615/// the stock Edit in the slot and its own further along the bar. An untagged submenu whose title
616/// is the stock menu's title is that menu, so it takes the slot instead of being appended.
617fn 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    // Match against the slot's localized name, not the stock menu's label: it is the same
627    // string where a stock menu exists, and it still identifies the slot where none does. That
628    // second case is File: no platform ships a stock File, yet an app's hand-built File belongs
629    // in the File slot rather than adrift after View.
630    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
640/// The slot's standard name in the current locale, the same catalog key a stock menu is labeled
641/// from, so an app's "Edit" matches in English and its "Édition" matches under `--locale fr`.
642fn 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
662/// Do two menu titles name the same menu? Compared case-insensitively, without surrounding space
663/// and without the `&` mnemonic markers GTK and Windows carry: `&View` and `View` are one menu.
664/// Both titles come from the same catalog in the same locale at the same moment, so a localized
665/// bar compares localized titles and still matches.
666fn 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    /// Every stock slot appears, in bar order, with the app's own menus between View and Window.
699    #[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    /// An app that builds a standard menu by hand (an "Edit" submenu with no `bar_role`) gets
727    /// one Edit menu, in the Edit slot, not the stock one plus its own further along the bar.
728    /// This is the duplicate the showcase's macOS bar showed: Showcase, Edit, View,
729    /// File, Edit, View, Window, Help.
730    #[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                // File is always the app's own; Window/Help are the platform's.
738                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    /// The title match ignores case, surrounding space, and the `&` mnemonics GTK/Windows carry.
753    #[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    /// A claimed slot replaces the stock menu in place: it does not also get the stock one,
762    /// and it does not slide into the app-menu run.
763    #[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    /// The bar order is the backend's, not one hardcoded shape: KDE trails Settings and Help,
780    /// GNOME and Windows trail Help alone, and neither grows a macOS Window menu.
781    #[test]
782    fn each_platform_gets_its_own_bar_order() {
783        use day_spec::MenuBarRole as R;
784        // File is the app's own everywhere; no backend ships a stock one.
785        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    /// A backend with no stock menu for a slot has no such menu.
815    #[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        // A second, distinct action gets a distinct id and doesn't fire the first.
838        let id2 = register_menu_action(Rc::new(|| {}));
839        assert_ne!(id, id2);
840
841        // Unknown / zero ids are silent no-ops (role items, stale ids).
842        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); // stale native dispatch after teardown: silent no-op
861    }
862}