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