Skip to main content

waft_widgets/widgets/
platform_menu_bar.rs

1//! Flutter counterpart: `widgets/platform_menu_bar.dart`.
2
3use std::cell::{Cell, RefCell};
4use std::collections::HashMap;
5use std::fmt::{self, Debug};
6use std::rc::Rc;
7
8use waft_embedder::{
9    IconImage, MenuEntry, MenuId, MenuItem, MenuItemCheck, MenuShortcut, ProvidedItem,
10    ShortcutModifiers, TargetPlatform,
11};
12use waft_foundation::{
13    App, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsProperty, FlagProperty, Handle,
14    IterableProperty, StringProperty, VoidCallback,
15};
16use waft_services::LogicalKeyboardKey;
17
18use crate::WidgetsBinding;
19use crate::framework::{
20    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
21};
22use crate::widgets::actions::{Actions, IntentRef};
23use crate::widgets::basic::SizedBox;
24use crate::widgets::focus_manager::FocusManager;
25use crate::widgets::shortcuts::{CharacterActivator, SingleActivator};
26
27/// A class used by [`MenuSerializableShortcut`] to describe the shortcut for serialization to
28/// send to the platform for rendering a [`PlatformMenuBar`].
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct ShortcutSerialization {
31    trigger: Option<LogicalKeyboardKey>,
32    character: Option<String>,
33    alt: Option<bool>,
34    control: Option<bool>,
35    meta: Option<bool>,
36    shift: Option<bool>,
37    internal: MenuShortcut,
38}
39
40impl ShortcutSerialization {
41    /// Creates a [`ShortcutSerialization`] representing a single character.
42    ///
43    /// This is used by a [`CharacterActivator`] to serialize itself.
44    pub fn character(
45        character: impl Into<String>,
46        alt: bool,
47        control: bool,
48        meta: bool,
49    ) -> ShortcutSerialization {
50        let character = character.into();
51        debug_assert_eq!(character.chars().count(), 1);
52        let key = character.chars().next().map_or(0, u64::from);
53        ShortcutSerialization {
54            internal: MenuShortcut {
55                key,
56                modifiers: ShortcutModifiers {
57                    meta,
58                    control,
59                    alt,
60                    shift: false,
61                },
62            },
63            character: Some(character),
64            trigger: None,
65            alt: Some(alt),
66            control: Some(control),
67            meta: Some(meta),
68            shift: None,
69        }
70    }
71
72    /// Creates a [`ShortcutSerialization`] representing a specific [`LogicalKeyboardKey`] and
73    /// modifiers.
74    ///
75    /// This is used by a [`SingleActivator`] to serialize itself.
76    pub fn modifier(
77        trigger: LogicalKeyboardKey,
78        alt: bool,
79        control: bool,
80        meta: bool,
81        shift: bool,
82    ) -> ShortcutSerialization {
83        debug_assert!(
84            ![
85                LogicalKeyboardKey::ALT,
86                LogicalKeyboardKey::ALT_LEFT,
87                LogicalKeyboardKey::ALT_RIGHT,
88                LogicalKeyboardKey::CONTROL,
89                LogicalKeyboardKey::CONTROL_LEFT,
90                LogicalKeyboardKey::CONTROL_RIGHT,
91                LogicalKeyboardKey::META,
92                LogicalKeyboardKey::META_LEFT,
93                LogicalKeyboardKey::META_RIGHT,
94                LogicalKeyboardKey::SHIFT,
95                LogicalKeyboardKey::SHIFT_LEFT,
96                LogicalKeyboardKey::SHIFT_RIGHT,
97            ]
98            .contains(&trigger),
99            "Specifying a modifier key as a trigger is not allowed. Use provided boolean \
100             parameters instead."
101        );
102        ShortcutSerialization {
103            internal: MenuShortcut {
104                key: trigger.key_id,
105                modifiers: ShortcutModifiers {
106                    meta,
107                    control,
108                    alt,
109                    shift,
110                },
111            },
112            trigger: Some(trigger),
113            character: None,
114            alt: Some(alt),
115            control: Some(control),
116            meta: Some(meta),
117            shift: Some(shift),
118        }
119    }
120
121    /// The keyboard key that triggers this shortcut, if any.
122    pub fn trigger(&self) -> Option<LogicalKeyboardKey> {
123        self.trigger
124    }
125
126    /// The character that triggers this shortcut, if any.
127    pub fn character_value(&self) -> Option<&str> {
128        self.character.as_deref()
129    }
130
131    /// If this shortcut has a [`trigger`](Self::trigger), this indicates whether or not the alt
132    /// modifier needs to be down or not.
133    pub fn alt(&self) -> Option<bool> {
134        self.alt
135    }
136
137    /// If this shortcut has a [`trigger`](Self::trigger), this indicates whether or not the
138    /// control modifier needs to be down or not.
139    pub fn control(&self) -> Option<bool> {
140        self.control
141    }
142
143    /// If this shortcut has a [`trigger`](Self::trigger), this indicates whether or not the meta
144    /// (also known as the Windows or Command key) modifier needs to be down or not.
145    pub fn meta(&self) -> Option<bool> {
146        self.meta
147    }
148
149    /// If this shortcut has a [`trigger`](Self::trigger), this indicates whether or not the shift
150    /// modifier needs to be down or not.
151    pub fn shift(&self) -> Option<bool> {
152        self.shift
153    }
154
155    /// Converts the internal representation to the shortcut a menu item carries to the platform.
156    pub fn to_menu_shortcut(&self) -> MenuShortcut {
157        self.internal
158    }
159}
160
161/// A mixin allowing a `ShortcutActivator` to provide data for serialization of the shortcut
162/// when sending to the platform.
163///
164/// This is meant for those who have written their own `ShortcutActivator` implementor, and
165/// would like to have it work for menus in a [`PlatformMenuBar`] as well.
166///
167/// Keep in mind that there are limits to the capabilities of the platform APIs, and not all
168/// kinds of `ShortcutActivator`s will work with them.
169pub trait MenuSerializableShortcut: Debug {
170    /// Implement this in a `ShortcutActivator` implementor to allow it to be serialized for use
171    /// in a [`PlatformMenuBar`].
172    fn serialize_for_menu(&self) -> ShortcutSerialization;
173}
174
175pub type MenuSerializableShortcutRef = Rc<dyn MenuSerializableShortcut>;
176
177impl MenuSerializableShortcut for SingleActivator {
178    fn serialize_for_menu(&self) -> ShortcutSerialization {
179        ShortcutSerialization::modifier(self.trigger, self.alt, self.control, self.meta, self.shift)
180    }
181}
182
183impl MenuSerializableShortcut for CharacterActivator {
184    fn serialize_for_menu(&self) -> ShortcutSerialization {
185        ShortcutSerialization::character(self.character.clone(), self.alt, self.control, self.meta)
186    }
187}
188
189/// An abstract delegate that can be used to set [`WidgetsBinding::set_platform_menu_delegate`]
190/// to provide for managing platform menus.
191///
192/// This can be implemented to provide a different menu plugin than the default system-provided
193/// plugin for managing [`PlatformMenuBar`] menus.
194///
195/// The [`set_menus`](Self::set_menus) method allows for setting of the menu hierarchy when the
196/// [`PlatformMenuBar`] menu hierarchy changes.
197///
198/// This delegate doesn't handle the results of clicking on a menu item, which is left to the
199/// implementor to handle for their implementation.
200pub trait PlatformMenuDelegate {
201    /// Sets the entire menu hierarchy for a platform-rendered menu bar.
202    ///
203    /// The `top_level_menus` argument is the list of menus that appear in the menu bar, which
204    /// themselves can have children.
205    ///
206    /// To update the menu hierarchy or menu item state, call [`set_menus`](Self::set_menus) with
207    /// the modified hierarchy, and it will overwrite the previous menu state.
208    fn set_menus(&self, app: &mut App, top_level_menus: &[PlatformMenuItemRef]);
209
210    /// Clears any existing platform-rendered menus and leaves the application with no menus.
211    ///
212    /// It is not necessary to call this before updating the menu with
213    /// [`set_menus`](Self::set_menus).
214    fn clear_menus(&self, app: &mut App);
215
216    /// This is called by [`PlatformMenuBar`] when it is initialized, to be sure that only one is
217    /// active at a time.
218    ///
219    /// If the lock is successfully acquired, it will return true.
220    fn debug_lock_delegate(&self, context: BuildContext) -> bool;
221
222    /// This is called by [`PlatformMenuBar`] when it is disposed, so that another one can take
223    /// over.
224    ///
225    /// If it successfully unlocks the delegate, it will return true.
226    fn debug_unlock_delegate(&self, context: BuildContext) -> bool;
227}
228
229pub type PlatformMenuDelegateRef = Rc<dyn PlatformMenuDelegate>;
230
231/// The signature for a function that generates unique menu item IDs for serialization of a
232/// [`PlatformMenuItem`].
233pub type MenuItemSerializableIdGenerator<'a> = dyn FnMut(PlatformMenuItemRef) -> MenuId + 'a;
234
235/// The platform menu delegate that hands the menus to the host's menu bar
236/// (`Platform::menu_bar`), and dispatches a choice the host reports
237/// (`EmbedderClient::menu_selected`) to the item chosen.
238///
239/// An instance of this is set on [`WidgetsBinding::platform_menu_delegate`] by default when the
240/// [`WidgetsBinding`] is initialized.
241pub struct DefaultPlatformMenuDelegate {
242    // Map of distributed IDs to menu items.
243    id_map: RefCell<HashMap<MenuId, PlatformMenuItemRef>>,
244    // An ever increasing value used to dole out IDs.
245    serial: Cell<MenuId>,
246    // The context used to "lock" this delegate to a specific instance of PlatformMenuBar to
247    // make sure there is only one.
248    locked_context: Cell<Option<BuildContext>>,
249}
250
251impl DefaultPlatformMenuDelegate {
252    /// Creates a [`DefaultPlatformMenuDelegate`], which hears the choices the host reports from
253    /// now on.
254    pub fn new(app: &mut App) -> Rc<DefaultPlatformMenuDelegate> {
255        let delegate = Rc::new(DefaultPlatformMenuDelegate {
256            id_map: RefCell::default(),
257            serial: Cell::new(0),
258            locked_context: Cell::new(None),
259        });
260        let handler = Rc::downgrade(&delegate);
261        app.platform_callbacks_mut().on_menu_selected = Some(Rc::new(move |app, id| {
262            if let Some(delegate) = handler.upgrade() {
263                delegate.method_call_handler(app, id);
264            }
265        }));
266        delegate
267    }
268
269    /// Get the next serialization ID.
270    ///
271    /// This is called by each item when serializing a new object so that it has a unique ID.
272    fn get_id(&self, item: PlatformMenuItemRef) -> MenuId {
273        self.serial.set(self.serial.get() + 1);
274        self.id_map.borrow_mut().insert(self.serial.get(), item);
275        self.serial.get()
276    }
277
278    // Handles the choice the host reports, to forward to the selection callbacks.
279    fn method_call_handler(&self, app: &mut App, id: MenuId) {
280        let item = self.id_map.borrow().get(&id).cloned();
281        debug_assert!(
282            item.is_some(),
283            "Received a menu choice for a menu item with an ID that was not recognized: {id}"
284        );
285        let Some(item) = item else {
286            return;
287        };
288        select_menu_item(app, &item);
289    }
290}
291
292/// The body of Dart's `_methodCallHandler` for an item chosen: its `onSelected`, or its intent
293/// invoked on the primary focus. A [`PlatformTrayIcon`](super::platform_tray_icon::PlatformTrayIcon)
294/// dispatches its menu's choices the same way.
295pub(crate) fn select_menu_item(app: &mut App, item: &PlatformMenuItemRef) {
296    debug_assert!(
297        item.on_selected().is_none() || item.on_selected_intent().is_none(),
298        "Only one of PlatformMenuItem.onSelected or PlatformMenuItem.onSelectedIntent may be \
299         specified"
300    );
301    if let Some(on_selected) = item.on_selected().cloned() {
302        on_selected(app);
303    }
304    if let Some(intent) = item.on_selected_intent().cloned() {
305        let context = FocusManager::instance(app)
306            .primary_focus(app)
307            .and_then(|focus| focus.context(app))
308            .expect("a menu item's intent is invoked on the primary focus");
309        Actions::maybe_invoke(app, context, &*intent);
310    }
311}
312
313impl PlatformMenuDelegate for DefaultPlatformMenuDelegate {
314    fn clear_menus(&self, app: &mut App) {
315        self.set_menus(app, &[]);
316    }
317
318    fn set_menus(&self, app: &mut App, top_level_menus: &[PlatformMenuItemRef]) {
319        self.id_map.borrow_mut().clear();
320        let mut representation = Vec::new();
321        for child_item in top_level_menus {
322            representation
323                .extend(Rc::clone(child_item).to_menu_entries(self, &mut |item| self.get_id(item)));
324        }
325        let platform = app.platform();
326        if let Some(menu_bar) = platform.menu_bar() {
327            menu_bar.set_menus(&representation);
328        }
329    }
330
331    fn debug_lock_delegate(&self, context: BuildContext) -> bool {
332        if cfg!(debug_assertions) {
333            // It's OK to lock if the lock isn't set, but not OK if a different context is
334            // locking it.
335            if self
336                .locked_context
337                .get()
338                .is_some_and(|locked| locked != context)
339            {
340                return false;
341            }
342            self.locked_context.set(Some(context));
343        }
344        true
345    }
346
347    fn debug_unlock_delegate(&self, context: BuildContext) -> bool {
348        if cfg!(debug_assertions) {
349            // It's OK to unlock if the lock isn't set, but not OK if a different context is
350            // unlocking it.
351            if self
352                .locked_context
353                .get()
354                .is_some_and(|locked| locked != context)
355            {
356                return false;
357            }
358            self.locked_context.set(None);
359        }
360        true
361    }
362}
363
364/// A menu bar that uses the platform's native APIs to construct and render a menu described by
365/// a [`PlatformMenu`]/[`PlatformMenuItem`] hierarchy.
366///
367/// This widget is especially useful on macOS, where a system menu is a required part of every
368/// application. Where the host has no menu bar (`Platform::menu_bar` is `None`), the menus show
369/// nowhere, and the app draws its own.
370///
371/// As far as the framework is concerned, this widget has no visual representation, and
372/// intercepts no events: it just returns the `child` from its build function. This is because
373/// all of the rendering, shortcuts, and event handling for the menu is handled by the host. It
374/// is only part of the widget tree to provide a convenient refresh mechanism for the menu data.
375///
376/// There can only be one [`PlatformMenuBar`] at a time using the same
377/// [`PlatformMenuDelegate`]. It will assert if more than one is detected.
378pub struct PlatformMenuBar {
379    pub key: Option<KeyRef>,
380    /// The widget below this widget in the tree.
381    pub child: Option<WidgetRef>,
382    /// The list of menu items that are the top level children of the [`PlatformMenuBar`].
383    ///
384    /// Whenever the menus list is modified, a new list should be provided.
385    pub menus: Vec<PlatformMenuItemRef>,
386}
387
388impl PlatformMenuBar {
389    /// Creates a [`PlatformMenuBar`] of `menus`.
390    pub fn new(menus: Vec<PlatformMenuItemRef>) -> PlatformMenuBar {
391        PlatformMenuBar {
392            key: None,
393            child: None,
394            menus,
395        }
396    }
397
398    pub fn key(mut self, key: KeyRef) -> PlatformMenuBar {
399        self.key = Some(key);
400        self
401    }
402
403    #[cfg_attr(debug_assertions, track_caller)]
404    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> PlatformMenuBar {
405        self.child = Some(child.into_widget());
406        self
407    }
408}
409
410impl Debug for PlatformMenuBar {
411    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412        f.debug_struct("PlatformMenuBar")
413            .field("menus", &self.menus)
414            .finish_non_exhaustive()
415    }
416}
417
418impl StatefulWidget for PlatformMenuBar {
419    type State = PlatformMenuBarState;
420
421    fn key(&self) -> Option<&KeyRef> {
422        self.key.as_ref()
423    }
424
425    fn create_state(&self) -> PlatformMenuBarState {
426        PlatformMenuBarState {
427            state: StateData::new(),
428            descendants: Vec::new(),
429        }
430    }
431}
432
433pub struct PlatformMenuBarState {
434    state: StateData<PlatformMenuBar>,
435    descendants: Vec<PlatformMenuItemRef>,
436}
437
438impl PlatformMenuBarState {
439    // Updates the data structures for the menu and send them to the platform plugin.
440    fn update_menu(self: Handle<Self>, app: &mut App) {
441        let menus = self.widget(app).menus.clone();
442        let delegate = WidgetsBinding::instance(app).platform_menu_delegate(app);
443        delegate.set_menus(app, &menus);
444    }
445}
446
447impl State for PlatformMenuBarState {
448    type Widget = PlatformMenuBar;
449    crate::state_accessors!();
450
451    fn init_state(self: Handle<Self>, app: &mut App) {
452        let delegate = WidgetsBinding::instance(app).platform_menu_delegate(app);
453        let context = self.context(app);
454        debug_assert!(
455            delegate.debug_lock_delegate(context),
456            "More than one active PlatformMenuBar detected. Only one active platform-rendered \
457             menu bar is allowed at a time."
458        );
459        delegate.clear_menus(app);
460        self.update_menu(app);
461    }
462
463    fn dispose(self: Handle<Self>, app: &mut App) {
464        let delegate = WidgetsBinding::instance(app).platform_menu_delegate(app);
465        let context = self.context(app);
466        debug_assert!(
467            delegate.debug_unlock_delegate(context),
468            "tried to unlock the DefaultPlatformMenuDelegate more than once with context \
469             {context:?}."
470        );
471        delegate.clear_menus(app);
472    }
473
474    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &PlatformMenuBar) {
475        let mut new_descendants = Vec::new();
476        for item in &self.widget(app).menus {
477            new_descendants.push(Rc::clone(item));
478            new_descendants.extend(item.descendants());
479        }
480        if !same_items(&new_descendants, &app.get(self).descendants) {
481            app.get_mut(self).descendants = new_descendants;
482            self.update_menu(app);
483        }
484    }
485
486    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
487        // PlatformMenuBar is really about managing the platform menu bar, and doesn't do any
488        // rendering or event handling in the framework.
489        self.widget(app)
490            .child
491            .clone()
492            .unwrap_or_else(|| SizedBox::new().into_widget())
493    }
494}
495
496/// Dart's `listEquals` of menu items, which compares them by identity.
497pub(crate) fn same_items(a: &[PlatformMenuItemRef], b: &[PlatformMenuItemRef]) -> bool {
498    a.len() == b.len() && a.iter().zip(b).all(|(a, b)| Rc::ptr_eq(a, b))
499}
500
501pub type PlatformMenuItemRef = Rc<dyn PlatformMenuItem>;
502
503/// An item in a [`PlatformMenu`]: Dart's `PlatformMenuItem` as the base every menu entry of a
504/// [`PlatformMenuBar`] extends. A plain item is a [`PlainPlatformMenuItem`].
505///
506/// A [`PlatformMenuItem`] may be used to define the leaves of a menu hierarchy, its
507/// [`PlatformMenu`]s the branches, and [`PlatformMenuItemGroup`]s the groups divided from the
508/// rest.
509pub trait PlatformMenuItem: Debug {
510    /// The required label used for rendering the menu item.
511    fn label(&self) -> &str;
512
513    /// The optional tooltip text that is displayed when the user hovers over the menu item.
514    fn tooltip(&self) -> Option<&str> {
515        None
516    }
517
518    /// The optional shortcut that selects this [`PlatformMenuItem`].
519    ///
520    /// This shortcut is only enabled when [`on_selected`](Self::on_selected) is set.
521    fn shortcut(&self) -> Option<&MenuSerializableShortcutRef> {
522        None
523    }
524
525    /// An optional callback that is called when this [`PlatformMenuItem`] is selected.
526    ///
527    /// At most one of [`on_selected`](Self::on_selected) and
528    /// [`on_selected_intent`](Self::on_selected_intent) may be set. If neither field is set,
529    /// this menu item will be disabled.
530    fn on_selected(&self) -> Option<&VoidCallback> {
531        None
532    }
533
534    /// Returns a callback, if any, to be invoked if the platform menu receives a "Menu.opened"
535    /// method call from the platform for this item.
536    ///
537    /// Only items that have submenus will have this callback invoked.
538    fn on_open(&self) -> Option<&VoidCallback> {
539        None
540    }
541
542    /// Returns a callback, if any, to be invoked if the platform menu receives a "Menu.closed"
543    /// method call from the platform for this item.
544    ///
545    /// Only items that have submenus will have this callback invoked.
546    fn on_close(&self) -> Option<&VoidCallback> {
547        None
548    }
549
550    /// An optional intent that is invoked when this [`PlatformMenuItem`] is selected.
551    ///
552    /// At most one of [`on_selected`](Self::on_selected) and
553    /// [`on_selected_intent`](Self::on_selected_intent) may be set. If neither field is set,
554    /// this menu item will be disabled.
555    fn on_selected_intent(&self) -> Option<&IntentRef> {
556        None
557    }
558
559    /// The check the item shows, and which.
560    fn check(&self) -> MenuItemCheck {
561        MenuItemCheck::Plain
562    }
563
564    /// The image the item shows beside its label.
565    fn icon(&self) -> Option<&IconImage> {
566        None
567    }
568
569    /// Returns all descendant [`PlatformMenuItem`]s of this item.
570    ///
571    /// Returns an empty list if this type of menu item doesn't have descendants.
572    fn descendants(&self) -> Vec<PlatformMenuItemRef> {
573        Vec::new()
574    }
575
576    /// Returns the list of group members if this menu item is a "grouping" menu item, such as
577    /// [`PlatformMenuItemGroup`].
578    ///
579    /// Defaults to an empty list.
580    fn members(&self) -> Vec<PlatformMenuItemRef> {
581        Vec::new()
582    }
583
584    /// Converts the representation of this item into the entries the host's menu takes.
585    fn to_menu_entries(
586        self: Rc<Self>,
587        delegate: &dyn PlatformMenuDelegate,
588        get_id: &mut MenuItemSerializableIdGenerator<'_>,
589    ) -> Vec<MenuEntry>;
590
591    /// Dart's `PlatformMenuItem.debugFillProperties`, which an implementor's own body calls
592    /// where Dart writes `super`.
593    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
594        fill_platform_menu_item_properties(self, properties);
595    }
596
597    /// Dart's `PlatformMenuItem.toStringShort`: the identity, then the label in parentheses.
598    fn to_string_short(&self) -> String {
599        format!(
600            "{}({})",
601            waft_foundation::describe_identity(
602                waft_foundation::bare_type_name(std::any::type_name::<Self>()),
603                self as *const Self as *const () as usize as u64,
604            ),
605            self.label()
606        )
607    }
608
609    /// Dart's `PlatformMenuItem.toDiagnosticsNode(name:)`, from `Diagnosticable`.
610    fn diagnostics_node(&self, name: Option<String>) -> waft_foundation::DiagnosticableNode {
611        let mut properties = DiagnosticPropertiesBuilder::new();
612        self.debug_fill_properties(&mut properties);
613        waft_foundation::DiagnosticableNode::from_parts(name, self.to_string_short(), properties)
614    }
615
616    /// Dart's `Diagnosticable.toString`, which a group's member list prints.
617    fn diagnostic_string(&self) -> String {
618        use waft_foundation::{DiagnosticLevel, DiagnosticsNode, DiagnosticsTreeStyle};
619        self.diagnostics_node(None)
620            .with_style(DiagnosticsTreeStyle::SingleLine)
621            .to_string_with(None, DiagnosticLevel::Info)
622    }
623}
624
625/// The bodies of Dart's `PlatformMenuItem` base class, which its implementors reach as `super`.
626pub struct PlatformMenuItemBase;
627
628/// Dart's `PlatformMenuItem.debugFillProperties`, one body for its implementors.
629pub fn fill_platform_menu_item_properties<T: PlatformMenuItem + ?Sized>(
630    item: &T,
631    properties: &mut DiagnosticPropertiesBuilder,
632) {
633    properties.add(StringProperty::new("label", Some(item.label().to_string())));
634    properties.add(
635        StringProperty::new("tooltip", item.tooltip().map(str::to_string)).default_value(None),
636    );
637    properties.add(
638        DiagnosticsProperty::<String>::new(
639            "shortcut",
640            item.shortcut().map(|shortcut| format!("{shortcut:?}")),
641        )
642        .default_value(None),
643    );
644    properties
645        .add(FlagProperty::new("enabled", Some(item.on_selected().is_some())).if_false("DISABLED"));
646}
647
648impl PlatformMenuItemBase {
649    /// Converts the given [`PlatformMenuItem`] into the entry the host's menu takes.
650    pub fn serialize(
651        item: PlatformMenuItemRef,
652        _delegate: &dyn PlatformMenuDelegate,
653        get_id: &mut MenuItemSerializableIdGenerator<'_>,
654    ) -> MenuEntry {
655        let shortcut = item
656            .shortcut()
657            .map(|shortcut| shortcut.serialize_for_menu().to_menu_shortcut());
658        let menu_item = MenuItem {
659            label: item.label().to_owned(),
660            enabled: item.on_selected().is_some() || item.on_selected_intent().is_some(),
661            check: item.check(),
662            shortcut,
663            icon: item.icon().cloned(),
664        };
665        MenuEntry::Item {
666            id: get_id(item),
667            item: menu_item,
668        }
669    }
670}
671
672/// A [`PlatformMenuItem`] that is a leaf of a menu hierarchy: Dart's `PlatformMenuItem` itself.
673pub struct PlainPlatformMenuItem {
674    pub label: String,
675    pub tooltip: Option<String>,
676    pub shortcut: Option<MenuSerializableShortcutRef>,
677    pub on_selected: Option<VoidCallback>,
678    pub on_selected_intent: Option<IntentRef>,
679    pub check: MenuItemCheck,
680    pub icon: Option<IconImage>,
681}
682
683impl PlainPlatformMenuItem {
684    /// Creates a [`PlainPlatformMenuItem`] labelled `label`, disabled until it has an
685    /// [`on_selected`](Self::on_selected) or an [`on_selected_intent`](Self::on_selected_intent).
686    pub fn new(label: impl Into<String>) -> PlainPlatformMenuItem {
687        PlainPlatformMenuItem {
688            label: label.into(),
689            tooltip: None,
690            shortcut: None,
691            on_selected: None,
692            on_selected_intent: None,
693            check: MenuItemCheck::Plain,
694            icon: None,
695        }
696    }
697
698    pub fn tooltip(mut self, tooltip: impl Into<String>) -> PlainPlatformMenuItem {
699        self.tooltip = Some(tooltip.into());
700        self
701    }
702
703    pub fn shortcut(mut self, shortcut: MenuSerializableShortcutRef) -> PlainPlatformMenuItem {
704        self.shortcut = Some(shortcut);
705        self
706    }
707
708    pub fn on_selected(mut self, on_selected: VoidCallback) -> PlainPlatformMenuItem {
709        debug_assert!(
710            self.on_selected_intent.is_none(),
711            "Only one of onSelected or onSelectedIntent may be specified"
712        );
713        self.on_selected = Some(on_selected);
714        self
715    }
716
717    pub fn on_selected_intent(mut self, intent: IntentRef) -> PlainPlatformMenuItem {
718        debug_assert!(
719            self.on_selected.is_none(),
720            "Only one of onSelected or onSelectedIntent may be specified"
721        );
722        self.on_selected_intent = Some(intent);
723        self
724    }
725
726    pub fn check(mut self, check: MenuItemCheck) -> PlainPlatformMenuItem {
727        self.check = check;
728        self
729    }
730
731    pub fn icon(mut self, icon: IconImage) -> PlainPlatformMenuItem {
732        self.icon = Some(icon);
733        self
734    }
735}
736
737impl Debug for PlainPlatformMenuItem {
738    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
739        f.debug_struct("PlatformMenuItem")
740            .field("label", &self.label)
741            .field("tooltip", &self.tooltip)
742            .field("shortcut", &self.shortcut)
743            .field("enabled", &self.on_selected.is_some())
744            .finish()
745    }
746}
747
748impl PlatformMenuItem for PlainPlatformMenuItem {
749    fn label(&self) -> &str {
750        &self.label
751    }
752
753    fn tooltip(&self) -> Option<&str> {
754        self.tooltip.as_deref()
755    }
756
757    fn shortcut(&self) -> Option<&MenuSerializableShortcutRef> {
758        self.shortcut.as_ref()
759    }
760
761    fn on_selected(&self) -> Option<&VoidCallback> {
762        self.on_selected.as_ref()
763    }
764
765    fn on_selected_intent(&self) -> Option<&IntentRef> {
766        self.on_selected_intent.as_ref()
767    }
768
769    fn check(&self) -> MenuItemCheck {
770        self.check
771    }
772
773    fn icon(&self) -> Option<&IconImage> {
774        self.icon.as_ref()
775    }
776
777    fn to_menu_entries(
778        self: Rc<Self>,
779        delegate: &dyn PlatformMenuDelegate,
780        get_id: &mut MenuItemSerializableIdGenerator<'_>,
781    ) -> Vec<MenuEntry> {
782        vec![PlatformMenuItemBase::serialize(self, delegate, get_id)]
783    }
784}
785
786/// A class for representing menu items that have child submenus.
787pub struct PlatformMenu {
788    pub label: String,
789    pub tooltip: Option<String>,
790    /// A callback that is called when this menu is opened.
791    pub on_open: Option<VoidCallback>,
792    /// A callback that is called when this menu is closed.
793    pub on_close: Option<VoidCallback>,
794    /// The menu items in the submenu opened by this menu item.
795    ///
796    /// If this is an empty list, this [`PlatformMenu`] will be disabled.
797    pub menus: Vec<PlatformMenuItemRef>,
798}
799
800impl PlatformMenu {
801    /// Creates a [`PlatformMenu`] labelled `label`, of `menus`.
802    pub fn new(label: impl Into<String>, menus: Vec<PlatformMenuItemRef>) -> PlatformMenu {
803        PlatformMenu {
804            label: label.into(),
805            tooltip: None,
806            on_open: None,
807            on_close: None,
808            menus,
809        }
810    }
811
812    pub fn tooltip(mut self, tooltip: impl Into<String>) -> PlatformMenu {
813        self.tooltip = Some(tooltip.into());
814        self
815    }
816
817    pub fn on_open(mut self, on_open: VoidCallback) -> PlatformMenu {
818        self.on_open = Some(on_open);
819        self
820    }
821
822    pub fn on_close(mut self, on_close: VoidCallback) -> PlatformMenu {
823        self.on_close = Some(on_close);
824        self
825    }
826
827    /// Returns all descendant [`PlatformMenuItem`]s of this item.
828    pub fn get_descendants(item: &PlatformMenu) -> Vec<PlatformMenuItemRef> {
829        let mut descendants = Vec::new();
830        for child in &item.menus {
831            descendants.push(Rc::clone(child));
832            descendants.extend(child.descendants());
833        }
834        descendants
835    }
836
837    /// Converts the supplied object to the entry the host's menu takes.
838    pub fn serialize(
839        item: Rc<PlatformMenu>,
840        delegate: &dyn PlatformMenuDelegate,
841        get_id: &mut MenuItemSerializableIdGenerator<'_>,
842    ) -> MenuEntry {
843        let mut result: Vec<MenuEntry> = Vec::new();
844        for child_item in &item.menus {
845            result.extend(Rc::clone(child_item).to_menu_entries(delegate, get_id));
846        }
847        strip_dividers(&mut result);
848        let enabled = !item.menus.is_empty();
849        MenuEntry::Submenu {
850            label: item.label.clone(),
851            id: get_id(item),
852            enabled,
853            entries: result,
854        }
855    }
856}
857
858/// The part of Dart's `PlatformMenu.serialize` that strips dividers, which a
859/// [`PlatformTrayIcon`](super::platform_tray_icon::PlatformTrayIcon)'s menu, a menu of no
860/// [`PlatformMenu`], strips too.
861pub(crate) fn strip_dividers(result: &mut Vec<MenuEntry>) {
862    // To avoid doing type checking for groups, just filter out when there are multiple
863    // sequential dividers, or when they are first or last, since groups may be interleaved
864    // with non-groups, and non-groups may also add dividers.
865    let mut previous_is_divider: Option<bool> = None;
866    result.retain(|entry| {
867        let is_divider = matches!(entry, MenuEntry::Separator);
868        if previous_is_divider.is_none() && is_divider {
869            // Strip any leading dividers.
870            return false;
871        }
872        if previous_is_divider == Some(true) && is_divider {
873            // Strip any duplicate dividers.
874            return false;
875        }
876        previous_is_divider = Some(is_divider);
877        true
878    });
879    if matches!(result.last(), Some(MenuEntry::Separator)) {
880        result.pop();
881    }
882}
883
884impl Debug for PlatformMenu {
885    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
886        f.debug_struct("PlatformMenu")
887            .field("label", &self.label)
888            .field("enabled", &!self.menus.is_empty())
889            .field("menus", &self.menus)
890            .finish()
891    }
892}
893
894impl PlatformMenu {
895    /// Dart's `PlatformMenu.debugDescribeChildren`: the items of the submenu.
896    pub fn debug_describe_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
897        self.menus
898            .iter()
899            .map(|menu| Rc::new(menu.diagnostics_node(None)) as Rc<dyn DiagnosticsNode>)
900            .collect()
901    }
902}
903
904impl PlatformMenuItem for PlatformMenu {
905    fn label(&self) -> &str {
906        &self.label
907    }
908
909    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
910        fill_platform_menu_item_properties(self, properties);
911        properties.add(StringProperty::new("label", Some(self.label.clone())));
912        properties
913            .add(FlagProperty::new("enabled", Some(!self.menus.is_empty())).if_false("DISABLED"));
914    }
915
916    fn tooltip(&self) -> Option<&str> {
917        self.tooltip.as_deref()
918    }
919
920    fn on_open(&self) -> Option<&VoidCallback> {
921        self.on_open.as_ref()
922    }
923
924    fn on_close(&self) -> Option<&VoidCallback> {
925        self.on_close.as_ref()
926    }
927
928    fn descendants(&self) -> Vec<PlatformMenuItemRef> {
929        PlatformMenu::get_descendants(self)
930    }
931
932    fn to_menu_entries(
933        self: Rc<Self>,
934        delegate: &dyn PlatformMenuDelegate,
935        get_id: &mut MenuItemSerializableIdGenerator<'_>,
936    ) -> Vec<MenuEntry> {
937        vec![PlatformMenu::serialize(self, delegate, get_id)]
938    }
939}
940
941/// A class that groups other menu items into sections delineated by dividers.
942///
943/// Visual dividers will be added before and after this group if other menu items appear in the
944/// [`PlatformMenu`], and the leading one omitted if it is first and the trailing one omitted if
945/// it is last in the menu.
946pub struct PlatformMenuItemGroup {
947    /// The [`PlatformMenuItem`]s that are members of this menu item group.
948    ///
949    /// An assertion will be thrown if there isn't at least one member of the group.
950    pub members: Vec<PlatformMenuItemRef>,
951}
952
953impl PlatformMenuItemGroup {
954    /// Creates a [`PlatformMenuItemGroup`] of `members`.
955    pub fn new(members: Vec<PlatformMenuItemRef>) -> PlatformMenuItemGroup {
956        PlatformMenuItemGroup { members }
957    }
958
959    /// Converts the supplied object to the entries the host's menu takes.
960    pub fn serialize(
961        group: &dyn PlatformMenuItem,
962        delegate: &dyn PlatformMenuDelegate,
963        get_id: &mut MenuItemSerializableIdGenerator<'_>,
964    ) -> Vec<MenuEntry> {
965        let mut entries = vec![MenuEntry::Separator];
966        for item in group.members() {
967            entries.extend(item.to_menu_entries(delegate, get_id));
968        }
969        entries.push(MenuEntry::Separator);
970        entries
971    }
972}
973
974impl Debug for PlatformMenuItemGroup {
975    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
976        f.debug_struct("PlatformMenuItemGroup")
977            .field("members", &self.members)
978            .finish()
979    }
980}
981
982impl PlatformMenuItem for PlatformMenuItemGroup {
983    fn label(&self) -> &str {
984        ""
985    }
986
987    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
988        fill_platform_menu_item_properties(self, properties);
989        properties.add(IterableProperty::<String>::new(
990            "members",
991            self.members
992                .iter()
993                .map(|member| member.diagnostic_string())
994                .collect::<Vec<String>>(),
995        ));
996    }
997
998    fn members(&self) -> Vec<PlatformMenuItemRef> {
999        self.members.clone()
1000    }
1001
1002    fn to_menu_entries(
1003        self: Rc<Self>,
1004        delegate: &dyn PlatformMenuDelegate,
1005        get_id: &mut MenuItemSerializableIdGenerator<'_>,
1006    ) -> Vec<MenuEntry> {
1007        debug_assert!(
1008            !self.members.is_empty(),
1009            "There must be at least one member in a PlatformMenuItemGroup"
1010        );
1011        PlatformMenuItemGroup::serialize(&*self, delegate, get_id)
1012    }
1013}
1014
1015/// A class for [`PlatformMenuItem`]s that do not have handlers, but are provided by the
1016/// platform.
1017///
1018/// These are typically standard menu items like "Quit" or "Hide", or Edit's commands, which the
1019/// host sends to the focused view.
1020///
1021/// Check [`PlatformProvidedMenuItem::has_menu`] to see if the platform provides the given type.
1022pub struct PlatformProvidedMenuItem {
1023    /// The type of default menu this is.
1024    pub type_: PlatformProvidedMenuItemType,
1025    /// True if this [`PlatformProvidedMenuItem`] should be enabled or not.
1026    pub enabled: bool,
1027}
1028
1029impl PlatformProvidedMenuItem {
1030    /// Creates a [`PlatformProvidedMenuItem`] of `type_`, enabled.
1031    pub fn new(type_: PlatformProvidedMenuItemType) -> PlatformProvidedMenuItem {
1032        PlatformProvidedMenuItem {
1033            type_,
1034            enabled: true,
1035        }
1036    }
1037
1038    pub fn enabled(mut self, enabled: bool) -> PlatformProvidedMenuItem {
1039        self.enabled = enabled;
1040        self
1041    }
1042
1043    /// Checks to see if the given default menu type is supported on this platform.
1044    pub fn has_menu(app: &App, menu: PlatformProvidedMenuItemType) -> bool {
1045        match app.platform().target_platform() {
1046            TargetPlatform::Android
1047            | TargetPlatform::IOS
1048            | TargetPlatform::Fuchsia
1049            | TargetPlatform::Linux
1050            | TargetPlatform::Windows => false,
1051            TargetPlatform::MacOS => menu.provided_item().is_some(),
1052        }
1053    }
1054}
1055
1056impl Debug for PlatformProvidedMenuItem {
1057    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1058        f.debug_struct("PlatformProvidedMenuItem")
1059            .field("type", &self.type_)
1060            .field("enabled", &self.enabled)
1061            .finish()
1062    }
1063}
1064
1065impl PlatformMenuItem for PlatformProvidedMenuItem {
1066    fn label(&self) -> &str {
1067        // The label is ignored for platform provided menus.
1068        ""
1069    }
1070
1071    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
1072        fill_platform_menu_item_properties(self, properties);
1073        properties.add(FlagProperty::new("enabled", Some(self.enabled)).if_false("DISABLED"));
1074    }
1075
1076    fn to_menu_entries(
1077        self: Rc<Self>,
1078        _delegate: &dyn PlatformMenuDelegate,
1079        get_id: &mut MenuItemSerializableIdGenerator<'_>,
1080    ) -> Vec<MenuEntry> {
1081        let Some(item) = self.type_.provided_item() else {
1082            debug_assert!(
1083                false,
1084                "No platform provides a menu for {:?}. Call PlatformProvidedMenuItem::has_menu \
1085                 to determine this before instantiating one.",
1086                self.type_
1087            );
1088            return Vec::new();
1089        };
1090        let enabled = self.enabled;
1091        vec![MenuEntry::Provided {
1092            id: get_id(self),
1093            item,
1094            enabled,
1095        }]
1096    }
1097}
1098
1099/// The list of possible platform provided, prebuilt menus for use in a [`PlatformMenuBar`].
1100///
1101/// These are menus that the platform typically provides that cannot be reproduced in the
1102/// framework without platform access, or the platform's own commands for the focused view.
1103#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1104pub enum PlatformProvidedMenuItemType {
1105    /// The system provided "About" menu item.
1106    About,
1107    /// The system provided "Quit" menu item.
1108    Quit,
1109    /// The system provided "Services" submenu.
1110    ServicesSubmenu,
1111    /// The system provided "Hide" menu item.
1112    Hide,
1113    /// The system provided "Hide Others" menu item.
1114    HideOtherApplications,
1115    /// The system provided "Show All" menu item.
1116    ShowAllApplications,
1117    /// The system provided "Start Dictation..." menu item.
1118    StartSpeaking,
1119    /// The system provided "Stop Dictation..." menu item.
1120    StopSpeaking,
1121    /// The system provided "Enter Full Screen" menu item.
1122    ToggleFullScreen,
1123    /// The system provided "Minimize" menu item.
1124    MinimizeWindow,
1125    /// The system provided "Zoom" menu item.
1126    ZoomWindow,
1127    /// The system provided "Bring To Front" menu item.
1128    ArrangeWindowsInFront,
1129    /// The system provided "Undo" menu item, sent to the focused view.
1130    Undo,
1131    /// The system provided "Redo" menu item, sent to the focused view.
1132    Redo,
1133    /// The system provided "Cut" menu item, sent to the focused view.
1134    Cut,
1135    /// The system provided "Copy" menu item, sent to the focused view.
1136    Copy,
1137    /// The system provided "Paste" menu item, sent to the focused view.
1138    Paste,
1139    /// The system provided "Select All" menu item, sent to the focused view.
1140    SelectAll,
1141    /// The system provided "Delete" menu item, sent to the focused view.
1142    Delete,
1143}
1144
1145impl PlatformProvidedMenuItemType {
1146    /// The item the host provides for this type; none for one no host provides.
1147    fn provided_item(self) -> Option<ProvidedItem> {
1148        Some(match self {
1149            PlatformProvidedMenuItemType::About => ProvidedItem::About,
1150            PlatformProvidedMenuItemType::Quit => ProvidedItem::Quit,
1151            PlatformProvidedMenuItemType::ServicesSubmenu => ProvidedItem::Services,
1152            PlatformProvidedMenuItemType::Hide => ProvidedItem::Hide,
1153            PlatformProvidedMenuItemType::HideOtherApplications => ProvidedItem::HideOthers,
1154            PlatformProvidedMenuItemType::ShowAllApplications => ProvidedItem::ShowAll,
1155            PlatformProvidedMenuItemType::StartSpeaking
1156            | PlatformProvidedMenuItemType::StopSpeaking => return None,
1157            PlatformProvidedMenuItemType::ToggleFullScreen => ProvidedItem::ToggleFullScreen,
1158            PlatformProvidedMenuItemType::MinimizeWindow => ProvidedItem::Minimize,
1159            PlatformProvidedMenuItemType::ZoomWindow => ProvidedItem::Zoom,
1160            PlatformProvidedMenuItemType::ArrangeWindowsInFront => ProvidedItem::BringAllToFront,
1161            PlatformProvidedMenuItemType::Undo => ProvidedItem::Undo,
1162            PlatformProvidedMenuItemType::Redo => ProvidedItem::Redo,
1163            PlatformProvidedMenuItemType::Cut => ProvidedItem::Cut,
1164            PlatformProvidedMenuItemType::Copy => ProvidedItem::Copy,
1165            PlatformProvidedMenuItemType::Paste => ProvidedItem::Paste,
1166            PlatformProvidedMenuItemType::SelectAll => ProvidedItem::SelectAll,
1167            PlatformProvidedMenuItemType::Delete => ProvidedItem::Delete,
1168        })
1169    }
1170}
1171
1172#[cfg(test)]
1173mod tests {
1174    use std::cell::RefCell;
1175
1176    use waft_services::LogicalKeyboardKey;
1177    use waft_test::{MockMenuBar, TestPlatform};
1178
1179    use super::*;
1180    use crate::testing::WidgetTester;
1181
1182    /// A tester on a macOS host whose menu bar is `menu_bar`.
1183    fn tester_with_menu_bar(menu_bar: &MockMenuBar) -> WidgetTester {
1184        WidgetTester::with_platform(
1185            TestPlatform::new()
1186                .on(TargetPlatform::MacOS)
1187                .with_menu_bar(Rc::new(menu_bar.clone())),
1188        )
1189    }
1190
1191    /// A File menu with Open, which records its choice into `chosen`, a group holding Save,
1192    /// disabled, and the system's Quit.
1193    fn menus(chosen: &Rc<RefCell<Vec<&'static str>>>) -> Vec<PlatformMenuItemRef> {
1194        let open = Rc::clone(chosen);
1195        vec![Rc::new(PlatformMenu::new(
1196            "File",
1197            vec![
1198                Rc::new(
1199                    PlainPlatformMenuItem::new("Open")
1200                        .shortcut(Rc::new(
1201                            SingleActivator::new(LogicalKeyboardKey::KEY_O).meta(true),
1202                        ))
1203                        .on_selected(Rc::new(move |_app| open.borrow_mut().push("Open"))),
1204                ),
1205                Rc::new(PlatformMenuItemGroup::new(vec![Rc::new(
1206                    PlainPlatformMenuItem::new("Save"),
1207                )])),
1208                Rc::new(PlatformProvidedMenuItem::new(
1209                    PlatformProvidedMenuItemType::Quit,
1210                )),
1211            ],
1212        ))]
1213    }
1214
1215    #[test]
1216    fn the_menu_bar_reaches_the_host_and_a_choice_reaches_its_item() {
1217        let menu_bar = MockMenuBar::new();
1218        let tester = &mut tester_with_menu_bar(&menu_bar);
1219        let chosen = Rc::new(RefCell::new(Vec::new()));
1220        tester.pump_widget(PlatformMenuBar::new(menus(&chosen)));
1221
1222        let set = menu_bar.menus();
1223        let [
1224            MenuEntry::Submenu {
1225                label,
1226                enabled,
1227                entries,
1228                ..
1229            },
1230        ] = &set[..]
1231        else {
1232            panic!("one top-level menu: {set:?}");
1233        };
1234        assert_eq!(label, "File");
1235        assert!(enabled);
1236        let [
1237            MenuEntry::Item { item: open, .. },
1238            MenuEntry::Separator,
1239            MenuEntry::Item { item: save, .. },
1240            MenuEntry::Separator,
1241            MenuEntry::Provided { item, .. },
1242        ] = &entries[..]
1243        else {
1244            panic!("Open, the group between separators, and Quit: {entries:?}");
1245        };
1246        assert!(open.enabled);
1247        assert_eq!(
1248            open.shortcut,
1249            Some(MenuShortcut {
1250                key: LogicalKeyboardKey::KEY_O.key_id,
1251                modifiers: ShortcutModifiers {
1252                    meta: true,
1253                    ..ShortcutModifiers::default()
1254                },
1255            })
1256        );
1257        assert!(!save.enabled, "an item with no callback is disabled");
1258        assert_eq!(*item, ProvidedItem::Quit);
1259
1260        let open_id = menu_bar.id_of(&["File", "Open"]).expect("Open has an id");
1261        choose(tester, open_id);
1262        assert_eq!(*chosen.borrow(), ["Open"]);
1263    }
1264
1265    /// Reports the choice of `id` as the host does, through the platform callback the delegate
1266    /// set.
1267    fn choose(tester: &WidgetTester, id: MenuId) {
1268        tester.update(|app| {
1269            let callback = app
1270                .platform_callbacks()
1271                .on_menu_selected
1272                .clone()
1273                .expect("the default delegate hears choices");
1274            callback(app, id);
1275        });
1276    }
1277
1278    #[test]
1279    fn leading_trailing_and_doubled_dividers_are_stripped() {
1280        let menu_bar = MockMenuBar::new();
1281        let tester = &mut tester_with_menu_bar(&menu_bar);
1282        let item = || -> PlatformMenuItemRef { Rc::new(PlainPlatformMenuItem::new("Item")) };
1283        let group =
1284            |members| -> PlatformMenuItemRef { Rc::new(PlatformMenuItemGroup::new(members)) };
1285        tester.pump_widget(PlatformMenuBar::new(vec![Rc::new(PlatformMenu::new(
1286            "Menu",
1287            vec![
1288                group(vec![item()]),
1289                group(vec![item()]),
1290                group(vec![item()]),
1291            ],
1292        ))]));
1293        let [MenuEntry::Submenu { entries, .. }] = &menu_bar.menus()[..] else {
1294            panic!("one menu");
1295        };
1296        let shape: Vec<bool> = entries
1297            .iter()
1298            .map(|entry| matches!(entry, MenuEntry::Separator))
1299            .collect();
1300        assert_eq!(shape, [false, true, false, true, false]);
1301    }
1302
1303    #[test]
1304    fn a_platform_without_a_menu_bar_shows_the_menus_nowhere() {
1305        let tester = &mut WidgetTester::on(TargetPlatform::Windows);
1306        let chosen = Rc::new(RefCell::new(Vec::new()));
1307        tester.pump_widget(PlatformMenuBar::new(menus(&chosen)));
1308        assert!(
1309            !tester.update(|app| PlatformProvidedMenuItem::has_menu(
1310                app,
1311                PlatformProvidedMenuItemType::Quit
1312            )),
1313            "Windows provides no Quit item"
1314        );
1315    }
1316}