1use std::collections::{HashMap, HashSet};
8use std::fmt::{self, Debug};
9use std::rc::Rc;
10use std::sync::LazyLock;
11
12use waft_foundation::{
13 App, ChangeNotifier, ChangeNotifierData, DiagnosticPropertiesBuilder, DiagnosticableNode,
14 DiagnosticsProperty, FlagProperty, Handle, HandleId, ListenableObject, Listener,
15 MessageProperty, OptionRetained, Ref, Retained, describe_identity,
16};
17use waft_scheduler::{FrameCallback, SchedulerBinding};
18use waft_services::{
19 HardwareKeyboard, KeyEvent, KeyboardKey, KeyboardLockMode, LogicalKeyboardKey,
20};
21
22use crate::framework::{
23 BuildContext, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
24 StatelessWidget, WidgetRef,
25};
26use crate::widgets::actions::{Actions, IntentRef};
27use crate::widgets::focus_manager::{AnyFocusNode, KeyEventResult, primary_focus};
28use crate::widgets::focus_scope::Focus;
29
30static CONTROL_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
31 LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::CONTROL]))
32});
33static SHIFT_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
34 LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::SHIFT]))
35});
36static ALT_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
37 LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::ALT]))
38});
39static META_SYNONYMS: LazyLock<HashSet<LogicalKeyboardKey>> = LazyLock::new(|| {
40 LogicalKeyboardKey::expand_synonyms(&HashSet::from([LogicalKeyboardKey::META]))
41});
42
43#[derive(Clone, PartialEq, Eq)]
56pub struct KeySet<T: KeyboardKey + std::hash::Hash> {
57 keys: HashSet<T>,
58}
59
60impl<T: KeyboardKey + std::hash::Hash> KeySet<T> {
61 pub fn new(key1: T, key2: Option<T>, key3: Option<T>, key4: Option<T>) -> KeySet<T> {
67 let mut keys = HashSet::from([key1]);
68 let mut count = 1;
69 for key in [key2, key3, key4].into_iter().flatten() {
70 keys.insert(key);
71 count += 1;
72 }
73 debug_assert!(
74 keys.len() == count,
75 "Two or more provided keys are identical. Each key must appear only once."
76 );
77 KeySet { keys }
78 }
79
80 pub fn from_set(keys: HashSet<T>) -> KeySet<T> {
84 debug_assert!(!keys.is_empty());
85 KeySet { keys }
86 }
87
88 pub fn keys(&self) -> HashSet<T> {
90 self.keys.clone()
91 }
92}
93
94impl<T: KeyboardKey + std::hash::Hash> Debug for KeySet<T> {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 f.debug_struct("KeySet").field("keys", &self.keys).finish()
97 }
98}
99
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102pub enum LockState {
103 #[default]
105 Ignored,
106
107 Locked,
109
110 Unlocked,
112}
113
114pub trait ShortcutActivator: Debug {
138 fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
160 None
161 }
162
163 fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool;
177
178 fn debug_describe_keys(&self) -> String;
182
183 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
186 let _ = properties;
187 }
188
189 fn to_string_short(&self) -> String {
191 describe_identity(
192 waft_foundation::bare_type_name(std::any::type_name::<Self>()),
193 self as *const Self as *const () as usize as u64,
194 )
195 }
196
197 fn diagnostic_string(&self) -> String {
199 use waft_foundation::{DiagnosticLevel, DiagnosticsNode, DiagnosticsTreeStyle};
200 let mut builder = DiagnosticPropertiesBuilder::new();
201 self.debug_fill_properties(&mut builder);
202 DiagnosticableNode::from_parts(None, self.to_string_short(), builder)
203 .with_style(DiagnosticsTreeStyle::SingleLine)
204 .to_string_with(None, DiagnosticLevel::Info)
205 }
206}
207
208pub type ShortcutActivatorRef = Rc<dyn ShortcutActivator>;
210
211pub type ShortcutMap = Vec<(ShortcutActivatorRef, IntentRef)>;
214
215#[derive(Clone, PartialEq, Eq)]
230pub struct LogicalKeySet {
231 key_set: KeySet<LogicalKeyboardKey>,
234 triggers: HashSet<LogicalKeyboardKey>,
235}
236
237impl LogicalKeySet {
238 pub fn new(
244 key1: LogicalKeyboardKey,
245 key2: Option<LogicalKeyboardKey>,
246 key3: Option<LogicalKeyboardKey>,
247 key4: Option<LogicalKeyboardKey>,
248 ) -> LogicalKeySet {
249 LogicalKeySet::of(KeySet::new(key1, key2, key3, key4))
250 }
251
252 pub fn from_set(keys: HashSet<LogicalKeyboardKey>) -> LogicalKeySet {
254 LogicalKeySet::of(KeySet::from_set(keys))
255 }
256
257 fn of(key_set: KeySet<LogicalKeyboardKey>) -> LogicalKeySet {
258 let triggers = key_set
259 .keys()
260 .into_iter()
261 .flat_map(|key| match unmap_synonyms(key) {
262 Some(keys) => keys,
263 None => vec![key],
264 })
265 .collect();
266 LogicalKeySet { key_set, triggers }
267 }
268
269 pub fn keys(&self) -> HashSet<LogicalKeyboardKey> {
271 self.key_set.keys()
272 }
273
274 fn check_key_requirements(&self, pressed: &HashSet<LogicalKeyboardKey>) -> bool {
275 let collapsed_required = LogicalKeyboardKey::collapse_synonyms(&self.keys());
276 let collapsed_pressed = LogicalKeyboardKey::collapse_synonyms(pressed);
277 collapsed_required.len() == collapsed_pressed.len()
278 && collapsed_required.difference(&collapsed_pressed).count() == 0
279 }
280}
281
282fn modifiers() -> [LogicalKeyboardKey; 4] {
284 [
285 LogicalKeyboardKey::ALT,
286 LogicalKeyboardKey::CONTROL,
287 LogicalKeyboardKey::META,
288 LogicalKeyboardKey::SHIFT,
289 ]
290}
291
292fn unmap_synonyms(key: LogicalKeyboardKey) -> Option<Vec<LogicalKeyboardKey>> {
294 if key == LogicalKeyboardKey::CONTROL {
295 return Some(vec![
296 LogicalKeyboardKey::CONTROL_LEFT,
297 LogicalKeyboardKey::CONTROL_RIGHT,
298 ]);
299 }
300 if key == LogicalKeyboardKey::SHIFT {
301 return Some(vec![
302 LogicalKeyboardKey::SHIFT_LEFT,
303 LogicalKeyboardKey::SHIFT_RIGHT,
304 ]);
305 }
306 if key == LogicalKeyboardKey::ALT {
307 return Some(vec![
308 LogicalKeyboardKey::ALT_LEFT,
309 LogicalKeyboardKey::ALT_RIGHT,
310 ]);
311 }
312 if key == LogicalKeyboardKey::META {
313 return Some(vec![
314 LogicalKeyboardKey::META_LEFT,
315 LogicalKeyboardKey::META_RIGHT,
316 ]);
317 }
318 None
319}
320
321impl Debug for LogicalKeySet {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_struct("LogicalKeySet")
324 .field("keys", &self.debug_describe_keys())
325 .finish()
326 }
327}
328
329impl ShortcutActivator for LogicalKeySet {
330 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
331 properties.add(DiagnosticsProperty::<String>::new(
332 "keys",
333 Some(self.debug_describe_keys()),
334 ));
335 }
336
337 fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
338 Some(self.triggers.iter().copied().collect())
339 }
340
341 fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool {
342 if !matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_)) {
343 return false;
344 }
345 self.triggers.contains(&event.logical_key())
346 && self.check_key_requirements(&state.logical_keys_pressed(app))
347 }
348
349 fn debug_describe_keys(&self) -> String {
350 let mut sorted_keys: Vec<LogicalKeyboardKey> = self.keys().into_iter().collect();
351 sorted_keys.sort_by(|a, b| {
352 let a_is_modifier = !a.synonyms().is_empty() || modifiers().contains(a);
355 let b_is_modifier = !b.synonyms().is_empty() || modifiers().contains(b);
356 if a_is_modifier && !b_is_modifier {
357 return std::cmp::Ordering::Less;
358 }
359 if b_is_modifier && !a_is_modifier {
360 return std::cmp::Ordering::Greater;
361 }
362 a.debug_name().cmp(&b.debug_name())
363 });
364 sorted_keys
365 .iter()
366 .map(|key| {
367 key.debug_name()
368 .expect("a LogicalKeyboardKey has a debug name")
369 })
370 .collect::<Vec<String>>()
371 .join(" + ")
372 }
373}
374
375#[derive(Clone, Copy, Debug, PartialEq, Eq)]
405pub struct SingleActivator {
406 pub trigger: LogicalKeyboardKey,
412
413 pub control: bool,
420
421 pub shift: bool,
428
429 pub alt: bool,
436
437 pub meta: bool,
444
445 pub num_lock: LockState,
453
454 pub include_repeats: bool,
460}
461
462impl SingleActivator {
463 pub fn new(trigger: LogicalKeyboardKey) -> SingleActivator {
470 debug_assert!(
471 ![
472 LogicalKeyboardKey::CONTROL,
473 LogicalKeyboardKey::CONTROL_LEFT,
474 LogicalKeyboardKey::CONTROL_RIGHT,
475 LogicalKeyboardKey::SHIFT,
476 LogicalKeyboardKey::SHIFT_LEFT,
477 LogicalKeyboardKey::SHIFT_RIGHT,
478 LogicalKeyboardKey::ALT,
479 LogicalKeyboardKey::ALT_LEFT,
480 LogicalKeyboardKey::ALT_RIGHT,
481 LogicalKeyboardKey::META,
482 LogicalKeyboardKey::META_LEFT,
483 LogicalKeyboardKey::META_RIGHT,
484 ]
485 .contains(&trigger)
486 );
487 SingleActivator {
488 trigger,
489 control: false,
490 shift: false,
491 alt: false,
492 meta: false,
493 num_lock: LockState::Ignored,
494 include_repeats: true,
495 }
496 }
497
498 pub fn control(mut self, control: bool) -> SingleActivator {
500 self.control = control;
501 self
502 }
503
504 pub fn shift(mut self, shift: bool) -> SingleActivator {
506 self.shift = shift;
507 self
508 }
509
510 pub fn alt(mut self, alt: bool) -> SingleActivator {
512 self.alt = alt;
513 self
514 }
515
516 pub fn meta(mut self, meta: bool) -> SingleActivator {
518 self.meta = meta;
519 self
520 }
521
522 pub fn num_lock(mut self, num_lock: LockState) -> SingleActivator {
524 self.num_lock = num_lock;
525 self
526 }
527
528 pub fn include_repeats(mut self, include_repeats: bool) -> SingleActivator {
530 self.include_repeats = include_repeats;
531 self
532 }
533
534 fn should_accept_modifiers(&self, pressed: &HashSet<LogicalKeyboardKey>) -> bool {
535 self.control == intersects(pressed, &CONTROL_SYNONYMS)
536 && self.shift == intersects(pressed, &SHIFT_SYNONYMS)
537 && self.alt == intersects(pressed, &ALT_SYNONYMS)
538 && self.meta == intersects(pressed, &META_SYNONYMS)
539 }
540
541 fn should_accept_num_lock(&self, app: &App, state: Handle<HardwareKeyboard>) -> bool {
542 match self.num_lock {
543 LockState::Ignored => true,
544 LockState::Locked => state
545 .lock_modes_enabled(app)
546 .contains(&KeyboardLockMode::NumLock),
547 LockState::Unlocked => !state
548 .lock_modes_enabled(app)
549 .contains(&KeyboardLockMode::NumLock),
550 }
551 }
552}
553
554fn intersects(
556 pressed: &HashSet<LogicalKeyboardKey>,
557 synonyms: &HashSet<LogicalKeyboardKey>,
558) -> bool {
559 pressed.intersection(synonyms).next().is_some()
560}
561
562impl ShortcutActivator for SingleActivator {
563 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
564 properties.add(MessageProperty::new("keys", self.debug_describe_keys()));
565 properties.add(
566 FlagProperty::new("includeRepeats", Some(self.include_repeats))
567 .if_false("excluding repeats"),
568 );
569 }
570
571 fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
572 Some(vec![self.trigger])
573 }
574
575 fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool {
576 (matches!(event, KeyEvent::Down(_))
577 || (self.include_repeats && matches!(event, KeyEvent::Repeat(_))))
578 && self.trigger == event.logical_key()
579 && self.should_accept_modifiers(&state.logical_keys_pressed(app))
580 && self.should_accept_num_lock(app, state)
581 }
582
583 fn debug_describe_keys(&self) -> String {
585 let mut keys: Vec<String> = Vec::new();
586 if self.control {
587 keys.push("Control".to_string());
588 }
589 if self.alt {
590 keys.push("Alt".to_string());
591 }
592 if self.meta {
593 keys.push("Meta".to_string());
594 }
595 if self.shift {
596 keys.push("Shift".to_string());
597 }
598 keys.push(
599 self.trigger
600 .debug_name()
601 .unwrap_or_else(|| format!("{:?}", self.trigger)),
602 );
603 keys.join(" + ")
604 }
605}
606
607#[derive(Clone, Debug, PartialEq, Eq)]
630pub struct CharacterActivator {
631 pub alt: bool,
638
639 pub control: bool,
646
647 pub meta: bool,
654
655 pub include_repeats: bool,
662
663 pub character: String,
671}
672
673impl CharacterActivator {
674 pub fn new(character: impl Into<String>) -> CharacterActivator {
676 CharacterActivator {
677 alt: false,
678 control: false,
679 meta: false,
680 include_repeats: true,
681 character: character.into(),
682 }
683 }
684
685 pub fn alt(mut self, alt: bool) -> CharacterActivator {
687 self.alt = alt;
688 self
689 }
690
691 pub fn control(mut self, control: bool) -> CharacterActivator {
693 self.control = control;
694 self
695 }
696
697 pub fn meta(mut self, meta: bool) -> CharacterActivator {
699 self.meta = meta;
700 self
701 }
702
703 pub fn include_repeats(mut self, include_repeats: bool) -> CharacterActivator {
705 self.include_repeats = include_repeats;
706 self
707 }
708
709 fn should_accept_modifiers(&self, pressed: &HashSet<LogicalKeyboardKey>) -> bool {
710 self.control == intersects(pressed, &CONTROL_SYNONYMS)
712 && self.alt == intersects(pressed, &ALT_SYNONYMS)
713 && self.meta == intersects(pressed, &META_SYNONYMS)
714 }
715}
716
717impl ShortcutActivator for CharacterActivator {
718 fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
719 properties.add(MessageProperty::new(
720 "character",
721 self.debug_describe_keys(),
722 ));
723 properties.add(
724 FlagProperty::new("includeRepeats", Some(self.include_repeats))
725 .if_false("excluding repeats"),
726 );
727 }
728
729 fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool {
730 event.character() == Some(self.character.as_str())
732 && (matches!(event, KeyEvent::Down(_))
733 || (self.include_repeats && matches!(event, KeyEvent::Repeat(_))))
734 && self.should_accept_modifiers(&state.logical_keys_pressed(app))
735 }
736
737 fn debug_describe_keys(&self) -> String {
738 let mut keys: Vec<String> = Vec::new();
739 if self.alt {
740 keys.push("Alt".to_string());
741 }
742 if self.control {
743 keys.push("Control".to_string());
744 }
745 if self.meta {
746 keys.push("Meta".to_string());
747 }
748 keys.push(format!("'{}'", self.character));
749 keys.join(" + ")
750 }
751}
752
753pub struct ActivatorIntentPair {
756 activator: ShortcutActivatorRef,
757 intent: IntentRef,
758}
759
760impl ActivatorIntentPair {
761 pub fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
763 properties.add(DiagnosticsProperty::<String>::new(
764 "activator",
765 Some(self.activator.debug_describe_keys()),
766 ));
767 properties.add(DiagnosticsProperty::<String>::new(
768 "intent",
769 Some(self.intent.diagnostic_string()),
770 ));
771 }
772}
773
774pub struct ShortcutManagerData {
780 modal: bool,
781 shortcuts: ShortcutMap,
782 indexed_shortcuts_cache:
783 Option<Rc<HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>>>>,
784}
785
786impl ShortcutManagerData {
787 pub fn new() -> ShortcutManagerData {
789 ShortcutManagerData {
790 modal: false,
791 shortcuts: Vec::new(),
792 indexed_shortcuts_cache: None,
793 }
794 }
795}
796
797impl Default for ShortcutManagerData {
798 fn default() -> ShortcutManagerData {
799 ShortcutManagerData::new()
800 }
801}
802
803#[macro_export]
806macro_rules! shortcut_manager_accessors {
807 () => {
808 fn shortcut_manager_data(
809 self: ::waft_foundation::Handle<Self>,
810 app: &::waft_foundation::App,
811 ) -> &$crate::ShortcutManagerData {
812 &app.get(self).shortcut_manager
813 }
814
815 fn shortcut_manager_data_mut(
816 self: ::waft_foundation::Handle<Self>,
817 app: &mut ::waft_foundation::App,
818 ) -> &mut $crate::ShortcutManagerData {
819 &mut app.get_mut(self).shortcut_manager
820 }
821 };
822}
823
824pub trait ShortcutManagerBase: ChangeNotifier + Sized + 'static {
830 fn shortcut_manager_data(self: Handle<Self>, app: &App) -> &ShortcutManagerData;
833
834 fn shortcut_manager_data_mut(self: Handle<Self>, app: &mut App) -> &mut ShortcutManagerData;
836
837 fn as_shortcut_manager(self: Handle<Self>) -> AnyShortcutManager {
840 AnyShortcutManager {
841 id: self.id(),
842 vtable: const { &ShortcutManagerVTable::of::<Self>() },
843 }
844 }
845
846 fn modal(self: Handle<Self>, app: &App) -> bool {
858 self.shortcut_manager_data(app).modal
859 }
860
861 fn set_modal(self: Handle<Self>, app: &mut App, modal: bool) {
863 self.shortcut_manager_data_mut(app).modal = modal;
864 }
865
866 fn shortcuts(self: Handle<Self>, app: &App) -> ShortcutMap {
870 self.shortcut_manager_data(app).shortcuts.clone()
871 }
872
873 fn set_shortcuts(self: Handle<Self>, app: &mut App, value: ShortcutMap) {
875 if !same_shortcuts(&self.shortcut_manager_data(app).shortcuts, &value) {
876 let data = self.shortcut_manager_data_mut(app);
877 data.shortcuts = value;
878 data.indexed_shortcuts_cache = None;
879 self.notify_listeners(app);
880 }
881 }
882
883 fn indexed_shortcuts(
885 self: Handle<Self>,
886 app: &mut App,
887 ) -> Rc<HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>>> {
888 if let Some(cache) = self
889 .shortcut_manager_data(app)
890 .indexed_shortcuts_cache
891 .clone()
892 {
893 return cache;
894 }
895 let indexed = Rc::new(index_shortcuts(&self.shortcut_manager_data(app).shortcuts));
896 self.shortcut_manager_data_mut(app).indexed_shortcuts_cache = Some(Rc::clone(&indexed));
897 indexed
898 }
899
900 fn find(
904 self: Handle<Self>,
905 app: &mut App,
906 event: &KeyEvent,
907 state: Handle<HardwareKeyboard>,
908 ) -> Option<IntentRef> {
909 let indexed = self.indexed_shortcuts(app);
910 let key = Some(event.logical_key());
911 let candidates = indexed
912 .get(&key)
913 .into_iter()
914 .flatten()
915 .chain(indexed.get(&None).into_iter().flatten());
916 for activator_intent in candidates {
917 if activator_intent.activator.accepts(app, event, state) {
918 return Some(Rc::clone(&activator_intent.intent));
919 }
920 }
921 None
922 }
923
924 fn handle_keypress(
939 self: Handle<Self>,
940 app: &mut App,
941 context: BuildContext,
942 event: &KeyEvent,
943 ) -> KeyEventResult {
944 ShortcutManagerKeypress::handle_keypress(self, app, context, event)
945 }
946}
947
948pub trait ShortcutManagerKeypress: ShortcutManagerBase {
955 fn handle_keypress(
957 self: Handle<Self>,
958 app: &mut App,
959 context: BuildContext,
960 event: &KeyEvent,
961 ) -> KeyEventResult {
962 let _ = context;
964 let keyboard = HardwareKeyboard::instance(app);
965 let intent = self.find(app, event, keyboard);
966 let context = primary_focus(app).and_then(|node| node.context(app));
967
968 if let Some(intent) = intent
969 && let Some(context) = context
970 && let Some(action) = Actions::maybe_find(app, context, intent.intent_type())
971 {
972 let (enabled, invoke_result) = Actions::of(app, context).invoke_action_if_enabled(
973 app,
974 action,
975 &*intent,
976 Some(context),
977 );
978 if enabled {
979 return action.to_key_event_result(app, &*intent, invoke_result.as_ref());
980 }
981 }
982 if self.modal(app) {
983 KeyEventResult::SkipRemainingHandlers
984 } else {
985 KeyEventResult::Ignored
986 }
987 }
988}
989
990impl<T: ShortcutManagerBase> ShortcutManagerKeypress for T {}
991
992struct ShortcutManagerVTable {
994 type_name: fn() -> &'static str,
995 shortcuts: fn(&App, HandleId) -> ShortcutMap,
996 set_shortcuts: fn(&mut App, HandleId, ShortcutMap),
997 modal: fn(&App, HandleId) -> bool,
998 set_modal: fn(&mut App, HandleId, bool),
999 handle_keypress: fn(&mut App, HandleId, BuildContext, &KeyEvent) -> KeyEventResult,
1000 dispose: fn(&mut App, HandleId),
1001}
1002
1003fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
1005 Handle::from_id(id)
1006}
1007
1008impl ShortcutManagerVTable {
1009 const fn of<L: ShortcutManagerBase>() -> ShortcutManagerVTable {
1010 ShortcutManagerVTable {
1011 type_name: std::any::type_name::<L>,
1012 shortcuts: |app, id| L::shortcuts(resolve(id), app),
1013 set_shortcuts: |app, id, value| L::set_shortcuts(resolve(id), app, value),
1014 modal: |app, id| L::modal(resolve(id), app),
1015 set_modal: |app, id, value| L::set_modal(resolve(id), app, value),
1016 handle_keypress: |app, id, context, event| {
1017 L::handle_keypress(resolve(id), app, context, event)
1018 },
1019 dispose: |app, id| {
1020 let handle: Handle<L> = resolve(id);
1021 ChangeNotifierData::dispose(app, handle);
1022 },
1023 }
1024 }
1025}
1026
1027#[derive(Clone, Copy)]
1031pub struct AnyShortcutManager {
1032 id: HandleId,
1033 vtable: &'static ShortcutManagerVTable,
1034}
1035
1036pub type ShortcutManagerRef = Retained<AnyShortcutManager>;
1038
1039waft_foundation::erased_handle!(AnyShortcutManager: ShortcutManagerBase => ShortcutManagerBase::as_shortcut_manager);
1040
1041impl fmt::Debug for AnyShortcutManager {
1042 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1043 write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1044 }
1045}
1046
1047impl AnyShortcutManager {
1048 pub fn id(self) -> HandleId {
1050 self.id
1051 }
1052
1053 pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
1055 app.handle::<T>(self.id)
1056 }
1057
1058 pub fn shortcuts(self, app: &App) -> ShortcutMap {
1060 (self.vtable.shortcuts)(app, self.id)
1061 }
1062
1063 pub fn set_shortcuts(self, app: &mut App, value: ShortcutMap) {
1065 (self.vtable.set_shortcuts)(app, self.id, value);
1066 }
1067
1068 pub fn modal(self, app: &App) -> bool {
1070 (self.vtable.modal)(app, self.id)
1071 }
1072
1073 pub fn set_modal(self, app: &mut App, value: bool) {
1075 (self.vtable.set_modal)(app, self.id, value);
1076 }
1077
1078 pub fn handle_keypress(
1080 self,
1081 app: &mut App,
1082 context: BuildContext,
1083 event: &KeyEvent,
1084 ) -> KeyEventResult {
1085 (self.vtable.handle_keypress)(app, self.id, context, event)
1086 }
1087
1088 pub fn dispose(self, app: &mut App) {
1090 (self.vtable.dispose)(app, self.id);
1091 }
1092}
1093
1094pub struct ShortcutManager {
1103 change_notifier: ChangeNotifierData,
1104 shortcut_manager: ShortcutManagerData,
1105}
1106
1107impl ShortcutManager {
1108 pub fn new(app: &mut App) -> Ref<ShortcutManager> {
1112 app.create(ShortcutManager {
1113 change_notifier: ChangeNotifierData::new(),
1114 shortcut_manager: ShortcutManagerData::new(),
1115 })
1116 }
1117}
1118
1119impl ShortcutManagerBase for ShortcutManager {
1120 crate::shortcut_manager_accessors!();
1121}
1122
1123impl ShortcutManager {
1124 pub fn debug_fill_properties(
1127 self: Handle<Self>,
1128 app: &App,
1129 properties: &mut DiagnosticPropertiesBuilder,
1130 ) {
1131 let shortcuts = self.shortcuts(app);
1132 properties.add(DiagnosticsProperty::<String>::new(
1133 "shortcuts",
1134 Some(describe_shortcut_map_for_diagnostics(&shortcuts)),
1135 ));
1136 properties.add(
1137 FlagProperty::new("modal", Some(self.modal(app)))
1138 .if_true("modal")
1139 .default_value(Some(false)),
1140 );
1141 }
1142}
1143
1144fn describe_shortcut_map_for_diagnostics(shortcuts: &ShortcutMap) -> String {
1147 let entries: Vec<String> = shortcuts
1148 .iter()
1149 .map(|(activator, intent)| {
1150 format!(
1151 "{}: {}",
1152 activator.diagnostic_string(),
1153 intent.diagnostic_string()
1154 )
1155 })
1156 .collect();
1157 format!("{{{}}}", entries.join(", "))
1158}
1159
1160fn describe_shortcut_map(shortcuts: &ShortcutMap) -> String {
1163 let entries: Vec<String> = shortcuts
1164 .iter()
1165 .map(|(activator, intent)| {
1166 format!(
1167 "{{{}}}: {}",
1168 activator.debug_describe_keys(),
1169 intent.diagnostic_string()
1170 )
1171 })
1172 .collect();
1173 format!("{{{}}}", entries.join(", "))
1174}
1175
1176impl ChangeNotifier for ShortcutManager {
1177 fn change_notifier_data(&self) -> &ChangeNotifierData {
1178 &self.change_notifier
1179 }
1180
1181 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1182 &mut self.change_notifier
1183 }
1184}
1185
1186fn index_shortcuts(
1188 source: &ShortcutMap,
1189) -> HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>> {
1190 let mut result: HashMap<Option<LogicalKeyboardKey>, Vec<ActivatorIntentPair>> = HashMap::new();
1191 for (activator, intent) in source {
1192 let nullable_triggers = activator.triggers();
1193 let triggers: Vec<Option<LogicalKeyboardKey>> = match nullable_triggers {
1194 Some(triggers) => triggers.into_iter().map(Some).collect(),
1195 None => vec![None],
1196 };
1197 for trigger in triggers {
1198 result
1199 .entry(trigger)
1200 .or_default()
1201 .push(ActivatorIntentPair {
1202 activator: Rc::clone(activator),
1203 intent: Rc::clone(intent),
1204 });
1205 }
1206 }
1207 result
1208}
1209
1210fn same_shortcuts(a: &ShortcutMap, b: &ShortcutMap) -> bool {
1212 a.len() == b.len()
1213 && a.iter()
1214 .zip(b.iter())
1215 .all(|(a, b)| Rc::ptr_eq(&a.0, &b.0) && Rc::ptr_eq(&a.1, &b.1))
1216}
1217
1218pub struct Shortcuts {
1238 pub key: Option<KeyRef>,
1240
1241 pub manager: Option<ShortcutManagerRef>,
1249
1250 pub child: WidgetRef,
1252
1253 pub debug_label: Option<String>,
1257
1258 pub include_semantics: bool,
1262
1263 shortcuts: ShortcutMap,
1265}
1266
1267impl Shortcuts {
1268 #[cfg_attr(debug_assertions, track_caller)]
1278 pub fn new<K>(shortcuts: ShortcutMap, child: impl IntoWidget<K>) -> Shortcuts {
1279 Shortcuts {
1280 key: None,
1281 manager: None,
1282 child: child.into_widget(),
1283 debug_label: None,
1284 include_semantics: true,
1285 shortcuts,
1286 }
1287 }
1288
1289 #[cfg_attr(debug_assertions, track_caller)]
1294 pub fn manager<K>(manager: ShortcutManagerRef, child: impl IntoWidget<K>) -> Shortcuts {
1295 Shortcuts {
1296 manager: Some(manager),
1297 ..Shortcuts::new(Vec::new(), child)
1298 }
1299 }
1300
1301 pub fn key(mut self, key: KeyRef) -> Shortcuts {
1303 self.key = Some(key);
1304 self
1305 }
1306
1307 pub fn debug_label(mut self, debug_label: impl Into<String>) -> Shortcuts {
1309 self.debug_label = Some(debug_label.into());
1310 self
1311 }
1312
1313 pub fn include_semantics(mut self, include_semantics: bool) -> Shortcuts {
1315 self.include_semantics = include_semantics;
1316 self
1317 }
1318
1319 pub fn get_shortcuts(&self, app: &App) -> ShortcutMap {
1323 match self.manager.handle() {
1324 None => self.shortcuts.clone(),
1325 Some(manager) => manager.shortcuts(app),
1326 }
1327 }
1328}
1329
1330impl fmt::Debug for Shortcuts {
1331 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1332 f.debug_struct("Shortcuts")
1333 .field("manager", &self.manager)
1334 .field("debugLabel", &self.debug_label)
1335 .finish_non_exhaustive()
1336 }
1337}
1338
1339impl StatefulWidget for Shortcuts {
1340 type State = ShortcutsState;
1341
1342 fn key(&self) -> Option<&KeyRef> {
1343 self.key.as_ref()
1344 }
1345
1346 fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1347 properties.add(
1348 DiagnosticsProperty::<String>::new(
1349 "manager",
1350 self.manager.as_ref().map(|manager| {
1351 describe_identity("ShortcutManager", manager.id().identity_hash())
1352 }),
1353 )
1354 .default_value(None),
1355 );
1356 let description = match &self.debug_label {
1357 Some(label) if !label.is_empty() => Some(label.clone()),
1358 _ => Some(describe_shortcut_map(&self.shortcuts)),
1359 };
1360 properties
1361 .add(DiagnosticsProperty::<String>::new("shortcuts", description).with_show_name(true));
1362 }
1363
1364 fn create_state(&self) -> ShortcutsState {
1365 ShortcutsState {
1366 state: StateData::new(),
1367 internal_manager: None,
1368 }
1369 }
1370}
1371
1372pub struct ShortcutsState {
1374 state: StateData<Shortcuts>,
1375 internal_manager: Option<Ref<ShortcutManager>>,
1376}
1377
1378impl ShortcutsState {
1379 pub fn manager(self: Handle<Self>, app: &App) -> AnyShortcutManager {
1381 self.widget(app)
1382 .manager
1383 .handle()
1384 .or_else(|| {
1385 app.get(self)
1386 .internal_manager
1387 .handle()
1388 .map(ShortcutManagerBase::as_shortcut_manager)
1389 })
1390 .expect("a Shortcuts state has either the widget's manager or its own")
1391 }
1392
1393 fn handle_on_key_event(
1394 self: Handle<Self>,
1395 app: &mut App,
1396 node: AnyFocusNode,
1397 event: &KeyEvent,
1398 ) -> KeyEventResult {
1399 let Some(context) = node.context(app) else {
1400 return KeyEventResult::Ignored;
1401 };
1402 self.manager(app).handle_keypress(app, context, event)
1403 }
1404}
1405
1406impl State for ShortcutsState {
1407 type Widget = Shortcuts;
1408 crate::state_accessors!();
1409
1410 fn init_state(self: Handle<Self>, app: &mut App) {
1411 if self.widget(app).manager.is_none() {
1412 let manager = ShortcutManager::new(app);
1413 app.get_mut(self).internal_manager = Some(manager.clone());
1414 let shortcuts = self.widget(app).get_shortcuts(app);
1415 manager.set_shortcuts(app, shortcuts);
1416 }
1417 }
1418
1419 fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Shortcuts) {
1420 if self.widget(app).manager != old_widget.manager {
1421 if self.widget(app).manager.is_some() {
1422 if let Some(internal) = app.get_mut(self).internal_manager.take() {
1423 ChangeNotifierData::dispose(app, &internal);
1424 }
1425 } else if app.get(self).internal_manager.is_none() {
1426 let manager = ShortcutManager::new(app);
1427 app.get_mut(self).internal_manager = Some(manager);
1428 }
1429 }
1430 if let Some(internal) = app.get(self).internal_manager.handle() {
1431 let shortcuts = self.widget(app).get_shortcuts(app);
1432 internal.set_shortcuts(app, shortcuts);
1433 }
1434 }
1435
1436 fn dispose(self: Handle<Self>, app: &mut App) {
1437 if let Some(internal) = app.get(self).internal_manager.handle() {
1438 ChangeNotifierData::dispose(app, internal);
1439 }
1440 }
1441
1442 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1443 let widget = self.widget(app);
1444 let debug_label = match &widget.debug_label {
1445 Some(label) => format!("Shortcuts: {label}"),
1446 None => "Shortcuts".to_string(),
1447 };
1448 let include_semantics = widget.include_semantics;
1449 let child = widget.child.clone();
1450 Focus::new(child)
1451 .debug_label(debug_label)
1452 .can_request_focus(false)
1453 .on_key_event(Rc::new(move |app, node, event| {
1454 self.handle_on_key_event(app, node, event)
1455 }))
1456 .include_semantics(include_semantics)
1457 .into_widget()
1458 }
1459}
1460
1461pub struct CallbackShortcuts {
1477 pub key: Option<KeyRef>,
1479
1480 pub bindings: Vec<(ShortcutActivatorRef, Listener)>,
1490
1491 pub child: WidgetRef,
1493}
1494
1495impl CallbackShortcuts {
1496 #[cfg_attr(debug_assertions, track_caller)]
1498 pub fn new<K>(
1499 bindings: Vec<(ShortcutActivatorRef, Listener)>,
1500 child: impl IntoWidget<K>,
1501 ) -> CallbackShortcuts {
1502 CallbackShortcuts {
1503 key: None,
1504 bindings,
1505 child: child.into_widget(),
1506 }
1507 }
1508
1509 pub fn key(mut self, key: KeyRef) -> CallbackShortcuts {
1511 self.key = Some(key);
1512 self
1513 }
1514
1515 fn apply_key_event_binding(
1518 app: &mut App,
1519 binding: &(ShortcutActivatorRef, Listener),
1520 event: &KeyEvent,
1521 ) -> bool {
1522 let keyboard = HardwareKeyboard::instance(app);
1523 if binding.0.accepts(app, event, keyboard) {
1524 binding.1.call(app);
1525 return true;
1526 }
1527 false
1528 }
1529}
1530
1531impl fmt::Debug for CallbackShortcuts {
1532 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1533 f.debug_struct("CallbackShortcuts").finish_non_exhaustive()
1534 }
1535}
1536
1537impl StatelessWidget for CallbackShortcuts {
1538 fn key(&self) -> Option<&KeyRef> {
1539 self.key.as_ref()
1540 }
1541
1542 fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1543 let bindings: Rc<Vec<(ShortcutActivatorRef, Listener)>> = Rc::new(
1544 self.bindings
1545 .iter()
1546 .map(|(activator, callback)| (Rc::clone(activator), callback.clone()))
1547 .collect(),
1548 );
1549 Focus::new(self.child.clone())
1550 .can_request_focus(false)
1551 .skip_traversal(true)
1552 .on_key_event(Rc::new(move |app, _node, event| {
1553 let mut result = KeyEventResult::Ignored;
1554 for binding in bindings.iter() {
1556 result = if CallbackShortcuts::apply_key_event_binding(app, binding, event) {
1557 KeyEventResult::Handled
1558 } else {
1559 result
1560 };
1561 }
1562 result
1563 }))
1564 .into_widget()
1565 }
1566}
1567
1568pub struct ShortcutRegistryEntry {
1577 registry: Ref<ShortcutRegistry>,
1579}
1580
1581impl ShortcutRegistryEntry {
1582 pub fn registry(self: Handle<Self>, app: &App) -> Handle<ShortcutRegistry> {
1584 app.get(self).registry.handle()
1585 }
1586
1587 pub fn replace_all(self: Handle<Self>, app: &mut App, value: ShortcutMap) {
1595 let registry = app.get(self).registry.handle();
1596 registry.replace_all(app, self, value);
1597 }
1598
1599 pub fn dispose(self: Handle<Self>, app: &mut App) {
1604 let registry = app.get(self).registry.handle();
1605 registry.dispose_entry(app, self);
1606 }
1607}
1608
1609pub struct ShortcutRegistry {
1620 change_notifier: ChangeNotifierData,
1621 notification_scheduled: bool,
1622 disposed: bool,
1623 registered_shortcuts: Vec<(Handle<ShortcutRegistryEntry>, ShortcutMap)>,
1629}
1630
1631impl ShortcutRegistry {
1632 pub fn new(app: &mut App) -> Ref<ShortcutRegistry> {
1634 app.create(ShortcutRegistry {
1635 change_notifier: ChangeNotifierData::new(),
1636 notification_scheduled: false,
1637 disposed: false,
1638 registered_shortcuts: Vec::new(),
1639 })
1640 }
1641
1642 pub fn dispose(self: Handle<Self>, app: &mut App) {
1644 ChangeNotifierData::dispose(app, self);
1645 app.get_mut(self).disposed = true;
1646 }
1647
1648 pub fn shortcuts(self: Handle<Self>, app: &App) -> ShortcutMap {
1655 debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
1656 app.get(self).change_notifier_data()
1657 ));
1658 app.get(self)
1659 .registered_shortcuts
1660 .iter()
1661 .flat_map(|(_, shortcuts)| shortcuts.iter().cloned())
1662 .collect()
1663 }
1664
1665 pub fn add_all(
1681 self: Handle<Self>,
1682 app: &mut App,
1683 value: ShortcutMap,
1684 ) -> Ref<ShortcutRegistryEntry> {
1685 debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
1686 app.get(self).change_notifier_data()
1687 ));
1688 debug_assert!(
1689 !value.is_empty(),
1690 "Cannot register an empty map of shortcuts"
1691 );
1692 let registry = self.keep(app);
1693 let entry = app.create(ShortcutRegistryEntry { registry });
1694 app.get_mut(self)
1695 .registered_shortcuts
1696 .push((entry.handle(), value));
1697 self.notify_listeners_next_frame(app);
1698 entry
1699 }
1700
1701 fn notify_listeners_next_frame(self: Handle<Self>, app: &mut App) {
1706 if !app.get(self).notification_scheduled {
1707 let this = self.keep(app);
1708 SchedulerBinding::add_post_frame_callback(
1709 app,
1710 FrameCallback::new(move |app, _duration| {
1711 app.get_mut(&this).notification_scheduled = false;
1712 if !app.get(&this).disposed {
1713 this.notify_listeners(app);
1714 }
1715 }),
1716 None,
1718 );
1719 app.get_mut(self).notification_scheduled = true;
1720 }
1721 }
1722
1723 pub fn of(app: &mut App, context: BuildContext) -> Handle<ShortcutRegistry> {
1733 ShortcutRegistry::maybe_of(app, context).expect(
1734 "Unable to find a ShortcutRegistrar widget in the context.\n\
1735 ShortcutRegistrar.of() was called with a context that does not contain a \
1736 ShortcutRegistrar widget.",
1737 )
1738 }
1739
1740 pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<Handle<ShortcutRegistry>> {
1746 context
1747 .depend_on_inherited_widget_of_exact_type::<ShortcutRegistrarScope>(app)
1748 .map(|inherited| inherited.registry.handle())
1749 }
1750
1751 fn replace_all(
1753 self: Handle<Self>,
1754 app: &mut App,
1755 entry: Handle<ShortcutRegistryEntry>,
1756 value: ShortcutMap,
1757 ) {
1758 debug_assert!(ChangeNotifierData::debug_assert_not_disposed(
1759 app.get(self).change_notifier_data()
1760 ));
1761 debug_assert!(self.debug_check_entry_is_valid(app, entry));
1762 for registered in app.get_mut(self).registered_shortcuts.iter_mut() {
1763 if registered.0 == entry {
1764 registered.1 = value;
1765 break;
1766 }
1767 }
1768 self.notify_listeners_next_frame(app);
1769 }
1770
1771 fn dispose_entry(self: Handle<Self>, app: &mut App, entry: Handle<ShortcutRegistryEntry>) {
1773 debug_assert!(self.debug_check_entry_is_valid(app, entry));
1774 let registered = &mut app.get_mut(self).registered_shortcuts;
1775 let before = registered.len();
1776 registered.retain(|(registered, _)| *registered != entry);
1777 if app.get(self).registered_shortcuts.len() != before {
1778 self.notify_listeners_next_frame(app);
1779 }
1780 }
1781
1782 fn debug_check_entry_is_valid(
1783 self: Handle<Self>,
1784 app: &App,
1785 entry: Handle<ShortcutRegistryEntry>,
1786 ) -> bool {
1787 if !app
1788 .get(self)
1789 .registered_shortcuts
1790 .iter()
1791 .any(|(registered, _)| *registered == entry)
1792 {
1793 assert!(
1794 app.get(entry).registry != self,
1795 "entry {entry:?} is invalid.\nThe entry has already been disposed of. Tokens \
1796 are not valid after dispose is called on them, and should no longer be used."
1797 );
1798 panic!(
1799 "Foreign entry {entry:?} used.\nThis entry was not created by this registry, \
1800 it was created by {:?}, and should be used with that registry instead.",
1801 app.get(entry).registry
1802 );
1803 }
1804 true
1805 }
1806}
1807
1808impl ChangeNotifier for ShortcutRegistry {
1809 fn change_notifier_data(&self) -> &ChangeNotifierData {
1810 &self.change_notifier
1811 }
1812
1813 fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1814 &mut self.change_notifier
1815 }
1816}
1817
1818#[derive(Debug)]
1833pub struct ShortcutRegistrar {
1834 pub key: Option<KeyRef>,
1836
1837 pub child: WidgetRef,
1839}
1840
1841impl ShortcutRegistrar {
1842 #[cfg_attr(debug_assertions, track_caller)]
1844 pub fn new<K>(child: impl IntoWidget<K>) -> ShortcutRegistrar {
1845 ShortcutRegistrar {
1846 key: None,
1847 child: child.into_widget(),
1848 }
1849 }
1850
1851 pub fn key(mut self, key: KeyRef) -> ShortcutRegistrar {
1853 self.key = Some(key);
1854 self
1855 }
1856}
1857
1858impl StatefulWidget for ShortcutRegistrar {
1859 type State = ShortcutRegistrarState;
1860
1861 fn key(&self) -> Option<&KeyRef> {
1862 self.key.as_ref()
1863 }
1864
1865 fn create_state(&self) -> ShortcutRegistrarState {
1866 ShortcutRegistrarState {
1867 state: StateData::new(),
1868 registry: None,
1869 manager: None,
1870 shortcuts_changed: None,
1871 }
1872 }
1873}
1874
1875pub struct ShortcutRegistrarState {
1877 state: StateData<ShortcutRegistrar>,
1878 registry: Option<Ref<ShortcutRegistry>>,
1879 manager: Option<Ref<ShortcutManager>>,
1880 shortcuts_changed: Option<Listener>,
1882}
1883
1884impl ShortcutRegistrarState {
1885 pub fn registry(self: Handle<Self>, app: &App) -> Handle<ShortcutRegistry> {
1887 app.get(self)
1888 .registry
1889 .handle()
1890 .expect("created in init_state")
1891 }
1892
1893 pub fn manager(self: Handle<Self>, app: &App) -> Handle<ShortcutManager> {
1895 app.get(self)
1896 .manager
1897 .handle()
1898 .expect("created in init_state")
1899 }
1900
1901 fn shortcuts_changed(self: Handle<Self>, app: &mut App) {
1902 let registry = self.registry(app);
1905 let shortcuts = registry.shortcuts(app);
1906 self.manager(app).set_shortcuts(app, shortcuts);
1907 }
1908}
1909
1910impl State for ShortcutRegistrarState {
1911 type Widget = ShortcutRegistrar;
1912 crate::state_accessors!();
1913
1914 fn init_state(self: Handle<Self>, app: &mut App) {
1915 let registry = ShortcutRegistry::new(app);
1916 let manager = ShortcutManager::new(app);
1917 let this = app.get_mut(self);
1918 this.registry = Some(registry.clone());
1919 this.manager = Some(manager);
1920 let listener = Listener::handle_method(self, ShortcutRegistrarState::shortcuts_changed);
1921 app.get_mut(self).shortcuts_changed = Some(listener.clone());
1922 registry.add_listener(app, listener);
1923 }
1924
1925 fn dispose(self: Handle<Self>, app: &mut App) {
1926 let registry = self.registry(app);
1927 if let Some(listener) = app.get_mut(self).shortcuts_changed.take() {
1928 registry.remove_listener(app, &listener);
1929 }
1930 registry.dispose(app);
1931 let manager = self.manager(app);
1932 ChangeNotifierData::dispose(app, manager);
1933 }
1934
1935 fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1936 let this = app.get(self);
1937 let registry = this.registry.clone().expect("created in init_state");
1938 let manager: ShortcutManagerRef = this
1939 .manager
1940 .as_ref()
1941 .expect("created in init_state")
1942 .erase();
1943 let child = self.widget(app).child.clone();
1944 ShortcutRegistrarScope {
1945 registry,
1946 child: Shortcuts::manager(manager, child)
1947 .debug_label("<Shortcut Registrar>")
1948 .into_widget(),
1949 }
1950 .into_widget()
1951 }
1952}
1953
1954#[derive(Debug)]
1956struct ShortcutRegistrarScope {
1957 registry: Ref<ShortcutRegistry>,
1958 child: WidgetRef,
1959}
1960
1961impl InheritedWidget for ShortcutRegistrarScope {
1962 fn child(&self) -> &WidgetRef {
1963 &self.child
1964 }
1965
1966 fn update_should_notify(&self, old_widget: &ShortcutRegistrarScope) -> bool {
1967 self.registry != old_widget.registry
1968 }
1969}
1970
1971#[cfg(test)]
1972mod tests {
1973 use std::any::{Any, TypeId};
1974 use std::cell::RefCell;
1975 use std::time::Duration;
1976
1977 use waft_services::{KeyDownEvent, KeyUpEvent, PhysicalKeyboardKey};
1978
1979 use super::*;
1980 use crate::testing::test_widgets;
1981 use crate::widgets::actions::{ActionRef, CallbackAction, Intent};
1982 use crate::widgets::basic::SizedBox;
1983
1984 #[derive(Debug)]
1985 struct SaveIntent;
1986
1987 impl Intent for SaveIntent {
1988 fn as_any(&self) -> &dyn Any {
1989 self
1990 }
1991 }
1992
1993 fn key_down(physical: PhysicalKeyboardKey, logical: LogicalKeyboardKey) -> KeyEvent {
1994 KeyEvent::Down(KeyDownEvent::new(physical, logical, Duration::ZERO))
1995 }
1996
1997 fn key_up(physical: PhysicalKeyboardKey, logical: LogicalKeyboardKey) -> KeyEvent {
1998 KeyEvent::Up(KeyUpEvent::new(physical, logical, Duration::ZERO))
1999 }
2000
2001 fn save_action(app: &mut App, log: &Rc<RefCell<Vec<&'static str>>>) -> ActionRef {
2003 let log = Rc::clone(log);
2004 let action = CallbackAction::<SaveIntent>::new(
2005 app,
2006 Rc::new(move |_app, _intent| {
2007 log.borrow_mut().push("saved");
2008 None
2009 }),
2010 );
2011 action.into_erased()
2012 }
2013
2014 #[test]
2015 fn a_shortcut_maps_a_key_event_to_an_intent_and_invokes_its_action() {
2016 test_widgets(|tester| {
2017 let mut app = tester.cell.borrow_mut();
2018 let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
2019 let action = save_action(&mut app, &log);
2020 let shortcuts: ShortcutMap = vec![(
2021 Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_S).control(true)),
2022 Rc::new(SaveIntent),
2023 )];
2024 drop(app);
2025 tester.pump_widget(Shortcuts::new(
2026 shortcuts,
2027 Actions::new(
2028 HashMap::from([(TypeId::of::<SaveIntent>(), action)]),
2029 Focus::new(SizedBox::shrink()).autofocus(true),
2030 ),
2031 ));
2032 let mut app = tester.cell.borrow_mut();
2033
2034 let keyboard = HardwareKeyboard::instance(&mut app);
2035 assert!(!keyboard.handle_key_event(
2037 &mut app,
2038 &key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
2039 ));
2040 assert!(log.borrow().is_empty());
2041 keyboard.handle_key_event(
2042 &mut app,
2043 &key_up(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S),
2044 );
2045
2046 keyboard.handle_key_event(
2047 &mut app,
2048 &key_down(
2049 PhysicalKeyboardKey::CONTROL_LEFT,
2050 LogicalKeyboardKey::CONTROL_LEFT,
2051 ),
2052 );
2053 assert!(keyboard.handle_key_event(
2054 &mut app,
2055 &key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
2056 ));
2057 assert_eq!(*log.borrow(), ["saved"]);
2058 });
2059 }
2060
2061 #[test]
2062 fn a_logical_key_set_activates_on_the_whole_combination() {
2063 test_widgets(|tester| {
2064 let mut app = tester.cell.borrow_mut();
2065 let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
2066 let action = save_action(&mut app, &log);
2067 let shortcuts: ShortcutMap = vec![(
2068 Rc::new(LogicalKeySet::new(
2069 LogicalKeyboardKey::CONTROL,
2070 Some(LogicalKeyboardKey::KEY_S),
2071 None,
2072 None,
2073 )),
2074 Rc::new(SaveIntent),
2075 )];
2076 drop(app);
2077 tester.pump_widget(Shortcuts::new(
2078 shortcuts,
2079 Actions::new(
2080 HashMap::from([(TypeId::of::<SaveIntent>(), action)]),
2081 Focus::new(SizedBox::shrink()).autofocus(true),
2082 ),
2083 ));
2084 let mut app = tester.cell.borrow_mut();
2085
2086 let keyboard = HardwareKeyboard::instance(&mut app);
2087 keyboard.handle_key_event(
2088 &mut app,
2089 &key_down(
2090 PhysicalKeyboardKey::CONTROL_LEFT,
2091 LogicalKeyboardKey::CONTROL_LEFT,
2092 ),
2093 );
2094 assert!(keyboard.handle_key_event(
2095 &mut app,
2096 &key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
2097 ));
2098 assert_eq!(*log.borrow(), ["saved"]);
2099 });
2100 }
2101
2102 #[test]
2103 fn callback_shortcuts_call_every_binding_that_accepts_the_event() {
2104 test_widgets(|tester| {
2105 let app = tester.cell.borrow();
2106 let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
2107 let first = Rc::clone(&log);
2108 let second = Rc::clone(&log);
2109 let bindings: Vec<(ShortcutActivatorRef, Listener)> = vec![
2110 (
2111 Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_A)),
2112 Listener::new(move |_app| first.borrow_mut().push("first")),
2113 ),
2114 (
2115 Rc::new(CharacterActivator::new("a")),
2116 Listener::new(move |_app| second.borrow_mut().push("second")),
2117 ),
2118 ];
2119 drop(app);
2120 tester.pump_widget(CallbackShortcuts::new(
2121 bindings,
2122 Focus::new(SizedBox::shrink()).autofocus(true),
2123 ));
2124 let mut app = tester.cell.borrow_mut();
2125
2126 let keyboard = HardwareKeyboard::instance(&mut app);
2127 let event = KeyEvent::Down(
2128 KeyDownEvent::new(
2129 PhysicalKeyboardKey::KEY_A,
2130 LogicalKeyboardKey::KEY_A,
2131 Duration::ZERO,
2132 )
2133 .character("a"),
2134 );
2135 assert!(keyboard.handle_key_event(&mut app, &event));
2136 assert_eq!(*log.borrow(), ["first", "second"]);
2137 });
2138 }
2139
2140 #[test]
2141 fn the_manager_reindexes_and_notifies_when_its_shortcuts_change() {
2142 test_widgets(|tester| {
2143 tester.pump_widget(SizedBox::shrink().into_widget());
2144 let mut app = tester.cell.borrow_mut();
2145 let manager = ShortcutManager::new(&mut app);
2146 let notifications: Rc<RefCell<u32>> = Rc::default();
2147 let sink = Rc::clone(¬ifications);
2148 manager.add_listener(&mut app, Listener::new(move |_app| *sink.borrow_mut() += 1));
2149
2150 let activator: ShortcutActivatorRef =
2151 Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_S));
2152 let intent: IntentRef = Rc::new(SaveIntent);
2153 let shortcuts: ShortcutMap = vec![(Rc::clone(&activator), Rc::clone(&intent))];
2154 manager.set_shortcuts(&mut app, shortcuts.clone());
2155 assert_eq!(*notifications.borrow(), 1);
2156
2157 manager.set_shortcuts(&mut app, shortcuts);
2159 assert_eq!(*notifications.borrow(), 1);
2160
2161 let keyboard = HardwareKeyboard::instance(&mut app);
2162 let found = manager.find(
2163 &mut app,
2164 &key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S),
2165 keyboard,
2166 );
2167 assert!(found.is_some_and(|found| Rc::ptr_eq(&found, &intent)));
2168 });
2169 }
2170
2171 #[test]
2172 fn the_registry_merges_its_entries_into_the_registrars_manager() {
2173 test_widgets(|tester| {
2174 let mut app = tester.cell.borrow_mut();
2175 let log: Rc<RefCell<Vec<&'static str>>> = Rc::default();
2176 let action = save_action(&mut app, &log);
2177 let captured: Rc<std::cell::Cell<Option<BuildContext>>> = Rc::default();
2178 let sink = Rc::clone(&captured);
2179 drop(app);
2180 tester.pump_widget(ShortcutRegistrar::new(Actions::new(
2181 HashMap::from([(TypeId::of::<SaveIntent>(), action)]),
2182 crate::widgets::basic::Builder::new(move |_app, context| {
2183 sink.set(Some(context));
2184 Focus::new(SizedBox::shrink()).autofocus(true).into_widget()
2185 }),
2186 )));
2187 let mut app = tester.cell.borrow_mut();
2188 let context = captured.get().expect("the builder ran");
2189
2190 let registry = ShortcutRegistry::of(&mut app, context);
2191 let entry = registry.add_all(
2192 &mut app,
2193 vec![(
2194 Rc::new(SingleActivator::new(LogicalKeyboardKey::KEY_S)),
2195 Rc::new(SaveIntent),
2196 )],
2197 );
2198 waft_scheduler::SchedulerBinding::schedule_frame(
2202 &mut app,
2203 waft_scheduler::FrameTarget::EveryView,
2204 );
2205 drop(app);
2206 tester.pump();
2207 let mut app = tester.cell.borrow_mut();
2208
2209 let keyboard = HardwareKeyboard::instance(&mut app);
2210 assert!(keyboard.handle_key_event(
2211 &mut app,
2212 &key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
2213 ));
2214 assert_eq!(*log.borrow(), ["saved"]);
2215
2216 entry.dispose(&mut app);
2217 waft_scheduler::SchedulerBinding::schedule_frame(
2218 &mut app,
2219 waft_scheduler::FrameTarget::EveryView,
2220 );
2221 drop(app);
2222 tester.pump();
2223 let mut app = tester.cell.borrow_mut();
2224 log.borrow_mut().clear();
2225 keyboard.handle_key_event(
2226 &mut app,
2227 &key_up(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S),
2228 );
2229 assert!(!keyboard.handle_key_event(
2230 &mut app,
2231 &key_down(PhysicalKeyboardKey::KEY_S, LogicalKeyboardKey::KEY_S)
2232 ));
2233 assert!(log.borrow().is_empty());
2234 });
2235 }
2236}
2237
2238#[cfg(test)]
2239mod diagnostics_tests {
2240 use waft_rendering::testing::ignoring_hash_codes;
2241
2242 use super::*;
2243 use crate::testing::describe_properties;
2244 use crate::widgets::actions::ActivateIntent;
2245 use crate::widgets::basic::SizedBox;
2246 use crate::widgets::focus_traversal::{DirectionalFocusIntent, TraversalDirection};
2247
2248 #[test]
2250 fn a_logical_key_set_describes_its_keys() {
2251 let set = LogicalKeySet::new(
2252 LogicalKeyboardKey::KEY_A,
2253 Some(LogicalKeyboardKey::KEY_B),
2254 None,
2255 None,
2256 );
2257 assert_eq!(
2258 describe_properties(|properties| set.debug_fill_properties(properties)),
2259 ["keys: Key A + Key B"]
2260 );
2261 }
2262
2263 #[test]
2265 fn a_single_activator_describes_its_keys_and_repeats() {
2266 let single = SingleActivator::new(LogicalKeyboardKey::KEY_A);
2267 assert_eq!(
2268 describe_properties(|properties| single.debug_fill_properties(properties)),
2269 ["keys: Key A"]
2270 );
2271
2272 let no_repeats = SingleActivator::new(LogicalKeyboardKey::KEY_A).include_repeats(false);
2273 assert_eq!(
2274 describe_properties(|properties| no_repeats.debug_fill_properties(properties)),
2275 ["keys: Key A", "excluding repeats"]
2276 );
2277
2278 let combination = SingleActivator::new(LogicalKeyboardKey::KEY_A)
2279 .control(true)
2280 .shift(true)
2281 .alt(true)
2282 .meta(true);
2283 assert_eq!(
2284 describe_properties(|properties| combination.debug_fill_properties(properties)),
2285 ["keys: Control + Alt + Meta + Shift + Key A"]
2286 );
2287 }
2288
2289 #[test]
2291 fn shortcuts_describe_their_map() {
2292 let shortcuts: ShortcutMap = vec![
2293 (
2294 Rc::new(LogicalKeySet::new(
2295 LogicalKeyboardKey::SHIFT,
2296 Some(LogicalKeyboardKey::KEY_A),
2297 None,
2298 None,
2299 )),
2300 Rc::new(ActivateIntent),
2301 ),
2302 (
2303 Rc::new(LogicalKeySet::new(
2304 LogicalKeyboardKey::SHIFT,
2305 Some(LogicalKeyboardKey::ARROW_RIGHT),
2306 None,
2307 None,
2308 )),
2309 Rc::new(DirectionalFocusIntent::new(TraversalDirection::Right)),
2310 ),
2311 ];
2312 let widget = Shortcuts::new(shortcuts, SizedBox::shrink());
2313 let cell = waft_foundation::AppCell::new();
2314 let app = cell.borrow();
2315 let description =
2316 describe_properties(|properties| widget.debug_fill_properties(&app, properties));
2317 assert_eq!(
2318 ignoring_hash_codes(&description.join("\n")),
2319 "shortcuts: {{Shift + Key A}: ActivateIntent#00000, {Shift + Arrow Right}: DirectionalFocusIntent#00000(direction: right)}"
2320 );
2321 }
2322
2323 #[test]
2325 fn a_shortcuts_label_replaces_the_map() {
2326 let shortcuts: ShortcutMap = vec![(
2327 Rc::new(LogicalKeySet::new(
2328 LogicalKeyboardKey::KEY_A,
2329 Some(LogicalKeyboardKey::KEY_B),
2330 None,
2331 None,
2332 )),
2333 Rc::new(ActivateIntent),
2334 )];
2335 let widget = Shortcuts::new(shortcuts, SizedBox::shrink()).debug_label("<Debug Label>");
2336 let cell = waft_foundation::AppCell::new();
2337 let app = cell.borrow();
2338 assert_eq!(
2339 describe_properties(|properties| widget.debug_fill_properties(&app, properties)),
2340 ["shortcuts: <Debug Label>"]
2341 );
2342 }
2343}