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