cranpose 0.17.0

Build desktop, mobile and web apps with composable Rust functions
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! A tray icon and a native menu bar for desktop apps: Compose Desktop's
//! `Tray` and `MenuBar`. A composition describes them with [`Tray`] and
//! [`MenuBar`]; the desktop shell builds them on its main thread before the
//! event loop waits, and runs an item's callback as it runs an event handler.
//!
//! The tray icon shows on macOS, Windows and Linux; on Linux it is a
//! StatusNotifierItem over D-Bus, which GNOME shows with the AppIndicator
//! extension. The menu bar is the macOS application menu bar, after the
//! application menu, and on Windows the window's own menu bar. On Linux,
//! where the system has no menu bar outside GTK windows, Cranpose draws it
//! at the top of the window, as Compose Desktop does: see
//! [`WindowMenuBar`].

use std::{
    rc::Rc,
    sync::{Mutex, Once, PoisonError},
};

mod window_menu_bar;

use cranpose_app_shell::AppShell;
use cranpose_core::{DisposableEffect, SideEffect, remember};
use cranpose_render_wgpu::WgpuRenderer;
use cranpose_ui::{ImageBitmap, KeyCode, Modifiers, composable};
use muda::{
    CheckMenuItem, IsMenuItem, MenuId, PredefinedMenuItem, Submenu,
    accelerator::{Accelerator, CMD_OR_CTRL, Code, Modifiers as AcceleratorModifiers},
};
use tray_icon::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
pub use window_menu_bar::WindowMenuBar;
use winit::event_loop::EventLoopProxy;

/// The keys that run a menu item without opening its menu: Compose
/// Desktop's `KeyShortcut`. `modifiers.ctrl` is Command on macOS and Control
/// elsewhere, as in key events.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct KeyShortcut {
    /// The key pressed with the modifiers.
    pub key: KeyCode,
    /// The modifiers held with the key.
    pub modifiers: Modifiers,
}

impl KeyShortcut {
    /// `key` with `modifiers` held.
    pub fn new(key: KeyCode, modifiers: Modifiers) -> Self {
        Self { key, modifiers }
    }
}

/// A menu item that runs `on_click` when chosen: Compose Desktop's `Item`.
#[derive(Clone)]
pub struct MenuItem {
    /// The text the menu shows.
    pub label: String,
    /// Whether the item can be chosen; a disabled item shows dimmed.
    pub enabled: bool,
    /// The keys that choose the item without opening its menu.
    pub shortcut: Option<KeyShortcut>,
    /// Runs when the item is chosen, as an event handler runs.
    pub on_click: Rc<dyn Fn()>,
}

impl MenuItem {
    /// An enabled item `label` without a shortcut.
    pub fn new(label: impl Into<String>, on_click: impl Fn() + 'static) -> Self {
        Self {
            label: label.into(),
            enabled: true,
            shortcut: None,
            on_click: Rc::new(on_click),
        }
    }

    /// The item with `enabled` set.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }

    /// The item with `shortcut`.
    pub fn shortcut(mut self, shortcut: KeyShortcut) -> Self {
        self.shortcut = Some(shortcut);
        self
    }
}

/// A menu item with a check mark: Compose Desktop's `CheckboxItem`.
#[derive(Clone)]
pub struct CheckItem {
    /// The text the menu shows.
    pub label: String,
    /// Whether the check mark shows.
    pub checked: bool,
    /// Whether the item can be chosen.
    pub enabled: bool,
    /// Runs with the state a click asks for. The mark shows `checked` again
    /// at the next composition, so it stays where the app keeps it.
    pub on_change: Rc<dyn Fn(bool)>,
}

impl CheckItem {
    /// An enabled item `label`, checked when `checked` is set.
    pub fn new(
        label: impl Into<String>,
        checked: bool,
        on_change: impl Fn(bool) + 'static,
    ) -> Self {
        Self {
            label: label.into(),
            checked,
            enabled: true,
            on_change: Rc::new(on_change),
        }
    }

    /// The item with `enabled` set.
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
}

/// One line of a menu.
#[derive(Clone)]
pub enum MenuEntry {
    /// An item that runs a callback.
    Item(MenuItem),
    /// An item with a check mark.
    Check(CheckItem),
    /// A line between groups of items.
    Separator,
    /// An item that opens a menu of its own.
    Submenu(Menu),
}

/// A titled list of entries: a menu of the menu bar or a submenu. Compose
/// Desktop's `Menu`.
#[derive(Clone)]
pub struct Menu {
    /// The title the menu bar or the parent menu shows.
    pub title: String,
    /// The entries, top to bottom.
    pub entries: Vec<MenuEntry>,
}

impl Menu {
    /// An empty menu `title`.
    pub fn new(title: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            entries: Vec::new(),
        }
    }

    /// The menu with `item` added at the end.
    pub fn item(mut self, item: MenuItem) -> Self {
        self.entries.push(MenuEntry::Item(item));
        self
    }

    /// The menu with `item` added at the end.
    pub fn check(mut self, item: CheckItem) -> Self {
        self.entries.push(MenuEntry::Check(item));
        self
    }

    /// The menu with a separator added at the end.
    pub fn separator(mut self) -> Self {
        self.entries.push(MenuEntry::Separator);
        self
    }

    /// The menu with `menu` added at the end as a submenu.
    pub fn submenu(mut self, menu: Menu) -> Self {
        self.entries.push(MenuEntry::Submenu(menu));
        self
    }
}

/// What a tray icon shows and does: Compose Desktop's `Tray` arguments.
#[derive(Clone)]
pub struct TraySpec {
    /// The icon, in its pixel size; 32 by 32 or 64 by 64 suits most trays.
    pub icon: ImageBitmap,
    /// The text that shows while the pointer rests on the icon.
    pub tooltip: String,
    /// The menu a click on the icon opens: a right click when `on_action` is
    /// set, else any click.
    pub menu: Vec<MenuEntry>,
    /// Runs on a left click of the icon. Linux trays may not report clicks.
    pub on_action: Option<Rc<dyn Fn()>>,
}

impl TraySpec {
    /// A tray icon with `tooltip` and no menu.
    pub fn new(icon: ImageBitmap, tooltip: impl Into<String>) -> Self {
        Self {
            icon,
            tooltip: tooltip.into(),
            menu: Vec::new(),
            on_action: None,
        }
    }

    /// The tray with `menu` as its menu.
    pub fn menu(mut self, menu: Vec<MenuEntry>) -> Self {
        self.menu = menu;
        self
    }

    /// The tray with `on_action` run on a left click.
    pub fn on_action(mut self, on_action: impl Fn() + 'static) -> Self {
        self.on_action = Some(Rc::new(on_action));
        self
    }
}

/// Shows a tray icon while this composable is in the composition. The last
/// `Tray` composed wins while two are.
#[composable(no_skip)]
pub fn Tray(spec: TraySpec) {
    let owner = remember(next_owner).with(|owner| *owner);
    SideEffect(move || with_requests(|requests| requests.set_tray(owner, spec)));
    DisposableEffect(owner, move |scope| {
        scope.on_dispose(move || with_requests(|requests| requests.clear_tray(owner)))
    });
}

/// Shows `menus` in the menu bar while this composable is in the
/// composition: on macOS after the application menu, which keeps About,
/// Hide and Quit, on Windows in the main window, and on Linux in a bar
/// Cranpose draws at the top of the main window. On Windows and Linux the
/// items' shortcuts run them too. The last `MenuBar` composed wins while
/// two are.
#[composable(no_skip)]
pub fn MenuBar(menus: Vec<Menu>) {
    let owner = remember(next_owner).with(|owner| *owner);
    SideEffect(move || with_requests(|requests| requests.set_menu_bar(owner, menus)));
    DisposableEffect(owner, move |scope| {
        scope.on_dispose(move || with_requests(|requests| requests.clear_menu_bar(owner)))
    });
}

fn next_owner() -> u64 {
    crate::thread_state::with(|state| {
        let owner = state.native_menus_next_owner.get() + 1;
        state.native_menus_next_owner.set(owner);
        owner
    })
}

fn with_requests<R>(f: impl FnOnce(&mut MenuRequests) -> R) -> R {
    crate::thread_state::with(|state| f(&mut state.native_menus.borrow_mut()))
}

/// What the composition asks the shell to show, and whether that changed
/// since the shell last built it.
#[derive(Default)]
pub(crate) struct MenuRequests {
    tray: Option<(u64, TraySpec)>,
    menu_bar: Option<(u64, Vec<Menu>)>,
    revision: u64,
    /// Counts the menu bar's changes for the bar drawn in the window, which
    /// composes again when it moves.
    drawn_bar: Option<cranpose_core::MutableState<u64>>,
}

impl MenuRequests {
    fn set_tray(&mut self, owner: u64, spec: TraySpec) {
        let same = self
            .tray
            .as_ref()
            .is_some_and(|(held, current)| *held == owner && same_tray(current, &spec));
        self.tray = Some((owner, spec));
        if !same {
            self.revision += 1;
        }
    }

    fn clear_tray(&mut self, owner: u64) {
        if self.tray.as_ref().is_some_and(|(held, _)| *held == owner) {
            self.tray = None;
            self.revision += 1;
        }
    }

    fn set_menu_bar(&mut self, owner: u64, menus: Vec<Menu>) {
        let same = self.menu_bar.as_ref().is_some_and(|(held, current)| {
            *held == owner
                && current.len() == menus.len()
                && current.iter().zip(&menus).all(|(a, b)| same_menu(a, b))
        });
        self.menu_bar = Some((owner, menus));
        if !same {
            self.revision += 1;
        }
        // The drawn bar reads the menus again for their current callbacks.
        self.redraw_bar();
    }

    /// Composes the drawn bar again, when one shows.
    fn redraw_bar(&self) {
        if let Some(drawn) = self.drawn_bar {
            drawn.update(|count| *count += 1);
        }
    }

    /// The id of the item that `labels` name: the menu's title, then the
    /// labels down to the item. The tray menu has no title.
    #[cfg(feature = "robot")]
    fn id_of(&self, tray: bool, labels: &[String]) -> Option<String> {
        use std::fmt::Write;

        let (mut path, mut entries, rest) = if tray {
            ("tray".to_owned(), &self.tray.as_ref()?.1.menu[..], labels)
        } else {
            let (title, rest) = labels.split_first()?;
            let menus = &self.menu_bar.as_ref()?.1;
            let index = menus.iter().position(|menu| &menu.title == title)?;
            (format!("bar/{index}"), &menus[index].entries[..], rest)
        };
        for label in rest {
            let index = entries
                .iter()
                .position(|entry| entry_label(entry) == Some(label.as_str()))?;
            let _ = write!(path, "/{index}");
            if let MenuEntry::Submenu(menu) = &entries[index] {
                entries = &menu.entries;
            }
        }
        Some(path)
    }

    /// The entry at `path`: `tray/2` or `bar/1/0`, an index per menu level.
    fn entry(&self, path: &str) -> Option<&MenuEntry> {
        let mut parts = path.split('/');
        let mut entries: &[MenuEntry] = match parts.next()? {
            "tray" => &self.tray.as_ref()?.1.menu,
            "bar" => {
                &self
                    .menu_bar
                    .as_ref()?
                    .1
                    .get(parts.next()?.parse::<usize>().ok()?)?
                    .entries
            }
            _ => return None,
        };
        let mut entry = None;
        for part in parts {
            let found = entries.get(part.parse::<usize>().ok()?)?;
            if let MenuEntry::Submenu(menu) = found {
                entries = &menu.entries;
            }
            entry = Some(found);
        }
        entry
    }

    fn clear_menu_bar(&mut self, owner: u64) {
        if self
            .menu_bar
            .as_ref()
            .is_some_and(|(held, _)| *held == owner)
        {
            self.menu_bar = None;
            self.revision += 1;
            self.redraw_bar();
        }
    }
}

#[cfg(feature = "robot")]
fn entry_label(entry: &MenuEntry) -> Option<&str> {
    match entry {
        MenuEntry::Item(item) => Some(&item.label),
        MenuEntry::Check(item) => Some(&item.label),
        MenuEntry::Submenu(menu) => Some(&menu.title),
        MenuEntry::Separator => None,
    }
}

/// Whether the native tray built for `a` shows `b` too: everything but the
/// callbacks, which a click reads from the requests.
fn same_tray(a: &TraySpec, b: &TraySpec) -> bool {
    a.icon == b.icon
        && a.tooltip == b.tooltip
        && a.on_action.is_some() == b.on_action.is_some()
        && same_entries(&a.menu, &b.menu)
}

fn same_menu(a: &Menu, b: &Menu) -> bool {
    a.title == b.title && same_entries(&a.entries, &b.entries)
}

fn same_entries(a: &[MenuEntry], b: &[MenuEntry]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b).all(|pair| match pair {
            (MenuEntry::Item(a), MenuEntry::Item(b)) => {
                a.label == b.label && a.enabled == b.enabled && a.shortcut == b.shortcut
            }
            (MenuEntry::Check(a), MenuEntry::Check(b)) => {
                a.label == b.label && a.enabled == b.enabled && a.checked == b.checked
            }
            (MenuEntry::Separator, MenuEntry::Separator) => true,
            (MenuEntry::Submenu(a), MenuEntry::Submenu(b)) => same_menu(a, b),
            _ => false,
        })
}

/// A native menu or tray event, queued by the platform's handler until the
/// shell's main thread takes it.
enum NativeEvent {
    Menu(MenuId),
    TrayAction,
}

/// Events the platform reported, from any thread.
static EVENTS: Mutex<Vec<NativeEvent>> = Mutex::new(Vec::new());
/// Wakes the running event loop when an event is queued.
static WAKER: Mutex<Option<EventLoopProxy>> = Mutex::new(None);
static HANDLERS: Once = Once::new();

fn queue(event: NativeEvent) {
    EVENTS
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
        .push(event);
    if let Some(waker) = &*WAKER.lock().unwrap_or_else(PoisonError::into_inner) {
        waker.wake_up();
    }
}

/// The tray icon and menu bar the shell built, and the actions their items
/// run.
#[derive(Default)]
pub(crate) struct NativeMenus {
    built_revision: u64,
    /// A click flipped a check mark natively: build again to show the state
    /// the app keeps.
    stale: bool,
    tray: Option<tray_icon::TrayIcon>,
    #[cfg(target_os = "macos")]
    menu_bar: Option<muda::Menu>,
    /// The menu bar and the window it shows in.
    #[cfg(target_os = "windows")]
    menu_bar: Option<(muda::Menu, isize)>,
}

impl NativeMenus {
    /// Builds what the composition asks for, if it changed, and runs the
    /// actions of the items chosen since the last call. `menu_bar_due`
    /// holds the menu bar back until the application menu is installed.
    pub(crate) fn serve(
        &mut self,
        app: &mut AppShell<WgpuRenderer>,
        proxy: &EventLoopProxy,
        menu_bar_due: bool,
        window: Option<&dyn winit::window::Window>,
    ) {
        *WAKER.lock().unwrap_or_else(PoisonError::into_inner) = Some(proxy.clone());
        HANDLERS.call_once(|| {
            muda::MenuEvent::set_event_handler(Some(|event: muda::MenuEvent| {
                queue(NativeEvent::Menu(event.id));
            }));
            TrayIconEvent::set_event_handler(Some(|event: TrayIconEvent| {
                if let TrayIconEvent::Click {
                    button: MouseButton::Left,
                    button_state: MouseButtonState::Up,
                    ..
                } = event
                {
                    queue(NativeEvent::TrayAction);
                }
            }));
        });
        let revision = with_requests(|requests| requests.revision);
        if (revision != self.built_revision || self.stale) && menu_bar_due {
            self.build(window);
            self.built_revision = revision;
            self.stale = false;
        }
        let events = std::mem::take(&mut *EVENTS.lock().unwrap_or_else(PoisonError::into_inner));
        for event in events {
            self.run(event, app, proxy);
        }
    }

    fn run(
        &mut self,
        event: NativeEvent,
        app: &mut AppShell<WgpuRenderer>,
        proxy: &EventLoopProxy,
    ) {
        let callback: Option<Rc<dyn Fn()>> = with_requests(|requests| match &event {
            NativeEvent::TrayAction => requests.tray.as_ref()?.1.on_action.clone(),
            NativeEvent::Menu(id) => match requests.entry(id.as_ref())? {
                MenuEntry::Item(item) => Some(Rc::clone(&item.on_click)),
                MenuEntry::Check(item) => {
                    // The native mark flipped with the click.
                    self.stale = true;
                    let on_change = Rc::clone(&item.on_change);
                    let asked = !item.checked;
                    let callback: Rc<dyn Fn()> = Rc::new(move || on_change(asked));
                    Some(callback)
                }
                MenuEntry::Separator | MenuEntry::Submenu(_) => None,
            },
        });
        let Some(callback) = callback else {
            return;
        };
        if let Err(error) =
            crate::desktop_integration::run_as_event_handler(app, proxy, || callback())
        {
            log::warn!("cranpose: a menu action did not apply: {error}");
        }
    }

    fn build(&mut self, window: Option<&dyn winit::window::Window>) {
        let (tray, menu_bar) = with_requests(|requests| {
            (
                requests.tray.as_ref().map(|(_, spec)| spec.clone()),
                requests.menu_bar.as_ref().map(|(_, menus)| menus.clone()),
            )
        });
        self.build_tray(tray);
        self.build_menu_bar(menu_bar, window);
    }

    fn build_tray(&mut self, spec: Option<TraySpec>) {
        let Some(spec) = spec else {
            self.tray = None;
            return;
        };
        let icon = match tray_icon::Icon::from_rgba(
            spec.icon.rgba8_pixels().into_owned(),
            spec.icon.width(),
            spec.icon.height(),
        ) {
            Ok(icon) => icon,
            Err(error) => {
                log::warn!("cranpose: the tray icon is unusable: {error}");
                return;
            }
        };
        let menu = muda::Menu::new();
        if let Err(error) = menu.append_items(&item_refs(&build_items(&spec.menu, "tray"))) {
            log::warn!("cranpose: the tray menu could not be built: {error}");
        }
        let menu_on_left_click = spec.on_action.is_none();
        match &self.tray {
            Some(tray) => {
                if let Err(error) = tray.set_icon(Some(icon)) {
                    log::warn!("cranpose: the tray icon could not change: {error}");
                }
                if let Err(error) = tray.set_tooltip(Some(&spec.tooltip)) {
                    log::warn!("cranpose: the tray tooltip could not change: {error}");
                }
                tray.set_menu(Some(Box::new(menu)));
                tray.set_show_menu_on_left_click(menu_on_left_click);
            }
            None => {
                match TrayIconBuilder::new()
                    .with_icon(icon)
                    .with_tooltip(&spec.tooltip)
                    .with_menu(Box::new(menu))
                    .with_menu_on_left_click(menu_on_left_click)
                    .build()
                {
                    Ok(tray) => self.tray = Some(tray),
                    Err(error) => log::warn!("cranpose: the tray icon could not show: {error}"),
                }
            }
        }
    }

    #[cfg(target_os = "macos")]
    fn build_menu_bar(
        &mut self,
        menus: Option<Vec<Menu>>,
        _window: Option<&dyn winit::window::Window>,
    ) {
        let Some(menus) = menus else {
            if let Some(menu_bar) = self.menu_bar.take() {
                menu_bar.remove_for_nsapp();
                crate::macos_menu::install_application_menu();
            }
            return;
        };
        let menu_bar = muda::Menu::new();
        let application = Submenu::with_items(
            "",
            true,
            &[
                &PredefinedMenuItem::about(None, None),
                &PredefinedMenuItem::separator(),
                &PredefinedMenuItem::services(None),
                &PredefinedMenuItem::separator(),
                &PredefinedMenuItem::hide(None),
                &PredefinedMenuItem::hide_others(None),
                &PredefinedMenuItem::show_all(None),
                &PredefinedMenuItem::separator(),
                &PredefinedMenuItem::quit(None),
            ],
        );
        let mut items: Vec<Box<dyn IsMenuItem>> = Vec::with_capacity(menus.len() + 1);
        match application {
            Ok(application) => items.push(Box::new(application)),
            Err(error) => log::warn!("cranpose: the application menu could not be built: {error}"),
        }
        for (index, menu) in menus.iter().enumerate() {
            if let Some(submenu) = build_submenu(menu, &format!("bar/{index}")) {
                items.push(Box::new(submenu));
            }
        }
        if let Err(error) = menu_bar.append_items(&item_refs(&items)) {
            log::warn!("cranpose: the menu bar could not be built: {error}");
        }
        menu_bar.init_for_nsapp();
        self.menu_bar = Some(menu_bar);
    }

    #[cfg(target_os = "windows")]
    fn build_menu_bar(
        &mut self,
        menus: Option<Vec<Menu>>,
        window: Option<&dyn winit::window::Window>,
    ) {
        if let Some((menu_bar, hwnd)) = self.menu_bar.take() {
            crate::windows_menu::detach(&menu_bar, hwnd);
        }
        let (Some(menus), Some(window)) = (menus, window) else {
            return;
        };
        let menu_bar = muda::Menu::new();
        let items: Vec<Box<dyn IsMenuItem>> = menus
            .iter()
            .enumerate()
            .filter_map(|(index, menu)| build_submenu(menu, &format!("bar/{index}")))
            .map(|submenu| Box::new(submenu) as Box<dyn IsMenuItem>)
            .collect();
        if let Err(error) = menu_bar.append_items(&item_refs(&items)) {
            log::warn!("cranpose: the menu bar could not be built: {error}");
        }
        if let Some(hwnd) = crate::windows_menu::attach(&menu_bar, window) {
            self.menu_bar = Some((menu_bar, hwnd));
        }
    }

    /// Linux has no menu bar without GTK, which the shell does not take.
    #[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
    fn build_menu_bar(
        &mut self,
        _menus: Option<Vec<Menu>>,
        _window: Option<&dyn winit::window::Window>,
    ) {
    }
}

/// The native items of `entries`, each with its path under `path` as its id.
fn build_items(entries: &[MenuEntry], path: &str) -> Vec<Box<dyn IsMenuItem>> {
    let mut items: Vec<Box<dyn IsMenuItem>> = Vec::with_capacity(entries.len());
    for (index, entry) in entries.iter().enumerate() {
        let id = MenuId::new(format!("{path}/{index}"));
        match entry {
            MenuEntry::Item(item) => {
                items.push(Box::new(muda::MenuItem::with_id(
                    id,
                    &item.label,
                    item.enabled,
                    item.shortcut.and_then(accelerator),
                )));
            }
            MenuEntry::Check(item) => {
                items.push(Box::new(CheckMenuItem::with_id(
                    id,
                    &item.label,
                    item.enabled,
                    item.checked,
                    None,
                )));
            }
            MenuEntry::Separator => items.push(Box::new(PredefinedMenuItem::separator())),
            MenuEntry::Submenu(menu) => {
                if let Some(submenu) = build_submenu(menu, &format!("{path}/{index}")) {
                    items.push(Box::new(submenu));
                }
            }
        }
    }
    items
}

fn build_submenu(menu: &Menu, path: &str) -> Option<Submenu> {
    let items = build_items(&menu.entries, path);
    match Submenu::with_id_and_items(MenuId::new(path), &menu.title, true, &item_refs(&items)) {
        Ok(submenu) => Some(submenu),
        Err(error) => {
            log::warn!(
                "cranpose: the menu {:?} could not be built: {error}",
                menu.title
            );
            None
        }
    }
}

fn item_refs(items: &[Box<dyn IsMenuItem>]) -> Vec<&dyn IsMenuItem> {
    items.iter().map(Box::as_ref).collect()
}

/// The native accelerator of `shortcut`, or `None` for a key a menu cannot
/// take.
fn accelerator(shortcut: KeyShortcut) -> Option<Accelerator> {
    let modifiers = shortcut.modifiers;
    let mut native = AcceleratorModifiers::empty();
    for (held, flag) in [
        (modifiers.ctrl, CMD_OR_CTRL),
        (modifiers.shift, AcceleratorModifiers::SHIFT),
        (modifiers.alt, AcceleratorModifiers::ALT),
        (modifiers.meta, AcceleratorModifiers::META),
    ] {
        if held {
            native |= flag;
        }
    }
    Some(Accelerator::new(native, key_code(shortcut.key)?))
}

/// The native key of each key a menu shortcut can take.
const KEY_CODES: [(KeyCode, Code); 73] = [
    (KeyCode::A, Code::KeyA),
    (KeyCode::B, Code::KeyB),
    (KeyCode::C, Code::KeyC),
    (KeyCode::D, Code::KeyD),
    (KeyCode::E, Code::KeyE),
    (KeyCode::F, Code::KeyF),
    (KeyCode::G, Code::KeyG),
    (KeyCode::H, Code::KeyH),
    (KeyCode::I, Code::KeyI),
    (KeyCode::J, Code::KeyJ),
    (KeyCode::K, Code::KeyK),
    (KeyCode::L, Code::KeyL),
    (KeyCode::M, Code::KeyM),
    (KeyCode::N, Code::KeyN),
    (KeyCode::O, Code::KeyO),
    (KeyCode::P, Code::KeyP),
    (KeyCode::Q, Code::KeyQ),
    (KeyCode::R, Code::KeyR),
    (KeyCode::S, Code::KeyS),
    (KeyCode::T, Code::KeyT),
    (KeyCode::U, Code::KeyU),
    (KeyCode::V, Code::KeyV),
    (KeyCode::W, Code::KeyW),
    (KeyCode::X, Code::KeyX),
    (KeyCode::Y, Code::KeyY),
    (KeyCode::Z, Code::KeyZ),
    (KeyCode::Digit0, Code::Digit0),
    (KeyCode::Digit1, Code::Digit1),
    (KeyCode::Digit2, Code::Digit2),
    (KeyCode::Digit3, Code::Digit3),
    (KeyCode::Digit4, Code::Digit4),
    (KeyCode::Digit5, Code::Digit5),
    (KeyCode::Digit6, Code::Digit6),
    (KeyCode::Digit7, Code::Digit7),
    (KeyCode::Digit8, Code::Digit8),
    (KeyCode::Digit9, Code::Digit9),
    (KeyCode::F1, Code::F1),
    (KeyCode::F2, Code::F2),
    (KeyCode::F3, Code::F3),
    (KeyCode::F4, Code::F4),
    (KeyCode::F5, Code::F5),
    (KeyCode::F6, Code::F6),
    (KeyCode::F7, Code::F7),
    (KeyCode::F8, Code::F8),
    (KeyCode::F9, Code::F9),
    (KeyCode::F10, Code::F10),
    (KeyCode::F11, Code::F11),
    (KeyCode::F12, Code::F12),
    (KeyCode::ArrowUp, Code::ArrowUp),
    (KeyCode::ArrowDown, Code::ArrowDown),
    (KeyCode::ArrowLeft, Code::ArrowLeft),
    (KeyCode::ArrowRight, Code::ArrowRight),
    (KeyCode::Home, Code::Home),
    (KeyCode::End, Code::End),
    (KeyCode::PageUp, Code::PageUp),
    (KeyCode::PageDown, Code::PageDown),
    (KeyCode::Backspace, Code::Backspace),
    (KeyCode::Delete, Code::Delete),
    (KeyCode::Enter, Code::Enter),
    (KeyCode::Tab, Code::Tab),
    (KeyCode::Space, Code::Space),
    (KeyCode::Escape, Code::Escape),
    (KeyCode::Minus, Code::Minus),
    (KeyCode::Equal, Code::Equal),
    (KeyCode::BracketLeft, Code::BracketLeft),
    (KeyCode::BracketRight, Code::BracketRight),
    (KeyCode::Backslash, Code::Backslash),
    (KeyCode::Semicolon, Code::Semicolon),
    (KeyCode::Quote, Code::Quote),
    (KeyCode::Comma, Code::Comma),
    (KeyCode::Period, Code::Period),
    (KeyCode::Slash, Code::Slash),
    (KeyCode::Backquote, Code::Backquote),
];

fn key_code(key: KeyCode) -> Option<Code> {
    KEY_CODES
        .iter()
        .find(|(known, _)| *known == key)
        .map(|(_, code)| *code)
}

/// Chooses the item that `labels` name, as a click on it does: through the
/// native menu bar on macOS once it shows the menu and on Windows, else
/// through the event a click queues.
#[cfg(feature = "robot")]
pub(crate) fn choose(tray: bool, labels: &[String]) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    if !tray && menu_bar_shows(labels) {
        return choose_in_menu_bar(labels);
    }
    #[cfg(target_os = "windows")]
    if !tray {
        return crate::windows_menu::choose(labels);
    }
    let id = with_requests(|requests| requests.id_of(tray, labels))
        .ok_or_else(|| format!("no menu item {labels:?}"))?;
    queue(NativeEvent::Menu(MenuId::new(id)));
    Ok(())
}

/// Whether the macOS menu bar has the menu `labels` start with.
#[cfg(all(feature = "robot", target_os = "macos"))]
fn menu_bar_shows(labels: &[String]) -> bool {
    use objc2::MainThreadMarker;
    use objc2_app_kit::NSApplication;
    use objc2_foundation::NSString;

    let (Some(mtm), Some(title)) = (MainThreadMarker::new(), labels.first()) else {
        return false;
    };
    NSApplication::sharedApplication(mtm)
        .mainMenu()
        .is_some_and(|menu| menu.itemWithTitle(&NSString::from_str(title)).is_some())
}

/// Performs the action of the macOS menu bar item that `labels` name, as
/// AppKit does when the user chooses it.
#[cfg(all(feature = "robot", target_os = "macos"))]
fn choose_in_menu_bar(labels: &[String]) -> Result<(), String> {
    use objc2::MainThreadMarker;
    use objc2_app_kit::NSApplication;
    use objc2_foundation::NSString;

    let mtm = MainThreadMarker::new().ok_or("the menu bar answers on the main thread")?;
    let mut menu = NSApplication::sharedApplication(mtm)
        .mainMenu()
        .ok_or("no menu bar")?;
    let (last, parents) = labels.split_last().ok_or("no menu item named")?;
    for title in parents {
        menu = menu
            .itemWithTitle(&NSString::from_str(title))
            .and_then(|item| item.submenu())
            .ok_or_else(|| format!("no menu {title:?}"))?;
    }
    let index = menu.indexOfItemWithTitle(&NSString::from_str(last));
    if index < 0 {
        return Err(format!("no menu item {last:?}"));
    }
    menu.performActionForItemAtIndex(index);
    Ok(())
}

/// The root content under the bar drawn in the window, behind a handle
/// that equals itself, so the app does not compose again when only the bar
/// does.
#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
#[derive(Clone)]
struct HostedContent(Rc<std::cell::RefCell<dyn FnMut()>>);

#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
impl PartialEq for HostedContent {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

/// `content` under the menus of [`MenuBar`], in a bar Cranpose draws in the
/// window: Linux has no menu bar outside GTK windows, which the shell does
/// not use.
#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
pub(crate) fn with_window_menu_bar(content: impl FnMut() + 'static) -> impl FnMut() + 'static {
    let content = HostedContent(Rc::new(std::cell::RefCell::new(content)));
    move || MenuBarHost(content.clone())
}

#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
#[composable(no_skip)]
fn MenuBarHost(content: HostedContent) {
    let drawn = cranpose_core::rememberMutableStateOf(|| 0_u64);
    SideEffect(move || with_requests(|requests| requests.drawn_bar = Some(drawn)));
    drawn.get();
    let menus = with_requests(|requests| {
        requests
            .menu_bar
            .as_ref()
            .map(|(_, menus)| menus.clone())
            .unwrap_or_default()
    });
    window_menu_bar::bar_frame(Rc::new(menus), move || HostedRoot(content.clone()));
}

#[cfg(all(target_os = "linux", not(target_arch = "wasm32")))]
#[composable]
fn HostedRoot(content: HostedContent) {
    (content.0.borrow_mut())();
}