1use 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#[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 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 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 pub fn trigger(&self) -> Option<LogicalKeyboardKey> {
123 self.trigger
124 }
125
126 pub fn character_value(&self) -> Option<&str> {
128 self.character.as_deref()
129 }
130
131 pub fn alt(&self) -> Option<bool> {
134 self.alt
135 }
136
137 pub fn control(&self) -> Option<bool> {
140 self.control
141 }
142
143 pub fn meta(&self) -> Option<bool> {
146 self.meta
147 }
148
149 pub fn shift(&self) -> Option<bool> {
152 self.shift
153 }
154
155 pub fn to_menu_shortcut(&self) -> MenuShortcut {
157 self.internal
158 }
159}
160
161pub trait MenuSerializableShortcut: Debug {
170 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
189pub trait PlatformMenuDelegate {
201 fn set_menus(&self, app: &mut App, top_level_menus: &[PlatformMenuItemRef]);
209
210 fn clear_menus(&self, app: &mut App);
215
216 fn debug_lock_delegate(&self, context: BuildContext) -> bool;
221
222 fn debug_unlock_delegate(&self, context: BuildContext) -> bool;
227}
228
229pub type PlatformMenuDelegateRef = Rc<dyn PlatformMenuDelegate>;
230
231pub type MenuItemSerializableIdGenerator<'a> = dyn FnMut(PlatformMenuItemRef) -> MenuId + 'a;
234
235pub struct DefaultPlatformMenuDelegate {
242 id_map: RefCell<HashMap<MenuId, PlatformMenuItemRef>>,
244 serial: Cell<MenuId>,
246 locked_context: Cell<Option<BuildContext>>,
249}
250
251impl DefaultPlatformMenuDelegate {
252 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 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 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
292pub(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 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 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
364pub struct PlatformMenuBar {
379 pub key: Option<KeyRef>,
380 pub child: Option<WidgetRef>,
382 pub menus: Vec<PlatformMenuItemRef>,
386}
387
388impl PlatformMenuBar {
389 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 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 self.widget(app)
490 .child
491 .clone()
492 .unwrap_or_else(|| SizedBox::new().into_widget())
493 }
494}
495
496pub(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
503pub trait PlatformMenuItem: Debug {
510 fn label(&self) -> &str;
512
513 fn tooltip(&self) -> Option<&str> {
515 None
516 }
517
518 fn shortcut(&self) -> Option<&MenuSerializableShortcutRef> {
522 None
523 }
524
525 fn on_selected(&self) -> Option<&VoidCallback> {
531 None
532 }
533
534 fn on_open(&self) -> Option<&VoidCallback> {
539 None
540 }
541
542 fn on_close(&self) -> Option<&VoidCallback> {
547 None
548 }
549
550 fn on_selected_intent(&self) -> Option<&IntentRef> {
556 None
557 }
558
559 fn check(&self) -> MenuItemCheck {
561 MenuItemCheck::Plain
562 }
563
564 fn icon(&self) -> Option<&IconImage> {
566 None
567 }
568
569 fn descendants(&self) -> Vec<PlatformMenuItemRef> {
573 Vec::new()
574 }
575
576 fn members(&self) -> Vec<PlatformMenuItemRef> {
581 Vec::new()
582 }
583
584 fn to_menu_entries(
586 self: Rc<Self>,
587 delegate: &dyn PlatformMenuDelegate,
588 get_id: &mut MenuItemSerializableIdGenerator<'_>,
589 ) -> Vec<MenuEntry>;
590
591 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
594 fill_platform_menu_item_properties(self, properties);
595 }
596
597 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 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 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
625pub struct PlatformMenuItemBase;
627
628pub 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 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
672pub 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 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
786pub struct PlatformMenu {
788 pub label: String,
789 pub tooltip: Option<String>,
790 pub on_open: Option<VoidCallback>,
792 pub on_close: Option<VoidCallback>,
794 pub menus: Vec<PlatformMenuItemRef>,
798}
799
800impl PlatformMenu {
801 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 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 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
858pub(crate) fn strip_dividers(result: &mut Vec<MenuEntry>) {
862 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 return false;
871 }
872 if previous_is_divider == Some(true) && is_divider {
873 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 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
941pub struct PlatformMenuItemGroup {
947 pub members: Vec<PlatformMenuItemRef>,
951}
952
953impl PlatformMenuItemGroup {
954 pub fn new(members: Vec<PlatformMenuItemRef>) -> PlatformMenuItemGroup {
956 PlatformMenuItemGroup { members }
957 }
958
959 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
1015pub struct PlatformProvidedMenuItem {
1023 pub type_: PlatformProvidedMenuItemType,
1025 pub enabled: bool,
1027}
1028
1029impl PlatformProvidedMenuItem {
1030 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 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 ""
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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1104pub enum PlatformProvidedMenuItemType {
1105 About,
1107 Quit,
1109 ServicesSubmenu,
1111 Hide,
1113 HideOtherApplications,
1115 ShowAllApplications,
1117 StartSpeaking,
1119 StopSpeaking,
1121 ToggleFullScreen,
1123 MinimizeWindow,
1125 ZoomWindow,
1127 ArrangeWindowsInFront,
1129 Undo,
1131 Redo,
1133 Cut,
1135 Copy,
1137 Paste,
1139 SelectAll,
1141 Delete,
1143}
1144
1145impl PlatformProvidedMenuItemType {
1146 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 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 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 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}