Skip to main content

waft_widgets/widgets/
shortcuts.rs

1//! Flutter counterpart: `widgets/shortcuts.dart`.
2//!
3//! The shortcut system: a [`ShortcutActivator`] describes a key combination, the [`Shortcuts`]
4//! widget maps activators to `Intent`s through a [`ShortcutManager`], and [`ShortcutRegistrar`]
5//! lets descendants add bindings to a shared [`ShortcutRegistry`].
6
7use 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/// A set of `KeyboardKey`s that can be used as the keys in a map.
44///
45/// A key set contains the keys that are down simultaneously to represent a shortcut.
46///
47/// This is a thin wrapper around a set, but changes the equality comparison from an identity
48/// comparison to a contents comparison so that non-identical sets with the same keys in them
49/// will compare as equal.
50///
51/// See also:
52///
53///  * [`ShortcutManager`], which uses [`LogicalKeySet`] (a [`KeySet`] wrapper) to define its key
54///    map.
55#[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    /// A constructor for making a [`KeySet`] of up to four keys.
62    ///
63    /// If you need a set of more than four keys, use [`from_set`](Self::from_set).
64    ///
65    /// The same key may not appear more than once in the set.
66    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    /// Create a [`KeySet`] from a set of keys.
81    ///
82    /// The `keys` set must not be empty.
83    pub fn from_set(keys: HashSet<T>) -> KeySet<T> {
84        debug_assert!(!keys.is_empty());
85        KeySet { keys }
86    }
87
88    /// Returns a copy of the keys in this [`KeySet`].
89    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/// Determines how the state of a lock key is used to accept a shortcut.
101#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
102pub enum LockState {
103    /// The lock key state is not used to determine [`SingleActivator::accepts`] result.
104    #[default]
105    Ignored,
106
107    /// The lock key must be locked to trigger the shortcut.
108    Locked,
109
110    /// The lock key must be unlocked to trigger the shortcut.
111    Unlocked,
112}
113
114/// An interface to define the keyboard key combination to trigger a shortcut.
115///
116/// [`ShortcutActivator`]s are used by [`Shortcuts`] widgets, and are mapped to `Intent`s, the
117/// intended behavior that the key combination should trigger. When a [`Shortcuts`] widget
118/// receives a key event, its [`ShortcutManager`] looks up the first matching
119/// [`ShortcutActivator`], and signals the corresponding `Intent`, which might trigger an action
120/// as defined by a hierarchy of `Actions` widgets.
121///
122/// The matching [`ShortcutActivator`] is looked up in the following way:
123///
124///  * Find the registered [`ShortcutActivator`]s whose [`triggers`](Self::triggers) contain the
125///    incoming event.
126///  * Of the previous list, finds the first activator whose [`accepts`](Self::accepts) returns
127///    true in the order of insertion.
128///
129/// See also:
130///
131///  * [`SingleActivator`], an implementation that represents a single key combined with
132///    modifiers (control, shift, alt, meta).
133///  * [`CharacterActivator`], an implementation that represents key combinations that result in
134///    the specified character, such as question mark.
135///  * [`LogicalKeySet`], an implementation that requires one or more [`LogicalKeyboardKey`]s to
136///    be pressed at the same time. Prefer [`SingleActivator`] when possible.
137pub trait ShortcutActivator: Debug {
138    /// An optional property to provide all the keys that might be the final event to trigger
139    /// this shortcut.
140    ///
141    /// For example, for `Ctrl-A`, `LogicalKeyboardKey::KEY_A` is the only trigger, while
142    /// `LogicalKeyboardKey::CONTROL` is not, because the shortcut should only work by pressing
143    /// KeyA *after* Ctrl, but not before. For `Ctrl-A-E`, on the other hand, both KeyA and KeyE
144    /// should be triggers, since either of them is allowed to trigger.
145    ///
146    /// If provided, trigger keys can be used as a first-pass filter for incoming events in
147    /// order to optimize lookups, as `Intent`s are stored in a map and indexed by trigger keys.
148    /// It is up to the individual implementers of this interface to decide if they ignore
149    /// triggers or not.
150    ///
151    /// Implementations should make sure that the return value of this method does not change
152    /// throughout the lifespan of this object.
153    ///
154    /// This method might also return `None`, which means this activator declares all keys as
155    /// trigger keys. Activators whose [`triggers`](Self::triggers) return `None` will be tested
156    /// with [`accepts`](Self::accepts) on every event. Since this becomes a linear search, and
157    /// having too many might impact performance, it is preferred to return a non-`None`
158    /// [`triggers`](Self::triggers) whenever possible.
159    fn triggers(&self) -> Option<Vec<LogicalKeyboardKey>> {
160        None
161    }
162
163    /// Whether the triggering `event` and the keyboard `state` at the time of the event meet
164    /// required conditions, providing that the event is a triggering event.
165    ///
166    /// For example, for `Ctrl-A`, it has to check if the event is a key down event, if either
167    /// side of the Ctrl key is pressed, and none of the Shift keys, Alt keys, or Meta keys are
168    /// pressed; it doesn't have to check if KeyA is pressed, since it's already guaranteed.
169    ///
170    /// As a possible performance improvement, implementers of this function are encouraged (but
171    /// not required) to check the [`triggers`](Self::triggers) member, if it is not `None`, to
172    /// see if it contains the event's logical key before doing more complicated work.
173    ///
174    /// This method must not cause any side effects for the `state`. Typically this is only used
175    /// to query whether `HardwareKeyboard::logical_keys_pressed` contains a key.
176    fn accepts(&self, app: &App, event: &KeyEvent, state: Handle<HardwareKeyboard>) -> bool;
177
178    /// Returns a description of the key set that is short and readable.
179    ///
180    /// Intended to be used in debug mode for logging purposes.
181    fn debug_describe_keys(&self) -> String;
182
183    /// Dart's `ShortcutActivator.debugFillProperties`, from `Diagnosticable`: an activator
184    /// adds its own fields.
185    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
186        let _ = properties;
187    }
188
189    /// Dart's `ShortcutActivator.toStringShort`: the type and the identity.
190    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    /// Dart's `Diagnosticable.toString`, which a shortcut map's entries print.
198    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
208/// The erased [`ShortcutActivator`]: what a shortcut map is keyed by.
209pub type ShortcutActivatorRef = Rc<dyn ShortcutActivator>;
210
211/// Dart's `Map<ShortcutActivator, Intent>`: the pairs in insertion order, which is the order
212/// [`ShortcutManager`] indexes and searches them in.
213pub type ShortcutMap = Vec<(ShortcutActivatorRef, IntentRef)>;
214
215/// A set of [`LogicalKeyboardKey`]s that can be used as the keys in a map.
216///
217/// [`LogicalKeySet`] can be used as a [`ShortcutActivator`]. It is not recommended to use
218/// [`LogicalKeySet`] for a common shortcut such as `Delete` or `Ctrl+C`, prefer
219/// [`SingleActivator`] when possible, whose behavior more closely resembles that of typical
220/// platforms.
221///
222/// When used as a [`ShortcutActivator`], [`LogicalKeySet`] will activate the intent when all
223/// [`keys`](KeySet::keys) are pressed, and no others, except that modifier keys are considered
224/// without considering sides (e.g. control left and control right are considered the same).
225///
226/// This is also a thin wrapper around a set, but changes the equality comparison from an
227/// identity comparison to a contents comparison so that non-identical sets with the same keys
228/// in them will compare as equal.
229#[derive(Clone, PartialEq, Eq)]
230pub struct LogicalKeySet {
231    /// Dart's `class LogicalKeySet extends KeySet<LogicalKeyboardKey>`: the superclass's
232    /// fields.
233    key_set: KeySet<LogicalKeyboardKey>,
234    triggers: HashSet<LogicalKeyboardKey>,
235}
236
237impl LogicalKeySet {
238    /// A constructor for making a [`LogicalKeySet`] of up to four keys.
239    ///
240    /// If you need a set of more than four keys, use [`from_set`](Self::from_set).
241    ///
242    /// The same [`LogicalKeyboardKey`] may not appear more than once in the set.
243    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    /// Create a [`LogicalKeySet`] from a set of [`LogicalKeyboardKey`]s.
253    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    /// The keys this set was built from.
270    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
282/// Dart's `LogicalKeySet._modifiers`.
283fn modifiers() -> [LogicalKeyboardKey; 4] {
284    [
285        LogicalKeyboardKey::ALT,
286        LogicalKeyboardKey::CONTROL,
287        LogicalKeyboardKey::META,
288        LogicalKeyboardKey::SHIFT,
289    ]
290}
291
292/// Dart's `LogicalKeySet._unmapSynonyms`.
293fn 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            // Put the modifiers first. If it has a synonym, then it's something like shiftLeft,
353            // altRight, etc.
354            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/// A shortcut key combination of a single key and modifiers.
376///
377/// [`SingleActivator`] implements typical shortcuts such as:
378///
379///  * ArrowLeft
380///  * Shift + Delete
381///  * Control + Alt + Meta + Shift + A
382///
383/// More specifically, it creates shortcut key combinations that are composed of a
384/// [`trigger`](Self::trigger) key, and zero, some, or all of the four modifiers (control,
385/// shift, alt, meta). The shortcut is activated when the following conditions are met:
386///
387///  * The incoming event is a down event for a [`trigger`](Self::trigger) key.
388///  * If [`control`](Self::control) is true, then at least one control key must be held.
389///    Otherwise, no control keys must be held.
390///  * Similar conditions apply for the [`alt`](Self::alt), [`shift`](Self::shift), and
391///    [`meta`](Self::meta) keys.
392///
393/// This resembles the typical behavior of most operating systems, and handles modifier keys
394/// differently from [`LogicalKeySet`] in the following way:
395///
396///  * [`SingleActivator`]s allow additional non-modifier keys being pressed in order to
397///    activate the shortcut.
398///  * [`SingleActivator`]s do not consider modifiers to be a trigger key.
399///
400/// See also:
401///
402///  * [`CharacterActivator`], an activator that represents key combinations that result in the
403///    specified character, such as question mark.
404#[derive(Clone, Copy, Debug, PartialEq, Eq)]
405pub struct SingleActivator {
406    /// The non-modifier key of the shortcut that is pressed after all modifiers to activate the
407    /// shortcut.
408    ///
409    /// For example, for `Control + C`, [`trigger`](Self::trigger) should be
410    /// `LogicalKeyboardKey::KEY_C`.
411    pub trigger: LogicalKeyboardKey,
412
413    /// Whether either (or both) control keys should be held for [`trigger`](Self::trigger) to
414    /// activate the shortcut.
415    ///
416    /// It defaults to false, meaning all Control keys must be released when the event is
417    /// received in order to activate the shortcut. If it's true, then either or both Control
418    /// keys must be pressed.
419    pub control: bool,
420
421    /// Whether either (or both) shift keys should be held for [`trigger`](Self::trigger) to
422    /// activate the shortcut.
423    ///
424    /// It defaults to false, meaning all Shift keys must be released when the event is received
425    /// in order to activate the shortcut. If it's true, then either or both Shift keys must be
426    /// pressed.
427    pub shift: bool,
428
429    /// Whether either (or both) alt keys should be held for [`trigger`](Self::trigger) to
430    /// activate the shortcut.
431    ///
432    /// It defaults to false, meaning all Alt keys must be released when the event is received
433    /// in order to activate the shortcut. If it's true, then either or both Alt keys must be
434    /// pressed.
435    pub alt: bool,
436
437    /// Whether either (or both) meta keys should be held for [`trigger`](Self::trigger) to
438    /// activate the shortcut.
439    ///
440    /// It defaults to false, meaning all Meta keys must be released when the event is received
441    /// in order to activate the shortcut. If it's true, then either or both Meta keys must be
442    /// pressed.
443    pub meta: bool,
444
445    /// Whether the NumLock key state should be checked for [`trigger`](Self::trigger) to
446    /// activate the shortcut.
447    ///
448    /// It defaults to [`LockState::Ignored`], meaning the NumLock state is ignored when the
449    /// event is received in order to activate the shortcut. If it's [`LockState::Locked`], then
450    /// the NumLock key must be locked. If it's [`LockState::Unlocked`], then the NumLock key
451    /// must be unlocked.
452    pub num_lock: LockState,
453
454    /// Whether this activator accepts repeat events of the [`trigger`](Self::trigger) key.
455    ///
456    /// If [`include_repeats`](Self::include_repeats) is true, the activator is checked on all
457    /// key down or key repeat events for the [`trigger`](Self::trigger) key. If it is false,
458    /// only [`trigger`](Self::trigger) key events which are key down events will be considered.
459    pub include_repeats: bool,
460}
461
462impl SingleActivator {
463    /// Triggered when the [`trigger`](Self::trigger) key is pressed while the modifiers are
464    /// held.
465    ///
466    /// The [`trigger`](Self::trigger) should be the non-modifier key that is pressed after all
467    /// the modifiers, such as `LogicalKeyboardKey::KEY_C` as in `Ctrl+C`. It must not be a
468    /// modifier key (sided or unsided).
469    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    /// Dart `SingleActivator(control:)`.
499    pub fn control(mut self, control: bool) -> SingleActivator {
500        self.control = control;
501        self
502    }
503
504    /// Dart `SingleActivator(shift:)`.
505    pub fn shift(mut self, shift: bool) -> SingleActivator {
506        self.shift = shift;
507        self
508    }
509
510    /// Dart `SingleActivator(alt:)`.
511    pub fn alt(mut self, alt: bool) -> SingleActivator {
512        self.alt = alt;
513        self
514    }
515
516    /// Dart `SingleActivator(meta:)`.
517    pub fn meta(mut self, meta: bool) -> SingleActivator {
518        self.meta = meta;
519        self
520    }
521
522    /// Dart `SingleActivator(numLock:)`.
523    pub fn num_lock(mut self, num_lock: LockState) -> SingleActivator {
524        self.num_lock = num_lock;
525        self
526    }
527
528    /// Dart `SingleActivator(includeRepeats:)`.
529    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
554/// Dart's `pressed.intersection(synonyms).isNotEmpty`.
555fn 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    /// Returns a short and readable description of the key combination.
584    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/// A shortcut combination that is triggered by a key event that produces a specific character.
608///
609/// Keys often produce different characters when combined with modifiers. For example, it might
610/// be helpful for the user to bring up a help menu by pressing the question mark ('?'). However,
611/// there is no logical key that directly represents a question mark. Although 'Shift+Slash'
612/// produces a '?' character on a US keyboard, its logical key is still considered a Slash key,
613/// and hard-coding 'Shift+Slash' in this situation is unfriendly to other keyboard layouts.
614///
615/// For example, `CharacterActivator::new("?")` is triggered when a key combination results in a
616/// question mark, which is 'Shift+Slash' on a US keyboard, but 'Shift+Comma' on a French
617/// keyboard.
618///
619/// The [`alt`](Self::alt), [`control`](Self::control), and [`meta`](Self::meta) flags represent
620/// whether the respective modifier keys should be held (true) or released (false). They default
621/// to false. [`CharacterActivator`] cannot check shifted keys, since the Shift key affects the
622/// resulting character, and will accept whether either of the Shift keys are pressed or not, as
623/// long as the key event produces the correct character.
624///
625/// See also:
626///
627///  * [`SingleActivator`], an activator that represents a single key combined with modifiers,
628///    such as `Ctrl+C` or `Ctrl-Right Arrow`.
629#[derive(Clone, Debug, PartialEq, Eq)]
630pub struct CharacterActivator {
631    /// Whether either (or both) Alt keys should be held for the
632    /// [`character`](Self::character) to activate the shortcut.
633    ///
634    /// It defaults to false, meaning all Alt keys must be released when the event is received
635    /// in order to activate the shortcut. If it's true, then either one or both Alt keys must
636    /// be pressed.
637    pub alt: bool,
638
639    /// Whether either (or both) Control keys should be held for the
640    /// [`character`](Self::character) to activate the shortcut.
641    ///
642    /// It defaults to false, meaning all Control keys must be released when the event is
643    /// received in order to activate the shortcut. If it's true, then either one or both
644    /// Control keys must be pressed.
645    pub control: bool,
646
647    /// Whether either (or both) Meta keys should be held for the
648    /// [`character`](Self::character) to activate the shortcut.
649    ///
650    /// It defaults to false, meaning all Meta keys must be released when the event is received
651    /// in order to activate the shortcut. If it's true, then either one or both Meta keys must
652    /// be pressed.
653    pub meta: bool,
654
655    /// Whether this activator accepts repeat events of the [`character`](Self::character).
656    ///
657    /// If [`include_repeats`](Self::include_repeats) is true, the activator is checked on all
658    /// key down and key repeat events for the [`character`](Self::character). If it is false,
659    /// only the [`character`](Self::character) events that are key down events will be
660    /// considered.
661    pub include_repeats: bool,
662
663    /// The character which triggers the shortcut.
664    ///
665    /// This is typically a single-character string, such as '?' or 'Å“', although
666    /// [`CharacterActivator`] doesn't check the length of [`character`](Self::character) or
667    /// whether it can be matched by any key combination at all. It is case-sensitive, since the
668    /// [`character`](Self::character) is directly compared to the character reported by the
669    /// platform.
670    pub character: String,
671}
672
673impl CharacterActivator {
674    /// Triggered when the key event yields the given character.
675    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    /// Dart `CharacterActivator(alt:)`.
686    pub fn alt(mut self, alt: bool) -> CharacterActivator {
687        self.alt = alt;
688        self
689    }
690
691    /// Dart `CharacterActivator(control:)`.
692    pub fn control(mut self, control: bool) -> CharacterActivator {
693        self.control = control;
694        self
695    }
696
697    /// Dart `CharacterActivator(meta:)`.
698    pub fn meta(mut self, meta: bool) -> CharacterActivator {
699        self.meta = meta;
700        self
701    }
702
703    /// Dart `CharacterActivator(includeRepeats:)`.
704    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        // Doesn't look for shift, since the character will encode that.
711        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        // Ignore triggers, since we're only interested in the character.
731        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
753/// Dart's `_ActivatorIntentPair`: one entry of a manager's shortcut index. Its fields are
754/// private, as Dart's are.
755pub struct ActivatorIntentPair {
756    activator: ShortcutActivatorRef,
757    intent: IntentRef,
758}
759
760impl ActivatorIntentPair {
761    /// Dart's `_ActivatorIntentPair.debugFillProperties`.
762    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
774// ---------------------------------------------------------------------------------------------
775// ShortcutManager
776
777/// The fields Dart's `ShortcutManager` declares; a manager carries this bag under the field
778/// `shortcut_manager` ([`shortcut_manager_accessors!`](crate::shortcut_manager_accessors)).
779pub 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    /// The bag of a freshly created manager.
788    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/// The accessors [`ShortcutManagerBase`] asks for, for a struct whose bag is the field
804/// `shortcut_manager`.
805#[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
824/// The members Dart's `ShortcutManager` declares, over a [`ShortcutManagerData`] bag.
825///
826/// Dart's class is both instantiated ([`ShortcutManager`]) and subclassed (`RadioGroup`'s
827/// manager ignores a key event while no radio in its group has focus), so the bodies live on
828/// this trait and each Dart class is a leaf struct that implements it.
829pub trait ShortcutManagerBase: ChangeNotifier + Sized + 'static {
830    /// Dart's `ShortcutManager` fields, held under the field `shortcut_manager`
831    /// ([`shortcut_manager_accessors!`](crate::shortcut_manager_accessors)).
832    fn shortcut_manager_data(self: Handle<Self>, app: &App) -> &ShortcutManagerData;
833
834    /// See [`shortcut_manager_data`](Self::shortcut_manager_data).
835    fn shortcut_manager_data_mut(self: Handle<Self>, app: &mut App) -> &mut ShortcutManagerData;
836
837    /// This manager as the erased [`AnyShortcutManager`] — what to pass where a Dart API takes
838    /// a `ShortcutManager`.
839    fn as_shortcut_manager(self: Handle<Self>) -> AnyShortcutManager {
840        AnyShortcutManager {
841            id: self.id(),
842            vtable: const { &ShortcutManagerVTable::of::<Self>() },
843        }
844    }
845
846    /// True if the [`ShortcutManagerBase`] should not pass on keys that it doesn't handle to
847    /// any key-handling widgets that are ancestors to this one.
848    ///
849    /// Setting [`modal`](Self::modal) to true will prevent any key event given to this manager
850    /// from being given to any ancestor managers, even if that key doesn't appear in the
851    /// [`shortcuts`](Self::shortcuts) map.
852    ///
853    /// The net effect of setting [`modal`](Self::modal) to true is to return
854    /// [`KeyEventResult::SkipRemainingHandlers`] from
855    /// [`handle_keypress`](Self::handle_keypress) if it does not exist in the shortcut map,
856    /// instead of returning [`KeyEventResult::Ignored`].
857    fn modal(self: Handle<Self>, app: &App) -> bool {
858        self.shortcut_manager_data(app).modal
859    }
860
861    /// Dart `ShortcutManager(modal:)`.
862    fn set_modal(self: Handle<Self>, app: &mut App, modal: bool) {
863        self.shortcut_manager_data_mut(app).modal = modal;
864    }
865
866    /// Returns the shortcut map.
867    ///
868    /// When the map is changed, listeners to this manager will be notified.
869    fn shortcuts(self: Handle<Self>, app: &App) -> ShortcutMap {
870        self.shortcut_manager_data(app).shortcuts.clone()
871    }
872
873    /// See [`shortcuts`](Self::shortcuts).
874    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    /// Dart's `ShortcutManager._indexedShortcuts`.
884    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    /// Returns the `Intent`, if any, that matches the current set of pressed keys.
901    ///
902    /// Returns `None` if no intent matches the current set of pressed keys.
903    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    /// Handles a key press `event` in the given `context`.
925    ///
926    /// If a key mapping is found, then the associated action will be invoked using the `Intent`
927    /// activated by the [`ShortcutActivator`] in the [`shortcuts`](Self::shortcuts) map, and the
928    /// currently focused widget's context (from `FocusManager::primary_focus`).
929    ///
930    /// Returns [`KeyEventResult::Handled`] if an action was invoked, otherwise
931    /// [`KeyEventResult::SkipRemainingHandlers`] if [`modal`](Self::modal) is true, or if it
932    /// maps to a `DoNothingAction` with `consumes_key` set to false, and in all other cases
933    /// returns [`KeyEventResult::Ignored`].
934    ///
935    /// In order for an action to be invoked (and [`KeyEventResult::Handled`] returned), a
936    /// [`ShortcutActivator`] must accept the given `KeyEvent`, be mapped to an `Intent`, the
937    /// `Intent` must be mapped to an `Action`, and the `Action` must be enabled.
938    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
948/// Flutter's `ShortcutManager.handleKeypress` body that an override calls through `super`.
949///
950/// A trait default cannot call `super`, and a leaf's own
951/// [`ShortcutManagerBase::handle_keypress`] shadows the default it would call; this sibling
952/// trait, blanket-implemented for every manager, carries that body (the shape `ElementBase` has
953/// for `Element`).
954pub trait ShortcutManagerKeypress: ShortcutManagerBase {
955    /// Flutter's `ShortcutManager.handleKeypress`.
956    fn handle_keypress(
957        self: Handle<Self>,
958        app: &mut App,
959        context: BuildContext,
960        event: &KeyEvent,
961    ) -> KeyEventResult {
962        // Dart shadows the `context` parameter with the primary focus's own context.
963        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
992/// The vtable of an erased [`AnyShortcutManager`]: one `&'static` table per leaf type.
993struct 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
1003/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
1004fn 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/// Erased `ShortcutManager`: one identity and a static vtable.
1028///
1029/// This is what a field or parameter Dart types as `ShortcutManager` becomes.
1030#[derive(Clone, Copy)]
1031pub struct AnyShortcutManager {
1032    id: HandleId,
1033    vtable: &'static ShortcutManagerVTable,
1034}
1035
1036/// A field Dart types as the erased object, kept: AnyShortcutManager with its count.
1037pub 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    /// The arena id behind this handle.
1049    pub fn id(self) -> HandleId {
1050        self.id
1051    }
1052
1053    /// Dart's `manager as T`: the typed handle when this manager is a `T`, else `None`.
1054    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
1055        app.handle::<T>(self.id)
1056    }
1057
1058    /// See [`ShortcutManagerBase::shortcuts`].
1059    pub fn shortcuts(self, app: &App) -> ShortcutMap {
1060        (self.vtable.shortcuts)(app, self.id)
1061    }
1062
1063    /// See [`ShortcutManagerBase::set_shortcuts`].
1064    pub fn set_shortcuts(self, app: &mut App, value: ShortcutMap) {
1065        (self.vtable.set_shortcuts)(app, self.id, value);
1066    }
1067
1068    /// See [`ShortcutManagerBase::modal`].
1069    pub fn modal(self, app: &App) -> bool {
1070        (self.vtable.modal)(app, self.id)
1071    }
1072
1073    /// See [`ShortcutManagerBase::set_modal`].
1074    pub fn set_modal(self, app: &mut App, value: bool) {
1075        (self.vtable.set_modal)(app, self.id, value);
1076    }
1077
1078    /// See [`ShortcutManagerBase::handle_keypress`].
1079    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    /// `ChangeNotifier.dispose` on the manager behind this handle.
1089    pub fn dispose(self, app: &mut App) {
1090        (self.vtable.dispose)(app, self.id);
1091    }
1092}
1093
1094/// A manager of keyboard shortcut bindings used by [`Shortcuts`] to handle key events.
1095///
1096/// The manager may be listened to (with `add_listener` / `remove_listener`) for change
1097/// notifications when the shortcuts change.
1098///
1099/// Typically, a [`Shortcuts`] widget supplies its own manager, but in uncommon cases where
1100/// overriding the usual shortcut manager behavior is desired, a custom [`ShortcutManagerBase`]
1101/// may be supplied.
1102pub struct ShortcutManager {
1103    change_notifier: ChangeNotifierData,
1104    shortcut_manager: ShortcutManagerData,
1105}
1106
1107impl ShortcutManager {
1108    /// Constructs a [`ShortcutManager`].
1109    ///
1110    /// Dart's optional `shortcuts` and `modal` arguments are the setters.
1111    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    /// Dart's `ShortcutManager.debugFillProperties`, which a [`Shortcuts`] dump prints through
1125    /// the manager's `toString`.
1126    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
1144/// Dart's `Map.toString` for a shortcut map, which the manager's dump prints: each key by its
1145/// `toString`, each intent by its own.
1146fn 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
1160/// Dart's `ShortcutMapProperty` description, which the [`Shortcuts`] widget prints: each key by
1161/// `debugDescribeKeys`, in braces.
1162fn 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
1186/// Dart's `ShortcutManager._indexShortcuts`.
1187fn 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
1210/// Dart's `mapEquals` on a shortcut map, whose keys and values are reference types.
1211fn 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
1218// ---------------------------------------------------------------------------------------------
1219// Shortcuts
1220
1221/// A widget that creates key bindings to specific actions for its descendants.
1222///
1223/// This widget establishes a [`ShortcutManager`] to be used by its descendants when invoking an
1224/// `Action` via a keyboard key combination that maps to an `Intent`.
1225///
1226/// This is similar to but more powerful than the [`CallbackShortcuts`] widget. Unlike
1227/// [`CallbackShortcuts`], this widget separates key bindings and their implementations. This
1228/// separation allows [`Shortcuts`] to have key bindings that adapt to the focused context.
1229///
1230/// See also:
1231///
1232///  * [`CallbackShortcuts`], a simpler but less flexible widget that defines key bindings that
1233///    invoke callbacks.
1234///  * `Intent`, a trait for values containing a description of a user action to be invoked.
1235///  * `Action`, a trait for defining an invocation of a user action.
1236///  * `CallbackAction`, a class for creating an action from a callback.
1237pub struct Shortcuts {
1238    /// See [`Widget::key`](crate::Widget::key).
1239    pub key: Option<KeyRef>,
1240
1241    /// The [`ShortcutManagerBase`] that will manage the mapping between key combinations and
1242    /// `Action`s.
1243    ///
1244    /// If this widget was created with [`Shortcuts::manager`], then
1245    /// [`ShortcutManagerBase::shortcuts`] will be used as the source for shortcuts. If
1246    /// [`Shortcuts::new`] is used, this manager will be `None`, and a default-constructed
1247    /// [`ShortcutManager`] will be used.
1248    pub manager: Option<ShortcutManagerRef>,
1249
1250    /// The widget below this widget in the tree.
1251    pub child: WidgetRef,
1252
1253    /// The debug label that is printed for this node when logged.
1254    ///
1255    /// If this label is set, then it will be displayed instead of the shortcut map when logged.
1256    pub debug_label: Option<String>,
1257
1258    /// Whether to include semantics from `Focus`.
1259    ///
1260    /// Defaults to true.
1261    pub include_semantics: bool,
1262
1263    /// Dart's `Shortcuts._shortcuts`.
1264    shortcuts: ShortcutMap,
1265}
1266
1267impl Shortcuts {
1268    /// Creates a [`Shortcuts`] widget that owns the map of shortcuts and creates its own
1269    /// manager.
1270    ///
1271    /// When using this constructor, [`manager`](Self::manager) is `None`.
1272    ///
1273    /// See also:
1274    ///
1275    ///  * [`Shortcuts::manager`], a constructor that uses a [`ShortcutManagerBase`] to manage
1276    ///    the shortcuts list instead.
1277    #[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    /// Creates a [`Shortcuts`] widget that uses the `manager` to manage the map of shortcuts.
1290    ///
1291    /// If this constructor is used, [`get_shortcuts`](Self::get_shortcuts) will return the
1292    /// contents of [`ShortcutManagerBase::shortcuts`].
1293    #[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    /// Dart `Shortcuts(key:)`.
1302    pub fn key(mut self, key: KeyRef) -> Shortcuts {
1303        self.key = Some(key);
1304        self
1305    }
1306
1307    /// Dart `Shortcuts(debugLabel:)`.
1308    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    /// Dart `Shortcuts(includeSemantics:)`.
1314    pub fn include_semantics(mut self, include_semantics: bool) -> Shortcuts {
1315        self.include_semantics = include_semantics;
1316        self
1317    }
1318
1319    /// The map of shortcuts that describes the mapping between a key sequence defined by a
1320    /// [`ShortcutActivator`] and the `Intent` that will be emitted when that key sequence is
1321    /// pressed.
1322    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
1372/// Dart's `_ShortcutsState`.
1373pub struct ShortcutsState {
1374    state: StateData<Shortcuts>,
1375    internal_manager: Option<Ref<ShortcutManager>>,
1376}
1377
1378impl ShortcutsState {
1379    /// The manager in effect: the widget's, or the one this state created.
1380    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
1461// ---------------------------------------------------------------------------------------------
1462// CallbackShortcuts
1463
1464/// A widget that binds key combinations to specific callbacks.
1465///
1466/// This is similar to but simpler than the [`Shortcuts`] widget as it doesn't require `Intent`s
1467/// and `Actions` widgets. Instead, it accepts a map of [`ShortcutActivator`]s to callbacks.
1468///
1469/// Unlike [`Shortcuts`], this widget does not separate key bindings and their implementations.
1470/// That separation allows [`Shortcuts`] to have key bindings that adapt to the focused context.
1471///
1472/// See also:
1473///
1474///  * [`Shortcuts`], a more powerful widget for defining key bindings.
1475///  * `Focus`, a widget that defines which widgets can receive keyboard focus.
1476pub struct CallbackShortcuts {
1477    /// See [`Widget::key`](crate::Widget::key).
1478    pub key: Option<KeyRef>,
1479
1480    /// A map of key combinations to callbacks used to define the shortcut bindings.
1481    ///
1482    /// If a descendant of this widget has focus, and a key is pressed, the activator keys of
1483    /// this map will be asked if they accept the key event. If they do, then the corresponding
1484    /// callback is invoked, and the key event propagation is halted. If none of the activators
1485    /// accept the key event, then the key event continues to be propagated up the focus chain.
1486    ///
1487    /// If more than one activator accepts the key event, then all of the callbacks associated
1488    /// with activators that accept the key event are invoked.
1489    pub bindings: Vec<(ShortcutActivatorRef, Listener)>,
1490
1491    /// The widget below this widget in the tree.
1492    pub child: WidgetRef,
1493}
1494
1495impl CallbackShortcuts {
1496    /// Creates a [`CallbackShortcuts`] widget.
1497    #[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    /// Dart `CallbackShortcuts(key:)`.
1510    pub fn key(mut self, key: KeyRef) -> CallbackShortcuts {
1511        self.key = Some(key);
1512        self
1513    }
1514
1515    /// A helper function to make the stack trace more useful if the callback panics, by
1516    /// providing the activator and event as arguments that will appear in the stack trace.
1517    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                // Activates all key bindings that match, returns "handled" if any handle it.
1555                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
1568// ---------------------------------------------------------------------------------------------
1569// ShortcutRegistry
1570
1571/// An entry returned by [`ShortcutRegistry::add_all`] that allows the caller to identify the
1572/// shortcuts they registered with the [`ShortcutRegistry`] through the [`ShortcutRegistrar`].
1573///
1574/// When the entry is no longer needed, [`dispose`](Self::dispose) should be called, and the
1575/// entry should no longer be used.
1576pub struct ShortcutRegistryEntry {
1577    /// The [`ShortcutRegistry`] that this entry was issued by.
1578    registry: Ref<ShortcutRegistry>,
1579}
1580
1581impl ShortcutRegistryEntry {
1582    /// The [`ShortcutRegistry`] that this entry was issued by.
1583    pub fn registry(self: Handle<Self>, app: &App) -> Handle<ShortcutRegistry> {
1584        app.get(self).registry.handle()
1585    }
1586
1587    /// Replaces the given shortcut bindings in the [`ShortcutRegistry`] that this entry was
1588    /// created from.
1589    ///
1590    /// It will assert if this entry has already been disposed.
1591    ///
1592    /// If two equivalent, but different, [`ShortcutActivator`]s are added, all of them will be
1593    /// executed when triggered.
1594    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    /// Called when the entry is no longer needed.
1600    ///
1601    /// Calling this will remove all shortcuts associated with this [`ShortcutRegistryEntry`]
1602    /// from the [`registry`](Self::registry).
1603    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
1609/// A class used by [`ShortcutRegistrar`] that allows adding or removing shortcut bindings by
1610/// descendants of the [`ShortcutRegistrar`].
1611///
1612/// You can reach the nearest [`ShortcutRegistry`] using [`of`](Self::of) and
1613/// [`maybe_of`](Self::maybe_of).
1614///
1615/// The registry may be listened to (with `add_listener` / `remove_listener`) for change
1616/// notifications when the registered shortcuts change. Change notifications take place after the
1617/// current frame is drawn, so that widgets that are not descendants of the registry can listen
1618/// to it.
1619pub struct ShortcutRegistry {
1620    change_notifier: ChangeNotifierData,
1621    notification_scheduled: bool,
1622    disposed: bool,
1623    /// Dart's `_registeredShortcuts`, in insertion order: that is the order
1624    /// [`shortcuts`](Self::shortcuts) merges the entries in.
1625    ///
1626    /// An entry is named, not kept: it is its caller's, and keeps this registry; the registration
1627    /// is cut by [`ShortcutRegistryEntry::dispose`].
1628    registered_shortcuts: Vec<(Handle<ShortcutRegistryEntry>, ShortcutMap)>,
1629}
1630
1631impl ShortcutRegistry {
1632    /// Creates an instance of [`ShortcutRegistry`].
1633    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    /// Discards any resources used by this object.
1643    pub fn dispose(self: Handle<Self>, app: &mut App) {
1644        ChangeNotifierData::dispose(app, self);
1645        app.get_mut(self).disposed = true;
1646    }
1647
1648    /// Gets the combined shortcut bindings from all contexts that are registered with this
1649    /// [`ShortcutRegistry`].
1650    ///
1651    /// Listeners will be notified when the value returned by this getter changes.
1652    ///
1653    /// Returns a copy: modifying the returned map will have no effect.
1654    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    /// Adds all the given shortcut bindings to this [`ShortcutRegistry`], and returns an entry
1666    /// for managing those bindings.
1667    ///
1668    /// [`ShortcutRegistryEntry::dispose`] should be called on the entry when these shortcuts are
1669    /// no longer needed. This will remove them from the registry, and invalidate the entry.
1670    ///
1671    /// If two equivalent, but different, [`ShortcutActivator`]s are added, all of them will be
1672    /// executed when triggered.
1673    ///
1674    /// See also:
1675    ///
1676    ///  * [`ShortcutRegistryEntry::replace_all`], a function used to replace the set of
1677    ///    shortcuts associated with a particular entry.
1678    ///  * [`ShortcutRegistryEntry::dispose`], a function used to remove the set of shortcuts
1679    ///    associated with a particular entry.
1680    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    /// Subscriber notification has to happen in the next frame because shortcuts are often
1702    /// registered that affect things in the overlay or different parts of the tree, and so can
1703    /// cause build ordering issues if notifications happen during the build. The
1704    /// `notification_scheduled` check makes sure we only notify once per frame.
1705    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                // The registry knows no element, so no view.
1717                None,
1718            );
1719            app.get_mut(self).notification_scheduled = true;
1720        }
1721    }
1722
1723    /// Returns the [`ShortcutRegistry`] that belongs to the [`ShortcutRegistrar`] which most
1724    /// tightly encloses the given [`BuildContext`].
1725    ///
1726    /// If no [`ShortcutRegistrar`] widget encloses the context given, [`of`](Self::of) panics.
1727    ///
1728    /// See also:
1729    ///
1730    ///  * [`maybe_of`](Self::maybe_of), which is similar to this function, but will return
1731    ///    `None` if it doesn't find a [`ShortcutRegistrar`] ancestor.
1732    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    /// Returns the [`ShortcutRegistry`] of the [`ShortcutRegistrar`] that most tightly encloses
1741    /// the given [`BuildContext`].
1742    ///
1743    /// If no [`ShortcutRegistrar`] widget encloses the given context, [`maybe_of`](Self::maybe_of)
1744    /// will return `None`.
1745    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    /// Replaces all the shortcuts associated with the given entry from this registry.
1752    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    /// Removes all the shortcuts associated with the given entry from this registry.
1772    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/// A widget that holds a [`ShortcutRegistry`] which allows descendants to add, remove, or
1819/// replace shortcuts.
1820///
1821/// This widget holds a [`ShortcutRegistry`] so that its descendants can find it with
1822/// [`ShortcutRegistry::of`] or [`ShortcutRegistry::maybe_of`].
1823///
1824/// The registered shortcuts are valid whenever a widget below this one in the hierarchy has
1825/// focus.
1826///
1827/// To add shortcuts to the registry, call [`ShortcutRegistry::of`] or
1828/// [`ShortcutRegistry::maybe_of`] to get the [`ShortcutRegistry`], and then add them using
1829/// [`ShortcutRegistry::add_all`], which will return a [`ShortcutRegistryEntry`] which must be
1830/// disposed by calling [`ShortcutRegistryEntry::dispose`] when the shortcuts are no longer
1831/// needed.
1832#[derive(Debug)]
1833pub struct ShortcutRegistrar {
1834    /// See [`Widget::key`](crate::Widget::key).
1835    pub key: Option<KeyRef>,
1836
1837    /// The widget below this widget in the tree.
1838    pub child: WidgetRef,
1839}
1840
1841impl ShortcutRegistrar {
1842    /// Creates a [`ShortcutRegistrar`].
1843    #[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    /// Dart `ShortcutRegistrar(key:)`.
1852    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
1875/// Dart's `_ShortcutRegistrarState`.
1876pub struct ShortcutRegistrarState {
1877    state: StateData<ShortcutRegistrar>,
1878    registry: Option<Ref<ShortcutRegistry>>,
1879    manager: Option<Ref<ShortcutManager>>,
1880    /// Dart's `_shortcutsChanged` tear-off, kept so that it can be removed again.
1881    shortcuts_changed: Option<Listener>,
1882}
1883
1884impl ShortcutRegistrarState {
1885    /// The registry this state owns.
1886    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    /// The manager this state owns.
1894    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        // This shouldn't need to update the widget, and avoids calling set_state during the
1903        // build phase.
1904        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/// Dart's `_ShortcutRegistrarScope`.
1955#[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    /// A `CallbackAction` for [`SaveIntent`] that records that it ran.
2002    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            // Without the modifier the activator does not accept the event.
2036            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(&notifications);
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            // The same pairs are not a change.
2158            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            // The registry notifies its listeners after the frame the entry was added in, a frame
2199            // nothing else asks for here (a Waft-only case), so the case asks for it as a Dart test
2200            // would with `tester.binding.scheduleFrame()`.
2201            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    /// `shortcuts_test.dart`, "LogicalKeySet diagnostics work."
2249    #[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    /// `shortcuts_test.dart`, "diagnostics.": single key, no repeats, combination.
2264    #[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    /// `shortcuts_test.dart`, "Shortcuts diagnostics work."
2290    #[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    /// `shortcuts_test.dart`, "Shortcuts diagnostics work when debugLabel specified."
2324    #[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}