day-core 0.6.2

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Menu action dispatch (§ menus). The model ([`day_spec::MenuItem`]) is toolkit-neutral and carries
//! only ids for its actions; the closures live here, keyed by id. A backend fires
//! `Event::MenuAction(id)` when a native item is chosen; the event pump routes it to
//! [`dispatch_menu_action`], which runs the app's closure. Ids are process-unique and monotonic.

use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

day_reactive::tls_slots! {
    menu;
    static ACTIONS: RefCell<HashMap<u64, Rc<dyn Fn()>>> = RefCell::new(HashMap::new());
    static NEXT_ID: Cell<u64> = const { Cell::new(1) };
    /// The app menu as last installed (post-injection). The dayscript `menu:` step
    /// matches against it, and late `register_preferences` re-forwards it.
    static APP_MENU_MODEL: RefCell<Vec<day_spec::MenuItem>> = const { RefCell::new(Vec::new()) };
    /// The action ids the current app menu registered, so replacing the menu (the reactive
    /// re-lower on a locale change) can drop the stale closures without touching context
    /// menus, which share the `ACTIONS` map.
    static APP_MENU_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
    /// The dispatch ids the installed Dock menu holds, swept on the next install.
    static DOCK_MENU_IDS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
    /// The app's own Dock menu entries, kept so a launch-time install can put them back after
    /// the shortcuts.
    static DOCK_MENU_MODEL: RefCell<Vec<day_spec::MenuItem>> = const { RefCell::new(Vec::new()) };
    /// Whether the toolkit currently holds a non-empty Dock menu.
    static DOCK_MENU_SHOWN: Cell<bool> = const { Cell::new(false) };
}

/// Forget every menu action and the last-installed app menu: a re-mount (docs/settings.md
/// "Appearance on Android"). The closures a previous mount registered capture that mount's
/// reactive graph, which has just been disposed; keeping them would leave the menu bar invoking
/// a dead tree.
pub fn reset_menus() {
    ACTIONS.with(|a| a.borrow_mut().clear());
    APP_MENU_MODEL.with(|m| m.borrow_mut().clear());
    APP_MENU_IDS.with(|i| i.borrow_mut().clear());
}

/// Register an app closure for a menu item and return its dispatch id (nonzero). The `day-pieces`
/// menu builder calls this while lowering a menu tree to the [`day_spec::MenuItem`] model.
/// Move the closure registered under `from` onto `to`, dropping `from`.
///
/// Used when an app-menu install turns out to be the same menu with new closures: the native
/// side keeps dispatching the ids it already has, and this points them at the current handlers.
/// (Toolbars never need it: their items dispatch through stable slot ids, see
/// `day_core::toolbar`.)
pub fn rebind_action(from: u64, to: u64) {
    if from == 0 || to == 0 || from == to {
        return;
    }
    ACTIONS.with(|m| {
        let mut m = m.borrow_mut();
        if let Some(f) = m.remove(&from) {
            m.insert(to, f);
        }
    });
}

/// Drop the closure registered under `id`: a toolbar item's, once no contribution carries it.
pub(crate) fn forget_action(id: u64) {
    ACTIONS.with(|m| {
        m.borrow_mut().remove(&id);
    });
}

pub fn register_menu_action(f: Rc<dyn Fn()>) -> u64 {
    let id = next_action_id();
    ACTIONS.with(|m| m.borrow_mut().insert(id, f));
    id
}

/// Register an app closure whose lifetime is tied to the current scope: the id is dropped
/// from the dispatch map when that scope is disposed. This is the registrar for closures
/// owned by a piece build (context menus, nav-row menus, nav `bar_action`), which are
/// re-registered on every rebuild; without the cleanup each remount leaks the previous
/// build's closure (and whatever app state it captured) for the process lifetime.
///
/// The app menu and toolbars stay on plain [`register_menu_action`]: their ids are managed
/// by shape-rebinding ([`rebind_action`]) and toolbar slots plus explicit sweeps, and a scope cleanup firing
/// after a rebind would remove an id the platform still dispatches.
pub fn register_scoped_menu_action(f: Rc<dyn Fn()>) -> u64 {
    let id = register_menu_action(f);
    day_reactive::Scope::current().on_cleanup(move || {
        ACTIONS.with(|m| {
            m.borrow_mut().remove(&id);
        });
    });
    id
}

/// The next dispatch id (nonzero, monotonic). Toolbar value callbacks draw from this same
/// counter (docs/toolbars.md) so a toolbar id can never collide with a menu id.
pub(crate) fn next_action_id() -> u64 {
    NEXT_ID.with(|c| {
        let id = c.get();
        c.set(id.wrapping_add(1).max(1));
        id
    })
}

/// Run the closure registered for `id` (no-op if none). Called by the event pump on
/// `Event::MenuAction`. Runs inside a reactive batch so multiple signal writes coalesce.
pub fn dispatch_menu_action(id: u64) {
    // A toolbar button or pull-down entry carries its bar's stable slot id (docs/toolbars.md).
    let id = crate::toolbar::resolve_slot(id);
    let f = ACTIONS.with(|m| m.borrow().get(&id).cloned());
    if let Some(f) = f {
        day_reactive::batch(|| f());
        return;
    }
    // An id with no closure means something native is still wired to an action whose scope has
    // been disposed: a menu or a nav-bar button that draws normally and does nothing when
    // pressed. Silent before, and undiagnosable from the outside: the press produces no event,
    // no log line, no visible change.
    log::warn!(
        "menu action {id} has no handler — the build that registered it was disposed and \
         whatever is still wired to it (an app menu, a context menu, a nav-bar action) was not \
         updated. The native side needs the NEW id."
    );
}

/// Set the application menu (menu bar / app-bar overflow / iPad main menu). Retains the
/// model (post-injection, [`app_menu_model`]), injects the auto Preferences item when one
/// is registered (docs/windows.md), drops the previous app menu's action closures (context
/// menus share the map and are untouched), and forwards to the backend.
/// Whether two menu models describe the same menu (labels, shortcuts, roles, enablement and
/// nesting), ignoring the action ids, which are re-registered on every build.
fn same_shape(a: &[day_spec::MenuItem], b: &[day_spec::MenuItem]) -> bool {
    a.len() == b.len() && a.iter().zip(b).all(|(x, y)| shape_of(x) == shape_of(y))
}

fn shape_of(item: &day_spec::MenuItem) -> day_spec::MenuItem {
    let mut i = item.clone();
    blank_ids(std::slice::from_mut(&mut i));
    i
}

fn blank_ids(items: &mut [day_spec::MenuItem]) {
    for item in items {
        match item {
            day_spec::MenuItem::Action { action, .. } => *action = 0,
            day_spec::MenuItem::Submenu { items, .. } => blank_ids(items),
            day_spec::MenuItem::Separator => {}
        }
    }
}

/// Move `next`'s closures onto the ids `prev` already published to the platform.
fn rebind_menu(next: &mut [day_spec::MenuItem], prev: &[day_spec::MenuItem]) {
    for (new, old) in next.iter_mut().zip(prev) {
        match (new, old) {
            (
                day_spec::MenuItem::Action { action: new_id, .. },
                day_spec::MenuItem::Action { action: old_id, .. },
            ) => {
                if new_id != old_id {
                    rebind_action(*new_id, *old_id);
                    *new_id = *old_id;
                }
            }
            (
                day_spec::MenuItem::Submenu { items: n, .. },
                day_spec::MenuItem::Submenu { items: o, .. },
            ) => rebind_menu(n, o),
            _ => {}
        }
    }
}

pub fn set_app_menu(items: Vec<day_spec::MenuItem>) {
    let items = inject_preferences(items);
    let mut items = inject_about(items);

    // The same concern the toolbar has (docs/toolbars.md): an app declares its menu inside the
    // page build, so every route change
    // re-installs the same menu with freshly registered closures. Rebuilding the native menu bar
    // for that is churn at best, and on macOS it closes a menu the user has open, so a menu
    // that differs only in its action ids rebinds onto the ids the platform already holds.
    let unchanged = APP_MENU_MODEL.with(|m| same_shape(&m.borrow(), &items));
    if unchanged {
        let installed = APP_MENU_MODEL.with(|m| m.borrow().clone());
        rebind_menu(&mut items, &installed);
        APP_MENU_MODEL.with(|m| *m.borrow_mut() = items);
        return;
    }

    let new_ids = collect_action_ids(&items);
    // The prefs/new-window/undo dispatch ids are registered outside menu lowering (by
    // `day::register_*` and `undo_action_id`) and outlive any menu install; never sweep them.
    let durable = [
        crate::windows::preferences_action_id(),
        crate::windows::about_action_id(),
        crate::windows::check_for_updates_action_id(),
        crate::windows::new_window_action_id(),
        crate::undo_action_id(false),
        crate::undo_action_id(true),
        crate::edit_action_id(day_spec::EditOp::Cut),
        crate::edit_action_id(day_spec::EditOp::Copy),
        crate::edit_action_id(day_spec::EditOp::Paste),
        crate::edit_action_id(day_spec::EditOp::SelectAll),
    ];
    let stale: Vec<u64> = APP_MENU_IDS.with(|ids| {
        ids.borrow()
            .iter()
            .copied()
            .filter(|id| !new_ids.contains(id) && !durable.contains(id))
            .collect()
    });
    ACTIONS.with(|m| {
        let mut m = m.borrow_mut();
        for id in stale {
            m.remove(&id);
        }
    });
    APP_MENU_IDS.with(|ids| *ids.borrow_mut() = new_ids);
    APP_MENU_MODEL.with(|m| *m.borrow_mut() = items.clone());
    crate::with_tree(|t| t.set_app_menu(items));
}

/// Install the app's Dock menu (docs/menus.md "Dock menu"): `items` go above the app's
/// `[[shortcuts]]` and the system's own items when the user right-clicks the Dock icon
/// (`Cap::DockMenu`, macOS). An empty vec leaves only the shortcuts. Replacing the menu drops the
/// previous install's action closures.
pub fn set_dock_menu(items: Vec<day_spec::MenuItem>) {
    let new_ids = collect_action_ids(&items);
    let stale: Vec<u64> = DOCK_MENU_IDS.with(|ids| {
        ids.borrow()
            .iter()
            .copied()
            .filter(|id| !new_ids.contains(id))
            .collect()
    });
    ACTIONS.with(|m| {
        let mut m = m.borrow_mut();
        for id in stale {
            m.remove(&id);
        }
    });
    DOCK_MENU_IDS.with(|ids| *ids.borrow_mut() = new_ids);
    DOCK_MENU_MODEL.with(|m| *m.borrow_mut() = items);
    install_dock_menu();
}

/// Send the Dock menu to the toolkit: the app's launcher shortcuts first, as the platform's own
/// apps list their quick actions, then the app's `dock_menu` entries. Called at launch, so the
/// shortcuts are there before the app installs anything, and on every `set_dock_menu`.
pub(crate) fn install_dock_menu() {
    let mut items = crate::shortcuts::shortcut_menu_items();
    let app = DOCK_MENU_MODEL.with(|m| m.borrow().clone());
    if !items.is_empty() && !app.is_empty() {
        items.push(day_spec::MenuItem::Separator);
    }
    items.extend(app);
    // Nothing to show and nothing shown: leave the toolkit alone (most apps never have a menu).
    if items.is_empty() && !DOCK_MENU_SHOWN.with(|c| c.get()) {
        return;
    }
    DOCK_MENU_SHOWN.with(|c| c.set(!items.is_empty()));
    crate::with_tree(|t| t.set_dock_menu(&items));
}

/// The app menu as last installed (post-injection). The dayscript `menu:` step walks it to
/// resolve an item's dispatch id; backends re-read it on late preferences registration.
pub fn app_menu_model() -> Vec<day_spec::MenuItem> {
    APP_MENU_MODEL.with(|m| m.borrow().clone())
}

/// Whether any app menu was installed (an empty model = the backend default menu is up).
pub fn app_menu_installed() -> bool {
    APP_MENU_MODEL.with(|m| !m.borrow().is_empty())
}

/// Re-forward the retained model through the injection pass: the self-heal for
/// `register_preferences` running after `app_menu` (docs/menus.md ordering note).
/// Did the app install a menu model of its own (`app_menu`)? `false` means it is running on the
/// backend's default menu bar, which the backend builds before `root()` runs, so a backend that
/// puts registration-dependent items there (Settings…, File ▸ New Window) has to rebuild it once
/// the app's registrations are in. day-toolkit-appkit does exactly that.
pub fn has_app_menu() -> bool {
    APP_MENU_MODEL.with(|m| !m.borrow().is_empty())
}

pub(crate) fn reinstall_app_menu() {
    let items = APP_MENU_MODEL.with(|m| m.borrow().clone());
    if !items.is_empty() {
        set_app_menu(items);
    }
}

/// Inject the auto Settings…/Preferences item (docs/windows.md): when a preferences piece
/// is registered and the model carries an inert `role(Preferences)` item (id 0), rewrite
/// its id to the registered action; when the model has no Preferences item at all, append
/// `separator + item` to the first top-level submenu (the File menu by convention). An
/// app-supplied `.action` (nonzero id) always wins. Backends give the item its platform
/// placement (macOS hoists it into the App menu) and label fallback.
fn inject_preferences(mut items: Vec<day_spec::MenuItem>) -> Vec<day_spec::MenuItem> {
    let prefs_id = crate::windows::preferences_action_id();
    if prefs_id == 0 {
        return items;
    }
    fn rewrite(items: &mut [day_spec::MenuItem], prefs_id: u64) -> bool {
        use day_spec::MenuItem as M;
        for it in items.iter_mut() {
            match it {
                M::Action { action, role, .. }
                    if *role == Some(day_spec::MenuRole::Preferences) =>
                {
                    if *action == 0 {
                        *action = prefs_id;
                    }
                    return true;
                }
                M::Submenu { items, .. } => {
                    if rewrite(items, prefs_id) {
                        return true;
                    }
                }
                _ => {}
            }
        }
        false
    }
    if rewrite(&mut items, prefs_id) {
        return items;
    }
    let item = day_spec::MenuItem::Action {
        id: None,
        action: prefs_id,
        // Empty label: each backend falls back to its localized role label
        // ("Settings…" on macOS, "Preferences" elsewhere).
        label: String::new(),
        shortcut: Some(day_spec::Shortcut::primary(",")),
        enabled: true,
        checked: None,
        role: Some(day_spec::MenuRole::Preferences),
        icon: None,
    };
    if let Some(day_spec::MenuItem::Submenu { items: first, .. }) = items
        .iter_mut()
        .find(|it| matches!(it, day_spec::MenuItem::Submenu { .. }))
    {
        first.push(day_spec::MenuItem::Separator);
        first.push(item);
    } else {
        items.push(item);
    }
    items
}

/// Inject the About and Check for Updates… commands (docs/settings.md): an inert
/// `role(About)` / `role(CheckForUpdates)` item (id 0) is rewritten to the registered action,
/// so an app that placed the role itself keeps its placement. When the model has no About at
/// all but an About is registered, About (and the updater command, when registered) are
/// appended to the app's Help menu if it has one; otherwise the stock Help menu
/// ([`MenuBarStyle::stock`]) supplies them, and macOS hoists both into the App menu whichever
/// way they arrive.
fn inject_about(mut items: Vec<day_spec::MenuItem>) -> Vec<day_spec::MenuItem> {
    use day_spec::{MenuItem as M, MenuRole as R};
    let about_id = crate::windows::about_action_id();
    let updates_id = crate::windows::check_for_updates_action_id();
    if about_id == 0 && updates_id == 0 {
        return items;
    }
    // Rewrite inert role items in place; report whether each role appears at all.
    fn rewrite(items: &mut [M], role: R, id: u64) -> bool {
        let mut found = false;
        for it in items.iter_mut() {
            match it {
                M::Action {
                    action, role: r, ..
                } if *r == Some(role) => {
                    if *action == 0 {
                        *action = id;
                    }
                    found = true;
                }
                M::Submenu { items, .. } => {
                    found |= rewrite(items, role, id);
                }
                _ => {}
            }
        }
        found
    }
    let has_about = rewrite(&mut items, R::About, about_id);
    let has_updates = rewrite(&mut items, R::CheckForUpdates, updates_id);
    let act = |role: R, action: u64| M::Action {
        id: None,
        action,
        // Empty label: each backend falls back to its localized role label.
        label: String::new(),
        shortcut: None,
        enabled: true,
        checked: None,
        role: Some(role),
        icon: None,
    };
    let mut missing = Vec::new();
    if about_id != 0 && !has_about {
        missing.push(act(R::About, about_id));
    }
    if updates_id != 0 && !has_updates {
        missing.push(act(R::CheckForUpdates, updates_id));
    }
    if missing.is_empty() {
        return items;
    }
    // Only an app-owned Help menu takes them here; without one the stock Help menu does.
    if let Some(M::Submenu { items: help, .. }) = items.iter_mut().find(|it| {
        matches!(it, M::Submenu { role, label, .. }
            if *role == Some(day_spec::MenuBarRole::Help) || *label == day_localization::t(day_localization::key::day_help))
    }) {
        help.extend(missing);
    }
    items
}

/// The dispatch ids a menu model holds (status items sweep theirs when replaced).
pub(crate) fn collect_ids(items: &[day_spec::MenuItem]) -> Vec<u64> {
    collect_action_ids(items)
}

/// Drop the closures behind `ids`: a menu that held them was replaced or removed.
pub(crate) fn forget_actions(ids: &[u64]) {
    ACTIONS.with(|m| {
        let mut m = m.borrow_mut();
        for id in ids {
            m.remove(id);
        }
    });
}

fn collect_action_ids(items: &[day_spec::MenuItem]) -> Vec<u64> {
    let mut ids = Vec::new();
    fn walk(items: &[day_spec::MenuItem], ids: &mut Vec<u64>) {
        for it in items {
            match it {
                day_spec::MenuItem::Action { action, .. } if *action != 0 => ids.push(*action),
                day_spec::MenuItem::Submenu { items, .. } => walk(items, ids),
                _ => {}
            }
        }
    }
    walk(items, &mut ids);
    ids
}

/// Arrange an app's top-level menus into the platform's standard bar, filling every standard
/// slot the app did not claim with the backend's stock menu.
///
/// Which desktop's menu-bar conventions a backend follows. A toolkit picks the style of the
/// platform it is native to, not the one it happens to be compiled on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MenuBarStyle {
    /// macOS: an app menu, and a Window menu the toolkit installs natively.
    Macos,
    /// GNOME / GTK on Linux.
    Gnome,
    /// KDE Plasma / Qt on Linux.
    Kde,
    /// Windows.
    Windows,
}

impl MenuBarStyle {
    /// The standard slots before and after the app's own menus on this desktop.
    pub fn bar_order(
        self,
    ) -> (
        &'static [day_spec::MenuBarRole],
        &'static [day_spec::MenuBarRole],
    ) {
        use day_spec::MenuBarRole as B;
        const LEADING: &[day_spec::MenuBarRole] = &[B::File, B::Edit, B::View];
        match self {
            // Only macOS has a Window menu; the Linux and Windows shells own window management.
            MenuBarStyle::Macos => (LEADING, &[B::Window, B::Help]),
            MenuBarStyle::Gnome | MenuBarStyle::Windows => (LEADING, &[B::Help]),
            MenuBarStyle::Kde => (LEADING, &[B::Settings, B::Help]),
        }
    }

    /// This desktop's stock menu for a slot, as a pure model: every entry is a `MenuRole`, so
    /// each backend renders it with its own native command and localized label and nothing here
    /// is toolkit- or app-specific.
    ///
    /// `File` is always the app's own. `Window` is `None` even on macOS because the toolkit
    /// installs it natively (only AppKit can append the live window list). `Settings` is `None`
    /// for now everywhere: Preferences is placed before a backend sees the model
    /// (`inject_preferences`), so a stock Settings menu would be a second copy of it.
    pub fn stock(self, role: day_spec::MenuBarRole) -> Option<day_spec::MenuItem> {
        use day_spec::{MenuBarRole as B, MenuItem as MI, MenuRole as R};
        // About and Check for Updates… dispatch to the registered Day actions when the app
        // registered them (docs/settings.md); every other role keeps the backend's native
        // command (action 0).
        let act = |r: R| MI::Action {
            id: None,
            action: match r {
                R::About => crate::windows::about_action_id(),
                R::CheckForUpdates => crate::windows::check_for_updates_action_id(),
                _ => 0,
            },
            label: String::new(),
            shortcut: None,
            enabled: true,
            checked: None,
            role: Some(r),
            icon: None,
        };
        let sub = |key: &str, items: Vec<MI>| {
            Some(MI::Submenu {
                label: day_localization::t(key),
                items,
                role: None,
            })
        };
        match role {
            B::Edit => sub(
                "day_edit",
                vec![
                    act(R::Undo),
                    act(R::Redo),
                    MI::Separator,
                    act(R::Cut),
                    act(R::Copy),
                    act(R::Paste),
                    act(R::Delete),
                    act(R::SelectAll),
                ],
            ),
            B::View => sub("day_view", vec![act(R::Fullscreen)]),
            // macOS keeps About in the app menu; the other desktops keep it in Help. An empty
            // Help menu still earns its place on macOS, where AppKit fills it with the help search.
            B::Help => match self {
                MenuBarStyle::Macos => sub("day_help", Vec::new()),
                _ => {
                    let mut items = vec![act(R::About)];
                    if crate::windows::check_for_updates_action_id() != 0 {
                        items.push(act(R::CheckForUpdates));
                    }
                    sub("day_help", items)
                }
            },
            _ => None,
        }
    }
}

/// Assemble the bar for a desktop's conventions: [`standard_menu_bar`] with that style's slot
/// order and stock menus.
pub fn standard_menu_bar_for(
    style: MenuBarStyle,
    app_menus: Vec<day_spec::MenuItem>,
) -> Vec<day_spec::MenuItem> {
    let (leading, trailing) = style.bar_order();
    standard_menu_bar(app_menus, leading, trailing, |r| style.stock(r))
}

/// `leading` are the slots before the app's own menus and `trailing` the ones after; each
/// backend passes its platform's bar (macOS trails Window and Help; KDE trails Settings and
/// Help; GNOME and Windows trail Help alone). `stock` returns the backend's house version of a
/// slot, or `None` where that platform has no such menu. Menus the app tagged with
/// [`day_spec::MenuBarRole`] replace the stock one in place, so an app customizes a standard menu by
/// claiming it rather than by rebuilding the whole bar.
pub fn standard_menu_bar(
    app_menus: Vec<day_spec::MenuItem>,
    leading: &[day_spec::MenuBarRole],
    trailing: &[day_spec::MenuBarRole],
    stock: impl Fn(day_spec::MenuBarRole) -> Option<day_spec::MenuItem>,
) -> Vec<day_spec::MenuItem> {
    use day_spec::MenuBarRole as R;
    let _ = R::File;

    let mut claimed: Vec<(R, day_spec::MenuItem)> = Vec::new();
    let mut own: Vec<day_spec::MenuItem> = Vec::new();
    for item in app_menus {
        match &item {
            day_spec::MenuItem::Submenu { role: Some(r), .. } => claimed.push((*r, item)),
            _ => own.push(item),
        }
    }
    let mut out: Vec<day_spec::MenuItem> = leading
        .iter()
        .filter_map(|r| take_slot(*r, &mut claimed, &mut own, &stock))
        .collect();
    let trailing_menus: Vec<day_spec::MenuItem> = trailing
        .iter()
        .filter_map(|r| take_slot(*r, &mut claimed, &mut own, &stock))
        .collect();
    out.append(&mut own);
    out.extend(trailing_menus);
    // A role the platform does not know about still belongs on the bar rather than vanishing.
    out.extend(claimed.into_iter().map(|(_, m)| m));
    out
}

/// Fill one bar slot: the app's role-tagged menu if it claimed the slot, else its own menu that
/// IS this standard menu by title, else the platform's stock one.
///
/// The title fallback is what keeps a bar from showing the same menu twice. Tagging a submenu
/// with a [`day_spec::MenuBarRole`] is how an app claims a slot, but an app that builds
/// its own "Edit" (the natural thing to write, and what the showcase did) would otherwise get
/// the stock Edit in the slot and its own further along the bar. An untagged submenu whose title
/// is the stock menu's title is that menu, so it takes the slot instead of being appended.
fn take_slot(
    role: day_spec::MenuBarRole,
    claimed: &mut Vec<(day_spec::MenuBarRole, day_spec::MenuItem)>,
    own: &mut Vec<day_spec::MenuItem>,
    stock: &impl Fn(day_spec::MenuBarRole) -> Option<day_spec::MenuItem>,
) -> Option<day_spec::MenuItem> {
    if let Some(i) = claimed.iter().position(|(cr, _)| *cr == role) {
        return Some(claimed.remove(i).1);
    }
    // Match against the slot's localized name, not the stock menu's label: it is the same
    // string where a stock menu exists, and it still identifies the slot where none does. That
    // second case is File: no platform ships a stock File, yet an app's hand-built File belongs
    // in the File slot rather than adrift after View.
    if let Some(title) = role_title(role)
        && let Some(i) = own
            .iter()
            .position(|m| submenu_label(m).is_some_and(|l| menu_titles_match(l, &title)))
    {
        return Some(own.remove(i));
    }
    stock(role)
}

/// The slot's standard name in the current locale, the same catalog key a stock menu is labeled
/// from, so an app's "Edit" matches in English and its "Édition" matches under `--locale fr`.
fn role_title(role: day_spec::MenuBarRole) -> Option<String> {
    use day_spec::MenuBarRole as B;
    let key = match role {
        B::File => "day_file",
        B::Edit => "day_edit",
        B::View => "day_view",
        B::Window => "day_window",
        B::Help => "day_help",
        _ => return None,
    };
    Some(day_localization::t(key))
}

fn submenu_label(item: &day_spec::MenuItem) -> Option<&str> {
    match item {
        day_spec::MenuItem::Submenu { label, .. } => Some(label),
        _ => None,
    }
}

/// Do two menu titles name the same menu? Compared case-insensitively, without surrounding space
/// and without the `&` mnemonic markers GTK and Windows carry: `&View` and `View` are one menu.
/// Both titles come from the same catalog in the same locale at the same moment, so a localized
/// bar compares localized titles and still matches.
fn menu_titles_match(a: &str, b: &str) -> bool {
    let norm = |s: &str| s.replace('&', "").trim().to_lowercase();
    norm(a) == norm(b)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::Cell;

    use day_spec::MenuBarRole as BR;
    const MAC_LEADING: &[BR] = &[BR::File, BR::Edit, BR::View];
    const MAC_TRAILING: &[BR] = &[BR::Window, BR::Help];

    fn sub(label: &str, role: Option<day_spec::MenuBarRole>) -> day_spec::MenuItem {
        day_spec::MenuItem::Submenu {
            label: label.into(),
            items: Vec::new(),
            role,
        }
    }

    fn labels(items: &[day_spec::MenuItem]) -> Vec<String> {
        items
            .iter()
            .map(|i| match i {
                day_spec::MenuItem::Submenu { label, .. } => label.clone(),
                _ => String::new(),
            })
            .collect()
    }

    /// Every stock slot appears, in bar order, with the app's own menus between View and Window.
    #[test]
    fn stock_menus_fill_the_slots_an_app_left_open() {
        use day_spec::MenuBarRole as R;
        let out = standard_menu_bar(
            vec![sub("Go", None), sub("Article", None)],
            MAC_LEADING,
            MAC_TRAILING,
            |r| {
                Some(sub(
                    match r {
                        R::File => "File",
                        R::Edit => "Edit",
                        R::View => "View",
                        R::Window => "Window",
                        R::Help => "Help",
                        _ => "?",
                    },
                    Some(r),
                ))
            },
        );
        assert_eq!(
            labels(&out),
            ["File", "Edit", "View", "Go", "Article", "Window", "Help"]
        );
    }

    /// An app that builds a standard menu by hand (an "Edit" submenu with no `bar_role`) gets
    /// one Edit menu, in the Edit slot, not the stock one plus its own further along the bar.
    /// This is the duplicate the showcase's macOS bar showed: Showcase, Edit, View,
    /// File, Edit, View, Window, Help.
    #[test]
    fn an_untagged_menu_named_like_a_stock_one_takes_its_slot() {
        let bar = standard_menu_bar(
            vec![sub("File", None), sub("Edit", None), sub("View", None)],
            &[BR::File, BR::Edit, BR::View],
            &[BR::Window, BR::Help],
            |r| match r {
                // File is always the app's own; Window/Help are the platform's.
                BR::File => None,
                BR::Edit => Some(sub("Edit", Some(BR::Edit))),
                BR::View => Some(sub("View", Some(BR::View))),
                BR::Window => Some(sub("Window", Some(BR::Window))),
                _ => Some(sub("Help", Some(BR::Help))),
            },
        );
        assert_eq!(
            labels(&bar),
            ["File", "Edit", "View", "Window", "Help"],
            "a hand-built standard menu must not double the stock one"
        );
    }

    /// The title match ignores case, surrounding space, and the `&` mnemonics GTK/Windows carry.
    #[test]
    fn menu_titles_match_across_mnemonics_and_case() {
        assert!(menu_titles_match("&View", "View"));
        assert!(menu_titles_match("edit ", "Edit"));
        assert!(menu_titles_match("Ansicht", "ansicht"));
        assert!(!menu_titles_match("Edit", "View"));
    }

    /// A claimed slot replaces the stock menu in place: it does not also get the stock one,
    /// and it does not slide into the app-menu run.
    #[test]
    fn a_claimed_slot_replaces_the_stock_menu_in_place() {
        use day_spec::MenuBarRole as R;
        let out = standard_menu_bar(
            vec![sub("My File", Some(R::File)), sub("Go", None)],
            MAC_LEADING,
            MAC_TRAILING,
            |r| Some(sub("stock", Some(r))),
        );
        let l = labels(&out);
        assert_eq!(l[0], "My File", "the app's File sits in the File slot");
        assert_eq!(l.iter().filter(|s| *s == "My File").count(), 1);
        assert!(!l.contains(&"File".to_string()));
        assert_eq!(l[3], "Go", "app menus still follow the leading slots");
    }

    /// The bar order is the backend's, not one hardcoded shape: KDE trails Settings and Help,
    /// GNOME and Windows trail Help alone, and neither grows a macOS Window menu.
    #[test]
    fn each_platform_gets_its_own_bar_order() {
        use day_spec::MenuBarRole as R;
        // File is the app's own everywhere; no backend ships a stock one.
        let stock = |r: R| {
            let label = match r {
                R::Edit => "Edit",
                R::View => "View",
                R::Settings => "Settings",
                R::Help => "Help",
                R::Window => "Window",
                _ => return None,
            };
            Some(sub(label, Some(r)))
        };
        let kde = standard_menu_bar(
            vec![sub("Go", None)],
            &[R::File, R::Edit, R::View],
            &[R::Settings, R::Help],
            stock,
        );
        assert_eq!(labels(&kde), ["Edit", "View", "Go", "Settings", "Help"]);

        let gnome = standard_menu_bar(
            vec![sub("Go", None)],
            &[R::File, R::Edit, R::View],
            &[R::Help],
            stock,
        );
        assert_eq!(labels(&gnome), ["Edit", "View", "Go", "Help"]);
        assert!(!labels(&gnome).contains(&"Window".to_string()));
    }

    /// A backend with no stock menu for a slot has no such menu.
    #[test]
    fn a_slot_with_no_stock_menu_is_omitted() {
        use day_spec::MenuBarRole as R;
        let out = standard_menu_bar(vec![sub("Go", None)], MAC_LEADING, MAC_TRAILING, |r| {
            (r == R::Edit).then(|| sub("Edit", Some(r)))
        });
        assert_eq!(labels(&out), ["Edit", "Go"]);
    }

    #[test]
    fn dispatch_runs_the_registered_action_by_id() {
        thread_local! { static FIRED: Cell<u32> = const { Cell::new(0) }; }
        let id = register_menu_action(Rc::new(|| FIRED.with(|c| c.set(c.get() + 1))));
        assert_ne!(
            id, 0,
            "ids are nonzero so role-only items (id 0) never dispatch"
        );
        assert_eq!(FIRED.with(Cell::get), 0);

        dispatch_menu_action(id);
        assert_eq!(FIRED.with(Cell::get), 1, "the closure ran exactly once");

        // A second, distinct action gets a distinct id and doesn't fire the first.
        let id2 = register_menu_action(Rc::new(|| {}));
        assert_ne!(id, id2);

        // Unknown / zero ids are silent no-ops (role items, stale ids).
        dispatch_menu_action(0);
        dispatch_menu_action(u64::MAX);
        assert_eq!(FIRED.with(Cell::get), 1);
    }

    #[test]
    fn scoped_action_is_reclaimed_when_its_scope_dies() {
        let scope = day_reactive::Scope::child();
        let id = scope.enter(|| register_scoped_menu_action(Rc::new(|| {})));
        assert!(
            ACTIONS.with(|m| m.borrow().contains_key(&id)),
            "registered while the scope is alive"
        );
        scope.dispose();
        assert!(
            !ACTIONS.with(|m| m.borrow().contains_key(&id)),
            "disposal must reclaim the closure — this is the remount leak"
        );
        dispatch_menu_action(id); // stale native dispatch after teardown: silent no-op
    }
}