smart_keymap/key/
chorded.rs

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
#![doc = include_str!("doc_de_chorded.md")]

use core::fmt::Debug;

use serde::Deserialize;

use crate::{input, key};

use key::PressedKey;

pub use crate::init::MAX_CHORDS;

/// The maximum number of keys in a chord.
const MAX_CHORD_SIZE: usize = 2;

/// Chords are defined by an (unordered) set of indices into the keymap.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "std", serde(untagged))]
pub enum ChordIndices {
    /// A chord from two keys.
    Chord2(u16, u16),
}

impl ChordIndices {
    /// Returns whether the given index is part of the chord.
    pub fn has_index(&self, index: u16) -> bool {
        match self {
            ChordIndices::Chord2(i0, i1) => i0 == &index || i1 == &index,
        }
    }

    /// Returns whether the chord is satisfied by the given indices.
    pub fn is_satisfied_by(&self, indices: &[u16]) -> bool {
        match self {
            ChordIndices::Chord2(i0, i1) => indices.contains(i0) && indices.contains(i1),
        }
    }
}

/// Chord definitions.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
pub struct Config {
    /// The timeout (in number of ticks) for a chorded key to resolve.
    ///
    /// (Resolves as passthrough key if no chord is satisfied).
    #[serde(default = "default_timeout")]
    pub timeout: u16,

    /// The keymap chords.
    #[serde(default = "default_chords")]
    #[serde(deserialize_with = "deserialize_chords")]
    pub chords: [Option<ChordIndices>; MAX_CHORDS],
}

fn default_timeout() -> u16 {
    DEFAULT_CONFIG.timeout
}

fn default_chords() -> [Option<ChordIndices>; MAX_CHORDS] {
    DEFAULT_CONFIG.chords
}

/// Deserialize chords for [Config].
fn deserialize_chords<'de, D>(
    deserializer: D,
) -> Result<[Option<ChordIndices>; MAX_CHORDS], D::Error>
where
    D: serde::Deserializer<'de>,
{
    let mut v: heapless::Vec<Option<ChordIndices>, MAX_CHORDS> =
        Deserialize::deserialize(deserializer)?;

    while !v.is_full() {
        v.push(None).unwrap();
    }

    v.into_array()
        .map_err(|_| serde::de::Error::custom("unable to deserialize"))
}

/// Default config.
pub const DEFAULT_CONFIG: Config = Config {
    timeout: 200,
    chords: [None; MAX_CHORDS],
};

impl Default for Config {
    /// Returns the default context.
    fn default() -> Self {
        DEFAULT_CONFIG
    }
}

/// Chord definitions.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Context {
    /// The config used by the context.
    pub config: Config,

    pressed_indices: [Option<u16>; MAX_CHORD_SIZE * MAX_CHORDS],
}

/// Default context.
pub const DEFAULT_CONTEXT: Context = Context::from_config(DEFAULT_CONFIG);

impl Context {
    /// Constructs a context from the given config
    pub const fn from_config(config: Config) -> Context {
        let pressed_indices = [None; MAX_CHORD_SIZE * MAX_CHORDS];
        Context {
            config,
            pressed_indices,
        }
    }

    /// Returns the chord indices for the given pressed indices.
    ///
    /// The returned vec is empty if any of the indices are not part of a chord.
    pub fn chords_for_indices(
        &self,
        indices: &[u16],
    ) -> heapless::Vec<ChordIndices, { MAX_CHORDS }> {
        self.config
            .chords
            .iter()
            .filter_map(|&c| c)
            .filter(|c| indices.iter().all(|i| c.has_index(*i)))
            .collect()
    }

    // All the indices (including the given index) from chords which
    //  include the given index.
    //
    // e.g. for chords {01, 12},
    //  sibling_indices(0) -> [0, 1]
    //  sibling_indices(1) -> [0, 1, 2]
    fn sibling_indices(&self, index: u16) -> heapless::Vec<u16, { MAX_CHORD_SIZE * MAX_CHORDS }> {
        let mut res: heapless::Vec<u16, { MAX_CHORD_SIZE * MAX_CHORDS }> = heapless::Vec::new();

        let chords = self.chords_for_indices(&[index]);

        chords.iter().for_each(|ch| match ch {
            ChordIndices::Chord2(i0, i1) => {
                if let Err(pos) = res.binary_search(&i0) {
                    res.insert(pos, *i0).unwrap();
                }
                if let Err(pos) = res.binary_search(&i1) {
                    res.insert(pos, *i1).unwrap();
                }
            }
        });

        res
    }

    fn insert_pressed_index(&mut self, pos: usize, index: u16) {
        if self.pressed_indices.is_empty() {
            return;
        }

        let mut i = self.pressed_indices.len() - 1;
        while i > pos {
            self.pressed_indices[i] = self.pressed_indices[i - 1];
            i -= 1;
        }

        self.pressed_indices[pos] = Some(index);
    }

    fn remove_pressed_index(&mut self, pos: usize) {
        if self.pressed_indices.is_empty() {
            return;
        }

        let mut i = pos;
        while i < self.pressed_indices.len() - 1 {
            self.pressed_indices[i] = self.pressed_indices[i + 1];
            i += 1;
        }

        self.pressed_indices[self.pressed_indices.len() - 1] = None;
    }

    fn press_index(&mut self, index: u16) {
        match self
            .pressed_indices
            .binary_search_by_key(&index, |&k| k.unwrap_or(u16::MAX))
        {
            Ok(_) => {}
            Err(pos) => self.insert_pressed_index(pos, index),
        }
    }

    fn release_index(&mut self, index: u16) {
        match self
            .pressed_indices
            .binary_search_by_key(&index, |&k| k.unwrap_or(u16::MAX))
        {
            Ok(pos) => self.remove_pressed_index(pos),
            Err(_) => {}
        }
    }

    fn pressed_indices(&self) -> heapless::Vec<u16, { MAX_CHORD_SIZE * MAX_CHORDS }> {
        self.pressed_indices.iter().filter_map(|&i| i).collect()
    }

    /// Updates the context for the given key event.
    pub fn handle_event(&mut self, event: key::Event<Event>) {
        match event {
            key::Event::Input(input::Event::Press { keymap_index }) => {
                self.press_index(keymap_index);
            }
            key::Event::Input(input::Event::Release { keymap_index }) => {
                self.release_index(keymap_index);
            }
            key::Event::Key {
                keymap_index,
                key_event,
            } => match key_event {
                // Release the index if resolved as passthrough
                Event::ChordResolved(false) => {
                    self.release_index(keymap_index);
                }
                _ => {}
            },
            _ => {}
        }
    }
}

/// Primary Chorded key (with a passthrough key).
///
/// The primary key is the key with the lowest index in the chord,
///  and has the key used for the resolved chord.
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
pub struct Key<K> {
    chord: K,
    passthrough: K,
}

impl<K: key::Key + Copy> Key<K>
where
    K::Context: Into<Context>,
    K::Event: TryInto<Event>,
    K::Event: From<Event>,
{
    /// Constructs new chorded key.
    pub const fn new(chord: K, passthrough: K) -> Self {
        Key { chord, passthrough }
    }

    /// Constructs new pressed key.
    pub fn new_pressed_key(
        &self,
        context: K::Context,
        keymap_index: u16,
    ) -> (
        input::PressedKey<Self, PressedKeyState<K>>,
        key::PressedKeyEvents<K::Event>,
    ) {
        let mut pk = input::PressedKey {
            keymap_index,
            key: *self,
            pressed_key_state: PressedKeyState::new(context, keymap_index),
        };
        let timeout_ev = Event::Timeout;
        let sch_ev = key::ScheduledEvent::after(
            context.into().config.timeout,
            key::Event::key_event(keymap_index, timeout_ev),
        );

        let mut pke = key::PressedKeyEvents::scheduled_event(sch_ev.into_scheduled_event());

        let n_pke = pk
            .pressed_key_state
            .check_resolution(context, keymap_index, self);
        pke.extend(n_pke);

        (pk, pke)
    }

    /// Maps the Key of the Key into a new type.
    pub fn map_key<T: key::Key + Copy>(self, f: fn(K) -> T) -> Key<T> {
        let Key { chord, passthrough } = self;
        Key {
            chord: f(chord),
            passthrough: f(passthrough),
        }
    }

    /// Maps the Key of the Key into a new type.
    pub fn into_key<T: key::Key + Copy>(self) -> Key<T>
    where
        K: Into<T>,
    {
        self.map_key(|k| k.into())
    }
}

/// Auxiliary chorded key (with a passthrough key).
///
/// The auxiliary keys are chorded keys,
///  but don't store the resolved chord key.
/// (i.e. After te primary chorded key, the remaining keys
///  in the chord are defined with auxiliary chorded keys).
#[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
pub struct AuxiliaryKey<K> {
    passthrough: K,
}

impl<K: key::Key + Copy> AuxiliaryKey<K>
where
    K::Context: Into<Context>,
    K::Event: TryInto<Event>,
    K::Event: From<Event>,
{
    /// Constructs new auxiliary chorded key.
    pub const fn new(passthrough: K) -> Self {
        AuxiliaryKey { passthrough }
    }

    /// Constructs new pressed key.
    pub fn new_pressed_key(
        &self,
        context: K::Context,
        keymap_index: u16,
    ) -> (
        input::PressedKey<Self, PressedKeyState<K>>,
        key::PressedKeyEvents<K::Event>,
    ) {
        let mut pk = input::PressedKey {
            keymap_index,
            key: *self,
            pressed_key_state: PressedKeyState::new(context, keymap_index),
        };
        let timeout_ev = Event::Timeout;
        let sch_ev = key::ScheduledEvent::after(
            context.into().config.timeout,
            key::Event::key_event(keymap_index, timeout_ev),
        );

        let mut pke = key::PressedKeyEvents::scheduled_event(sch_ev.into_scheduled_event());

        let n_pke = pk
            .pressed_key_state
            .check_resolution(context, keymap_index, self);
        pke.extend(n_pke);

        (pk, pke)
    }

    /// Maps the Key of the Key into a new type.
    pub fn map_key<T: key::Key + Copy>(self, f: fn(K) -> T) -> AuxiliaryKey<T> {
        let AuxiliaryKey { passthrough } = self;
        AuxiliaryKey {
            passthrough: f(passthrough),
        }
    }

    /// Maps the Key of the Key into a new type.
    pub fn into_key<T: key::Key + Copy>(self) -> AuxiliaryKey<T>
    where
        K: Into<T>,
    {
        self.map_key(|k| k.into())
    }
}

/// Trait for [PressedKeyState].
pub trait ChordedKey<K: key::Key> {
    /// The chorded key's "passthrough" key.
    fn passthrough_key(&self) -> &K;

    /// The chorded key's "chorded" key.
    fn chorded_key(&self) -> Option<&K>;
}

impl<K: key::Key> ChordedKey<K> for Key<K> {
    fn passthrough_key(&self) -> &K {
        &self.passthrough
    }

    fn chorded_key(&self) -> Option<&K> {
        Some(&self.chord)
    }
}

impl<K: key::Key> ChordedKey<K> for AuxiliaryKey<K> {
    fn passthrough_key(&self) -> &K {
        &self.passthrough
    }

    fn chorded_key(&self) -> Option<&K> {
        None
    }
}

/// Events for chorded keys.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
pub enum Event {
    /// The chorded key was resolved. (true if chord, false if passthrough)
    ChordResolved(bool),

    /// Timed out waiting for chord to be satisfied.
    Timeout,
}

/// Whether enough keys have been pressed to satisfy a chord.
///
/// In the case of non-overlapping chords,
///  a satisfied chord is a resolved chord.
///
/// In the case of overlapping chords,
///  e.g. "chord 01" and "chord 012",
///  pressed "01" is satisfies "chord 01".
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ChordSatisfaction {
    /// Status where not enough keys have been pressed to satisfy a chord.
    Unsatisfied,
    /// Status where enough keys have been pressed to satisfy a chord.
    Satisfied,
}

/// Whether the pressed key state has resolved to a chord or not.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ChordResolution<PK> {
    /// Resolved as chord.
    Chord(Option<PK>),
    /// Resolved as passthrough key.
    Passthrough(PK),
}

/// State for pressed keys.
#[derive(Debug, PartialEq)]
pub enum PressedKeyState<K: key::Key> {
    /// Waiting for more [Event]s
    Pending {
        /// The keymap indices which have been pressed.
        pressed_indices: heapless::Vec<u16, { MAX_CHORD_SIZE }>,
        /// Whether the chord has been satisfied.
        satisfaction: ChordSatisfaction,
    },
    /// Chord resolved from [Event]s
    Resolved(ChordResolution<K::PressedKey>),
}

impl<K: key::Key> PressedKeyState<K>
where
    K::Context: Into<Context>,
    K::Event: TryInto<Event>,
    K::Event: From<Event>,
{
    /// Constructs a new [PressedKeyState].
    pub fn new(context: K::Context, keymap_index: u16) -> Self {
        let sibling_indices = context.into().sibling_indices(keymap_index);
        let pressed_indices: heapless::Vec<u16, MAX_CHORD_SIZE> = context
            .into()
            .pressed_indices()
            .iter()
            .filter(|i| sibling_indices.contains(i))
            .copied()
            .collect();

        Self::Pending {
            pressed_indices,
            satisfaction: ChordSatisfaction::Unsatisfied,
        }
    }

    fn check_resolution<C: ChordedKey<K>>(
        &mut self,
        context: K::Context,
        keymap_index: u16,
        key: &C,
    ) -> key::PressedKeyEvents<K::Event> {
        match self {
            Self::Pending {
                pressed_indices,
                satisfaction: _,
            } => {
                let ctx: Context = context.into();
                let chords = ctx.chords_for_indices(pressed_indices.as_slice());
                match chords.as_slice() {
                    [ch] if ch.is_satisfied_by(&pressed_indices) => {
                        // Only one chord is satisfied by pressed indices.
                        //
                        // This resolves the aux key.
                        self.resolve_as_chord(context, keymap_index, key)
                    }
                    [] => {
                        // Otherwise, this key state resolves to "Passthrough",
                        //  since it has been interrupted by an unrelated key press.
                        self.resolve_as_passthrough(context, keymap_index, key)
                    }
                    _ => {
                        // Overlapping chords.
                        key::PressedKeyEvents::no_events()
                    }
                }
            }
            _ => key::PressedKeyEvents::no_events(),
        }
    }

    fn resolve_as_passthrough<C: ChordedKey<K>>(
        &mut self,
        context: K::Context,
        keymap_index: u16,
        key: &C,
    ) -> key::PressedKeyEvents<K::Event> {
        let k = key.passthrough_key();
        let (pk, mut n_pke) = k.new_pressed_key(context, keymap_index);
        *self = Self::Resolved(ChordResolution::Passthrough(pk));

        let resolved_ev = Event::ChordResolved(false);
        let key_ev = key::Event::key_event(keymap_index, resolved_ev);
        let sch_ev = key::ScheduledEvent::immediate(key_ev);
        n_pke.add_event(sch_ev.into_scheduled_event());

        n_pke
    }

    fn resolve_as_chord<C: ChordedKey<K>>(
        &mut self,
        context: K::Context,
        keymap_index: u16,
        key: &C,
    ) -> key::PressedKeyEvents<K::Event> {
        let resolved_ev = Event::ChordResolved(true);
        let key_ev = key::Event::key_event(keymap_index, resolved_ev);

        if let Some(k) = key.chorded_key() {
            let (pk, mut n_pke) = k.new_pressed_key(context, keymap_index);
            *self = Self::Resolved(ChordResolution::Chord(Some(pk)));
            let sch_ev = key::ScheduledEvent::immediate(key_ev);
            n_pke.add_event(sch_ev.into_scheduled_event());
            n_pke
        } else {
            *self = Self::Resolved(ChordResolution::Chord(None));
            key::PressedKeyEvents::event(key_ev.into_key_event())
        }
    }

    /// Handle PKS for primary chorded key.
    pub fn handle_event_for<C: ChordedKey<K>>(
        &mut self,
        context: K::Context,
        keymap_index: u16,
        key: &C,
        event: key::Event<K::Event>,
    ) -> key::PressedKeyEvents<K::Event> {
        let mut pke = key::PressedKeyEvents::no_events();

        match self {
            Self::Pending {
                pressed_indices,
                satisfaction: _,
            } => {
                match event {
                    key::Event::Key {
                        keymap_index: _ev_idx,
                        key_event,
                    } => {
                        if let Ok(ev) = key_event.try_into() {
                            match ev {
                                Event::Timeout => {
                                    // Timed out before chord unambiguously resolved.
                                    //  So, the key behaves as the passthrough key.
                                    let n_pke =
                                        self.resolve_as_passthrough(context, keymap_index, key);
                                    pke.extend(n_pke);
                                }
                                _ => {}
                            }
                        }
                    }
                    key::Event::Input(input::Event::Press {
                        keymap_index: pressed_keymap_index,
                    }) => {
                        // Another key was pressed.
                        // Check if the other key belongs to this key's chord indices,

                        let pos = pressed_indices
                            .binary_search(&keymap_index)
                            .unwrap_or_else(|e| e);

                        let push_res = pressed_indices.insert(pos, pressed_keymap_index);

                        // pressed_indices has capacity of MAX_CHORD_SIZE.
                        // pressed_indices will only be full without resolving
                        // if multiple chords with max chord size
                        //  having the same indices.
                        if push_res.is_err() {
                            panic!();
                        }

                        let n_pke = self.check_resolution(context, keymap_index, key);
                        pke.extend(n_pke);
                    }
                    key::Event::Input(input::Event::Release {
                        keymap_index: released_keymap_index,
                    }) => {
                        if released_keymap_index == keymap_index {
                            // This key state resolves to "Passthrough",
                            //  since it has been released before resolving as chord.
                            let n_pke = self.resolve_as_passthrough(context, keymap_index, key);
                            pke.extend(n_pke);
                        }
                    }
                    _ => {}
                }
            }
            Self::Resolved(chord_res) => match chord_res {
                ChordResolution::Chord(Some(pk)) => {
                    let n_pke = pk.handle_event(context, event);
                    pke.extend(n_pke);
                }
                ChordResolution::Passthrough(pk) => {
                    let n_pke = pk.handle_event(context, event);
                    pke.extend(n_pke);
                }
                _ => {}
            },
        }

        pke
    }

    /// Key output from the pressed key state.
    pub fn key_output(&self) -> key::KeyOutputState {
        use key::PressedKey as _;

        match self {
            Self::Pending { .. } => key::KeyOutputState::pending(),
            Self::Resolved(ChordResolution::Chord(None)) => key::KeyOutputState::no_output(),
            Self::Resolved(ChordResolution::Chord(Some(pk))) => pk.key_output(),
            Self::Resolved(ChordResolution::Passthrough(pk)) => pk.key_output(),
        }
    }
}

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

    use key::composite;
    use key::keyboard;

    use key::Context as _;
    use key::PressedKey;

    #[test]
    fn test_timeout_resolves_unsatisfied_aux_state_as_passthrough_key() {
        // Assemble: an Auxilary chorded key, and its PKS.
        let context = key::composite::Context::default();
        let expected_key = keyboard::Key::new(0x04);
        let chorded_key = AuxiliaryKey {
            passthrough: expected_key,
        };
        let keymap_index: u16 = 0;
        let mut pks: PressedKeyState<keyboard::Key> = PressedKeyState::new(context, keymap_index);

        // Act: handle a timeout ev.
        let timeout_ev = key::Event::key_event(keymap_index, Event::Timeout).into_key_event();
        let _actual_events = pks.handle_event_for(context, keymap_index, &chorded_key, timeout_ev);
        let actual_output = pks.key_output();

        // Assert: should have same events, and output as the aux's key's passthrough key.
        let (pk, _expected_events) =
            key::Key::new_pressed_key(&expected_key, context, keymap_index);
        // assert_eq!(expected_events, actual_events);
        let expected_output = pk.key_output();
        assert_eq!(expected_output, actual_output);
    }

    // #[test]
    // fn test_timeout_resolves_satisfied_key_state_as_chord() {}

    #[test]
    fn test_press_non_chorded_key_resolves_aux_state_as_interrupted() {
        // Assemble: an Auxilary chorded key, and its PKS.
        let context = key::composite::Context::default();
        let expected_key = keyboard::Key::new(0x04);
        let chorded_key = AuxiliaryKey {
            passthrough: expected_key,
        };
        let keymap_index: u16 = 0;
        let mut pks: PressedKeyState<keyboard::Key> = PressedKeyState::new(context, keymap_index);

        // Act: handle a key press, for an index that's not part of any chord.
        let non_chord_press = input::Event::Press { keymap_index: 9 }.into();
        let _actual_events =
            pks.handle_event_for(context, keymap_index, &chorded_key, non_chord_press);
        let actual_output = pks.key_output();

        // Assert: should have same events, and output as the aux's key's passthrough key.
        let (pk, _expected_events) =
            key::Key::new_pressed_key(&expected_key, context, keymap_index);
        // assert_eq!(expected_events, actual_events);
        let expected_output = pk.key_output();
        assert_eq!(expected_output, actual_output);
    }

    // "unambiguous" in the sense that the chord
    // is not overlapped by another chord.
    // e.g. chord "01" is overlapped by chord "012",
    //  and "pressed {0, 1}" would be 'ambiguous';
    //  wheres "pressed {0, 1, 2}" would be 'unambiguous'.

    #[test]
    fn test_press_chorded_key_resolves_unambiguous_aux_state_as_chord() {
        // Assemble: an Auxilary chorded key, and its PKS, with chord 01.
        let mut context = key::composite::Context {
            chorded_context: Context::from_config(Config {
                chords: [Some(ChordIndices::Chord2(0, 1)), None, None, None],
                ..DEFAULT_CONFIG
            }),
            ..composite::DEFAULT_CONTEXT
        };
        let passthrough = keyboard::Key::new(0x04);
        let chorded_key = AuxiliaryKey { passthrough };
        let keymap_index: u16 = 0;
        context.handle_event(key::Event::Input(input::Event::Press { keymap_index: 0 }));
        let mut pks: PressedKeyState<keyboard::Key> = PressedKeyState::new(context, keymap_index);

        // Act: handle a key press, for an index that completes (satisfies unambiguously) the chord.
        let chord_press = input::Event::Press { keymap_index: 1 }.into();
        let _actual_events = pks.handle_event_for(context, keymap_index, &chorded_key, chord_press);
        let actual_output = pks.key_output();

        // Assert: resolved aux key should have no events, should have (resolved) no output.
        // let _expected_events = key::PressedKeyEvents::no_events();
        // assert_eq!(expected_events, actual_events);
        let expected_output = key::KeyOutputState::no_output();
        assert_eq!(expected_output, actual_output);
    }

    // #[test]
    // fn test_release_resolved_chord_state_releases_chord() {}

    // This is better covered with an integration test.
    // #[test]
    // fn test_release_resolved_aux_passthrough_state_releases_passthrough_key() {}

    #[test]
    fn test_release_pending_aux_state_resolves_as_tapped_key() {
        // Assemble: an Auxilary chorded key, and its PKS.
        let context = key::composite::Context::default();
        let expected_key = keyboard::Key::new(0x04);
        let chorded_key = AuxiliaryKey {
            passthrough: expected_key,
        };
        let keymap_index: u16 = 0;
        let mut pks: PressedKeyState<keyboard::Key> = PressedKeyState::new(context, keymap_index);

        // Act: handle a key press, for an index that's not part of any chord.
        let chorded_key_release = input::Event::Release { keymap_index }.into();
        let _actual_events =
            pks.handle_event_for(context, keymap_index, &chorded_key, chorded_key_release);
        let actual_output = pks.key_output();

        // Assert: should have same events, and output as the aux's key's passthrough key.
        let (pk, _expected_events) =
            key::Key::new_pressed_key(&expected_key, context, keymap_index);
        // assert_eq!(expected_events, actual_events);
        let expected_output = pk.key_output();
        assert_eq!(expected_output, actual_output);
    }
}