Skip to main content

iced_cube/
keys.rs

1//! Keyboard shortcuts that apps can rebind.
2//!
3//! Every interactive component has an `Action` enum and a
4//! `default_keymap()`, and an app can [`bind`](Keymap::bind),
5//! [`unbind`](Keymap::unbind) or [`clear`](Keymap::clear) the defaults.
6//! Some components, such as tabs and sliders, resolve their keymap
7//! themselves while they have keyboard focus or were the last thing
8//! pressed. For shortcuts that work from anywhere, the app subscribes with
9//! [`subscription`], stores each [`Event`] it receives, and resolves it
10//! through a component's [`Keymap`] into that component's own action. Here
11//! the app switches tabs with `Ctrl+Tab` from anywhere, while the tab list
12//! keeps its arrow keys for when it has focus.
13//!
14//! ```no_run
15//! # #[cfg(feature = "tabs")]
16//! # mod example {
17//! use iced::Subscription;
18//! use iced::keyboard::key::Named;
19//! use iced_cube::keys::{self, Chord, Keymap};
20//! use iced_cube::navigation::tabs::{self, Action};
21//!
22//! #[derive(Debug, Clone)]
23//! enum Message {
24//!     Key(keys::Event),
25//!     Tabs(tabs::Event<u8>),
26//! }
27//!
28//! struct App {
29//!     tabs: tabs::State<u8>,
30//!     keymap: Keymap<Action>,
31//! }
32//!
33//! impl App {
34//!     fn new() -> Self {
35//!         let keymap = Keymap::new()
36//!             .bind(Chord::named(Named::Tab).ctrl(), Action::Next)
37//!             .bind(Chord::named(Named::Tab).ctrl().shift(), Action::Previous);
38//!         Self { tabs: tabs::State::new([tabs::tab(1, "One"), tabs::tab(2, "Two")]), keymap }
39//!     }
40//!
41//!     fn update(&mut self, message: Message) {
42//!         let event = match message {
43//!             Message::Key(key) => self
44//!                 .keymap
45//!                 .resolve_event(&key)
46//!                 .and_then(|action| action.event(&self.tabs)),
47//!             Message::Tabs(event) => Some(event),
48//!         };
49//!         if let Some(event) = event {
50//!             let _ = self.tabs.update(event);
51//!         }
52//!     }
53//!
54//!     fn subscription(&self) -> Subscription<Message> {
55//!         keys::subscription().map(Message::Key)
56//!     }
57//! }
58//! # }
59//! ```
60
61use std::fmt;
62use std::hash::Hash;
63use std::str::FromStr;
64
65use iced::Subscription;
66use iced::advanced::subscription::{self as recipe, EventStream, Hasher, Recipe};
67use iced::event::Status;
68use iced::futures::{StreamExt, future};
69use iced::keyboard::{self, Key, Modifiers, key::Named};
70use iced::{mouse, touch, window};
71
72/// A key press delivered by [`subscription`].
73///
74/// A modifier key on its own, such as Alt, arrives as an event with no
75/// modifiers when it is released, and only if nothing else was pressed
76/// while it was held. So Alt followed by Up is one `Alt+ArrowUp` press,
77/// while Alt pressed and released alone is a lone `Alt`.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct Event {
80    pub key: Key,
81    pub modifiers: Modifiers,
82}
83
84/// Key presses that no widget captured, such as a focused text input,
85/// plus lone modifier keys as described on [`Event`].
86pub fn subscription() -> Subscription<Event> {
87    recipe::from_recipe(Listen)
88}
89
90struct Listen;
91
92#[cfg(not(target_arch = "wasm32"))]
93type Stream = iced::futures::stream::BoxStream<'static, Event>;
94#[cfg(target_arch = "wasm32")]
95type Stream = iced::futures::stream::LocalBoxStream<'static, Event>;
96
97impl Recipe for Listen {
98    type Output = Event;
99
100    fn hash(&self, state: &mut Hasher) {
101        std::any::TypeId::of::<Self>().hash(state);
102    }
103
104    fn stream(self: Box<Self>, input: EventStream) -> Stream {
105        let mut tracker = Tracker::default();
106        Box::pin(input.filter_map(move |event| {
107            let recipe::Event::Interaction { event, status, .. } = event else {
108                return future::ready(None);
109            };
110            future::ready(tracker.update(&event, status == Status::Captured))
111        }))
112    }
113}
114
115/// Turns raw iced events into the [`Event`]s that [`subscription`]
116/// delivers. Apps that listen to window events themselves can feed it
117/// every event, captured or not, to get the same behaviour.
118#[derive(Debug, Clone, Default, PartialEq, Eq)]
119pub struct Tracker {
120    held: Option<Named>,
121}
122
123impl Tracker {
124    pub fn new() -> Self {
125        Self::default()
126    }
127
128    /// The key event `event` delivers, if any. `captured` is whether a
129    /// widget already used it; captured events are not delivered, but a
130    /// captured key press still stops a held modifier counting as lone.
131    pub fn update(&mut self, event: &iced::Event, captured: bool) -> Option<Event> {
132        match event {
133            iced::Event::Keyboard(keyboard::Event::KeyPressed {
134                key,
135                modifiers,
136                repeat,
137                ..
138            }) => self.pressed(key, *modifiers, *repeat, captured),
139            iced::Event::Keyboard(keyboard::Event::KeyReleased { key, .. }) => {
140                self.released(key, captured)
141            }
142            iced::Event::Mouse(
143                mouse::Event::ButtonPressed(_) | mouse::Event::WheelScrolled { .. },
144            )
145            | iced::Event::Touch(touch::Event::FingerPressed { .. })
146            | iced::Event::Window(window::Event::Unfocused) => {
147                self.held = None;
148                None
149            }
150            _ => None,
151        }
152    }
153
154    fn pressed(
155        &mut self,
156        key: &Key,
157        modifiers: Modifiers,
158        repeat: bool,
159        captured: bool,
160    ) -> Option<Event> {
161        let Some(modifier) = modifier_key(key) else {
162            self.held = None;
163            return (!captured).then(|| Event {
164                key: key.clone(),
165                modifiers,
166            });
167        };
168        if repeat && self.held == Some(modifier) {
169            return None;
170        }
171        let others = modifiers.difference(modifier_flag(modifier));
172        self.held = (self.held.is_none() && others.is_empty()).then_some(modifier);
173        None
174    }
175
176    fn released(&mut self, key: &Key, captured: bool) -> Option<Event> {
177        let modifier = modifier_key(key)?;
178        let lone = self.held.take() == Some(modifier);
179        (lone && !captured).then(|| Event {
180            key: Key::Named(modifier),
181            modifiers: Modifiers::empty(),
182        })
183    }
184}
185
186fn modifier_key(key: &Key) -> Option<Named> {
187    match key {
188        Key::Named(
189            named @ (Named::Alt
190            | Named::AltGraph
191            | Named::Control
192            | Named::Shift
193            | Named::Super
194            | Named::Meta),
195        ) => Some(*named),
196        _ => None,
197    }
198}
199
200fn modifier_flag(key: Named) -> Modifiers {
201    match key {
202        Named::Alt | Named::AltGraph => Modifiers::ALT,
203        Named::Control => Modifiers::CTRL,
204        Named::Shift => Modifiers::SHIFT,
205        Named::Super | Named::Meta => Modifiers::LOGO,
206        _ => Modifiers::empty(),
207    }
208}
209
210/// Named keys a [`Chord`] understands: the canonical name first, then aliases.
211const NAMED: &[(Named, &[&str])] = &[
212    (Named::Enter, &["Enter", "Return"]),
213    (Named::Tab, &["Tab"]),
214    (Named::Space, &["Space", "Spacebar"]),
215    (Named::Escape, &["Escape", "Esc"]),
216    (Named::Backspace, &["Backspace"]),
217    (Named::Delete, &["Delete", "Del"]),
218    (Named::Insert, &["Insert", "Ins"]),
219    (Named::ArrowUp, &["ArrowUp", "Up"]),
220    (Named::ArrowDown, &["ArrowDown", "Down"]),
221    (Named::ArrowLeft, &["ArrowLeft", "Left"]),
222    (Named::ArrowRight, &["ArrowRight", "Right"]),
223    (Named::Home, &["Home"]),
224    (Named::End, &["End"]),
225    (Named::PageUp, &["PageUp", "PgUp"]),
226    (Named::PageDown, &["PageDown", "PgDn"]),
227    (Named::ContextMenu, &["Menu", "ContextMenu", "Apps"]),
228    (Named::F1, &["F1"]),
229    (Named::F2, &["F2"]),
230    (Named::F3, &["F3"]),
231    (Named::F4, &["F4"]),
232    (Named::F5, &["F5"]),
233    (Named::F6, &["F6"]),
234    (Named::F7, &["F7"]),
235    (Named::F8, &["F8"]),
236    (Named::F9, &["F9"]),
237    (Named::F10, &["F10"]),
238    (Named::F11, &["F11"]),
239    (Named::F12, &["F12"]),
240];
241
242/// Display name of the logo key on this platform.
243const LOGO: &str = if cfg!(target_os = "macos") {
244    "Cmd"
245} else {
246    "Super"
247};
248
249/// A key plus the modifiers held with it, such as `Ctrl+Shift+Tab`.
250///
251/// Parse one from a string: modifiers and the key are joined by `+`, and
252/// case does not matter. Modifiers are `Ctrl`, `Shift`, `Alt` (or
253/// `Option`), `Cmd` (or `Super`, `Meta`) and `Mod`, which is Cmd on macOS
254/// and Ctrl elsewhere. Keys are a single character (`K`, `/`, `+`) or a
255/// name: `Enter`, `Tab`, `Space`, `Escape`, `Backspace`, `Delete`,
256/// `Insert`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `Home`,
257/// `End`, `PageUp`, `PageDown`, `Menu` (the context menu key) and `F1` to
258/// `F12`.
259///
260/// ```
261/// use iced_cube::keys::Chord;
262///
263/// let chord: Chord = "ctrl+shift+tab".parse().unwrap();
264/// assert_eq!(chord.to_string(), "Ctrl+Shift+Tab");
265/// ```
266#[derive(Debug, Clone, PartialEq, Eq, Hash)]
267pub struct Chord {
268    key: Key,
269    modifiers: Modifiers,
270}
271
272impl Chord {
273    /// A chord for `key`. Characters are stored in lower case.
274    pub fn new(key: Key, modifiers: Modifiers) -> Self {
275        Self {
276            key: normalise(key),
277            modifiers,
278        }
279    }
280
281    /// A named key with no modifiers.
282    pub fn named(key: Named) -> Self {
283        Self::new(Key::Named(key), Modifiers::empty())
284    }
285
286    /// A character key with no modifiers.
287    pub fn character(key: char) -> Self {
288        Self::new(Key::Character(key.to_string().into()), Modifiers::empty())
289    }
290
291    pub fn ctrl(self) -> Self {
292        self.with(Modifiers::CTRL)
293    }
294
295    pub fn shift(self) -> Self {
296        self.with(Modifiers::SHIFT)
297    }
298
299    pub fn alt(self) -> Self {
300        self.with(Modifiers::ALT)
301    }
302
303    /// Adds the logo key: Cmd on macOS, Super or the Windows key elsewhere.
304    pub fn logo(self) -> Self {
305        self.with(Modifiers::LOGO)
306    }
307
308    /// Adds Cmd on macOS and Ctrl elsewhere.
309    pub fn command(self) -> Self {
310        self.with(Modifiers::COMMAND)
311    }
312
313    fn with(mut self, modifiers: Modifiers) -> Self {
314        self.modifiers |= modifiers;
315        self
316    }
317
318    pub fn key(&self) -> &Key {
319        &self.key
320    }
321
322    pub fn modifiers(&self) -> Modifiers {
323        self.modifiers
324    }
325
326    /// Whether a key press with exactly these modifiers triggers the chord.
327    pub fn matches(&self, key: &Key, modifiers: Modifiers) -> bool {
328        self.modifiers == modifiers && same_key(&self.key, key)
329    }
330}
331
332fn normalise(key: Key) -> Key {
333    match key {
334        Key::Character(text) => Key::Character(text.to_lowercase().into()),
335        key => key,
336    }
337}
338
339fn same_key(chord: &Key, pressed: &Key) -> bool {
340    match (chord, pressed) {
341        (Key::Character(a), Key::Character(b)) => a.as_str() == b.to_lowercase(),
342        (a, b) => a == b,
343    }
344}
345
346/// Why a string is not a valid [`Chord`].
347#[derive(Debug, Clone, PartialEq, Eq)]
348pub enum ParseChordError {
349    Empty,
350    /// A `+` with nothing on one side, such as `Ctrl+`.
351    MissingKey,
352    UnknownModifier(String),
353    UnknownKey(String),
354}
355
356impl fmt::Display for ParseChordError {
357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
358        match self {
359            Self::Empty => write!(f, "empty key chord"),
360            Self::MissingKey => write!(f, "key chord has an empty part"),
361            Self::UnknownModifier(name) => write!(f, "unknown modifier \"{name}\""),
362            Self::UnknownKey(name) => write!(f, "unknown key \"{name}\""),
363        }
364    }
365}
366
367impl std::error::Error for ParseChordError {}
368
369impl FromStr for Chord {
370    type Err = ParseChordError;
371
372    fn from_str(value: &str) -> Result<Self, Self::Err> {
373        let value = value.trim();
374        if value.is_empty() {
375            return Err(ParseChordError::Empty);
376        }
377
378        // A trailing "++" means the key itself is "+".
379        let (modifiers, key) = match value.strip_suffix("++") {
380            Some(rest) => (Some(rest), "+"),
381            None if value == "+" => (None, "+"),
382            None => match value.rsplit_once('+') {
383                Some((rest, key)) => (Some(rest), key),
384                None => (None, value),
385            },
386        };
387
388        let mut chord = Chord::new(parse_key(key.trim())?, Modifiers::empty());
389        let Some(modifiers) = modifiers else {
390            return Ok(chord);
391        };
392        for name in modifiers.split('+') {
393            chord = chord.with(parse_modifier(name.trim())?);
394        }
395        Ok(chord)
396    }
397}
398
399impl TryFrom<&str> for Chord {
400    type Error = ParseChordError;
401
402    fn try_from(value: &str) -> Result<Self, Self::Error> {
403        value.parse()
404    }
405}
406
407fn parse_key(name: &str) -> Result<Key, ParseChordError> {
408    if name.is_empty() {
409        return Err(ParseChordError::MissingKey);
410    }
411    if let Some((named, _)) = NAMED
412        .iter()
413        .find(|(_, names)| names.iter().any(|alias| alias.eq_ignore_ascii_case(name)))
414    {
415        return Ok(Key::Named(*named));
416    }
417    let mut chars = name.chars();
418    match (chars.next(), chars.next()) {
419        (Some(_), None) => Ok(Key::Character(name.into())),
420        _ => Err(ParseChordError::UnknownKey(name.to_owned())),
421    }
422}
423
424fn parse_modifier(name: &str) -> Result<Modifiers, ParseChordError> {
425    if name.is_empty() {
426        return Err(ParseChordError::MissingKey);
427    }
428    let modifiers = match name.to_ascii_lowercase().as_str() {
429        "ctrl" | "control" => Modifiers::CTRL,
430        "shift" => Modifiers::SHIFT,
431        "alt" | "option" | "opt" => Modifiers::ALT,
432        "cmd" | "command" | "super" | "meta" | "logo" | "win" => Modifiers::LOGO,
433        "mod" => Modifiers::COMMAND,
434        _ => return Err(ParseChordError::UnknownModifier(name.to_owned())),
435    };
436    Ok(modifiers)
437}
438
439impl fmt::Display for Chord {
440    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441        for (modifier, name) in [
442            (Modifiers::CTRL, "Ctrl"),
443            (Modifiers::ALT, "Alt"),
444            (Modifiers::SHIFT, "Shift"),
445            (Modifiers::LOGO, LOGO),
446        ] {
447            if self.modifiers.contains(modifier) {
448                write!(f, "{name}+")?;
449            }
450        }
451        match &self.key {
452            Key::Named(named) => match NAMED.iter().find(|(key, _)| key == named) {
453                Some((_, names)) => write!(f, "{}", names.first().copied().unwrap_or_default()),
454                None => write!(f, "{named:?}"),
455            },
456            Key::Character(text) => write!(f, "{}", text.to_uppercase()),
457            Key::Unidentified => write!(f, "Unidentified"),
458        }
459    }
460}
461
462/// A component action that can be bound to keys.
463pub trait Action: Copy + PartialEq + fmt::Debug + 'static {
464    /// Every action, in the order they are documented.
465    const ALL: &'static [Self];
466
467    /// The component's default shortcuts.
468    fn defaults() -> Keymap<Self>;
469
470    /// A short name, such as `"Next"`.
471    fn name(self) -> &'static str;
472
473    /// One sentence describing what the action does.
474    fn description(self) -> &'static str;
475}
476
477/// Chords bound to actions. Each chord triggers at most one action; an
478/// action may have several chords.
479#[derive(Debug, Clone, PartialEq)]
480pub struct Keymap<A> {
481    bindings: Vec<(Chord, A)>,
482}
483
484impl<A> Default for Keymap<A> {
485    fn default() -> Self {
486        Self {
487            bindings: Vec::new(),
488        }
489    }
490}
491
492impl<A> Keymap<A> {
493    /// An empty keymap.
494    pub fn new() -> Self {
495        Self::default()
496    }
497
498    /// Binds `chord` to `action`, replacing whatever the chord did before.
499    pub fn bind(mut self, chord: Chord, action: A) -> Self {
500        match self.bindings.iter_mut().find(|(bound, _)| *bound == chord) {
501            Some(binding) => binding.1 = action,
502            None => self.bindings.push((chord, action)),
503        }
504        self
505    }
506
507    /// Removes the binding for `chord`, if there is one.
508    pub fn unbind(mut self, chord: &Chord) -> Self {
509        self.bindings.retain(|(bound, _)| bound != chord);
510        self
511    }
512
513    /// Removes every binding.
514    pub fn clear(mut self) -> Self {
515        self.bindings.clear();
516        self
517    }
518
519    /// Every binding, in the order it was added.
520    pub fn bindings(&self) -> impl Iterator<Item = (&Chord, &A)> {
521        self.bindings.iter().map(|(chord, action)| (chord, action))
522    }
523
524    pub fn len(&self) -> usize {
525        self.bindings.len()
526    }
527
528    pub fn is_empty(&self) -> bool {
529        self.bindings.is_empty()
530    }
531}
532
533impl<A: Clone> Keymap<A> {
534    /// The action bound to a key press, if any.
535    pub fn resolve(&self, key: &Key, modifiers: Modifiers) -> Option<A> {
536        self.bindings
537            .iter()
538            .find(|(chord, _)| chord.matches(key, modifiers))
539            .map(|(_, action)| action.clone())
540    }
541
542    /// The action bound to a key press from [`subscription`], if any.
543    pub fn resolve_event(&self, event: &Event) -> Option<A> {
544        self.resolve(&event.key, event.modifiers)
545    }
546}
547
548impl<A: Clone + PartialEq> Keymap<A> {
549    /// The chords bound to `action`.
550    pub fn chords(&self, action: &A) -> Vec<&Chord> {
551        self.bindings
552            .iter()
553            .filter(|(_, bound)| bound == action)
554            .map(|(chord, _)| chord)
555            .collect()
556    }
557
558    /// Removes every chord bound to `action`.
559    pub fn unbind_action(mut self, action: &A) -> Self {
560        self.bindings.retain(|(_, bound)| bound != action);
561        self
562    }
563
564    /// Chords grouped by action, in the order each action first appears.
565    pub fn grouped(&self) -> Vec<(A, Vec<Chord>)> {
566        let mut groups: Vec<(A, Vec<Chord>)> = Vec::new();
567        for (chord, action) in &self.bindings {
568            match groups.iter_mut().find(|(bound, _)| bound == action) {
569                Some((_, chords)) => chords.push(chord.clone()),
570                None => groups.push((action.clone(), vec![chord.clone()])),
571            }
572        }
573        groups
574    }
575}
576
577impl<A: Action> Keymap<A> {
578    /// The default shortcuts of the component that owns `A`.
579    pub fn defaults() -> Self {
580        A::defaults()
581    }
582}
583
584#[cfg(test)]
585mod tests {
586    use super::*;
587
588    fn chord(value: &str) -> Chord {
589        value.parse().unwrap()
590    }
591
592    fn character(value: &str) -> Key {
593        Key::Character(value.into())
594    }
595
596    #[test]
597    fn parses_named_keys_with_modifiers() {
598        let parsed = chord("Ctrl+Shift+Tab");
599        assert_eq!(parsed.key(), &Key::Named(Named::Tab));
600        assert_eq!(parsed.modifiers(), Modifiers::CTRL | Modifiers::SHIFT);
601        assert_eq!(chord("Escape"), Chord::named(Named::Escape));
602        assert_eq!(chord("ArrowRight"), Chord::named(Named::ArrowRight));
603    }
604
605    #[test]
606    fn parsing_ignores_case_and_accepts_aliases() {
607        assert_eq!(chord("ctrl+k"), chord("Ctrl+K"));
608        assert_eq!(chord("CONTROL + K"), chord("Ctrl+K"));
609        assert_eq!(chord("esc"), Chord::named(Named::Escape));
610        assert_eq!(chord("right"), Chord::named(Named::ArrowRight));
611        assert_eq!(chord("Option+PgDn"), Chord::named(Named::PageDown).alt());
612        assert_eq!(chord("Meta+S"), Chord::character('s').logo());
613        assert_eq!(chord("ContextMenu"), Chord::named(Named::ContextMenu));
614        assert_eq!(chord("Menu").to_string(), "Menu");
615    }
616
617    #[test]
618    fn mod_is_the_platform_command_key() {
619        let parsed = chord("Mod+K");
620        assert_eq!(parsed.modifiers(), Modifiers::COMMAND);
621        if cfg!(target_os = "macos") {
622            assert_eq!(parsed, chord("Cmd+K"));
623        } else {
624            assert_eq!(parsed, chord("Ctrl+K"));
625        }
626    }
627
628    #[test]
629    fn plus_can_be_the_key() {
630        assert_eq!(chord("+").key(), &character("+"));
631        let zoom = chord("Ctrl++");
632        assert_eq!(zoom.key(), &character("+"));
633        assert_eq!(zoom.modifiers(), Modifiers::CTRL);
634    }
635
636    #[test]
637    fn rejects_invalid_chords() {
638        assert_eq!("".parse::<Chord>(), Err(ParseChordError::Empty));
639        assert_eq!("  ".parse::<Chord>(), Err(ParseChordError::Empty));
640        assert_eq!("Ctrl+".parse::<Chord>(), Err(ParseChordError::MissingKey));
641        assert_eq!("Ctrl++K".parse::<Chord>(), Err(ParseChordError::MissingKey));
642        assert_eq!(
643            "Hyper+K".parse::<Chord>(),
644            Err(ParseChordError::UnknownModifier("Hyper".into()))
645        );
646        assert_eq!(
647            "Ctrl+Banana".parse::<Chord>(),
648            Err(ParseChordError::UnknownKey("Banana".into()))
649        );
650    }
651
652    #[test]
653    fn displays_in_canonical_form() {
654        assert_eq!(chord("shift+ctrl+tab").to_string(), "Ctrl+Shift+Tab");
655        assert_eq!(chord("ctrl+k").to_string(), "Ctrl+K");
656        assert_eq!(chord("esc").to_string(), "Escape");
657        assert_eq!(chord("alt+up").to_string(), "Alt+ArrowUp");
658        assert_eq!(chord("Ctrl++").to_string(), "Ctrl++");
659    }
660
661    #[test]
662    fn display_round_trips() {
663        for value in ["Ctrl+Alt+Shift+Cmd+F5", "Space", "Mod+/", "Shift+End", "+"] {
664            let parsed = chord(value);
665            assert_eq!(chord(&parsed.to_string()), parsed, "{value}");
666        }
667    }
668
669    #[test]
670    fn matches_exact_modifiers_and_any_case() {
671        let save = chord("Ctrl+S");
672        assert!(save.matches(&character("s"), Modifiers::CTRL));
673        assert!(save.matches(&character("S"), Modifiers::CTRL));
674        assert!(!save.matches(&character("s"), Modifiers::empty()));
675        assert!(!save.matches(&character("s"), Modifiers::CTRL | Modifiers::SHIFT));
676        assert!(!save.matches(&Key::Named(Named::Tab), Modifiers::CTRL));
677        assert!(chord("Tab").matches(&Key::Named(Named::Tab), Modifiers::empty()));
678    }
679
680    #[derive(Debug, Clone, Copy, PartialEq)]
681    enum Test {
682        Open,
683        Close,
684    }
685
686    fn keymap() -> Keymap<Test> {
687        Keymap::new()
688            .bind(chord("Ctrl+O"), Test::Open)
689            .bind(chord("Enter"), Test::Open)
690            .bind(chord("Escape"), Test::Close)
691    }
692
693    #[test]
694    fn resolves_bound_chords_only() {
695        let keymap = keymap();
696        assert_eq!(
697            keymap.resolve(&character("o"), Modifiers::CTRL),
698            Some(Test::Open)
699        );
700        assert_eq!(
701            keymap.resolve(&Key::Named(Named::Escape), Modifiers::empty()),
702            Some(Test::Close)
703        );
704        assert_eq!(keymap.resolve(&character("o"), Modifiers::empty()), None);
705        let event = Event {
706            key: Key::Named(Named::Enter),
707            modifiers: Modifiers::empty(),
708        };
709        assert_eq!(keymap.resolve_event(&event), Some(Test::Open));
710    }
711
712    #[test]
713    fn bind_replaces_an_existing_chord() {
714        let keymap = keymap().bind(chord("Enter"), Test::Close);
715        assert_eq!(keymap.len(), 3);
716        assert_eq!(
717            keymap.resolve(&Key::Named(Named::Enter), Modifiers::empty()),
718            Some(Test::Close)
719        );
720    }
721
722    #[test]
723    fn unbind_and_clear() {
724        let keymap = keymap().unbind(&chord("Escape"));
725        assert_eq!(
726            keymap.resolve(&Key::Named(Named::Escape), Modifiers::empty()),
727            None
728        );
729        assert_eq!(keymap.len(), 2);
730        let unchanged = keymap.clone().unbind(&chord("F1"));
731        assert_eq!(unchanged, keymap);
732        assert!(keymap.clear().is_empty());
733    }
734
735    #[test]
736    fn chords_grouped_and_unbound_by_action() {
737        let keymap = keymap();
738        assert_eq!(keymap.chords(&Test::Open).len(), 2);
739        let grouped = keymap.grouped();
740        assert_eq!(grouped.len(), 2);
741        assert_eq!(grouped[0].0, Test::Open);
742        assert_eq!(grouped[0].1, vec![chord("Ctrl+O"), chord("Enter")]);
743        assert_eq!(grouped[1], (Test::Close, vec![chord("Escape")]));
744        let closed = keymap.unbind_action(&Test::Open);
745        assert_eq!(closed.len(), 1);
746    }
747
748    fn press(key: Key, modifiers: Modifiers) -> iced::Event {
749        press_repeat(key, modifiers, false)
750    }
751
752    fn press_repeat(key: Key, modifiers: Modifiers, repeat: bool) -> iced::Event {
753        iced::Event::Keyboard(keyboard::Event::KeyPressed {
754            modified_key: key.clone(),
755            key,
756            physical_key: keyboard::key::Physical::Unidentified(
757                keyboard::key::NativeCode::Unidentified,
758            ),
759            location: keyboard::Location::Standard,
760            modifiers,
761            text: None,
762            repeat,
763        })
764    }
765
766    fn release(key: Key, modifiers: Modifiers) -> iced::Event {
767        iced::Event::Keyboard(keyboard::Event::KeyReleased {
768            modified_key: key.clone(),
769            key,
770            physical_key: keyboard::key::Physical::Unidentified(
771                keyboard::key::NativeCode::Unidentified,
772            ),
773            location: keyboard::Location::Standard,
774            modifiers,
775        })
776    }
777
778    fn feed(events: &[iced::Event]) -> Vec<Event> {
779        let mut tracker = Tracker::new();
780        events
781            .iter()
782            .filter_map(|event| tracker.update(event, false))
783            .collect()
784    }
785
786    fn alt() -> Key {
787        Key::Named(Named::Alt)
788    }
789
790    fn lone(named: Named) -> Event {
791        Event {
792            key: Key::Named(named),
793            modifiers: Modifiers::empty(),
794        }
795    }
796
797    #[test]
798    fn a_lone_modifier_arrives_on_release() {
799        let events = feed(&[
800            press(alt(), Modifiers::ALT),
801            release(alt(), Modifiers::empty()),
802        ]);
803        assert_eq!(events, vec![lone(Named::Alt)]);
804    }
805
806    #[test]
807    fn a_modifier_used_in_a_chord_is_not_lone() {
808        let up = Key::Named(Named::ArrowUp);
809        let events = feed(&[
810            press(alt(), Modifiers::ALT),
811            press(up.clone(), Modifiers::ALT),
812            release(up.clone(), Modifiers::ALT),
813            release(alt(), Modifiers::empty()),
814        ]);
815        assert_eq!(
816            events,
817            vec![Event {
818                key: up,
819                modifiers: Modifiers::ALT
820            }]
821        );
822    }
823
824    #[test]
825    fn key_repeat_keeps_a_modifier_lone() {
826        let events = feed(&[
827            press(alt(), Modifiers::ALT),
828            press_repeat(alt(), Modifiers::ALT, true),
829            release(alt(), Modifiers::empty()),
830        ]);
831        assert_eq!(events, vec![lone(Named::Alt)]);
832    }
833
834    #[test]
835    fn two_modifiers_together_are_not_lone() {
836        let ctrl = Key::Named(Named::Control);
837        let events = feed(&[
838            press(ctrl.clone(), Modifiers::CTRL),
839            press(alt(), Modifiers::CTRL | Modifiers::ALT),
840            release(alt(), Modifiers::CTRL),
841            release(ctrl, Modifiers::empty()),
842        ]);
843        assert!(events.is_empty());
844    }
845
846    #[test]
847    fn a_click_while_held_stops_a_modifier_being_lone() {
848        let events = feed(&[
849            press(alt(), Modifiers::ALT),
850            iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
851            release(alt(), Modifiers::empty()),
852        ]);
853        assert!(events.is_empty());
854    }
855
856    #[test]
857    fn a_tap_while_held_stops_a_modifier_being_lone() {
858        let events = feed(&[
859            press(alt(), Modifiers::ALT),
860            iced::Event::Touch(touch::Event::FingerPressed {
861                id: touch::Finger(1),
862                position: iced::Point::ORIGIN,
863            }),
864            release(alt(), Modifiers::empty()),
865        ]);
866        assert!(events.is_empty());
867    }
868
869    #[test]
870    fn captured_keys_are_not_delivered_but_still_break_a_lone_modifier() {
871        let mut tracker = Tracker::new();
872        let up = Key::Named(Named::ArrowUp);
873        assert_eq!(tracker.update(&press(alt(), Modifiers::ALT), false), None);
874        assert_eq!(tracker.update(&press(up, Modifiers::ALT), true), None);
875        assert_eq!(
876            tracker.update(&release(alt(), Modifiers::empty()), false),
877            None
878        );
879    }
880
881    #[test]
882    fn ordinary_presses_pass_through_unchanged() {
883        let events = feed(&[press(character("k"), Modifiers::CTRL)]);
884        assert_eq!(
885            events,
886            vec![Event {
887                key: character("k"),
888                modifiers: Modifiers::CTRL
889            }]
890        );
891    }
892}