iced-cube 0.0.5

Themeable application components for the iced GUI library, with Lucide icons
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
//! Keyboard shortcuts that apps can rebind.
//!
//! iced has no focus model for most widgets, so shortcuts are app-wide: the
//! app subscribes with [`subscription`], stores each [`Event`] it receives,
//! and resolves it through a component's [`Keymap`] into that component's
//! own action. Every interactive component has an `Action` enum and a
//! `default_keymap()`, and an app can [`bind`](Keymap::bind),
//! [`unbind`](Keymap::unbind) or [`clear`](Keymap::clear) the defaults.
//!
//! ```no_run
//! # #[cfg(feature = "tabs")]
//! # mod example {
//! use iced::Subscription;
//! use iced::keyboard::key::Named;
//! use iced_cube::keys::{self, Chord, Keymap};
//! use iced_cube::navigation::tabs::{self, Action};
//!
//! #[derive(Debug, Clone)]
//! enum Message {
//!     Key(keys::Event),
//!     Tabs(tabs::Event<u8>),
//! }
//!
//! struct App {
//!     tabs: tabs::State<u8>,
//!     keymap: Keymap<Action>,
//! }
//!
//! impl App {
//!     fn new() -> Self {
//!         let keymap = tabs::default_keymap()
//!             .unbind(&Chord::named(Named::ArrowLeft))
//!             .unbind(&Chord::named(Named::ArrowRight));
//!         Self { tabs: tabs::State::new([tabs::tab(1, "One"), tabs::tab(2, "Two")]), keymap }
//!     }
//!
//!     fn update(&mut self, message: Message) {
//!         let event = match message {
//!             Message::Key(key) => self
//!                 .keymap
//!                 .resolve_event(&key)
//!                 .and_then(|action| action.event(&self.tabs)),
//!             Message::Tabs(event) => Some(event),
//!         };
//!         if let Some(event) = event {
//!             let _ = self.tabs.update(event);
//!         }
//!     }
//!
//!     fn subscription(&self) -> Subscription<Message> {
//!         keys::subscription().map(Message::Key)
//!     }
//! }
//! # }
//! ```

use std::fmt;
use std::hash::Hash;
use std::str::FromStr;

use iced::Subscription;
use iced::advanced::subscription::{self as recipe, EventStream, Hasher, Recipe};
use iced::event::Status;
use iced::futures::{StreamExt, future};
use iced::keyboard::{self, Key, Modifiers, key::Named};
use iced::{mouse, window};

/// A key press delivered by [`subscription`].
///
/// A modifier key on its own, such as Alt, arrives as an event with no
/// modifiers when it is released, and only if nothing else was pressed
/// while it was held. So Alt followed by Up is one `Alt+ArrowUp` press,
/// while Alt pressed and released alone is a lone `Alt`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Event {
    pub key: Key,
    pub modifiers: Modifiers,
}

/// Key presses that no widget captured, such as a focused text input,
/// plus lone modifier keys as described on [`Event`].
pub fn subscription() -> Subscription<Event> {
    recipe::from_recipe(Listen)
}

struct Listen;

#[cfg(not(target_arch = "wasm32"))]
type Stream = iced::futures::stream::BoxStream<'static, Event>;
#[cfg(target_arch = "wasm32")]
type Stream = iced::futures::stream::LocalBoxStream<'static, Event>;

impl Recipe for Listen {
    type Output = Event;

    fn hash(&self, state: &mut Hasher) {
        std::any::TypeId::of::<Self>().hash(state);
    }

    fn stream(self: Box<Self>, input: EventStream) -> Stream {
        let mut tracker = Tracker::default();
        Box::pin(input.filter_map(move |event| {
            let recipe::Event::Interaction { event, status, .. } = event else {
                return future::ready(None);
            };
            future::ready(tracker.update(&event, status == Status::Captured))
        }))
    }
}

/// Turns raw iced events into the [`Event`]s that [`subscription`]
/// delivers. Apps that listen to window events themselves can feed it
/// every event, captured or not, to get the same behaviour.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Tracker {
    held: Option<Named>,
}

impl Tracker {
    pub fn new() -> Self {
        Self::default()
    }

    /// The key event `event` delivers, if any. `captured` is whether a
    /// widget already used it; captured events are not delivered, but a
    /// captured key press still stops a held modifier counting as lone.
    pub fn update(&mut self, event: &iced::Event, captured: bool) -> Option<Event> {
        match event {
            iced::Event::Keyboard(keyboard::Event::KeyPressed {
                key,
                modifiers,
                repeat,
                ..
            }) => self.pressed(key, *modifiers, *repeat, captured),
            iced::Event::Keyboard(keyboard::Event::KeyReleased { key, .. }) => {
                self.released(key, captured)
            }
            iced::Event::Mouse(
                mouse::Event::ButtonPressed(_) | mouse::Event::WheelScrolled { .. },
            )
            | iced::Event::Window(window::Event::Unfocused) => {
                self.held = None;
                None
            }
            _ => None,
        }
    }

    fn pressed(
        &mut self,
        key: &Key,
        modifiers: Modifiers,
        repeat: bool,
        captured: bool,
    ) -> Option<Event> {
        let Some(modifier) = modifier_key(key) else {
            self.held = None;
            return (!captured).then(|| Event {
                key: key.clone(),
                modifiers,
            });
        };
        if repeat && self.held == Some(modifier) {
            return None;
        }
        let others = modifiers.difference(modifier_flag(modifier));
        self.held = (self.held.is_none() && others.is_empty()).then_some(modifier);
        None
    }

    fn released(&mut self, key: &Key, captured: bool) -> Option<Event> {
        let modifier = modifier_key(key)?;
        let lone = self.held.take() == Some(modifier);
        (lone && !captured).then(|| Event {
            key: Key::Named(modifier),
            modifiers: Modifiers::empty(),
        })
    }
}

fn modifier_key(key: &Key) -> Option<Named> {
    match key {
        Key::Named(
            named @ (Named::Alt
            | Named::AltGraph
            | Named::Control
            | Named::Shift
            | Named::Super
            | Named::Meta),
        ) => Some(*named),
        _ => None,
    }
}

fn modifier_flag(key: Named) -> Modifiers {
    match key {
        Named::Alt | Named::AltGraph => Modifiers::ALT,
        Named::Control => Modifiers::CTRL,
        Named::Shift => Modifiers::SHIFT,
        Named::Super | Named::Meta => Modifiers::LOGO,
        _ => Modifiers::empty(),
    }
}

/// Named keys a [`Chord`] understands: the canonical name first, then aliases.
const NAMED: &[(Named, &[&str])] = &[
    (Named::Enter, &["Enter", "Return"]),
    (Named::Tab, &["Tab"]),
    (Named::Space, &["Space", "Spacebar"]),
    (Named::Escape, &["Escape", "Esc"]),
    (Named::Backspace, &["Backspace"]),
    (Named::Delete, &["Delete", "Del"]),
    (Named::Insert, &["Insert", "Ins"]),
    (Named::ArrowUp, &["ArrowUp", "Up"]),
    (Named::ArrowDown, &["ArrowDown", "Down"]),
    (Named::ArrowLeft, &["ArrowLeft", "Left"]),
    (Named::ArrowRight, &["ArrowRight", "Right"]),
    (Named::Home, &["Home"]),
    (Named::End, &["End"]),
    (Named::PageUp, &["PageUp", "PgUp"]),
    (Named::PageDown, &["PageDown", "PgDn"]),
    (Named::ContextMenu, &["Menu", "ContextMenu", "Apps"]),
    (Named::F1, &["F1"]),
    (Named::F2, &["F2"]),
    (Named::F3, &["F3"]),
    (Named::F4, &["F4"]),
    (Named::F5, &["F5"]),
    (Named::F6, &["F6"]),
    (Named::F7, &["F7"]),
    (Named::F8, &["F8"]),
    (Named::F9, &["F9"]),
    (Named::F10, &["F10"]),
    (Named::F11, &["F11"]),
    (Named::F12, &["F12"]),
];

/// Display name of the logo key on this platform.
const LOGO: &str = if cfg!(target_os = "macos") {
    "Cmd"
} else {
    "Super"
};

/// A key plus the modifiers held with it, such as `Ctrl+Shift+Tab`.
///
/// Parse one from a string: modifiers and the key are joined by `+`, and
/// case does not matter. Modifiers are `Ctrl`, `Shift`, `Alt` (or
/// `Option`), `Cmd` (or `Super`, `Meta`) and `Mod`, which is Cmd on macOS
/// and Ctrl elsewhere. Keys are a single character (`K`, `/`, `+`) or a
/// name: `Enter`, `Tab`, `Space`, `Escape`, `Backspace`, `Delete`,
/// `Insert`, `ArrowUp`, `ArrowDown`, `ArrowLeft`, `ArrowRight`, `Home`,
/// `End`, `PageUp`, `PageDown`, `Menu` (the context menu key) and `F1` to
/// `F12`.
///
/// ```
/// use iced_cube::keys::Chord;
///
/// let chord: Chord = "ctrl+shift+tab".parse().unwrap();
/// assert_eq!(chord.to_string(), "Ctrl+Shift+Tab");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Chord {
    key: Key,
    modifiers: Modifiers,
}

impl Chord {
    /// A chord for `key`. Characters are stored in lower case.
    pub fn new(key: Key, modifiers: Modifiers) -> Self {
        Self {
            key: normalise(key),
            modifiers,
        }
    }

    /// A named key with no modifiers.
    pub fn named(key: Named) -> Self {
        Self::new(Key::Named(key), Modifiers::empty())
    }

    /// A character key with no modifiers.
    pub fn character(key: char) -> Self {
        Self::new(Key::Character(key.to_string().into()), Modifiers::empty())
    }

    pub fn ctrl(self) -> Self {
        self.with(Modifiers::CTRL)
    }

    pub fn shift(self) -> Self {
        self.with(Modifiers::SHIFT)
    }

    pub fn alt(self) -> Self {
        self.with(Modifiers::ALT)
    }

    /// Adds the logo key: Cmd on macOS, Super or the Windows key elsewhere.
    pub fn logo(self) -> Self {
        self.with(Modifiers::LOGO)
    }

    /// Adds Cmd on macOS and Ctrl elsewhere.
    pub fn command(self) -> Self {
        self.with(Modifiers::COMMAND)
    }

    fn with(mut self, modifiers: Modifiers) -> Self {
        self.modifiers |= modifiers;
        self
    }

    pub fn key(&self) -> &Key {
        &self.key
    }

    pub fn modifiers(&self) -> Modifiers {
        self.modifiers
    }

    /// Whether a key press with exactly these modifiers triggers the chord.
    pub fn matches(&self, key: &Key, modifiers: Modifiers) -> bool {
        self.modifiers == modifiers && same_key(&self.key, key)
    }
}

fn normalise(key: Key) -> Key {
    match key {
        Key::Character(text) => Key::Character(text.to_lowercase().into()),
        key => key,
    }
}

fn same_key(chord: &Key, pressed: &Key) -> bool {
    match (chord, pressed) {
        (Key::Character(a), Key::Character(b)) => a.as_str() == b.to_lowercase(),
        (a, b) => a == b,
    }
}

/// Why a string is not a valid [`Chord`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ParseChordError {
    Empty,
    /// A `+` with nothing on one side, such as `Ctrl+`.
    MissingKey,
    UnknownModifier(String),
    UnknownKey(String),
}

impl fmt::Display for ParseChordError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => write!(f, "empty key chord"),
            Self::MissingKey => write!(f, "key chord has an empty part"),
            Self::UnknownModifier(name) => write!(f, "unknown modifier \"{name}\""),
            Self::UnknownKey(name) => write!(f, "unknown key \"{name}\""),
        }
    }
}

impl std::error::Error for ParseChordError {}

impl FromStr for Chord {
    type Err = ParseChordError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let value = value.trim();
        if value.is_empty() {
            return Err(ParseChordError::Empty);
        }

        // A trailing "++" means the key itself is "+".
        let (modifiers, key) = match value.strip_suffix("++") {
            Some(rest) => (Some(rest), "+"),
            None if value == "+" => (None, "+"),
            None => match value.rsplit_once('+') {
                Some((rest, key)) => (Some(rest), key),
                None => (None, value),
            },
        };

        let mut chord = Chord::new(parse_key(key.trim())?, Modifiers::empty());
        let Some(modifiers) = modifiers else {
            return Ok(chord);
        };
        for name in modifiers.split('+') {
            chord = chord.with(parse_modifier(name.trim())?);
        }
        Ok(chord)
    }
}

impl TryFrom<&str> for Chord {
    type Error = ParseChordError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        value.parse()
    }
}

fn parse_key(name: &str) -> Result<Key, ParseChordError> {
    if name.is_empty() {
        return Err(ParseChordError::MissingKey);
    }
    if let Some((named, _)) = NAMED
        .iter()
        .find(|(_, names)| names.iter().any(|alias| alias.eq_ignore_ascii_case(name)))
    {
        return Ok(Key::Named(*named));
    }
    let mut chars = name.chars();
    match (chars.next(), chars.next()) {
        (Some(_), None) => Ok(Key::Character(name.into())),
        _ => Err(ParseChordError::UnknownKey(name.to_owned())),
    }
}

fn parse_modifier(name: &str) -> Result<Modifiers, ParseChordError> {
    if name.is_empty() {
        return Err(ParseChordError::MissingKey);
    }
    let modifiers = match name.to_ascii_lowercase().as_str() {
        "ctrl" | "control" => Modifiers::CTRL,
        "shift" => Modifiers::SHIFT,
        "alt" | "option" | "opt" => Modifiers::ALT,
        "cmd" | "command" | "super" | "meta" | "logo" | "win" => Modifiers::LOGO,
        "mod" => Modifiers::COMMAND,
        _ => return Err(ParseChordError::UnknownModifier(name.to_owned())),
    };
    Ok(modifiers)
}

impl fmt::Display for Chord {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (modifier, name) in [
            (Modifiers::CTRL, "Ctrl"),
            (Modifiers::ALT, "Alt"),
            (Modifiers::SHIFT, "Shift"),
            (Modifiers::LOGO, LOGO),
        ] {
            if self.modifiers.contains(modifier) {
                write!(f, "{name}+")?;
            }
        }
        match &self.key {
            Key::Named(named) => match NAMED.iter().find(|(key, _)| key == named) {
                Some((_, names)) => write!(f, "{}", names.first().copied().unwrap_or_default()),
                None => write!(f, "{named:?}"),
            },
            Key::Character(text) => write!(f, "{}", text.to_uppercase()),
            Key::Unidentified => write!(f, "Unidentified"),
        }
    }
}

/// A component action that can be bound to keys.
pub trait Action: Copy + PartialEq + fmt::Debug + 'static {
    /// Every action, in the order they are documented.
    const ALL: &'static [Self];

    /// The component's default shortcuts.
    fn defaults() -> Keymap<Self>;

    /// A short name, such as `"Next"`.
    fn name(self) -> &'static str;

    /// One sentence describing what the action does.
    fn description(self) -> &'static str;
}

/// Chords bound to actions. Each chord triggers at most one action; an
/// action may have several chords.
#[derive(Debug, Clone, PartialEq)]
pub struct Keymap<A> {
    bindings: Vec<(Chord, A)>,
}

impl<A> Default for Keymap<A> {
    fn default() -> Self {
        Self {
            bindings: Vec::new(),
        }
    }
}

impl<A> Keymap<A> {
    /// An empty keymap.
    pub fn new() -> Self {
        Self::default()
    }

    /// Binds `chord` to `action`, replacing whatever the chord did before.
    pub fn bind(mut self, chord: Chord, action: A) -> Self {
        match self.bindings.iter_mut().find(|(bound, _)| *bound == chord) {
            Some(binding) => binding.1 = action,
            None => self.bindings.push((chord, action)),
        }
        self
    }

    /// Removes the binding for `chord`, if there is one.
    pub fn unbind(mut self, chord: &Chord) -> Self {
        self.bindings.retain(|(bound, _)| bound != chord);
        self
    }

    /// Removes every binding.
    pub fn clear(mut self) -> Self {
        self.bindings.clear();
        self
    }

    /// Every binding, in the order it was added.
    pub fn bindings(&self) -> impl Iterator<Item = (&Chord, &A)> {
        self.bindings.iter().map(|(chord, action)| (chord, action))
    }

    pub fn len(&self) -> usize {
        self.bindings.len()
    }

    pub fn is_empty(&self) -> bool {
        self.bindings.is_empty()
    }
}

impl<A: Clone> Keymap<A> {
    /// The action bound to a key press, if any.
    pub fn resolve(&self, key: &Key, modifiers: Modifiers) -> Option<A> {
        self.bindings
            .iter()
            .find(|(chord, _)| chord.matches(key, modifiers))
            .map(|(_, action)| action.clone())
    }

    /// The action bound to a key press from [`subscription`], if any.
    pub fn resolve_event(&self, event: &Event) -> Option<A> {
        self.resolve(&event.key, event.modifiers)
    }
}

impl<A: Clone + PartialEq> Keymap<A> {
    /// The chords bound to `action`.
    pub fn chords(&self, action: &A) -> Vec<&Chord> {
        self.bindings
            .iter()
            .filter(|(_, bound)| bound == action)
            .map(|(chord, _)| chord)
            .collect()
    }

    /// Removes every chord bound to `action`.
    pub fn unbind_action(mut self, action: &A) -> Self {
        self.bindings.retain(|(_, bound)| bound != action);
        self
    }

    /// Chords grouped by action, in the order each action first appears.
    pub fn grouped(&self) -> Vec<(A, Vec<Chord>)> {
        let mut groups: Vec<(A, Vec<Chord>)> = Vec::new();
        for (chord, action) in &self.bindings {
            match groups.iter_mut().find(|(bound, _)| bound == action) {
                Some((_, chords)) => chords.push(chord.clone()),
                None => groups.push((action.clone(), vec![chord.clone()])),
            }
        }
        groups
    }
}

impl<A: Action> Keymap<A> {
    /// The default shortcuts of the component that owns `A`.
    pub fn defaults() -> Self {
        A::defaults()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn chord(value: &str) -> Chord {
        value.parse().unwrap()
    }

    fn character(value: &str) -> Key {
        Key::Character(value.into())
    }

    #[test]
    fn parses_named_keys_with_modifiers() {
        let parsed = chord("Ctrl+Shift+Tab");
        assert_eq!(parsed.key(), &Key::Named(Named::Tab));
        assert_eq!(parsed.modifiers(), Modifiers::CTRL | Modifiers::SHIFT);
        assert_eq!(chord("Escape"), Chord::named(Named::Escape));
        assert_eq!(chord("ArrowRight"), Chord::named(Named::ArrowRight));
    }

    #[test]
    fn parsing_ignores_case_and_accepts_aliases() {
        assert_eq!(chord("ctrl+k"), chord("Ctrl+K"));
        assert_eq!(chord("CONTROL + K"), chord("Ctrl+K"));
        assert_eq!(chord("esc"), Chord::named(Named::Escape));
        assert_eq!(chord("right"), Chord::named(Named::ArrowRight));
        assert_eq!(chord("Option+PgDn"), Chord::named(Named::PageDown).alt());
        assert_eq!(chord("Meta+S"), Chord::character('s').logo());
        assert_eq!(chord("ContextMenu"), Chord::named(Named::ContextMenu));
        assert_eq!(chord("Menu").to_string(), "Menu");
    }

    #[test]
    fn mod_is_the_platform_command_key() {
        let parsed = chord("Mod+K");
        assert_eq!(parsed.modifiers(), Modifiers::COMMAND);
        if cfg!(target_os = "macos") {
            assert_eq!(parsed, chord("Cmd+K"));
        } else {
            assert_eq!(parsed, chord("Ctrl+K"));
        }
    }

    #[test]
    fn plus_can_be_the_key() {
        assert_eq!(chord("+").key(), &character("+"));
        let zoom = chord("Ctrl++");
        assert_eq!(zoom.key(), &character("+"));
        assert_eq!(zoom.modifiers(), Modifiers::CTRL);
    }

    #[test]
    fn rejects_invalid_chords() {
        assert_eq!("".parse::<Chord>(), Err(ParseChordError::Empty));
        assert_eq!("  ".parse::<Chord>(), Err(ParseChordError::Empty));
        assert_eq!("Ctrl+".parse::<Chord>(), Err(ParseChordError::MissingKey));
        assert_eq!("Ctrl++K".parse::<Chord>(), Err(ParseChordError::MissingKey));
        assert_eq!(
            "Hyper+K".parse::<Chord>(),
            Err(ParseChordError::UnknownModifier("Hyper".into()))
        );
        assert_eq!(
            "Ctrl+Banana".parse::<Chord>(),
            Err(ParseChordError::UnknownKey("Banana".into()))
        );
    }

    #[test]
    fn displays_in_canonical_form() {
        assert_eq!(chord("shift+ctrl+tab").to_string(), "Ctrl+Shift+Tab");
        assert_eq!(chord("ctrl+k").to_string(), "Ctrl+K");
        assert_eq!(chord("esc").to_string(), "Escape");
        assert_eq!(chord("alt+up").to_string(), "Alt+ArrowUp");
        assert_eq!(chord("Ctrl++").to_string(), "Ctrl++");
    }

    #[test]
    fn display_round_trips() {
        for value in ["Ctrl+Alt+Shift+Cmd+F5", "Space", "Mod+/", "Shift+End", "+"] {
            let parsed = chord(value);
            assert_eq!(chord(&parsed.to_string()), parsed, "{value}");
        }
    }

    #[test]
    fn matches_exact_modifiers_and_any_case() {
        let save = chord("Ctrl+S");
        assert!(save.matches(&character("s"), Modifiers::CTRL));
        assert!(save.matches(&character("S"), Modifiers::CTRL));
        assert!(!save.matches(&character("s"), Modifiers::empty()));
        assert!(!save.matches(&character("s"), Modifiers::CTRL | Modifiers::SHIFT));
        assert!(!save.matches(&Key::Named(Named::Tab), Modifiers::CTRL));
        assert!(chord("Tab").matches(&Key::Named(Named::Tab), Modifiers::empty()));
    }

    #[derive(Debug, Clone, Copy, PartialEq)]
    enum Test {
        Open,
        Close,
    }

    fn keymap() -> Keymap<Test> {
        Keymap::new()
            .bind(chord("Ctrl+O"), Test::Open)
            .bind(chord("Enter"), Test::Open)
            .bind(chord("Escape"), Test::Close)
    }

    #[test]
    fn resolves_bound_chords_only() {
        let keymap = keymap();
        assert_eq!(
            keymap.resolve(&character("o"), Modifiers::CTRL),
            Some(Test::Open)
        );
        assert_eq!(
            keymap.resolve(&Key::Named(Named::Escape), Modifiers::empty()),
            Some(Test::Close)
        );
        assert_eq!(keymap.resolve(&character("o"), Modifiers::empty()), None);
        let event = Event {
            key: Key::Named(Named::Enter),
            modifiers: Modifiers::empty(),
        };
        assert_eq!(keymap.resolve_event(&event), Some(Test::Open));
    }

    #[test]
    fn bind_replaces_an_existing_chord() {
        let keymap = keymap().bind(chord("Enter"), Test::Close);
        assert_eq!(keymap.len(), 3);
        assert_eq!(
            keymap.resolve(&Key::Named(Named::Enter), Modifiers::empty()),
            Some(Test::Close)
        );
    }

    #[test]
    fn unbind_and_clear() {
        let keymap = keymap().unbind(&chord("Escape"));
        assert_eq!(
            keymap.resolve(&Key::Named(Named::Escape), Modifiers::empty()),
            None
        );
        assert_eq!(keymap.len(), 2);
        let unchanged = keymap.clone().unbind(&chord("F1"));
        assert_eq!(unchanged, keymap);
        assert!(keymap.clear().is_empty());
    }

    #[test]
    fn chords_grouped_and_unbound_by_action() {
        let keymap = keymap();
        assert_eq!(keymap.chords(&Test::Open).len(), 2);
        let grouped = keymap.grouped();
        assert_eq!(grouped.len(), 2);
        assert_eq!(grouped[0].0, Test::Open);
        assert_eq!(grouped[0].1, vec![chord("Ctrl+O"), chord("Enter")]);
        assert_eq!(grouped[1], (Test::Close, vec![chord("Escape")]));
        let closed = keymap.unbind_action(&Test::Open);
        assert_eq!(closed.len(), 1);
    }

    fn press(key: Key, modifiers: Modifiers) -> iced::Event {
        press_repeat(key, modifiers, false)
    }

    fn press_repeat(key: Key, modifiers: Modifiers, repeat: bool) -> iced::Event {
        iced::Event::Keyboard(keyboard::Event::KeyPressed {
            modified_key: key.clone(),
            key,
            physical_key: keyboard::key::Physical::Unidentified(
                keyboard::key::NativeCode::Unidentified,
            ),
            location: keyboard::Location::Standard,
            modifiers,
            text: None,
            repeat,
        })
    }

    fn release(key: Key, modifiers: Modifiers) -> iced::Event {
        iced::Event::Keyboard(keyboard::Event::KeyReleased {
            modified_key: key.clone(),
            key,
            physical_key: keyboard::key::Physical::Unidentified(
                keyboard::key::NativeCode::Unidentified,
            ),
            location: keyboard::Location::Standard,
            modifiers,
        })
    }

    fn feed(events: &[iced::Event]) -> Vec<Event> {
        let mut tracker = Tracker::new();
        events
            .iter()
            .filter_map(|event| tracker.update(event, false))
            .collect()
    }

    fn alt() -> Key {
        Key::Named(Named::Alt)
    }

    fn lone(named: Named) -> Event {
        Event {
            key: Key::Named(named),
            modifiers: Modifiers::empty(),
        }
    }

    #[test]
    fn a_lone_modifier_arrives_on_release() {
        let events = feed(&[
            press(alt(), Modifiers::ALT),
            release(alt(), Modifiers::empty()),
        ]);
        assert_eq!(events, vec![lone(Named::Alt)]);
    }

    #[test]
    fn a_modifier_used_in_a_chord_is_not_lone() {
        let up = Key::Named(Named::ArrowUp);
        let events = feed(&[
            press(alt(), Modifiers::ALT),
            press(up.clone(), Modifiers::ALT),
            release(up.clone(), Modifiers::ALT),
            release(alt(), Modifiers::empty()),
        ]);
        assert_eq!(
            events,
            vec![Event {
                key: up,
                modifiers: Modifiers::ALT
            }]
        );
    }

    #[test]
    fn key_repeat_keeps_a_modifier_lone() {
        let events = feed(&[
            press(alt(), Modifiers::ALT),
            press_repeat(alt(), Modifiers::ALT, true),
            release(alt(), Modifiers::empty()),
        ]);
        assert_eq!(events, vec![lone(Named::Alt)]);
    }

    #[test]
    fn two_modifiers_together_are_not_lone() {
        let ctrl = Key::Named(Named::Control);
        let events = feed(&[
            press(ctrl.clone(), Modifiers::CTRL),
            press(alt(), Modifiers::CTRL | Modifiers::ALT),
            release(alt(), Modifiers::CTRL),
            release(ctrl, Modifiers::empty()),
        ]);
        assert!(events.is_empty());
    }

    #[test]
    fn a_click_while_held_stops_a_modifier_being_lone() {
        let events = feed(&[
            press(alt(), Modifiers::ALT),
            iced::Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left)),
            release(alt(), Modifiers::empty()),
        ]);
        assert!(events.is_empty());
    }

    #[test]
    fn captured_keys_are_not_delivered_but_still_break_a_lone_modifier() {
        let mut tracker = Tracker::new();
        let up = Key::Named(Named::ArrowUp);
        assert_eq!(tracker.update(&press(alt(), Modifiers::ALT), false), None);
        assert_eq!(tracker.update(&press(up, Modifiers::ALT), true), None);
        assert_eq!(
            tracker.update(&release(alt(), Modifiers::empty()), false),
            None
        );
    }

    #[test]
    fn ordinary_presses_pass_through_unchanged() {
        let events = feed(&[press(character("k"), Modifiers::CTRL)]);
        assert_eq!(
            events,
            vec![Event {
                key: character("k"),
                modifiers: Modifiers::CTRL
            }]
        );
    }
}