Skip to main content

kanata_keyberon/
layout.rs

1//! Layout management.
2
3/// A procedural macro to generate [Layers](type.Layers.html)
4/// ## Syntax
5/// Items inside the macro are converted to Actions as such:
6/// - [`Action::KeyCode`]: Idents are automatically understood as keycodes: `A`, `RCtrl`, `Space`
7///     - Punctuation, numbers and other literals that aren't special to the rust parser are converted
8///       to KeyCodes as well: `,` becomes `KeyCode::Commma`, `2` becomes `KeyCode::Kb2`, `/` becomes `KeyCode::Slash`
9///     - Characters which require shifted keys are converted to `Action::MultipleKeyCodes(&[LShift, <character>])`:
10///       `!` becomes `Action::MultipleKeyCodes(&[LShift, Kb1])` etc
11///     - Characters special to the rust parser (parentheses, brackets, braces, quotes, apostrophes, underscores, backslashes and backticks)
12///       left alone cause parsing errors and as such have to be enclosed by apostrophes: `'['` becomes `KeyCode::LBracket`,
13///       `'\''` becomes `KeyCode::Quote`, `'\\'` becomes `KeyCode::BSlash`
14/// - [`Action::NoOp`]: Lowercase `n`
15/// - [`Action::Trans`]: Lowercase `t`
16/// - [`Action::Layer`]: A number in parentheses: `(1)`, `(4 - 2)`, `(0x4u8 as usize)`
17/// - [`Action::MultipleActions`]: Actions in brackets: `[LCtrl S]`, `[LAlt LCtrl C]`, `[(2) B {Action::NoOp}]`
18/// - Other `Action`s: anything in braces (`{}`) is copied unchanged to the final layout - `{ Action::Custom(42) }`
19///   simply becomes `Action::Custom(42)`
20///
21/// **Important note**: comma (`,`) is a keycode on its own, and can't be used to separate keycodes as one would have
22/// to do when not using a macro.
23pub use kanata_keyberon_macros::*;
24
25mod contextual_execution;
26use contextual_execution::*;
27
28use std::num::NonZeroU16;
29
30use crate::chord::*;
31use crate::key_code::KeyCode;
32use crate::{action::*, multikey_buffer::MultiKeyBuffer};
33use arraydeque::ArrayDeque;
34use heapless::Vec;
35
36use State::*;
37
38/// The coordinate type.
39/// First item is either 0 or 1 denoting real key or virtual key, respectively.
40/// Second item is the position in layout.
41pub type KCoord = (u8, u16);
42
43/// The Layers type.
44///
45/// `Layers` type is an array of layers which contain the description
46/// of actions on the switch matrix. For example `layers[1][2][3]`
47/// corresponds to the key on the first layer, row 2, column 3.
48/// The generic parameters are in order: the number of columns, rows and layers,
49/// and the type contained in custom actions.
50pub type Layers<'a, const C: usize, const R: usize, T = core::convert::Infallible> =
51    &'a [[[Action<'a, T>; C]; R]];
52
53const QUEUE_SIZE: usize = 32;
54pub type QueueLen = u8;
55
56#[test]
57fn check_queue_size() {
58    use std::convert::TryFrom;
59    let _v = QueueLen::try_from(QUEUE_SIZE).unwrap();
60}
61
62/// The current event queue.
63///
64/// Events can be retrieved by iterating over this struct and calling [Queued::event].
65pub(crate) type Queue = ArrayDeque<Queued, QUEUE_SIZE, arraydeque::behavior::Wrapping>;
66
67/// A list of queued press events. Used for special handling of potentially multiple press events
68/// that occur during a Waiting event.
69type PressedQueue = ArrayDeque<KCoord, QUEUE_SIZE>;
70
71/// The maximum number of actions that can be activated concurrently via chord decomposition or
72/// activation of multiple switch cases using fallthrough.
73pub const ACTION_QUEUE_LEN: usize = 8;
74
75pub const CUSTOM_EVENT_RELEASE_QUEUE_LEN: usize = 16;
76
77/// The queue is currently only used for chord decomposition when a longer chord does not result in
78/// an action, but splitting it into smaller chords would. The buffer size of 8 should be more than
79/// enough for real world usage, but if one wanted to be extra safe, this should be ChordKeys::BITS
80/// since that should guarantee that all potentially queueable actions can fit.
81type ActionQueue<'a, T> =
82    ArrayDeque<QueuedAction<'a, T>, ACTION_QUEUE_LEN, arraydeque::behavior::Wrapping>;
83type CustomEventReleaseQueue<'a, T> =
84    ArrayDeque<&'a T, CUSTOM_EVENT_RELEASE_QUEUE_LEN, arraydeque::behavior::Wrapping>;
85type Delay = u16;
86pub(crate) type QueuedAction<'a, T> = Option<(KCoord, Delay, &'a Action<'a, T>, LayerStack)>;
87
88pub const REAL_KEY_ROW: u8 = 0;
89
90const HISTORICAL_EVENT_LEN: usize = 8;
91const EXTRA_WAITING_LEN: usize = 8;
92#[test]
93fn extra_waiting_size_constraint() {
94    assert!(EXTRA_WAITING_LEN < i8::MAX as usize);
95}
96
97/// The layout manager. It takes `Event`s and `tick`s as input, and
98/// generate keyboard reports.
99pub struct Layout<'a, const C: usize, const R: usize, T = core::convert::Infallible>
100where
101    T: 'a + std::fmt::Debug,
102{
103    /// Fallback for transparent keys inside actions that are on `default_layer`.
104    pub src_keys: &'a [Action<'a, T>; C],
105    pub layers: &'a [[[Action<'a, T>; C]; R]],
106    pub default_layer: usize,
107    /// Key states.
108    pub states: Vec<State<'a, T>, 64>,
109    pub waiting: Option<WaitingState<'a, T>>,
110    pub extra_waiting:
111        ArrayDeque<WaitingState<'a, T>, EXTRA_WAITING_LEN, arraydeque::behavior::Wrapping>,
112    pub tap_dance_eager: Option<TapDanceEagerState<'a, T>>,
113    pub queue: Queue,
114    pub oneshot: OneShotState,
115    pub keys_to_suppress_for_one_cycle: Vec<KeyCode, 8>,
116    pub last_press_tracker: LastPressTracker,
117    pub active_sequences: ArrayDeque<SequenceState<'a, T>, 4, arraydeque::behavior::Wrapping>,
118    pub action_queue: ActionQueue<'a, T>,
119    pub custom_event_release_queue: CustomEventReleaseQueue<'a, T>,
120    pub rpt_action: Option<&'a Action<'a, T>>,
121    pub historical_keys: History<KeyCode>,
122    pub historical_inputs: History<KCoord>,
123    /// Historical inputs where tap-holds that resolve to a hold or timeout are deleted.
124    /// Used for prior-idle calculations.
125    /// Ideally whether timeout behaviour is excluded would be configurable such that
126    /// timeout activations are only excluded when the timeout would resolve
127    /// to the same action as hold.
128    /// For now avoid that complexity, such behaviour can be added later via a flag on the
129    /// TapHoldConfiguration without much concern if it is desired.
130    pub historical_inputs_sans_holds_or_timeouts: History<KCoord>,
131    pub quick_tap_hold_timeout: bool,
132    /// If a different key was pressed within this many ticks before a HoldTap key,
133    /// immediately resolve as tap (typing streak detection). 0 = disabled.
134    pub tap_hold_require_prior_idle: u16,
135    pub chords_v2: Option<ChordsV2<'a, T>>,
136    /// History of device IDs that sent events, most-recent-first.
137    /// Used by `(device-history N recency)` switch conditions.
138    pub device_history: ArrayDeque<Option<std::num::NonZeroU8>, 8, arraydeque::behavior::Wrapping>,
139    rpt_multikey_key_buffer: MultiKeyBuffer<'a, T>,
140    trans_resolution_behavior_v2: bool,
141    delegate_to_first_layer: bool,
142    contextual_execution: ContextualExecution,
143    /// Tracks tap-hold activation events (hold/tap resolved).
144    /// Only stores data when the `tap_hold_tracker` feature is enabled;
145    /// otherwise this is a zero-sized no-op.
146    pub tap_hold_tracker: crate::tap_hold_tracker::TapHoldTracker,
147}
148
149pub use crate::tap_hold_tracker::{HoldActivatedInfo, TapActivatedInfo};
150
151#[derive(Debug)]
152pub struct History<T> {
153    events: ArrayDeque<T, HISTORICAL_EVENT_LEN, arraydeque::behavior::Wrapping>,
154    ticks_since_occurrences: ArrayDeque<u16, HISTORICAL_EVENT_LEN, arraydeque::behavior::Wrapping>,
155}
156
157#[derive(Copy, Clone, Debug)]
158pub struct HistoricalEvent<T> {
159    pub event: T,
160    pub ticks_since_occurrence: u16,
161}
162
163impl<T> History<T>
164where
165    T: Copy,
166{
167    fn new() -> Self {
168        Self {
169            ticks_since_occurrences: ArrayDeque::new(),
170            events: ArrayDeque::new(),
171        }
172    }
173
174    fn tick_hist(&mut self) {
175        let ticks = self.ticks_since_occurrences.as_uninit_slice_mut();
176        for tick_count in ticks {
177            unsafe {
178                *tick_count.assume_init_mut() = tick_count.assume_init().saturating_add(1);
179            }
180        }
181    }
182
183    fn push_front(&mut self, event: T) {
184        self.ticks_since_occurrences.push_front(0);
185        self.events.push_front(event);
186    }
187
188    pub fn iter_hevents(&self) -> impl Iterator<Item = HistoricalEvent<T>> + '_ + Clone {
189        self.events
190            .iter()
191            .copied()
192            .zip(self.ticks_since_occurrences.iter().copied())
193            .map(|(event, ticks_since_occurrence)| HistoricalEvent {
194                event,
195                ticks_since_occurrence,
196            })
197    }
198}
199
200/// An event on the key matrix.
201#[derive(Debug, Copy, Clone, PartialEq, Eq)]
202pub enum Event {
203    /// Press event with coordinates (i, j).
204    Press(u8, u16),
205    /// Release event with coordinates (i, j).
206    Release(u8, u16),
207}
208impl Event {
209    /// Returns the coordinates (i, j) of the event.
210    pub fn coord(self) -> KCoord {
211        match self {
212            Event::Press(i, j) => (i, j),
213            Event::Release(i, j) => (i, j),
214        }
215    }
216
217    /// Transforms the coordinates of the event.
218    ///
219    /// # Example
220    ///
221    /// ```
222    /// # use kanata_keyberon::layout::Event;
223    /// assert_eq!(
224    ///     Event::Press(3, 10),
225    ///     Event::Press(3, 1).transform(|i, j| (i, 11 - j)),
226    /// );
227    /// ```
228    pub fn transform(self, f: impl FnOnce(u8, u16) -> KCoord) -> Self {
229        match self {
230            Event::Press(i, j) => {
231                let (i, j) = f(i, j);
232                Event::Press(i, j)
233            }
234            Event::Release(i, j) => {
235                let (i, j) = f(i, j);
236                Event::Release(i, j)
237            }
238        }
239    }
240
241    /// Returns `true` if the event is a key press.
242    pub fn is_press(self) -> bool {
243        match self {
244            Event::Press(..) => true,
245            Event::Release(..) => false,
246        }
247    }
248
249    /// Returns `true` if the event is a key release.
250    pub fn is_release(self) -> bool {
251        match self {
252            Event::Release(..) => true,
253            Event::Press(..) => false,
254        }
255    }
256}
257
258/// Event from custom action.
259#[derive(Debug, Default, PartialEq, Eq)]
260pub enum CustomEvent<'a, T: 'a> {
261    /// No custom action.
262    #[default]
263    NoEvent,
264    /// The given custom action key is pressed.
265    Press(&'a T),
266    /// The given custom action key is released.
267    Release(&'a T),
268}
269impl<T> CustomEvent<'_, T> {
270    /// Update an event according to a new event.
271    ///
272    ///The event can only be modified in the order `NoEvent < Press <
273    /// Release`
274    fn update(&mut self, e: Self) {
275        use CustomEvent::*;
276        match (&e, &self) {
277            (Release(_), NoEvent) | (Release(_), Press(_)) => *self = e,
278            (Press(_), NoEvent) => *self = e,
279            _ => (),
280        }
281    }
282}
283
284/// Metadata about normal key flags.
285#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
286pub struct NormalKeyFlags(pub u8);
287
288pub const NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION: u8 = 0x01;
289pub const NORMAL_KEY_FLAG_CLEAR_ON_NEXT_RELEASE: u8 = 0x02;
290
291impl NormalKeyFlags {
292    pub fn nkf_clear_on_next_action(self) -> bool {
293        (self.0 & NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION) == NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION
294    }
295    pub fn nkf_clear_on_next_release(self) -> bool {
296        (self.0 & NORMAL_KEY_FLAG_CLEAR_ON_NEXT_RELEASE) == NORMAL_KEY_FLAG_CLEAR_ON_NEXT_RELEASE
297    }
298}
299
300#[derive(Debug, Eq, PartialEq)]
301pub enum State<'a, T: 'a> {
302    NormalKey {
303        keycode: KeyCode,
304        coord: KCoord,
305        flags: NormalKeyFlags,
306    },
307    LayerModifier {
308        value: usize,
309        coord: KCoord,
310    },
311    Custom {
312        value: &'a T,
313        coord: KCoord,
314    },
315    FakeKey {
316        keycode: KeyCode,
317    }, // Fake key event for sequences
318    RepeatingSequence {
319        sequence: &'a &'a [SequenceEvent<'a, T>],
320        coord: KCoord,
321    },
322    SeqCustomPending(&'a T),
323    SeqCustomActive(&'a T),
324    Tombstone,
325    NoOpInput {
326        coord: KCoord,
327    },
328}
329impl<T> Copy for State<'_, T> {}
330impl<T> Clone for State<'_, T> {
331    fn clone(&self) -> Self {
332        *self
333    }
334}
335impl<'a, T: 'a> State<'a, T> {
336    pub fn keycode(&self) -> Option<KeyCode> {
337        match self {
338            NormalKey { keycode, .. } => Some(*keycode),
339            FakeKey { keycode } => Some(*keycode),
340            _ => None,
341        }
342    }
343    pub fn coord(&self) -> Option<KCoord> {
344        match self {
345            NormalKey { coord, .. }
346            | LayerModifier { coord, .. }
347            | Custom { coord, .. }
348            | NoOpInput { coord }
349            | RepeatingSequence { coord, .. } => Some(*coord),
350            _ => None,
351        }
352    }
353    fn keycode_in_coords(&self, coords: &OneShotCoords) -> Option<KeyCode> {
354        match self {
355            NormalKey { keycode, coord, .. } => {
356                if coords.contains(coord) {
357                    Some(*keycode)
358                } else {
359                    None
360                }
361            }
362            _ => None,
363        }
364    }
365    /// Returns None if the key has been released and Some otherwise.
366    pub fn release(
367        &self,
368        c: KCoord,
369        custom: &mut CustomEvent<'a, T>,
370        custom_release_queue: &mut CustomEventReleaseQueue<'a, T>,
371    ) -> Option<Self> {
372        match *self {
373            NormalKey { coord, .. }
374            | LayerModifier { coord, .. }
375            | RepeatingSequence { coord, .. }
376            | NoOpInput { coord }
377                if coord == c =>
378            {
379                None
380            }
381            Custom { value, coord } if coord == c => {
382                match custom {
383                    CustomEvent::NoEvent => custom.update(CustomEvent::Release(value)),
384                    _ => {
385                        if custom_release_queue.push_back(value).is_some() {
386                            panic!("overflowed custom action release queue");
387                        }
388                    }
389                }
390                None
391            }
392            _ => Some(*self),
393        }
394    }
395    pub fn release_state(&self, s: ReleasableState) -> Option<Self> {
396        match (*self, s) {
397            (
398                NormalKey { keycode: k1, .. } | FakeKey { keycode: k1 },
399                ReleasableState::KeyCode(k2),
400            ) => {
401                if k1 == k2 {
402                    None
403                } else {
404                    Some(*self)
405                }
406            }
407            (LayerModifier { value: l1, .. }, ReleasableState::Layer(l2)) => {
408                if l1 == l2 {
409                    None
410                } else {
411                    Some(*self)
412                }
413            }
414            _ => Some(*self),
415        }
416    }
417    fn seq_release(&self, kc: KeyCode) -> Option<Self> {
418        match *self {
419            FakeKey { keycode, .. } if keycode == kc => None,
420            _ => Some(*self),
421        }
422    }
423    fn get_layer(&self) -> Option<usize> {
424        match self {
425            LayerModifier { value, .. } => Some(*value),
426            _ => None,
427        }
428    }
429    pub fn clear_on_next_release(&self) -> bool {
430        match self {
431            NormalKey { flags, .. } => {
432                (flags.0 & NORMAL_KEY_FLAG_CLEAR_ON_NEXT_RELEASE)
433                    == NORMAL_KEY_FLAG_CLEAR_ON_NEXT_RELEASE
434            }
435            _ => false,
436        }
437    }
438}
439
440#[derive(Copy, Clone, Debug)]
441pub(crate) struct TapDanceState<'a, T: 'a> {
442    actions: &'a [&'a Action<'a, T>],
443    timeout: u16,
444    num_taps: u16,
445}
446
447#[derive(Copy, Clone, Debug)]
448pub struct TapDanceEagerState<'a, T: 'a> {
449    coord: KCoord,
450    actions: &'a [&'a Action<'a, T>],
451    timeout: u16,
452    orig_timeout: u16,
453    num_taps: u16,
454}
455
456impl<T> TapDanceEagerState<'_, T> {
457    fn tick_tde(&mut self) {
458        self.timeout = self.timeout.saturating_sub(1);
459    }
460
461    fn is_expired(&self) -> bool {
462        self.timeout == 0 || usize::from(self.num_taps) >= self.actions.len()
463    }
464
465    fn set_expired(&mut self) {
466        self.timeout = 0;
467    }
468
469    fn incr_taps(&mut self) {
470        self.num_taps += 1;
471        self.timeout = self.orig_timeout;
472    }
473}
474
475#[derive(Debug)]
476pub(crate) enum WaitingConfig<'a, T: 'a + std::fmt::Debug> {
477    HoldTap(HoldTapConfig<'a>),
478    TapDance(TapDanceState<'a, T>),
479    Chord(&'a ChordsGroup<'a, T>),
480}
481
482#[derive(Debug)]
483pub struct WaitingState<'a, T: 'a + std::fmt::Debug> {
484    coord: KCoord,
485    timeout: u16,
486    on_press_reset_timeout_to: Option<NonZeroU16>,
487    delay: u16,
488    ticks: u16,
489    hold: &'a Action<'a, T>,
490    tap: &'a Action<'a, T>,
491    timeout_action: &'a Action<'a, T>,
492    config: WaitingConfig<'a, T>,
493    layer_stack: LayerStack,
494    prev_queue_len: QueueLen,
495}
496
497/// Actions that can be triggered for a key configured for HoldTap.
498#[derive(Debug, Copy, Clone, PartialEq, Eq)]
499pub enum WaitingAction {
500    /// Trigger the holding event.
501    Hold,
502    /// Trigger the tapping event.
503    Tap,
504    /// Trigger the timeout event.
505    Timeout,
506    /// Drop this event. It will act as if no key was pressed.
507    NoOp,
508}
509
510impl<'a, T: std::fmt::Debug> WaitingState<'a, T> {
511    fn tick_wt(
512        &mut self,
513        queued: &mut Queue,
514        action_queue: &mut ActionQueue<'a, T>,
515    ) -> Option<(WaitingAction, Option<PressedQueue>)> {
516        self.timeout = self.timeout.saturating_sub(1);
517        self.ticks = self.ticks.saturating_add(1);
518        let mut pq = None;
519        let (ret, cfg_change) = match self.config {
520            WaitingConfig::HoldTap(htc) => (self.handle_hold_tap(htc, queued), None),
521            WaitingConfig::TapDance(ref tds) => {
522                let (ret, num_taps) =
523                    self.handle_tap_dance(tds.num_taps, tds.actions.len(), queued);
524                self.prev_queue_len = queued.len() as u8;
525                // Due to ownership issues, handle_tap_dance can't contain all of the necessary
526                // logic.
527                if ret.is_some() {
528                    let idx = core::cmp::min(num_taps.into(), tds.actions.len()).saturating_sub(1);
529                    self.tap = tds.actions[idx];
530                }
531                if num_taps > tds.num_taps {
532                    self.timeout = tds.timeout;
533                }
534                (
535                    ret,
536                    Some(WaitingConfig::TapDance(TapDanceState { num_taps, ..*tds })),
537                )
538            }
539            WaitingConfig::Chord(config) => {
540                if let Some((ret, action, cpq)) = self.handle_chord(config, queued, action_queue) {
541                    self.tap = action;
542                    pq = Some(cpq);
543                    (Some(ret), None)
544                } else {
545                    (None, None)
546                }
547            }
548        };
549        if let Some(cfg) = cfg_change {
550            self.config = cfg;
551        }
552        ret.map(|v| (v, pq))
553    }
554
555    fn handle_hold_tap(&mut self, cfg: HoldTapConfig, queued: &Queue) -> Option<WaitingAction> {
556        if queued.len() as u8 == self.prev_queue_len && self.timeout > 0 {
557            // Fast path: nothing has changed since last tick and we haven't timed out yet.
558            return None;
559        }
560        if let Some(timeout_reset_val) = self.on_press_reset_timeout_to {
561            if let Some(last) = queued.iter().next_back() {
562                if last.event.is_press() {
563                    self.timeout = timeout_reset_val.into();
564                }
565            }
566        }
567        self.prev_queue_len = queued.len() as u8;
568        let mut skip_timeout = false;
569        match cfg {
570            HoldTapConfig::Default => (),
571            HoldTapConfig::HoldOnOtherKeyPress => {
572                if queued.iter().any(|s| s.event.is_press()) {
573                    return Some(WaitingAction::Hold);
574                }
575            }
576            HoldTapConfig::Order { buffer, .. } => {
577                // Like PermissiveHold: if another key was pressed AND released
578                // (while modifier is still held), resolve as Hold.
579                // If modifier is released first, the fallthrough below handles Tap.
580                //
581                // Buffer: key presses that occurred within `buffer` ticks of the
582                // hold-tap key press are ignored by release-order logic, allowing
583                // fast typing to resolve as Tap regardless of release order.
584                let mut queued = queued.iter();
585                while let Some(q) = queued.next() {
586                    if q.event.is_press() {
587                        // Elapsed ticks since this key entered the queue, compared against buffer window.
588                        let press_tick = self.ticks.saturating_sub(q.since);
589                        if press_tick < buffer {
590                            continue;
591                        }
592                        let (i, j) = q.event.coord();
593                        let target = Event::Release(i, j);
594                        if queued.clone().any(|q| q.event == target) {
595                            return Some(WaitingAction::Hold);
596                        }
597                    }
598                }
599            }
600            HoldTapConfig::PermissiveHold => {
601                let mut queued = queued.iter();
602                while let Some(q) = queued.next() {
603                    if q.event.is_press() {
604                        let (i, j) = q.event.coord();
605                        let target = Event::Release(i, j);
606                        if queued.clone().any(|q| q.event == target) {
607                            return Some(WaitingAction::Hold);
608                        }
609                    }
610                }
611            }
612            HoldTapConfig::Custom(func) => {
613                let (waiting_action, local_skip) = (func)(QueuedIter(queued.iter()), self.coord);
614                if waiting_action.is_some() {
615                    return waiting_action;
616                }
617                skip_timeout = local_skip;
618            }
619        }
620        if let Some(&Queued {
621            since: since_release,
622            ..
623        }) = queued
624            .iter()
625            .find(|s| self.is_corresponding_release(&s.event))
626        {
627            if self.timeout >= self.delay.saturating_sub(since_release) {
628                Some(WaitingAction::Tap)
629            } else {
630                Some(WaitingAction::Timeout)
631            }
632        } else if self.timeout == 0 && (!skip_timeout) {
633            Some(WaitingAction::Timeout)
634        } else {
635            None
636        }
637    }
638
639    fn handle_tap_dance(
640        &self,
641        num_taps: u16,
642        max_taps: usize,
643        queued: &mut Queue,
644    ) -> (Option<WaitingAction>, u16) {
645        if queued.len() as u8 == self.prev_queue_len && self.timeout > 0 {
646            // Fast path: nothing has changed since last tick and we haven't timed out yet.
647            return (None, num_taps);
648        }
649        // Evict events with the same coordinates except for the final release. E.g. if 3 taps have
650        // occurred, this will remove all `Press` events and 2 `Release` events. This is done so
651        // that the state machine processes the entire tap dance sequence as a single press and
652        // single release regardless of how many taps were actually done.
653        let evict_same_coord_events = |num_taps: u16, queued: &mut Queue| {
654            let mut releases_to_remove = num_taps.saturating_sub(1);
655            queued.retain(|s| {
656                let mut do_retain = true;
657                if self.is_corresponding_release(&s.event) {
658                    if releases_to_remove > 0 {
659                        do_retain = false;
660                        releases_to_remove = releases_to_remove.saturating_sub(1)
661                    }
662                } else if self.is_corresponding_press(&s.event) {
663                    do_retain = false;
664                }
665                do_retain
666            });
667        };
668        if self.timeout == 0 {
669            evict_same_coord_events(num_taps, queued);
670            return (Some(WaitingAction::Tap), num_taps);
671        }
672        // Get the number of sequential taps for this tap-dance key. If a different key was
673        // pressed, activate a tap-dance action.
674        match queued.iter().try_fold(1, |same_tap_count, s| {
675            if self.is_corresponding_press(&s.event) {
676                Ok(same_tap_count + 1)
677            } else if matches!(s.event, Event::Press(..)) {
678                Err((same_tap_count, ()))
679            } else {
680                Ok(same_tap_count)
681            }
682        }) {
683            Ok(num_taps) if usize::from(num_taps) >= max_taps => {
684                evict_same_coord_events(num_taps, queued);
685                (Some(WaitingAction::Tap), num_taps)
686            }
687            Ok(num_taps) => (None, num_taps),
688            Err((num_taps, _)) => {
689                evict_same_coord_events(num_taps, queued);
690                (Some(WaitingAction::Tap), num_taps)
691            }
692        }
693    }
694
695    fn handle_chord(
696        &mut self,
697        config: &'a ChordsGroup<'a, T>,
698        queued: &mut Queue,
699        action_queue: &mut ActionQueue<'a, T>,
700    ) -> Option<(WaitingAction, &'a Action<'a, T>, PressedQueue)> {
701        if queued.len() as u8 == self.prev_queue_len && self.timeout.saturating_sub(self.delay) > 0
702        {
703            // Fast path: nothing has changed since last tick and we haven't timed out yet.
704            return None;
705        }
706        self.prev_queue_len = queued.len() as u8;
707
708        // need to keep track of how many Press events we handled so we can filter them out later
709        let mut handled_press_events = 0;
710        let start_chord_coord = self.coord;
711        let mut released_coord = None;
712
713        // Compute the set of chord keys that are currently pressed
714        // `Ok` when chording mode may continue
715        // `Err` when it should end for various reasons
716        let active = queued
717            .iter()
718            .try_fold(config.get_keys(self.coord).unwrap_or(0), |active, s| {
719                if self.delay.saturating_sub(s.since) > self.timeout {
720                    Ok(active)
721                } else if let Some(chord_keys) = config.get_keys(s.event.coord()) {
722                    match s.event {
723                        Event::Press(_, _) => {
724                            handled_press_events += 1;
725                            Ok(active | chord_keys)
726                        }
727                        Event::Release(i, j) => {
728                            // release chord quickly by changing the coordinate to the released
729                            // key, to be consistent with chord decomposition behaviour.
730                            released_coord = Some((i, j));
731                            Err(active)
732                        }
733                    }
734                } else if matches!(s.event, Event::Press(..)) {
735                    Err(active) // pressed a non-chord key, abort
736                } else {
737                    Ok(active)
738                }
739            })
740            .and_then(|active| {
741                if self.timeout.saturating_sub(self.delay) == 0 {
742                    Err(active) // timeout expired, abort
743                } else {
744                    Ok(active)
745                }
746            });
747
748        let res = match active {
749            Ok(active) => {
750                // Chording mode still active, only trigger action if it's unambiguous
751                {
752                    let action = config.get_chord_if_unambiguous(active)?;
753                    if let Some(coord) = released_coord {
754                        self.coord = coord;
755                    }
756                    (WaitingAction::Tap, action)
757                }
758            }
759            Err(active) => {
760                // Abort chording mode. Trigger a chord action if there is one.
761                if let Some(action) = config.get_chord(active) {
762                    if let Some(coord) = released_coord {
763                        self.coord = coord;
764                    }
765                    (WaitingAction::Tap, action)
766                } else {
767                    self.decompose_chord_into_action_queue(config, queued, action_queue);
768                    (WaitingAction::NoOp, &Action::NoOp)
769                }
770            }
771        };
772
773        let mut pq = PressedQueue::new();
774        let _ = pq.push_back(start_chord_coord);
775
776        // Return all press events that were logically handled by this chording event
777        queued.retain(|s| {
778            if self.delay.saturating_sub(s.since) > self.timeout {
779                true
780            } else if matches!(s.event, Event::Press(i, j) if config.get_keys((i, j)).is_some())
781                && handled_press_events > 0
782            {
783                handled_press_events -= 1;
784                let _ = pq.push_back(s.event().coord());
785                false
786            } else {
787                true
788            }
789        });
790
791        Some((res.0, res.1, pq))
792    }
793
794    fn decompose_chord_into_action_queue(
795        &mut self,
796        config: &'a ChordsGroup<'a, T>,
797        queued: &Queue,
798        action_queue: &mut ActionQueue<'a, T>,
799    ) {
800        let mut chord_key_order = [0u128; ChordKeys::BITS as usize];
801
802        // Default to the initial coordinate. But if a key is released early (before the timeout
803        // occurs), use that key for action releases. That way the chord is released as early as
804        // possible.
805        let mut default_associated_coord = self.coord;
806
807        let starting_mask = config.get_keys(self.coord).unwrap_or(0);
808        let mut mask_bits_set = 1;
809        chord_key_order[0] = starting_mask;
810        let _ = queued.iter().try_fold(starting_mask, |active, s| {
811            if self.delay.saturating_sub(s.since) > self.timeout {
812                Ok(active)
813            } else if let Some(chord_keys) = config.get_keys(s.event.coord()) {
814                match s.event {
815                    Event::Press(..) => {
816                        if active | chord_keys != active {
817                            chord_key_order[mask_bits_set] = chord_keys;
818                            mask_bits_set += 1;
819                        }
820                        Ok(active | chord_keys)
821                    }
822                    Event::Release(i, j) => {
823                        default_associated_coord = (i, j);
824                        Err(active) // released a chord key, abort
825                    }
826                }
827            } else if matches!(s.event, Event::Press(..)) {
828                Err(active) // pressed a non-chord key, abort
829            } else {
830                Ok(active)
831            }
832        });
833        let len = mask_bits_set;
834        let chord_keys = &chord_key_order[0..len];
835
836        let get_coord_for_chord = |mask: ChordKeys| -> (u8, u16) {
837            if config.get_keys(default_associated_coord).unwrap_or(0) & mask > 0 {
838                // This might be a release.
839                // If it belongs to the associated action, prefer to use it.
840                return default_associated_coord;
841            }
842            if self.coord != default_associated_coord
843                && config.get_keys(self.coord).unwrap_or(0) & mask > 0
844            {
845                // The first coordinate not in queued
846                // so must be explicitly checked if it is not the default coord.
847                return self.coord;
848            }
849            queued
850                .iter()
851                .find_map(|q| {
852                    let coord = q.event.coord();
853                    let qmask = config.get_keys(coord).unwrap_or(0);
854                    match qmask & mask {
855                        0 => None,
856                        _ => Some(coord),
857                    }
858                })
859                .unwrap_or(default_associated_coord)
860        };
861
862        // Compute actions using the following description:
863        //
864        // Let's say we have a chord group with keys (h j k l). The full set (h j k l) is not
865        // defined with an action, but the user has pressed all of h, j, k, l in the listed order,
866        // so now kanata needs to break down the combo. How should it work?
867        //
868        // Figuratively "release" keys in reverse-temporal order until a valid chord is found. So
869        // first, l is figuratively released, and if (h j k) is a valid chord, that action will
870        // activate. If (l) by itself is valid that then activates after (h j k) is finished.
871        //
872        // In the case that (h j k) is not a chord, instead activate (h j). If that is a valid
873        // chord, then try to activate (k l) together, and if not, evaluate (k), then (l).
874        //
875        // If (h j) is not a valid chord, try to activate (h). Then try to activate (j k l). If
876        // that is invalid, try (j k), then (j). If (j k) is valid, try (l). If (j) is valid, try
877        // (k l). If (k l) is invalid, try (k) then (l).
878        //
879        // The possible executions, listed in descending order of priority (first listed has
880        // highest execution priority) are:
881        // (h   j   k   l)
882        // (h   j   k) (l)
883        // (h   j) (k   l)
884        // (h   j) (k) (l)
885        // (h) (j   k   l)
886        // (h) (j   k) (l)
887        // (h) (j) (k   l)
888        // (h) (j) (k) (l)
889
890        let mut start = 0;
891        let mut end = len;
892        let delay = self.delay + self.ticks;
893        while start < len {
894            let sub_chord = &chord_keys[start..end];
895            let chord_mask = sub_chord
896                .iter()
897                .copied()
898                .reduce(|acc, e| acc | e)
899                .unwrap_or(0);
900            if let Some(action) = config.get_chord(chord_mask) {
901                let coord = get_coord_for_chord(chord_mask);
902                // Note on LayerStack being default (empty):
903                // A chordv1 allows transparency, so this is broken right now,
904                // and could result in an infinite loop, because
905                // the queue activating code falls back to top-level resolution order
906                // if the stored layer stack is empty.
907                let _ = action_queue.push_back(Some((coord, delay, action, Default::default())));
908            } else {
909                end -= 1;
910                // shrink from end until something is found, or have checked up to and including
911                // the individual start key.
912                while end > start {
913                    let sub_chord = &chord_keys[start..end];
914                    let chord_mask = sub_chord
915                        .iter()
916                        .copied()
917                        .reduce(|acc, e| acc | e)
918                        .unwrap_or(0);
919                    if let Some(action) = config.get_chord(chord_mask) {
920                        let coord = get_coord_for_chord(chord_mask);
921                        let _ = action_queue.push_back(Some((
922                            coord,
923                            delay,
924                            action,
925                            Default::default(),
926                        )));
927                        break;
928                    }
929                    end -= 1;
930                }
931            }
932            start = if end <= start { start + 1 } else { end };
933            end = len;
934        }
935    }
936
937    fn is_corresponding_release(&self, event: &Event) -> bool {
938        matches!(event, Event::Release(i, j) if (*i, *j) == self.coord)
939    }
940
941    fn is_corresponding_press(&self, event: &Event) -> bool {
942        matches!(event, Event::Press(i, j) if (*i, *j) == self.coord)
943    }
944}
945
946type OneShotCoords = ArrayDeque<KCoord, ONE_SHOT_MAX_ACTIVE, arraydeque::behavior::Wrapping>;
947
948#[derive(Debug, Copy, Clone)]
949pub struct SequenceState<'a, T: 'a> {
950    cur_event: Option<SequenceEvent<'a, T>>,
951    delay: u32,              // Keeps track of SequenceEvent::Delay time remaining
952    tapped: Option<KeyCode>, // Keycode of a key that should be released at the next tick
953    remaining_events: &'a [SequenceEvent<'a, T>],
954}
955
956type ReleasedOneShotKeys = Vec<KCoord, ONE_SHOT_MAX_ACTIVE>;
957
958// Using a u16 for indices instead of usize.
959// Need to check against this value in code that creates layers.
960pub const MAX_LAYERS: usize = 60000;
961
962// Use heapless Vec for perf - avoid pointer indirections.
963// Use u16 for more efficient cache. 12*u16 = 3*u64 = 24 bytes.
964// Then there is a usize for the length, totaling 32 bytes.
965// Cache line is typically 64 bytes, so this takes half a cache line.
966// Above all assumes x86-64.
967pub const MAX_ACTIVE_LAYERS: usize = 12;
968
969/// Because we only need a read-only stack and efficient iteration over contained
970/// items, LayerStack items are in reverse order over usual back-to-front order
971/// of items in array-based stack implementations.
972type LayerStack = Vec<u16, MAX_ACTIVE_LAYERS>;
973
974/// Contains the state of one shot keys that are currently active.
975pub struct OneShotState {
976    /// KCoordinates of one shot keys that are active
977    pub keys: ArrayDeque<KCoord, ONE_SHOT_MAX_ACTIVE, arraydeque::behavior::Wrapping>,
978    /// KCoordinates of one shot keys that have been released
979    pub released_keys: ArrayDeque<KCoord, ONE_SHOT_MAX_ACTIVE, arraydeque::behavior::Wrapping>,
980    /// Fix #1874:
981    /// Represents the one-shot state that must not be released on physical key release.
982    /// Consider the case `(multi a (one-shot 100 b))`,
983    /// when only tracking coordinates (which this used to in the past),
984    /// the `a` would not release a even upon releasing the action key
985    /// because its state falls on the same coordinate as the oneshot b.
986    /// The fix is to explicitly know which key/layer states
987    /// — which are the only actions allowed within one-shot —
988    /// should be kept, and normally release others.
989    pub state_to_retain_on_release:
990        ArrayDeque<OneShotRetainableState, ONE_SHOT_MAX_ACTIVE, arraydeque::behavior::Wrapping>,
991    /// Used to keep track of already-pressed keys for the release variants.
992    pub other_pressed_keys: ArrayDeque<KCoord, ONE_SHOT_MAX_ACTIVE, arraydeque::behavior::Wrapping>,
993    /// Timeout (ms) after which all one shot keys expire
994    pub timeout: u16,
995    /// Contains the end config of the most recently pressed one shot key
996    pub end_config: OneShotEndConfig,
997    /// Marks if release of the one shot keys should be done on the next tick
998    pub release_on_next_tick: bool,
999    /// The number of ticks to delay the release of the one-shot activation
1000    /// for EndOnFirstPress(OrRepress).
1001    /// This used to not exist and effectively be 1 (1ms),
1002    /// but that is too short for some environments.
1003    /// When too short, applications or desktop environments process
1004    /// the key release before the next press,
1005    /// even if temporally the release was sent after.
1006    pub pause_input_processing_delay: u16,
1007    /// If pause_input_processing_delay is used, this will be >0,
1008    /// meaning input processing should be paused to prevent extra presses
1009    /// from coming in while OneShot has not yet been released.
1010    ///
1011    /// May also be reused for other purposes...
1012    pub pause_input_processing_ticks: u16,
1013
1014    /// Number of ticks to ignore press events for.
1015    pub ticks_to_ignore_events: u16,
1016}
1017
1018#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1019pub enum OneShotRetainableState {
1020    KeyCode { coord: KCoord, kc: KeyCode },
1021    Layer { coord: KCoord, layer: u16 },
1022}
1023
1024impl OneShotRetainableState {
1025    pub fn coord(&self) -> KCoord {
1026        match self {
1027            Self::KeyCode { coord, .. } | Self::Layer { coord, .. } => *coord,
1028        }
1029    }
1030}
1031
1032#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
1033enum OneShotHandlePressKey {
1034    OneShotKey(KCoord),
1035    Other(KCoord),
1036}
1037
1038impl OneShotState {
1039    fn tick_osh(&mut self) -> Option<ReleasedOneShotKeys> {
1040        if self.keys.is_empty() {
1041            return None;
1042        }
1043        self.ticks_to_ignore_events = self.ticks_to_ignore_events.saturating_sub(1);
1044        self.timeout = self.timeout.saturating_sub(1);
1045        if self.release_on_next_tick || self.timeout == 0 {
1046            self.release_on_next_tick = false;
1047            self.timeout = 0;
1048            self.pause_input_processing_ticks = 0;
1049            self.ticks_to_ignore_events = 0;
1050            self.keys.clear();
1051            self.other_pressed_keys.clear();
1052            self.state_to_retain_on_release.clear();
1053            Some(self.released_keys.drain(..).collect())
1054        } else {
1055            None
1056        }
1057    }
1058
1059    /// Returns the coordinates associated with an active oneshot.
1060    /// The intended use of this is for `rpt-any` to be able to repeat
1061    /// the output chord of a one-shot+normal key,
1062    /// which are two separate actions that users
1063    /// would likely want to combine under a repeat condition.
1064    fn handle_press(&mut self, key: OneShotHandlePressKey) -> OneShotCoords {
1065        let mut oneshot_coords = ArrayDeque::new();
1066        if self.keys.is_empty() || self.ticks_to_ignore_events > 0 {
1067            return oneshot_coords;
1068        }
1069        match key {
1070            OneShotHandlePressKey::OneShotKey(pressed_coord) => {
1071                if matches!(
1072                    self.end_config,
1073                    OneShotEndConfig::EndOnFirstReleaseOrRepress
1074                        | OneShotEndConfig::EndOnFirstPressOrRepress
1075                ) && self.keys.contains(&pressed_coord)
1076                {
1077                    self.release_on_next_tick = true;
1078                    oneshot_coords.extend(self.keys.iter().copied());
1079                }
1080
1081                self.released_keys.retain(|coord| *coord != pressed_coord);
1082            }
1083            OneShotHandlePressKey::Other(pressed_coord) => {
1084                if matches!(
1085                    self.end_config,
1086                    OneShotEndConfig::EndOnFirstPress | OneShotEndConfig::EndOnFirstPressOrRepress
1087                ) {
1088                    self.timeout = core::cmp::min(self.pause_input_processing_delay, self.timeout);
1089                    self.pause_input_processing_ticks = self.pause_input_processing_delay;
1090                } else {
1091                    let _ = self.other_pressed_keys.push_back(pressed_coord);
1092                }
1093                oneshot_coords.extend(self.keys.iter().copied());
1094            }
1095        };
1096        oneshot_coords
1097    }
1098
1099    /// Returns true if the caller should handle the release normally and false otherwise.
1100    /// The second value in the tuple represents an overflow of released one shot keys and should
1101    /// be released is it is `Some`.
1102    fn handle_release(&mut self, (i, j): KCoord) -> (bool, Option<KCoord>) {
1103        if self.keys.is_empty() {
1104            return (true, None);
1105        }
1106        if !self.keys.contains(&(i, j)) {
1107            if matches!(
1108                self.end_config,
1109                OneShotEndConfig::EndOnFirstRelease | OneShotEndConfig::EndOnFirstReleaseOrRepress
1110            ) && self.other_pressed_keys.contains(&(i, j))
1111            {
1112                self.release_on_next_tick = true;
1113            }
1114            (true, None)
1115        } else {
1116            // delay release for one shot keys
1117            (false, self.released_keys.push_back((i, j)))
1118        }
1119    }
1120
1121    fn add_state_to_retain(&mut self, state: OneShotRetainableState) {
1122        if !self.state_to_retain_on_release.contains(&state) {
1123            self.state_to_retain_on_release.push_back(state);
1124        }
1125    }
1126}
1127
1128/// An iterator over the currently queued events.
1129///
1130/// Events can be retrieved by iterating over this struct and calling [Queued::event].
1131#[derive(Clone)]
1132pub struct QueuedIter<'a>(arraydeque::Iter<'a, Queued>);
1133
1134impl<'a> Iterator for QueuedIter<'a> {
1135    type Item = &'a Queued;
1136    fn next(&mut self) -> Option<Self::Item> {
1137        self.0.next()
1138    }
1139    fn size_hint(&self) -> (usize, Option<usize>) {
1140        self.0.size_hint()
1141    }
1142}
1143
1144/// An event, waiting in a queue to be processed.
1145#[derive(Debug, Copy, Clone)]
1146pub struct Queued {
1147    pub(crate) event: Event,
1148    pub(crate) since: u16,
1149}
1150impl From<Event> for Queued {
1151    fn from(event: Event) -> Self {
1152        Queued { event, since: 0 }
1153    }
1154}
1155impl Queued {
1156    pub(crate) fn new_press(i: u8, j: u16) -> Self {
1157        Self {
1158            since: 0,
1159            event: Event::Press(i, j),
1160        }
1161    }
1162
1163    pub(crate) fn new_release(i: u8, j: u16) -> Self {
1164        Self {
1165            since: 0,
1166            event: Event::Release(i, j),
1167        }
1168    }
1169
1170    pub(crate) fn tick_qd(&mut self) {
1171        self.since = self.since.saturating_add(1);
1172    }
1173
1174    /// Get the [Event] from this object.
1175    pub fn event(&self) -> Event {
1176        self.event
1177    }
1178}
1179
1180#[derive(Default)]
1181pub struct LastPressTracker {
1182    pub coord: KCoord,
1183    pub tap_hold_timeout: u16,
1184}
1185
1186impl LastPressTracker {
1187    fn tick_lpt(&mut self) {
1188        self.tap_hold_timeout = self.tap_hold_timeout.saturating_sub(1);
1189    }
1190    fn update_coord(&mut self, coord: KCoord) {
1191        if coord.0 == REAL_KEY_ROW {
1192            // Only update if it's a real key press.
1193            self.coord = coord;
1194        }
1195    }
1196}
1197
1198impl<'a, const C: usize, const R: usize, T: 'a + Copy + std::fmt::Debug> Layout<'a, C, R, T> {
1199    /// Creates a new `Layout` object.
1200    fn new(layers: &'a [[[Action<T>; C]; R]]) -> Self {
1201        assert!(layers.len() < MAX_LAYERS);
1202        Self {
1203            src_keys: &[Action::NoOp; C],
1204            layers,
1205            default_layer: 0,
1206            states: Vec::new(),
1207            waiting: None,
1208            extra_waiting: ArrayDeque::new(),
1209            tap_dance_eager: None,
1210            queue: ArrayDeque::new(),
1211            oneshot: OneShotState {
1212                timeout: 0,
1213                end_config: OneShotEndConfig::EndOnFirstPress,
1214                keys: ArrayDeque::new(),
1215                released_keys: ArrayDeque::new(),
1216                state_to_retain_on_release: ArrayDeque::new(),
1217                other_pressed_keys: ArrayDeque::new(),
1218                release_on_next_tick: false,
1219                pause_input_processing_delay: 0,
1220                pause_input_processing_ticks: 0,
1221                ticks_to_ignore_events: 0,
1222            },
1223            keys_to_suppress_for_one_cycle: Vec::new(),
1224            last_press_tracker: Default::default(),
1225            active_sequences: ArrayDeque::new(),
1226            action_queue: ArrayDeque::new(),
1227            custom_event_release_queue: ArrayDeque::new(),
1228            rpt_action: None,
1229            historical_keys: History::new(),
1230            historical_inputs: History::new(),
1231            historical_inputs_sans_holds_or_timeouts: History::new(),
1232            rpt_multikey_key_buffer: unsafe { MultiKeyBuffer::new() },
1233            quick_tap_hold_timeout: false,
1234            tap_hold_require_prior_idle: 0,
1235            trans_resolution_behavior_v2: true,
1236            delegate_to_first_layer: false,
1237            chords_v2: None,
1238            device_history: ArrayDeque::new(),
1239            contextual_execution: ContextualExecution::new(),
1240            tap_hold_tracker: Default::default(),
1241        }
1242    }
1243    pub fn new_with_trans_action_settings(
1244        src_keys: &'a [Action<T>; C],
1245        layers: &'a [[[Action<T>; C]; R]],
1246        trans_resolution_behavior_v2: bool,
1247        delegate_to_first_layer: bool,
1248    ) -> Self {
1249        let mut new = Self::new(layers);
1250        new.src_keys = src_keys;
1251        new.trans_resolution_behavior_v2 = trans_resolution_behavior_v2;
1252        new.delegate_to_first_layer = delegate_to_first_layer;
1253        new
1254    }
1255
1256    /// Iterates on the key codes of the current state.
1257    pub fn keycodes(&self) -> impl Iterator<Item = KeyCode> + Clone + '_ {
1258        let keys_to_suppress_for_one_cycle = self.keys_to_suppress_for_one_cycle.clone();
1259        self.states
1260            .iter()
1261            .filter_map(State::keycode)
1262            .filter(move |kc| !keys_to_suppress_for_one_cycle.contains(kc))
1263    }
1264
1265    fn exclude_hold_or_timeout_from_history(coord: KCoord, history: &mut History<KCoord>) {
1266        if let Some((i, _)) = history
1267            .events
1268            .iter()
1269            .copied()
1270            .enumerate()
1271            .find(|(_i, ev)| *ev == coord)
1272        {
1273            history.ticks_since_occurrences.remove(i);
1274            history.events.remove(i);
1275        }
1276    }
1277
1278    fn waiting_into_hold(&mut self, idx: i8) -> CustomEvent<'a, T> {
1279        let waiting = if idx < 0 {
1280            self.waiting.as_ref()
1281        } else {
1282            self.extra_waiting.get(idx as usize)
1283        };
1284        if let Some(w) = waiting {
1285            let hold = w.hold;
1286            let coord = w.coord;
1287
1288            Self::exclude_hold_or_timeout_from_history(
1289                coord,
1290                &mut self.historical_inputs_sans_holds_or_timeouts,
1291            );
1292
1293            let delay = match w.config {
1294                WaitingConfig::HoldTap(..) | WaitingConfig::Chord(_) => w.delay + w.ticks,
1295                WaitingConfig::TapDance(_) => 0,
1296            };
1297            let layer_stack = w.layer_stack.clone();
1298            self.tap_hold_tracker.set_hold_activated(coord, &w.config);
1299            if idx < 0 {
1300                self.waiting = None;
1301            } else {
1302                self.extra_waiting.remove(idx as usize);
1303            }
1304            if coord == self.last_press_tracker.coord {
1305                self.last_press_tracker.tap_hold_timeout = 0;
1306            }
1307            // Similar issue happens for the quick tap-hold tap as with on-press release;
1308            // the rapidity of the release can cause issues. See pause_input_processing_delay
1309            // comments for more detail.
1310            self.oneshot.pause_input_processing_ticks = self.oneshot.pause_input_processing_delay;
1311            let mut custom_activation_count = 0;
1312            self.do_action(
1313                hold,
1314                coord,
1315                delay,
1316                false,
1317                &mut layer_stack.into_iter(),
1318                &mut custom_activation_count,
1319            )
1320        } else {
1321            CustomEvent::NoEvent
1322        }
1323    }
1324    fn waiting_into_tap(&mut self, pq: Option<PressedQueue>, idx: i8) -> CustomEvent<'a, T> {
1325        let waiting = if idx < 0 {
1326            self.waiting.as_ref()
1327        } else {
1328            self.extra_waiting.get(idx as usize)
1329        };
1330        if let Some(w) = waiting {
1331            let tap = w.tap;
1332            let coord = w.coord;
1333            let delay = match w.config {
1334                WaitingConfig::HoldTap(..) | WaitingConfig::Chord(_) => w.delay + w.ticks,
1335                WaitingConfig::TapDance(_) => 0,
1336            };
1337            let layer_stack = w.layer_stack.clone();
1338            self.tap_hold_tracker.set_tap_activated(coord, &w.config);
1339            if idx < 0 {
1340                self.waiting = None;
1341            } else {
1342                self.extra_waiting.remove(idx as usize);
1343            }
1344            let mut custom_activation_count = 0;
1345            let ret = self.do_action(
1346                tap,
1347                coord,
1348                delay,
1349                false,
1350                &mut layer_stack.clone().into_iter(),
1351                &mut custom_activation_count,
1352            );
1353
1354            if let Some(pq) = pq {
1355                let mut custom_activation_count = 0;
1356                self.contextual_execution.pause_historical_keys_updates = true;
1357                match tap {
1358                    Action::KeyCode(_)
1359                    | Action::MultipleKeyCodes(_)
1360                    | Action::OneShot(_)
1361                    | Action::Layer(_) => {
1362                        // The current intent of this block is to ensure that simple actions like
1363                        // key presses or layer-while-held remain pressed as long as a single key from
1364                        // the input chord remains held. The behaviour of these actions is correct in
1365                        // the case of repeating do_action, so there is currently no harm in doing
1366                        // this. Other action types are more problematic though.
1367                        for other_coord in pq.iter().copied() {
1368                            self.do_action(
1369                                tap,
1370                                other_coord,
1371                                delay,
1372                                false,
1373                                &mut layer_stack.clone().into_iter(),
1374                                &mut custom_activation_count,
1375                            );
1376                        }
1377                    }
1378                    Action::MultipleActions(acs) => {
1379                        // Like above block, but for the same simple actions within MultipleActions
1380                        for ac in acs.iter() {
1381                            if matches!(
1382                                ac,
1383                                Action::KeyCode(_)
1384                                    | Action::MultipleKeyCodes(_)
1385                                    | Action::OneShot(_)
1386                                    | Action::Layer(_)
1387                            ) {
1388                                for other_coord in pq.iter().copied() {
1389                                    self.do_action(
1390                                        ac,
1391                                        other_coord,
1392                                        delay,
1393                                        false,
1394                                        &mut layer_stack.clone().into_iter(),
1395                                        &mut custom_activation_count,
1396                                    );
1397                                }
1398                            }
1399                        }
1400                    }
1401                    _ => {}
1402                }
1403                self.contextual_execution.pause_historical_keys_updates = false;
1404            }
1405
1406            // Similar issue happens for the quick tap-hold tap as with on-press release;
1407            // the rapidity of the release can cause issues. See pause_input_processing_delay
1408            // comments for more detail.
1409            self.oneshot.pause_input_processing_ticks = self.oneshot.pause_input_processing_delay;
1410            ret
1411        } else {
1412            CustomEvent::NoEvent
1413        }
1414    }
1415    fn waiting_into_timeout(&mut self, idx: i8) -> CustomEvent<'a, T> {
1416        let waiting = if idx < 0 {
1417            self.waiting.as_ref()
1418        } else {
1419            self.extra_waiting.get(idx as usize)
1420        };
1421        if let Some(w) = waiting {
1422            let timeout_action = w.timeout_action;
1423            let coord = w.coord;
1424
1425            Self::exclude_hold_or_timeout_from_history(
1426                coord,
1427                &mut self.historical_inputs_sans_holds_or_timeouts,
1428            );
1429
1430            let delay = match w.config {
1431                WaitingConfig::HoldTap(..) | WaitingConfig::Chord(_) => w.delay + w.ticks,
1432                WaitingConfig::TapDance(_) => 0,
1433            };
1434            let layer_stack = w.layer_stack.clone();
1435            self.tap_hold_tracker.set_hold_activated(coord, &w.config);
1436            if idx < 0 {
1437                self.waiting = None;
1438            } else {
1439                self.extra_waiting.remove(idx as usize);
1440            }
1441            if coord == self.last_press_tracker.coord {
1442                self.last_press_tracker.tap_hold_timeout = 0;
1443            }
1444            let mut custom_activation_count = 0;
1445            self.do_action(
1446                timeout_action,
1447                coord,
1448                delay,
1449                false,
1450                &mut layer_stack.into_iter(),
1451                &mut custom_activation_count,
1452            )
1453        } else {
1454            CustomEvent::NoEvent
1455        }
1456    }
1457    fn drop_waiting(&mut self) -> CustomEvent<'a, T> {
1458        self.waiting = None;
1459        CustomEvent::NoEvent
1460    }
1461    /// A time event.
1462    ///
1463    /// This method must be called regularly, typically every millisecond.
1464    ///
1465    /// Returns the corresponding `CustomEvent`, allowing to manage
1466    /// custom actions thanks to the `Action::Custom` variant.
1467    pub fn tick(&mut self) -> CustomEvent<'a, T> {
1468        self.tick_layout()
1469    }
1470
1471    fn tick_layout(&mut self) -> CustomEvent<'a, T> {
1472        // Eagerly process released queued custom actions
1473        // then return; other items will be processed later!
1474        if let Some(released_custom_event) = self.custom_event_release_queue.pop_front() {
1475            return CustomEvent::Release(released_custom_event);
1476        }
1477
1478        let active_layer = self.current_layer() as u16;
1479        if let Some(chv2) = self.chords_v2.as_mut() {
1480            self.queue.extend(chv2.tick_chv2(active_layer).drain(0..));
1481            if let chord_action @ Some(_) = chv2.get_action_chv2() {
1482                self.action_queue.push_back(chord_action);
1483                self.oneshot.pause_input_processing_ticks =
1484                    self.oneshot.pause_input_processing_delay;
1485            }
1486        }
1487        self.keys_to_suppress_for_one_cycle.clear();
1488        if let Some(Some((coord, delay, action, layer_stack))) = self.action_queue.pop_front() {
1489            // If there's anything in the action queue, don't process anything else yet - execute
1490            // everything. Otherwise an action may never be released.
1491            let mut custom_activation_count = 0;
1492            return self.do_action(
1493                action,
1494                coord,
1495                delay,
1496                false,
1497                &mut layer_stack.into_iter(),
1498                &mut custom_activation_count,
1499            );
1500        }
1501        self.queue.iter_mut().for_each(Queued::tick_qd);
1502        self.last_press_tracker.tick_lpt();
1503        if let Some(ref mut tde) = self.tap_dance_eager {
1504            tde.tick_tde();
1505            if tde.is_expired() {
1506                self.tap_dance_eager = None;
1507            }
1508        }
1509        self.process_sequences();
1510
1511        self.historical_keys.tick_hist();
1512        self.historical_inputs.tick_hist();
1513        self.historical_inputs_sans_holds_or_timeouts.tick_hist();
1514
1515        let mut custom = CustomEvent::NoEvent;
1516        if let Some(released_keys) = self.oneshot.tick_osh() {
1517            for key in released_keys.iter() {
1518                custom.update(self.dequeue(Queued {
1519                    event: Event::Release(key.0, key.1),
1520                    since: 0,
1521                }));
1522            }
1523        }
1524
1525        custom.update(match &mut self.waiting {
1526            Some(w) => match w.tick_wt(&mut self.queue, &mut self.action_queue) {
1527                Some((WaitingAction::Hold, _)) => self.waiting_into_hold(-1),
1528                Some((WaitingAction::Tap, pq)) => self.waiting_into_tap(pq, -1),
1529                Some((WaitingAction::Timeout, _)) => self.waiting_into_timeout(-1),
1530                Some((WaitingAction::NoOp, _)) => self.drop_waiting(),
1531                None => CustomEvent::NoEvent,
1532            },
1533            None => {
1534                if self.extra_waiting.is_empty() {
1535                    // Due to the possible delay in the key release for EndOnFirstPress
1536                    // because some apps/DEs do not handle it properly if done too quickly,
1537                    // undesirable behaviour of extra presses making it in before
1538                    // the release happens might occur.
1539                    //
1540                    // A mitigation against that is to pause input processing.
1541                    if self.oneshot.pause_input_processing_ticks > 0 {
1542                        self.oneshot.pause_input_processing_ticks =
1543                            self.oneshot.pause_input_processing_ticks.saturating_sub(1);
1544                        CustomEvent::NoEvent
1545                    } else {
1546                        match self.queue.pop_front() {
1547                            Some(s) => self.dequeue(s),
1548                            None => CustomEvent::NoEvent,
1549                        }
1550                    }
1551                } else {
1552                    CustomEvent::NoEvent
1553                }
1554            }
1555        });
1556        let custom = self.process_extra_waitings(custom);
1557        self.process_sequence_custom(custom)
1558    }
1559    /// Takes care of draining and populating the `active_sequences` ArrayDeque,
1560    /// giving us sequences (aka macros) of nearly limitless length!
1561    fn process_sequences(&mut self) {
1562        // Iterate over all active sequence events
1563        for _ in 0..self.active_sequences.len() {
1564            if let Some(mut seq) = self.active_sequences.pop_front() {
1565                // If we've encountered a SequenceEvent::Delay we must count
1566                // that down completely before doing anything else...
1567                if seq.delay > 0 {
1568                    seq.delay = seq.delay.saturating_sub(1);
1569                } else if let Some(keycode) = seq.tapped {
1570                    // Clear out the Press() matching this Tap()'s keycode
1571                    self.states.retain(|s| s.seq_release(keycode).is_some());
1572                    seq.tapped = None;
1573                } else {
1574                    // Pull the next SequenceEvent
1575                    if let [e, tail @ ..] = seq.remaining_events {
1576                        seq.cur_event = Some(*e);
1577                        seq.remaining_events = tail;
1578                    }
1579                    // Process it (SequenceEvent)
1580                    match seq.cur_event {
1581                        Some(SequenceEvent::Complete) => {
1582                            seq.remaining_events = &[];
1583                        }
1584                        Some(SequenceEvent::Press(keycode)) => {
1585                            // Start tracking this fake key Press() event
1586                            let _ = self.states.push(FakeKey { keycode });
1587                            self.contextual_execution
1588                                .push_historical_key(&mut self.historical_keys, keycode);
1589                            // Fine to fake (0, 0). This is sequences anyway. In Kanata, nothing
1590                            // valid should be at (0, 0) that this would interfere with.
1591                            self.oneshot
1592                                .handle_press(OneShotHandlePressKey::Other((0, 0)));
1593                        }
1594                        Some(SequenceEvent::Tap(keycode)) => {
1595                            // Same as Press() except we track it for one tick via seq.tapped:
1596                            let _ = self.states.push(FakeKey { keycode });
1597                            self.contextual_execution
1598                                .push_historical_key(&mut self.historical_keys, keycode);
1599                            self.oneshot
1600                                .handle_press(OneShotHandlePressKey::Other((0, 0)));
1601                            seq.tapped = Some(keycode);
1602                        }
1603                        Some(SequenceEvent::Release(keycode)) => {
1604                            // Nothing valid should be at (0, 0). It's fine to fake this.
1605                            self.oneshot.handle_release((0, 0));
1606                            self.states.retain(|s| s.seq_release(keycode).is_some());
1607                        }
1608                        Some(SequenceEvent::Delay { duration }) if duration > 0 => {
1609                            // Setup a delay that will be decremented once per tick until 0
1610                            // -1 to start since this tick counts
1611                            seq.delay = duration - 1;
1612                        }
1613                        Some(SequenceEvent::Custom(custom)) => {
1614                            let _ = self.states.push(State::SeqCustomPending(custom));
1615                        }
1616                        _ => {} // We'll never get here
1617                    }
1618                }
1619                if !seq.remaining_events.is_empty() {
1620                    // Put it back
1621                    self.active_sequences.push_back(seq);
1622                }
1623            }
1624        }
1625        if self.active_sequences.is_empty() {
1626            // Push only the latest pressed repeating macro.
1627            if let Some(State::RepeatingSequence { sequence, .. }) = self
1628                .states
1629                .iter()
1630                .rev()
1631                .find(|s| matches!(s, State::RepeatingSequence { .. }))
1632            {
1633                self.active_sequences.push_back(SequenceState {
1634                    cur_event: None,
1635                    delay: 0,
1636                    tapped: None,
1637                    remaining_events: sequence,
1638                });
1639            }
1640        }
1641    }
1642
1643    fn process_extra_waitings(&mut self, current_custom: CustomEvent<'a, T>) -> CustomEvent<'a, T> {
1644        if !matches!(current_custom, CustomEvent::NoEvent) {
1645            return current_custom;
1646        }
1647        let mut waiting_action = (0, None);
1648        for (i, w) in self.extra_waiting.iter_mut().enumerate() {
1649            match w.tick_wt(&mut self.queue, &mut self.action_queue) {
1650                None => {}
1651                wa => {
1652                    waiting_action = (i as isize, wa);
1653                    // break - only complete one at a time even if potentially multiple have
1654                    // completed, so that only one custom event is returned.
1655                    //
1656                    // Theoretically if we could call the waiting_into_* functions, we could do that
1657                    // here and break only if custom is None, but that runs into mutability
1658                    // problems. I don't expect any perceptible degradation between from not doing
1659                    // the above.
1660                    break;
1661                }
1662            }
1663        }
1664        let i = waiting_action.0;
1665        match waiting_action.1 {
1666            Some((WaitingAction::Hold, _)) => self.waiting_into_hold(i as i8),
1667            Some((WaitingAction::Tap, pq)) => self.waiting_into_tap(pq, i as i8),
1668            Some((WaitingAction::Timeout, _)) => self.waiting_into_timeout(i as i8),
1669            Some((WaitingAction::NoOp, _)) => self.drop_waiting(),
1670            None => current_custom,
1671        }
1672    }
1673
1674    fn process_sequence_custom(
1675        &mut self,
1676        mut current_custom: CustomEvent<'a, T>,
1677    ) -> CustomEvent<'a, T> {
1678        if self.states.is_empty() || !matches!(current_custom, CustomEvent::NoEvent) {
1679            return current_custom;
1680        }
1681        // It is important to note that this code cannot simply be replaced by `retain_mut`.
1682        // The `retain_mut` function is not chosen
1683        // because it is important to break on the first `SeqCustom` that is discovered.
1684        // Such functionality could be replaced by a marker to ignore processing,
1685        // but for now that is not necessary.
1686        self.states.retain(|s| !matches!(s, State::Tombstone));
1687        for state in self.states.iter_mut() {
1688            match state {
1689                State::SeqCustomPending(custom) => {
1690                    current_custom.update(CustomEvent::Press(custom));
1691                    *state = State::SeqCustomActive(custom);
1692                    break;
1693                }
1694                State::SeqCustomActive(custom) => {
1695                    current_custom.update(CustomEvent::Release(custom));
1696                    *state = State::Tombstone;
1697                    break;
1698                }
1699                _ => continue,
1700            };
1701        }
1702        current_custom
1703    }
1704    fn dequeue(&mut self, queue: Queued) -> CustomEvent<'a, T> {
1705        use Event::*;
1706        match queue.event {
1707            Release(i, j) => {
1708                let mut custom = CustomEvent::NoEvent;
1709                let (do_release, overflow_key) = self.oneshot.handle_release((i, j));
1710                if do_release {
1711                    self.states.retain(|s| {
1712                        !s.clear_on_next_release()
1713                            && s.release((i, j), &mut custom, &mut self.custom_event_release_queue)
1714                                .is_some()
1715                    });
1716                } else {
1717                    // Fix #1874:
1718                    // Might still need to apply release,
1719                    // but need to check against states on same coordinate
1720                    // that aren't part of a OneShot.
1721                    self.states.retain(|s| {
1722                        match s {
1723                            NormalKey { coord, keycode, .. } => {
1724                                // NormalKey is a valid oneshot state,
1725                                // may need to keep.
1726                                *coord != (i, j)
1727                                    || self.oneshot.state_to_retain_on_release.contains(
1728                                        &OneShotRetainableState::KeyCode {
1729                                            coord: *coord,
1730                                            kc: *keycode,
1731                                        },
1732                                    )
1733                            }
1734                            LayerModifier { coord, value } => {
1735                                // LayerModifier is a valid oneshot state,
1736                                // may need to keep.
1737                                *coord != (i, j)
1738                                    || self.oneshot.state_to_retain_on_release.contains(
1739                                        &OneShotRetainableState::Layer {
1740                                            coord: *coord,
1741                                            layer: *value as u16,
1742                                        },
1743                                    )
1744                            }
1745                            // Everything else is not a valid oneshot state,
1746                            // if it falls on the same coordinate
1747                            // as a oneshot key, it should still be released here.
1748                            _ => {
1749                                !s.clear_on_next_release()
1750                                    && s.release(
1751                                        (i, j),
1752                                        &mut custom,
1753                                        &mut self.custom_event_release_queue,
1754                                    )
1755                                    .is_some()
1756                            }
1757                        }
1758                    });
1759                }
1760                if let Some((i2, j2)) = overflow_key {
1761                    self.states.retain(|s| {
1762                        s.release((i2, j2), &mut custom, &mut self.custom_event_release_queue)
1763                            .is_some()
1764                    });
1765                }
1766                custom
1767            }
1768
1769            Press(i, j) => {
1770                let mut layer_stack = self.trans_resolution_layer_order().into_iter();
1771                let mut custom_activation_count = 0;
1772                if let Some(tde) = &mut self.tap_dance_eager {
1773                    if (i, j) == self.last_press_tracker.coord && !tde.is_expired() {
1774                        let tde_action = tde.actions[usize::from(tde.num_taps)];
1775                        tde.incr_taps();
1776                        let custom = self.do_action(
1777                            tde_action,
1778                            (i, j),
1779                            queue.since,
1780                            false,
1781                            &mut layer_stack.skip(1),
1782                            &mut custom_activation_count,
1783                        );
1784                        custom
1785                    } else {
1786                        // i == 0 means real key, i == 1 means fake key. Let fake keys do whatever, but
1787                        // interrupt tap-dance-eager if real key.
1788                        if i == REAL_KEY_ROW {
1789                            tde.set_expired();
1790                        }
1791                        self.do_action(
1792                            &Action::Trans,
1793                            (i, j),
1794                            queue.since,
1795                            false,
1796                            &mut layer_stack,
1797                            &mut custom_activation_count,
1798                        )
1799                    }
1800                } else {
1801                    self.do_action(
1802                        &Action::Trans,
1803                        (i, j),
1804                        queue.since,
1805                        false,
1806                        &mut layer_stack,
1807                        &mut custom_activation_count,
1808                    )
1809                }
1810            }
1811        }
1812    }
1813    /// Register a key event.
1814    pub fn event(&mut self, event: Event) {
1815        if let Event::Press(x, y) = event {
1816            self.historical_inputs.push_front((x, y));
1817            self.historical_inputs_sans_holds_or_timeouts
1818                .push_front((x, y));
1819        }
1820        if let Some(overflow) = if let Some(ch) = self.chords_v2.as_mut() {
1821            ch.push_back_chv2(event.into())
1822        } else {
1823            self.queue.push_back(event.into())
1824        } {
1825            for i in -1..(EXTRA_WAITING_LEN as i8) {
1826                self.waiting_into_hold(i);
1827            }
1828            self.dequeue(overflow);
1829        }
1830    }
1831
1832    /// Put a key event at the front instead of back.
1833    /// These events will not participate in chordsv2.
1834    pub fn event_to_front(&mut self, event: Event) {
1835        if let Event::Press(x, y) = event {
1836            self.historical_inputs.push_front((x, y));
1837            self.historical_inputs_sans_holds_or_timeouts
1838                .push_front((x, y));
1839        }
1840        if let Some(overflow) = self.queue.push_front(event.into()) {
1841            for i in -1..(EXTRA_WAITING_LEN as i8) {
1842                self.waiting_into_hold(i);
1843            }
1844            self.dequeue(overflow);
1845        }
1846    }
1847
1848    /// Resolve coordinate to first non-Trans actions.
1849    /// Trans on base layer, resolves to key from defsrc.
1850    fn resolve_coord(
1851        &self,
1852        coord: KCoord,
1853        layer_stack: &mut (impl Iterator<Item = u16> + Clone),
1854    ) -> &'a Action<'a, T> {
1855        use crate::action::Action::*;
1856        let x = coord.0 as usize;
1857        let y = coord.1 as usize;
1858        assert!(x <= self.layers[0].len());
1859        assert!(y <= self.layers[0][0].len());
1860        for layer in layer_stack {
1861            assert!(usize::from(layer) <= self.layers.len());
1862            let action = &self.layers[usize::from(layer)][x][y];
1863            match action {
1864                Trans => continue,
1865                action => return action,
1866            }
1867        }
1868        if x == 0 { &self.src_keys[y] } else { &NoOp }
1869    }
1870    fn do_action(
1871        &mut self,
1872        action: &'a Action<'a, T>,
1873        coord: KCoord,
1874        delay: u16,
1875        is_oneshot: bool,
1876        layer_stack: &mut (impl Iterator<Item = u16> + Clone), // used to resolve Trans action
1877        custom_activation_count: &mut u8,
1878    ) -> CustomEvent<'a, T> {
1879        let mut action = action;
1880        if let Trans = action {
1881            action = self.resolve_coord(coord, layer_stack);
1882        }
1883        let action = action;
1884
1885        if self.last_press_tracker.coord != coord && coord.0 == REAL_KEY_ROW {
1886            self.last_press_tracker.tap_hold_timeout = 0;
1887        }
1888        use Action::*;
1889        self.states.retain(|s| match s {
1890            // Need to solve a problem here - if the output chord `S-=` is active, and then a
1891            // different keypress `=` happens, the `lsft =` states are cleared; but the `=`
1892            // is immediately re-added again. This means the release is never observed..
1893            //
1894            // Bug introduced:
1895            //
1896            // If doing something like typing parentheses using output chords,
1897            // e.g. S-9 followed by S-0,
1898            // the trivial fix will suppress the shift key for a bit
1899            // but the `0` still gets output,
1900            // resulting in an unshifted `0` which is incorrect.
1901            //
1902            // Fix added:
1903            //
1904            // Do not apply the suppression to modifiers.
1905            // Modifiers typically don't have a usage pattern similar to
1906            // the real use case of `S-=` followed by `=` example,
1907            // such as `S-=` followed by only `lsft`,
1908            // with a desire for the lone `lsft` to actually activate something.
1909            NormalKey { flags, keycode, .. } => match flags.nkf_clear_on_next_action() {
1910                true => {
1911                    self.oneshot.pause_input_processing_ticks += 2;
1912                    if !keycode.is_mod() {
1913                        let _ = self.keys_to_suppress_for_one_cycle.push(*keycode);
1914                    }
1915                    false
1916                }
1917                false => true,
1918            },
1919            _ => true,
1920        });
1921        match action {
1922            NoOp => {
1923                // There is an interaction between oneshot and chordsv2 here.
1924                // chordsv2 sends fake queued press/release events at the coordinate level in order
1925                // to trigger other "waiting" style actions, namely tap-hold. However, these can
1926                // potentially interfere with oneshot by triggering early oneshot activation. This
1927                // is resolved by ignoring actions at the coordinate at which the fake events are
1928                // sent.
1929                if !is_oneshot && coord != TRIGGER_TAPHOLD_COORD {
1930                    self.oneshot
1931                        .handle_press(OneShotHandlePressKey::Other(coord));
1932                }
1933                self.rpt_action = Some(action);
1934                let _ = self.states.push(NoOpInput { coord });
1935            }
1936            Src => {
1937                let action = &self.src_keys[usize::from(coord.1)];
1938                // Risk: infinite recursive resulting in stack overflow.
1939                // In practice this is not expected to happen.
1940                // The `src_keys` actions are all expected to be `KeyCode` or `NoOp` actions.
1941                self.do_action(
1942                    action,
1943                    coord,
1944                    delay,
1945                    is_oneshot,
1946                    &mut std::iter::empty(),
1947                    custom_activation_count,
1948                );
1949            }
1950            Trans => {
1951                // Transparent action should be resolved to non-transparent one near the top
1952                // of `do_action`.
1953                unreachable!("Trans action should have been resolved earlier")
1954            }
1955            Repeat => {
1956                // Notes around repeat:
1957                //
1958                // Though this action seems conceptually simple, in reality there are a lot of
1959                // decisions to be made around how exactly actions repeat. For example: in a
1960                // tap-dance action, would one expect the tap-dance to be repeated or the inner
1961                // action that was most activated within the tap-dance?
1962                //
1963                // Currently the answer to these questions is: what is easy/possible to do?
1964                // It is not consistent whether it is the outer or inner action.
1965                // The actions tap-dance and tap-hold will repeat the inner action and
1966                // not the outer (tap-dance|hold),
1967                // but multi will repeat the entire outer multi action.
1968                if let Some(ac) = self.rpt_action {
1969                    self.do_action(
1970                        ac,
1971                        coord,
1972                        delay,
1973                        is_oneshot,
1974                        &mut std::iter::empty(),
1975                        custom_activation_count,
1976                    );
1977                }
1978            }
1979            HoldTap(HoldTapAction {
1980                timeout,
1981                hold,
1982                tap,
1983                timeout_action,
1984                config,
1985                tap_hold_interval,
1986                on_press_reset_timeout_to,
1987                require_prior_idle,
1988            }) => {
1989                // Typing streak detection: if a different physical key was pressed
1990                // recently, resolve as tap immediately without entering WaitingState.
1991                // Per-action override takes precedence over the global defcfg value.
1992                let idle_threshold = require_prior_idle.unwrap_or(self.tap_hold_require_prior_idle);
1993                if idle_threshold > 0 {
1994                    let prior_idle_tap = self
1995                        .historical_inputs_sans_holds_or_timeouts
1996                        .iter_hevents()
1997                        .find(|prior| {
1998                            prior.event.0 == REAL_KEY_ROW
1999                              // Disregard this same press event
2000                              && prior.event != coord
2001                              // Disregard any presses that are actually still in the queue and
2002                              // unresolved.
2003                              && !self.queue.iter().any(|q| {
2004                                  // Events drained out of the chordsv2 queue are ticked
2005                                  // by both tick_chv2 and the layout queue tick on the drain cycle,
2006                                  // so a queued event's `since` can run ahead of its history entry's
2007                                  // age.
2008                                  //
2009                                  // It is possibly troublesome to fix that issue so give some leeway
2010                                  // in the comparison.
2011                                  q.since.abs_diff(prior.ticks_since_occurrence) <= 2
2012                                  && match q.event {
2013                                      Event::Press(0, j) => j == prior.event.1,
2014                                      _ => false
2015                                  }
2016                              })
2017                        })
2018                        .is_some_and(|prior| prior.ticks_since_occurrence <= idle_threshold);
2019                    if prior_idle_tap {
2020                        let custom = self.do_action(
2021                            tap,
2022                            coord,
2023                            delay,
2024                            is_oneshot,
2025                            layer_stack,
2026                            custom_activation_count,
2027                        );
2028                        self.last_press_tracker.update_coord(coord);
2029                        return custom;
2030                    }
2031                }
2032                let mut custom = CustomEvent::NoEvent;
2033                if *tap_hold_interval == 0
2034                    || coord != self.last_press_tracker.coord
2035                    || self.last_press_tracker.tap_hold_timeout == 0
2036                {
2037                    let ticks = match self.quick_tap_hold_timeout {
2038                        // Leave 1 tick to timeout as it will be consumed in the next processing cycle
2039                        true => delay.min(timeout.saturating_sub(1)),
2040                        false => 0,
2041                    };
2042                    let waiting: WaitingState<T> = WaitingState {
2043                        coord,
2044                        timeout: timeout.saturating_sub(ticks),
2045                        delay: delay.saturating_sub(ticks),
2046                        ticks,
2047                        on_press_reset_timeout_to: *on_press_reset_timeout_to,
2048                        hold,
2049                        tap,
2050                        timeout_action,
2051                        config: WaitingConfig::HoldTap(*config),
2052                        layer_stack: layer_stack.collect(),
2053                        prev_queue_len: QueueLen::MAX,
2054                    };
2055                    if self.waiting.is_some() {
2056                        self.extra_waiting.push_back(waiting);
2057                    } else {
2058                        self.waiting = Some(waiting);
2059                    }
2060                    self.last_press_tracker.tap_hold_timeout = *tap_hold_interval;
2061                } else {
2062                    self.last_press_tracker.tap_hold_timeout = 0;
2063                    custom.update(self.do_action(
2064                        tap,
2065                        coord,
2066                        delay,
2067                        is_oneshot,
2068                        layer_stack,
2069                        custom_activation_count,
2070                    ));
2071                }
2072                // Need to set tap_hold_tracker coord AFTER the checks.
2073                self.last_press_tracker.update_coord(coord);
2074                return custom;
2075            }
2076            &OneShot(oneshot) => {
2077                self.last_press_tracker.update_coord(coord);
2078                let custom = self.do_action(
2079                    oneshot.action,
2080                    coord,
2081                    delay,
2082                    true,
2083                    &mut std::iter::empty(),
2084                    custom_activation_count,
2085                );
2086                // Note - set rpt_action after doing the inner oneshot action. This means that the
2087                // whole oneshot will be repeated by rpt-any rather than only the inner action.
2088                self.rpt_action = Some(action);
2089                self.oneshot
2090                    .handle_press(OneShotHandlePressKey::OneShotKey(coord));
2091                self.oneshot.timeout = oneshot.timeout;
2092                self.oneshot.end_config = oneshot.end_config;
2093                if let Some(overflow) = self.oneshot.keys.push_back((coord.0, coord.1)) {
2094                    self.event(Event::Release(overflow.0, overflow.1));
2095                }
2096                return custom;
2097            }
2098            &OneShotIgnoreEventsTicks(ticks) => {
2099                self.last_press_tracker.update_coord(coord);
2100                self.rpt_action = Some(action);
2101                self.oneshot.ticks_to_ignore_events = ticks;
2102            }
2103            &TapDance(td) => {
2104                self.last_press_tracker.update_coord(coord);
2105                match td.config {
2106                    TapDanceConfig::Lazy => {
2107                        self.waiting = Some(WaitingState {
2108                            coord,
2109                            timeout: td.timeout,
2110                            delay,
2111                            ticks: 0,
2112                            hold: &Action::NoOp,
2113                            tap: &Action::NoOp,
2114                            timeout_action: &Action::NoOp,
2115                            on_press_reset_timeout_to: None,
2116                            config: WaitingConfig::TapDance(TapDanceState {
2117                                actions: td.actions,
2118                                timeout: td.timeout,
2119                                num_taps: 1,
2120                            }),
2121                            layer_stack: layer_stack.collect(),
2122                            prev_queue_len: QueueLen::MAX,
2123                        });
2124                    }
2125                    TapDanceConfig::Eager => {
2126                        match self.tap_dance_eager {
2127                            None => {
2128                                self.tap_dance_eager = Some(TapDanceEagerState {
2129                                    coord,
2130                                    actions: td.actions,
2131                                    timeout: td.timeout,
2132                                    orig_timeout: td.timeout,
2133                                    num_taps: 1,
2134                                })
2135                            }
2136                            Some(tde) => {
2137                                if tde.coord != coord {
2138                                    self.tap_dance_eager = Some(TapDanceEagerState {
2139                                        coord,
2140                                        actions: td.actions,
2141                                        timeout: td.timeout,
2142                                        orig_timeout: td.timeout,
2143                                        num_taps: 1,
2144                                    });
2145                                }
2146                            }
2147                        };
2148                        return self.do_action(
2149                            td.actions[0],
2150                            coord,
2151                            delay,
2152                            false,
2153                            layer_stack,
2154                            custom_activation_count,
2155                        );
2156                    }
2157                }
2158            }
2159            &Chords(chords) => {
2160                self.last_press_tracker.update_coord(coord);
2161                self.waiting = Some(WaitingState {
2162                    coord,
2163                    timeout: chords.timeout,
2164                    delay,
2165                    ticks: 0,
2166                    hold: &Action::NoOp,
2167                    tap: &Action::NoOp,
2168                    timeout_action: &Action::NoOp,
2169                    on_press_reset_timeout_to: None,
2170                    config: WaitingConfig::Chord(chords),
2171                    layer_stack: layer_stack.collect(),
2172                    prev_queue_len: QueueLen::MAX,
2173                });
2174            }
2175            &KeyCode(keycode) => {
2176                self.last_press_tracker.update_coord(coord);
2177                // Most-recent-first!
2178                self.contextual_execution
2179                    .push_historical_key(&mut self.historical_keys, keycode);
2180                let _ = self.states.push(NormalKey {
2181                    coord,
2182                    keycode,
2183                    flags: NormalKeyFlags(0),
2184                });
2185                let mut oneshot_coords = ArrayDeque::new();
2186                if !is_oneshot {
2187                    oneshot_coords = self
2188                        .oneshot
2189                        .handle_press(OneShotHandlePressKey::Other(coord));
2190                } else {
2191                    self.oneshot
2192                        .add_state_to_retain(OneShotRetainableState::KeyCode {
2193                            coord,
2194                            kc: keycode,
2195                        });
2196                }
2197                if oneshot_coords.is_empty() {
2198                    self.rpt_action = Some(action);
2199                } else {
2200                    self.rpt_action = None;
2201                    unsafe {
2202                        self.rpt_multikey_key_buffer.clear();
2203                        for kc in self
2204                            .states
2205                            .iter()
2206                            .filter_map(|kc| State::keycode_in_coords(kc, &oneshot_coords))
2207                        {
2208                            self.rpt_multikey_key_buffer.push(kc);
2209                        }
2210                        self.rpt_multikey_key_buffer.push(keycode);
2211                        self.rpt_action = Some(self.rpt_multikey_key_buffer.get_ref());
2212                    }
2213                }
2214            }
2215            &MultipleKeyCodes(v) => {
2216                self.last_press_tracker.update_coord(coord);
2217                for &keycode in *v {
2218                    // BUG:
2219                    // In the original implementation, activating an action sequence such as b ->
2220                    // S-b will not type a separate instance of "B" because b is already held and
2221                    // wont be re-sent by the outer processing loop.
2222                    //
2223                    // FIX:
2224                    // If `keycode` is not a mod, suppress it for a cycle if it exists in the
2225                    // status. This is not expected to have any negative perceptible effects.
2226                    if !keycode.is_mod() && self.keycodes().any(|kc| kc == keycode) {
2227                        let _ = self.keys_to_suppress_for_one_cycle.push(keycode);
2228                    }
2229                    self.contextual_execution
2230                        .push_historical_key(&mut self.historical_keys, keycode);
2231                    let _ = self.states.push(NormalKey {
2232                        coord,
2233                        keycode,
2234                        // In Kanata, this action is only ever used with output chords. Output
2235                        // chords within a one-shot are ignored because someone might do something
2236                        // like (one-shot C-S-lalt to get 3 modifiers. These are probably intended
2237                        // to remain held. However, other output chords are usually used to type
2238                        // symbols or accented characters, e.g. S-1 or RA-a. Clearing chord keys on
2239                        // the next action allows a subsequent typed key to not have modifiers
2240                        // alongside it. But if the symbol or accented character is held down, key
2241                        // repeat works just fine.
2242                        flags: NormalKeyFlags(if is_oneshot {
2243                            0
2244                        } else {
2245                            NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION
2246                        }),
2247                    });
2248                }
2249
2250                let mut oneshot_coords = ArrayDeque::new();
2251                if !is_oneshot {
2252                    oneshot_coords = self
2253                        .oneshot
2254                        .handle_press(OneShotHandlePressKey::Other(coord));
2255                } else {
2256                    for &keycode in *v {
2257                        self.oneshot
2258                            .add_state_to_retain(OneShotRetainableState::KeyCode {
2259                                coord,
2260                                kc: keycode,
2261                            });
2262                    }
2263                }
2264                if oneshot_coords.is_empty() {
2265                    self.rpt_action = Some(action);
2266                } else {
2267                    self.rpt_action = None;
2268                    unsafe {
2269                        self.rpt_multikey_key_buffer.clear();
2270                        for kc in self
2271                            .states
2272                            .iter()
2273                            .filter_map(|s| s.keycode_in_coords(&oneshot_coords))
2274                        {
2275                            self.rpt_multikey_key_buffer.push(kc);
2276                        }
2277                        for &keycode in *v {
2278                            self.rpt_multikey_key_buffer.push(keycode);
2279                        }
2280                        self.rpt_action = Some(self.rpt_multikey_key_buffer.get_ref());
2281                    }
2282                }
2283            }
2284            &MultipleActions(v) => {
2285                self.last_press_tracker.update_coord(coord);
2286                let mut custom = CustomEvent::NoEvent;
2287                for action in *v {
2288                    custom.update(self.do_action(
2289                        action,
2290                        coord,
2291                        delay,
2292                        is_oneshot,
2293                        &mut layer_stack.clone(),
2294                        custom_activation_count,
2295                    ));
2296                }
2297                // Save the whole multi action instead of the final action in multi so that Repeat
2298                // repeats all of the actions in this multi.
2299                self.rpt_action = Some(action);
2300                return custom;
2301            }
2302            Sequence { events } => {
2303                self.active_sequences.push_back(SequenceState {
2304                    cur_event: None,
2305                    delay: 0,
2306                    tapped: None,
2307                    remaining_events: events,
2308                });
2309                if !is_oneshot {
2310                    self.oneshot
2311                        .handle_press(OneShotHandlePressKey::Other(coord));
2312                }
2313                self.rpt_action = Some(action);
2314            }
2315            RepeatableSequence { events } => {
2316                self.active_sequences.push_back(SequenceState {
2317                    cur_event: None,
2318                    delay: 0,
2319                    tapped: None,
2320                    remaining_events: events,
2321                });
2322                let _ = self.states.push(RepeatingSequence {
2323                    sequence: events,
2324                    coord,
2325                });
2326                if !is_oneshot {
2327                    self.oneshot
2328                        .handle_press(OneShotHandlePressKey::Other(coord));
2329                }
2330                self.rpt_action = Some(action);
2331            }
2332            CancelSequences => {
2333                // Clear any and all running sequences then clean up any leftover FakeKey events
2334                self.active_sequences.clear();
2335                for fake_key in self.states.clone().iter() {
2336                    if let FakeKey { keycode } = *fake_key {
2337                        self.states.retain(|s| s.seq_release(keycode).is_some());
2338                    }
2339                }
2340                if !is_oneshot {
2341                    self.oneshot
2342                        .handle_press(OneShotHandlePressKey::Other(coord));
2343                }
2344                self.rpt_action = Some(action);
2345            }
2346            &Layer(value) => {
2347                self.last_press_tracker.update_coord(coord);
2348                let _ = self.states.push(LayerModifier { value, coord });
2349                if !is_oneshot {
2350                    self.oneshot
2351                        .handle_press(OneShotHandlePressKey::Other(coord));
2352                } else {
2353                    self.oneshot
2354                        .add_state_to_retain(OneShotRetainableState::Layer {
2355                            coord,
2356                            layer: value as u16,
2357                        });
2358                }
2359                // Notably missing in Layer and below in DefaultLayer is setting rpt_action. This
2360                // is so that if the Repeat key is on a different layer than the base, it can still
2361                // be used to repeat the previous non-layer-changing action.
2362            }
2363            DefaultLayer(value) => {
2364                self.last_press_tracker.update_coord(coord);
2365                self.set_default_layer(*value);
2366                if !is_oneshot {
2367                    self.oneshot
2368                        .handle_press(OneShotHandlePressKey::Other(coord));
2369                }
2370            }
2371            Custom(value) => {
2372                self.last_press_tracker.update_coord(coord);
2373                if !is_oneshot {
2374                    self.oneshot
2375                        .handle_press(OneShotHandlePressKey::Other(coord));
2376                }
2377                *custom_activation_count = custom_activation_count.saturating_add(1);
2378                self.rpt_action = Some(action);
2379                return match custom_activation_count {
2380                    0 | 1 => {
2381                        let _ = self.states.push(State::Custom { value, coord });
2382                        CustomEvent::Press(value)
2383                    }
2384                    _ => {
2385                        self.action_queue.push_back(Some((
2386                            coord,
2387                            delay,
2388                            action,
2389                            layer_stack.clone().collect(),
2390                        )));
2391                        CustomEvent::NoEvent
2392                    }
2393                };
2394            }
2395            ReleaseState(rs) => {
2396                self.states.retain(|s| s.release_state(*rs).is_some());
2397                if !is_oneshot {
2398                    self.oneshot
2399                        .handle_press(OneShotHandlePressKey::Other(coord));
2400                }
2401                self.rpt_action = Some(action);
2402            }
2403            Fork(fcfg) => {
2404                let ret = match self.states.iter().any(|s| match s {
2405                    NormalKey { keycode, .. } | FakeKey { keycode } => {
2406                        fcfg.right_triggers.contains(keycode)
2407                    }
2408                    _ => false,
2409                }) {
2410                    false => self.do_action(
2411                        &fcfg.left,
2412                        coord,
2413                        delay,
2414                        false,
2415                        &mut layer_stack.clone(),
2416                        custom_activation_count,
2417                    ),
2418                    true => self.do_action(
2419                        &fcfg.right,
2420                        coord,
2421                        delay,
2422                        false,
2423                        &mut layer_stack.clone(),
2424                        custom_activation_count,
2425                    ),
2426                };
2427                // Repeat the fork rather than the terminal action.
2428                self.rpt_action = Some(action);
2429                return ret;
2430            }
2431            Switch(sw) => {
2432                let active_keys = self.states.iter().filter_map(State::keycode);
2433                let active_coords = self.states.iter().filter_map(State::coord);
2434                let historical_keys = self.historical_keys.iter_hevents();
2435                let historical_coords = self.historical_inputs.iter_hevents();
2436                let layers = self.trans_resolution_layer_order().into_iter();
2437                let mut action_queue: ActionQueue<T> = Default::default();
2438                if let Some(f) = sw.init_fn {
2439                    f();
2440                }
2441                for ac in sw.actions(
2442                    active_keys,
2443                    active_coords,
2444                    historical_keys,
2445                    historical_coords,
2446                    layers,
2447                    // Note on truncating cast: I expect default layer to be in range by other
2448                    // assertions.
2449                    self.default_layer as u16,
2450                    self.device_history.iter().copied(),
2451                ) {
2452                    action_queue.push_back(Some((coord, delay, ac, layer_stack.clone().collect())));
2453                }
2454
2455                let mut custom = CustomEvent::NoEvent;
2456                while let Some(Some((coord, delay, action, layer_stack))) = action_queue.pop_front()
2457                {
2458                    custom.update(self.do_action(
2459                        action,
2460                        coord,
2461                        delay,
2462                        is_oneshot,
2463                        &mut layer_stack.into_iter(),
2464                        custom_activation_count,
2465                    ));
2466                }
2467
2468                self.rpt_action = Some(action);
2469                return custom;
2470            }
2471        }
2472        CustomEvent::NoEvent
2473    }
2474
2475    /// Obtain the index of the current active layer
2476    pub fn current_layer(&self) -> usize {
2477        self.states
2478            .iter()
2479            .rev()
2480            .find_map(State::get_layer)
2481            .unwrap_or(self.default_layer)
2482    }
2483
2484    pub fn active_held_layers(&self) -> impl Iterator<Item = u16> + Clone + '_ {
2485        self.states
2486            .iter()
2487            .filter_map(|s| State::get_layer(s).map(|l| l as u16))
2488            .rev()
2489    }
2490
2491    /// Returns a list indices of layers that should be used for [`Action::Trans`] resolution.
2492    pub fn trans_resolution_layer_order(&self) -> LayerStack {
2493        let current_layer = self.current_layer();
2494        if self.trans_resolution_behavior_v2 {
2495            let mut v = self.active_held_layers().collect::<LayerStack>();
2496            let _ = v.push(self.default_layer as u16);
2497            if self.delegate_to_first_layer && current_layer != 0 && self.default_layer != 0 {
2498                let _ = v.push(0);
2499            }
2500            v
2501        } else {
2502            let mut v = Vec::new();
2503            let _ = v.push(current_layer as u16);
2504            if self.delegate_to_first_layer && current_layer != 0 {
2505                let _ = v.push(0);
2506            }
2507            v
2508        }
2509    }
2510
2511    /// Sets the default layer for the layout
2512    pub fn set_default_layer(&mut self, value: usize) {
2513        if value < self.layers.len() {
2514            self.default_layer = value
2515        }
2516    }
2517}
2518
2519#[cfg(test)]
2520mod test {
2521    extern crate std;
2522    use super::{Event::*, Layout, *};
2523    use crate::action::Action::*;
2524    use crate::action::HoldTapConfig;
2525    use crate::action::{k, l};
2526    use crate::key_code::KeyCode;
2527    use crate::key_code::KeyCode::*;
2528    use std::collections::BTreeSet;
2529
2530    #[track_caller]
2531    fn assert_keys(expected: &[KeyCode], iter: impl Iterator<Item = KeyCode>) {
2532        let expected: BTreeSet<_> = expected.iter().copied().collect();
2533        let tested = iter.collect();
2534        assert_eq!(expected, tested);
2535    }
2536
2537    #[test]
2538    fn basic_hold_tap() {
2539        static LAYERS: Layers<2, 1> = &[
2540            [[
2541                HoldTap(&HoldTapAction {
2542                    on_press_reset_timeout_to: None,
2543                    require_prior_idle: None,
2544                    timeout: 200,
2545                    hold: l(1),
2546                    tap: k(Space),
2547                    timeout_action: k(RShift),
2548                    config: HoldTapConfig::Default,
2549                    tap_hold_interval: 0,
2550                }),
2551                HoldTap(&HoldTapAction {
2552                    on_press_reset_timeout_to: None,
2553                    require_prior_idle: None,
2554                    timeout: 200,
2555                    hold: k(LCtrl),
2556                    timeout_action: k(LShift),
2557                    tap: k(Enter),
2558                    config: HoldTapConfig::Default,
2559                    tap_hold_interval: 0,
2560                }),
2561            ]],
2562            [[Trans, MultipleKeyCodes(&[LCtrl, Enter].as_slice())]],
2563        ];
2564        let mut layout = Layout::new(LAYERS);
2565        assert_eq!(CustomEvent::NoEvent, layout.tick());
2566        assert_keys(&[], layout.keycodes());
2567        layout.event(Press(0, 1));
2568        assert_eq!(CustomEvent::NoEvent, layout.tick());
2569        assert_keys(&[], layout.keycodes());
2570        layout.event(Press(0, 0));
2571        assert_eq!(CustomEvent::NoEvent, layout.tick());
2572        assert_keys(&[], layout.keycodes());
2573        layout.event(Release(0, 0));
2574        for _ in 0..197 {
2575            assert_eq!(CustomEvent::NoEvent, layout.tick());
2576            assert_keys(&[], layout.keycodes());
2577        }
2578        assert_eq!(CustomEvent::NoEvent, layout.tick());
2579        assert_keys(&[], layout.keycodes());
2580        assert_eq!(CustomEvent::NoEvent, layout.tick());
2581        assert_keys(&[LShift], layout.keycodes());
2582        assert_eq!(CustomEvent::NoEvent, layout.tick());
2583        assert_keys(&[LShift], layout.keycodes());
2584        assert_eq!(CustomEvent::NoEvent, layout.tick());
2585        assert_keys(&[LShift, Space], layout.keycodes());
2586        assert_eq!(CustomEvent::NoEvent, layout.tick());
2587        assert_keys(&[LShift], layout.keycodes());
2588        layout.event(Release(0, 1));
2589        assert_eq!(CustomEvent::NoEvent, layout.tick());
2590        assert_keys(&[], layout.keycodes());
2591    }
2592
2593    #[test]
2594    fn basic_hold_tap_repress_timeout() {
2595        static LAYERS: Layers<2, 1> = &[
2596            [[
2597                HoldTap(&HoldTapAction {
2598                    on_press_reset_timeout_to: None,
2599                    require_prior_idle: None,
2600                    timeout: 200,
2601                    hold: l(1),
2602                    tap: k(Space),
2603                    timeout_action: l(1),
2604                    config: HoldTapConfig::Default,
2605                    tap_hold_interval: 0,
2606                }),
2607                HoldTap(&HoldTapAction {
2608                    on_press_reset_timeout_to: None,
2609                    require_prior_idle: None,
2610                    timeout: 200,
2611                    hold: k(LCtrl),
2612                    timeout_action: k(LCtrl),
2613                    tap: k(Enter),
2614                    config: HoldTapConfig::Default,
2615                    tap_hold_interval: 0,
2616                }),
2617            ]],
2618            [[Trans, MultipleKeyCodes(&[LCtrl, Enter].as_slice())]],
2619        ];
2620        let mut layout = Layout::new(LAYERS);
2621        assert_eq!(CustomEvent::NoEvent, layout.tick());
2622        assert_keys(&[], layout.keycodes());
2623        layout.event(Press(0, 1));
2624        assert_eq!(CustomEvent::NoEvent, layout.tick());
2625        assert_keys(&[], layout.keycodes());
2626        layout.event(Press(0, 0));
2627        assert_eq!(CustomEvent::NoEvent, layout.tick());
2628        assert_keys(&[], layout.keycodes());
2629        layout.event(Release(0, 0));
2630        for _ in 0..197 {
2631            assert_eq!(CustomEvent::NoEvent, layout.tick());
2632            assert_keys(&[], layout.keycodes());
2633        }
2634        assert_eq!(CustomEvent::NoEvent, layout.tick());
2635        assert_keys(&[], layout.keycodes());
2636        assert_eq!(CustomEvent::NoEvent, layout.tick());
2637        assert_keys(&[LCtrl], layout.keycodes());
2638        assert_eq!(CustomEvent::NoEvent, layout.tick());
2639        assert_keys(&[LCtrl], layout.keycodes());
2640        assert_eq!(CustomEvent::NoEvent, layout.tick());
2641        assert_keys(&[LCtrl, Space], layout.keycodes());
2642        assert_eq!(CustomEvent::NoEvent, layout.tick());
2643        assert_keys(&[LCtrl], layout.keycodes());
2644        layout.event(Release(0, 1));
2645        assert_eq!(CustomEvent::NoEvent, layout.tick());
2646        assert_keys(&[], layout.keycodes());
2647    }
2648
2649    #[test]
2650    fn hold_tap_interleaved_timeout() {
2651        static LAYERS: Layers<2, 1> = &[[[
2652            HoldTap(&HoldTapAction {
2653                on_press_reset_timeout_to: None,
2654                require_prior_idle: None,
2655                timeout: 200,
2656                hold: k(LAlt),
2657                timeout_action: k(LAlt),
2658                tap: k(Space),
2659                config: HoldTapConfig::Default,
2660                tap_hold_interval: 0,
2661            }),
2662            HoldTap(&HoldTapAction {
2663                on_press_reset_timeout_to: None,
2664                require_prior_idle: None,
2665                timeout: 20,
2666                hold: k(LCtrl),
2667                timeout_action: k(LCtrl),
2668                tap: k(Enter),
2669                config: HoldTapConfig::Default,
2670                tap_hold_interval: 0,
2671            }),
2672        ]]];
2673        let mut layout = Layout::new(LAYERS);
2674        assert_eq!(CustomEvent::NoEvent, layout.tick());
2675        assert_keys(&[], layout.keycodes());
2676        layout.event(Press(0, 0));
2677        assert_eq!(CustomEvent::NoEvent, layout.tick());
2678        assert_keys(&[], layout.keycodes());
2679        layout.event(Press(0, 1));
2680        for _ in 0..15 {
2681            assert_eq!(CustomEvent::NoEvent, layout.tick());
2682            assert_keys(&[], layout.keycodes());
2683        }
2684        layout.event(Release(0, 0));
2685        assert_eq!(CustomEvent::NoEvent, layout.tick());
2686        assert_keys(&[Space], layout.keycodes());
2687        for _ in 0..10 {
2688            assert_eq!(CustomEvent::NoEvent, layout.tick());
2689            assert_keys(&[Space], layout.keycodes());
2690        }
2691        layout.event(Release(0, 1));
2692        assert_eq!(CustomEvent::NoEvent, layout.tick());
2693        assert_keys(&[Space, LCtrl], layout.keycodes());
2694        assert_eq!(CustomEvent::NoEvent, layout.tick());
2695        assert_keys(&[LCtrl], layout.keycodes());
2696        assert_eq!(CustomEvent::NoEvent, layout.tick());
2697        assert_keys(&[], layout.keycodes());
2698        assert_eq!(CustomEvent::NoEvent, layout.tick());
2699        assert_keys(&[], layout.keycodes());
2700    }
2701
2702    #[test]
2703    fn hold_on_press() {
2704        static LAYERS: Layers<2, 1> = &[[[
2705            HoldTap(&HoldTapAction {
2706                on_press_reset_timeout_to: None,
2707                require_prior_idle: None,
2708                timeout: 200,
2709                hold: k(LAlt),
2710                timeout_action: k(LAlt),
2711                tap: k(Space),
2712                config: HoldTapConfig::HoldOnOtherKeyPress,
2713                tap_hold_interval: 0,
2714            }),
2715            k(Enter),
2716        ]]];
2717        let mut layout = Layout::new(LAYERS);
2718
2719        // Press another key before timeout
2720        assert_eq!(CustomEvent::NoEvent, layout.tick());
2721        assert_keys(&[], layout.keycodes());
2722        layout.event(Press(0, 0));
2723        assert_eq!(CustomEvent::NoEvent, layout.tick());
2724        assert_keys(&[], layout.keycodes());
2725        layout.event(Press(0, 1));
2726        assert_eq!(CustomEvent::NoEvent, layout.tick());
2727        assert_keys(&[LAlt], layout.keycodes());
2728        assert_eq!(CustomEvent::NoEvent, layout.tick());
2729        assert_keys(&[LAlt, Enter], layout.keycodes());
2730        layout.event(Release(0, 0));
2731        assert_eq!(CustomEvent::NoEvent, layout.tick());
2732        assert_keys(&[Enter], layout.keycodes());
2733        layout.event(Release(0, 1));
2734        assert_eq!(CustomEvent::NoEvent, layout.tick());
2735        assert_keys(&[], layout.keycodes());
2736        assert_eq!(CustomEvent::NoEvent, layout.tick());
2737        assert_keys(&[], layout.keycodes());
2738
2739        // Press another key after timeout
2740        assert_eq!(CustomEvent::NoEvent, layout.tick());
2741        assert_keys(&[], layout.keycodes());
2742        layout.event(Press(0, 0));
2743        for _ in 0..200 {
2744            assert_eq!(CustomEvent::NoEvent, layout.tick());
2745            assert_keys(&[], layout.keycodes());
2746        }
2747        assert_eq!(CustomEvent::NoEvent, layout.tick());
2748        assert_keys(&[LAlt], layout.keycodes());
2749        layout.event(Press(0, 1));
2750        assert_eq!(CustomEvent::NoEvent, layout.tick());
2751        assert_keys(&[LAlt, Enter], layout.keycodes());
2752        layout.event(Release(0, 0));
2753        assert_eq!(CustomEvent::NoEvent, layout.tick());
2754        assert_keys(&[Enter], layout.keycodes());
2755        layout.event(Release(0, 1));
2756        assert_eq!(CustomEvent::NoEvent, layout.tick());
2757        assert_keys(&[], layout.keycodes());
2758        assert_eq!(CustomEvent::NoEvent, layout.tick());
2759        assert_keys(&[], layout.keycodes());
2760    }
2761
2762    #[test]
2763    fn order_clean_tap() {
2764        // Press and release modifier with no other keys → Tap.
2765        static LAYERS: Layers<2, 1> = &[[[
2766            HoldTap(&HoldTapAction {
2767                on_press_reset_timeout_to: None,
2768                timeout: u16::MAX,
2769                hold: k(LAlt),
2770                timeout_action: k(Space),
2771                tap: k(Space),
2772                config: HoldTapConfig::Order { buffer: 0 },
2773                tap_hold_interval: 0,
2774                require_prior_idle: None,
2775            }),
2776            k(Enter),
2777        ]]];
2778        let mut layout = Layout::new(LAYERS);
2779
2780        layout.event(Press(0, 0));
2781        assert_eq!(CustomEvent::NoEvent, layout.tick());
2782        assert_keys(&[], layout.keycodes());
2783        for _ in 0..50 {
2784            assert_eq!(CustomEvent::NoEvent, layout.tick());
2785            assert_keys(&[], layout.keycodes());
2786        }
2787        layout.event(Release(0, 0));
2788        assert_eq!(CustomEvent::NoEvent, layout.tick());
2789        assert_keys(&[Space], layout.keycodes());
2790        assert_eq!(CustomEvent::NoEvent, layout.tick());
2791        assert_keys(&[], layout.keycodes());
2792    }
2793
2794    #[test]
2795    fn order_hold() {
2796        // Modifier down → other down → other up first → Hold.
2797        static LAYERS: Layers<2, 1> = &[[[
2798            HoldTap(&HoldTapAction {
2799                on_press_reset_timeout_to: None,
2800                timeout: u16::MAX,
2801                hold: k(LAlt),
2802                timeout_action: k(Space),
2803                tap: k(Space),
2804                config: HoldTapConfig::Order { buffer: 0 },
2805                tap_hold_interval: 0,
2806                require_prior_idle: None,
2807            }),
2808            k(Enter),
2809        ]]];
2810        let mut layout = Layout::new(LAYERS);
2811
2812        layout.event(Press(0, 0));
2813        assert_eq!(CustomEvent::NoEvent, layout.tick());
2814        assert_keys(&[], layout.keycodes());
2815        layout.event(Press(0, 1));
2816        assert_eq!(CustomEvent::NoEvent, layout.tick());
2817        assert_keys(&[], layout.keycodes());
2818        // Other key releases first → Hold
2819        layout.event(Release(0, 1));
2820        assert_eq!(CustomEvent::NoEvent, layout.tick());
2821        assert_keys(&[LAlt], layout.keycodes());
2822        assert_eq!(CustomEvent::NoEvent, layout.tick());
2823        assert_keys(&[LAlt, Enter], layout.keycodes());
2824        assert_eq!(CustomEvent::NoEvent, layout.tick());
2825        assert_keys(&[LAlt], layout.keycodes());
2826        // Release modifier
2827        layout.event(Release(0, 0));
2828        assert_eq!(CustomEvent::NoEvent, layout.tick());
2829        assert_keys(&[], layout.keycodes());
2830    }
2831
2832    #[test]
2833    fn order_tap() {
2834        // Modifier down → other down → modifier up first → Tap.
2835        static LAYERS: Layers<2, 1> = &[[[
2836            HoldTap(&HoldTapAction {
2837                on_press_reset_timeout_to: None,
2838                timeout: u16::MAX,
2839                hold: k(LAlt),
2840                timeout_action: k(Space),
2841                tap: k(Space),
2842                config: HoldTapConfig::Order { buffer: 0 },
2843                tap_hold_interval: 0,
2844                require_prior_idle: None,
2845            }),
2846            k(Enter),
2847        ]]];
2848        let mut layout = Layout::new(LAYERS);
2849
2850        layout.event(Press(0, 0));
2851        assert_eq!(CustomEvent::NoEvent, layout.tick());
2852        assert_keys(&[], layout.keycodes());
2853        layout.event(Press(0, 1));
2854        assert_eq!(CustomEvent::NoEvent, layout.tick());
2855        assert_keys(&[], layout.keycodes());
2856        // Modifier releases first → Tap
2857        layout.event(Release(0, 0));
2858        assert_eq!(CustomEvent::NoEvent, layout.tick());
2859        assert_keys(&[Space], layout.keycodes());
2860        assert_eq!(CustomEvent::NoEvent, layout.tick());
2861        assert_keys(&[Space, Enter], layout.keycodes());
2862    }
2863
2864    #[test]
2865    fn order_multi_key_hold() {
2866        // TH down → A down → B down → A up (while B still held) → TH up.
2867        // A's press+release cycle completes while TH is held → Hold.
2868        static LAYERS: Layers<3, 1> = &[[[
2869            HoldTap(&HoldTapAction {
2870                on_press_reset_timeout_to: None,
2871                timeout: u16::MAX,
2872                hold: k(LAlt),
2873                timeout_action: k(Space),
2874                tap: k(Space),
2875                config: HoldTapConfig::Order { buffer: 0 },
2876                tap_hold_interval: 0,
2877                require_prior_idle: None,
2878            }),
2879            k(Enter),
2880            k(Tab),
2881        ]]];
2882        let mut layout = Layout::new(LAYERS);
2883
2884        // TH down
2885        layout.event(Press(0, 0));
2886        assert_eq!(CustomEvent::NoEvent, layout.tick());
2887        assert_keys(&[], layout.keycodes());
2888        // A down
2889        layout.event(Press(0, 1));
2890        assert_eq!(CustomEvent::NoEvent, layout.tick());
2891        assert_keys(&[], layout.keycodes());
2892        // B down
2893        layout.event(Press(0, 2));
2894        assert_eq!(CustomEvent::NoEvent, layout.tick());
2895        assert_keys(&[], layout.keycodes());
2896        // A up — A's press+release cycle is complete → Hold resolves
2897        layout.event(Release(0, 1));
2898        assert_eq!(CustomEvent::NoEvent, layout.tick());
2899        assert_keys(&[LAlt], layout.keycodes());
2900        // Queued keys replay: Enter press, Tab press, Enter release
2901        assert_eq!(CustomEvent::NoEvent, layout.tick());
2902        assert_keys(&[LAlt, Enter], layout.keycodes());
2903        assert_eq!(CustomEvent::NoEvent, layout.tick());
2904        assert_keys(&[LAlt, Enter, Tab], layout.keycodes());
2905        assert_eq!(CustomEvent::NoEvent, layout.tick());
2906        assert_keys(&[LAlt, Tab], layout.keycodes());
2907        // Release B
2908        layout.event(Release(0, 2));
2909        assert_eq!(CustomEvent::NoEvent, layout.tick());
2910        assert_keys(&[LAlt], layout.keycodes());
2911        // Release TH
2912        layout.event(Release(0, 0));
2913        assert_eq!(CustomEvent::NoEvent, layout.tick());
2914        assert_keys(&[], layout.keycodes());
2915    }
2916
2917    #[test]
2918    fn order_buffer_ignores_press_within_window() {
2919        // TH down (buffer=50) → other key pressed+released within 50 ticks.
2920        // Without buffer this would be Hold (other key's press+release cycle
2921        // completes while TH held). With buffer=50, the press is ignored by
2922        // release-order logic, so TH remains unresolved. Releasing TH → Tap.
2923        static LAYERS: Layers<2, 1> = &[[[
2924            HoldTap(&HoldTapAction {
2925                on_press_reset_timeout_to: None,
2926                require_prior_idle: None,
2927                timeout: u16::MAX,
2928                hold: k(LAlt),
2929                timeout_action: k(Space),
2930                tap: k(Space),
2931                config: HoldTapConfig::Order { buffer: 50 },
2932                tap_hold_interval: 0,
2933            }),
2934            k(Enter),
2935        ]]];
2936        let mut layout = Layout::new(LAYERS);
2937
2938        // TH down
2939        layout.event(Press(0, 0));
2940        assert_eq!(CustomEvent::NoEvent, layout.tick());
2941        assert_keys(&[], layout.keycodes());
2942        // Other key pressed at tick ~1 (well within 50-tick buffer)
2943        layout.event(Press(0, 1));
2944        assert_eq!(CustomEvent::NoEvent, layout.tick());
2945        assert_keys(&[], layout.keycodes());
2946        // Other key released — would normally trigger Hold, but press is buffered
2947        layout.event(Release(0, 1));
2948        assert_eq!(CustomEvent::NoEvent, layout.tick());
2949        assert_keys(&[], layout.keycodes());
2950        // TH released → Tap (buffered press was ignored).
2951        // Space activates, then queued Enter press+release replays.
2952        layout.event(Release(0, 0));
2953        assert_eq!(CustomEvent::NoEvent, layout.tick());
2954        assert_keys(&[Space], layout.keycodes());
2955        assert_eq!(CustomEvent::NoEvent, layout.tick());
2956        assert_keys(&[Space, Enter], layout.keycodes());
2957        assert_eq!(CustomEvent::NoEvent, layout.tick());
2958        assert_keys(&[Space], layout.keycodes());
2959        assert_eq!(CustomEvent::NoEvent, layout.tick());
2960        assert_keys(&[], layout.keycodes());
2961    }
2962
2963    #[test]
2964    fn permissive_hold() {
2965        static LAYERS: Layers<2, 1> = &[[[
2966            HoldTap(&HoldTapAction {
2967                on_press_reset_timeout_to: None,
2968                require_prior_idle: None,
2969                timeout: 200,
2970                hold: k(LAlt),
2971                timeout_action: k(LAlt),
2972                tap: k(Space),
2973                config: HoldTapConfig::PermissiveHold,
2974                tap_hold_interval: 0,
2975            }),
2976            k(Enter),
2977        ]]];
2978        let mut layout = Layout::new(LAYERS);
2979
2980        // Press and release another key before timeout
2981        assert_eq!(CustomEvent::NoEvent, layout.tick());
2982        assert_keys(&[], layout.keycodes());
2983        layout.event(Press(0, 0));
2984        assert_eq!(CustomEvent::NoEvent, layout.tick());
2985        assert_keys(&[], layout.keycodes());
2986        layout.event(Press(0, 1));
2987        assert_eq!(CustomEvent::NoEvent, layout.tick());
2988        assert_keys(&[], layout.keycodes());
2989        layout.event(Release(0, 1));
2990        assert_eq!(CustomEvent::NoEvent, layout.tick());
2991        assert_keys(&[LAlt], layout.keycodes());
2992        assert_eq!(CustomEvent::NoEvent, layout.tick());
2993        assert_keys(&[LAlt, Enter], layout.keycodes());
2994        assert_eq!(CustomEvent::NoEvent, layout.tick());
2995        assert_keys(&[LAlt], layout.keycodes());
2996        assert_eq!(CustomEvent::NoEvent, layout.tick());
2997        assert_keys(&[LAlt], layout.keycodes());
2998        layout.event(Release(0, 0));
2999        assert_eq!(CustomEvent::NoEvent, layout.tick());
3000        assert_keys(&[], layout.keycodes());
3001        assert_eq!(CustomEvent::NoEvent, layout.tick());
3002        assert_keys(&[], layout.keycodes());
3003    }
3004
3005    #[test]
3006    fn simultaneous_hold() {
3007        static LAYERS: Layers<3, 1> = &[[[
3008            HoldTap(&HoldTapAction {
3009                on_press_reset_timeout_to: None,
3010                require_prior_idle: None,
3011                timeout: 200,
3012                hold: k(LAlt),
3013                timeout_action: k(LAlt),
3014                tap: k(Space),
3015                config: HoldTapConfig::Default,
3016                tap_hold_interval: 0,
3017            }),
3018            HoldTap(&HoldTapAction {
3019                on_press_reset_timeout_to: None,
3020                require_prior_idle: None,
3021                timeout: 200,
3022                hold: k(RAlt),
3023                timeout_action: k(RAlt),
3024                tap: k(A),
3025                config: HoldTapConfig::Default,
3026                tap_hold_interval: 0,
3027            }),
3028            HoldTap(&HoldTapAction {
3029                on_press_reset_timeout_to: None,
3030                require_prior_idle: None,
3031                timeout: 200,
3032                hold: k(LCtrl),
3033                timeout_action: k(LCtrl),
3034                tap: k(A),
3035                config: HoldTapConfig::Default,
3036                tap_hold_interval: 0,
3037            }),
3038        ]]];
3039        let mut layout = Layout::new(LAYERS);
3040        layout.quick_tap_hold_timeout = true;
3041
3042        // Press and release another key before timeout
3043        assert_eq!(CustomEvent::NoEvent, layout.tick());
3044        assert_keys(&[], layout.keycodes());
3045        layout.event(Press(0, 0));
3046        assert_eq!(CustomEvent::NoEvent, layout.tick());
3047        assert_keys(&[], layout.keycodes());
3048        layout.event(Press(0, 1));
3049        assert_eq!(CustomEvent::NoEvent, layout.tick());
3050        assert_keys(&[], layout.keycodes());
3051        layout.event(Press(0, 2));
3052        assert_eq!(CustomEvent::NoEvent, layout.tick());
3053        assert_keys(&[], layout.keycodes());
3054
3055        for _ in 0..196 {
3056            assert_eq!(CustomEvent::NoEvent, layout.tick());
3057            assert_keys(&[], layout.keycodes());
3058        }
3059        assert_eq!(CustomEvent::NoEvent, layout.tick());
3060        assert_keys(&[LAlt], layout.keycodes());
3061        assert_eq!(CustomEvent::NoEvent, layout.tick());
3062        assert_keys(&[LAlt], layout.keycodes());
3063        assert_eq!(CustomEvent::NoEvent, layout.tick());
3064        assert_keys(&[LAlt, RAlt], layout.keycodes());
3065        assert_eq!(CustomEvent::NoEvent, layout.tick());
3066        assert_keys(&[LAlt, RAlt], layout.keycodes());
3067        assert_eq!(CustomEvent::NoEvent, layout.tick());
3068        assert_keys(&[LAlt, RAlt, LCtrl], layout.keycodes());
3069    }
3070
3071    #[test]
3072    fn multiple_actions() {
3073        static LAYERS: Layers<2, 1> = &[
3074            [[MultipleActions(&[l(1), k(LShift)].as_slice()), k(F)]],
3075            [[Trans, k(E)]],
3076        ];
3077        let mut layout = Layout::new(LAYERS);
3078        assert_eq!(CustomEvent::NoEvent, layout.tick());
3079        assert_keys(&[], layout.keycodes());
3080        layout.event(Press(0, 0));
3081        assert_eq!(CustomEvent::NoEvent, layout.tick());
3082        assert_keys(&[LShift], layout.keycodes());
3083        layout.event(Press(0, 1));
3084        assert_eq!(CustomEvent::NoEvent, layout.tick());
3085        assert_keys(&[LShift, E], layout.keycodes());
3086        layout.event(Release(0, 1));
3087        layout.event(Release(0, 0));
3088        assert_eq!(CustomEvent::NoEvent, layout.tick());
3089        assert_keys(&[LShift], layout.keycodes());
3090        assert_eq!(CustomEvent::NoEvent, layout.tick());
3091        assert_keys(&[], layout.keycodes());
3092    }
3093
3094    #[test]
3095    fn custom() {
3096        static LAYERS: Layers<1, 1, i32> = &[[[Action::Custom(42)]]];
3097        let mut layout = Layout::new(LAYERS);
3098        assert_eq!(CustomEvent::NoEvent, layout.tick());
3099        assert_keys(&[], layout.keycodes());
3100
3101        // Custom event
3102        layout.event(Press(0, 0));
3103        assert_eq!(CustomEvent::Press(&42), layout.tick());
3104        assert_keys(&[], layout.keycodes());
3105
3106        // nothing more
3107        assert_eq!(CustomEvent::NoEvent, layout.tick());
3108        assert_keys(&[], layout.keycodes());
3109
3110        // release custom
3111        layout.event(Release(0, 0));
3112        assert_eq!(CustomEvent::Release(&42), layout.tick());
3113        assert_keys(&[], layout.keycodes());
3114    }
3115
3116    #[test]
3117    fn multiple_layers() {
3118        static LAYERS: Layers<2, 1> = &[
3119            [[l(1), l(2)]],
3120            [[k(A), l(3)]],
3121            [[l(0), k(B)]],
3122            [[k(C), k(D)]],
3123        ];
3124        let mut layout = Layout::new(LAYERS);
3125        assert_eq!(CustomEvent::NoEvent, layout.tick());
3126        assert_eq!(0, layout.current_layer());
3127        assert_keys(&[], layout.keycodes());
3128
3129        // press L1
3130        layout.event(Press(0, 0));
3131        assert_eq!(CustomEvent::NoEvent, layout.tick());
3132        assert_eq!(1, layout.current_layer());
3133        assert_keys(&[], layout.keycodes());
3134        // press L3 on L1
3135        layout.event(Press(0, 1));
3136        assert_eq!(CustomEvent::NoEvent, layout.tick());
3137        assert_eq!(3, layout.current_layer());
3138        assert_keys(&[], layout.keycodes());
3139        // release L1, still on l3
3140        layout.event(Release(0, 0));
3141        assert_eq!(CustomEvent::NoEvent, layout.tick());
3142        assert_eq!(3, layout.current_layer());
3143        assert_keys(&[], layout.keycodes());
3144        // press and release C on L3
3145        layout.event(Press(0, 0));
3146        assert_eq!(CustomEvent::NoEvent, layout.tick());
3147        assert_keys(&[C], layout.keycodes());
3148        layout.event(Release(0, 0));
3149        assert_eq!(CustomEvent::NoEvent, layout.tick());
3150        assert_keys(&[], layout.keycodes());
3151        // release L3, back to L0
3152        layout.event(Release(0, 1));
3153        assert_eq!(CustomEvent::NoEvent, layout.tick());
3154        assert_eq!(0, layout.current_layer());
3155        assert_keys(&[], layout.keycodes());
3156
3157        // back to empty, going to L2
3158        layout.event(Press(0, 1));
3159        assert_eq!(CustomEvent::NoEvent, layout.tick());
3160        assert_eq!(2, layout.current_layer());
3161        assert_keys(&[], layout.keycodes());
3162        // and press the L0 key on L2
3163        layout.event(Press(0, 0));
3164        assert_eq!(CustomEvent::NoEvent, layout.tick());
3165        assert_eq!(0, layout.current_layer());
3166        assert_keys(&[], layout.keycodes());
3167        // release the L0, back to L2
3168        layout.event(Release(0, 0));
3169        assert_eq!(CustomEvent::NoEvent, layout.tick());
3170        assert_eq!(2, layout.current_layer());
3171        assert_keys(&[], layout.keycodes());
3172        // release the L2, back to L0
3173        layout.event(Release(0, 1));
3174        assert_eq!(CustomEvent::NoEvent, layout.tick());
3175        assert_eq!(0, layout.current_layer());
3176        assert_keys(&[], layout.keycodes());
3177    }
3178
3179    #[test]
3180    fn custom_handler() {
3181        fn always_tap(_: QueuedIter, _: KCoord) -> (Option<WaitingAction>, bool) {
3182            (Some(WaitingAction::Tap), false)
3183        }
3184        fn always_hold(_: QueuedIter, _: KCoord) -> (Option<WaitingAction>, bool) {
3185            (Some(WaitingAction::Hold), false)
3186        }
3187        fn always_nop(_: QueuedIter, _: KCoord) -> (Option<WaitingAction>, bool) {
3188            (Some(WaitingAction::NoOp), false)
3189        }
3190        fn always_none(_: QueuedIter, _: KCoord) -> (Option<WaitingAction>, bool) {
3191            (None, false)
3192        }
3193        static LAYERS: Layers<4, 1> = &[[[
3194            HoldTap(&HoldTapAction {
3195                on_press_reset_timeout_to: None,
3196                require_prior_idle: None,
3197                timeout: 200,
3198                hold: k(Kb1),
3199                timeout_action: k(Kb1),
3200                tap: k(Kb0),
3201                config: HoldTapConfig::Custom(&always_tap),
3202                tap_hold_interval: 0,
3203            }),
3204            HoldTap(&HoldTapAction {
3205                on_press_reset_timeout_to: None,
3206                require_prior_idle: None,
3207                timeout: 200,
3208                hold: k(Kb3),
3209                timeout_action: k(Kb3),
3210                tap: k(Kb2),
3211                config: HoldTapConfig::Custom(&always_hold),
3212                tap_hold_interval: 0,
3213            }),
3214            HoldTap(&HoldTapAction {
3215                on_press_reset_timeout_to: None,
3216                require_prior_idle: None,
3217                timeout: 200,
3218                hold: k(Kb5),
3219                timeout_action: k(Kb5),
3220                tap: k(Kb4),
3221                config: HoldTapConfig::Custom(&always_nop),
3222                tap_hold_interval: 0,
3223            }),
3224            HoldTap(&HoldTapAction {
3225                on_press_reset_timeout_to: None,
3226                require_prior_idle: None,
3227                timeout: 200,
3228                hold: k(Kb7),
3229                timeout_action: k(Kb7),
3230                tap: k(Kb6),
3231                config: HoldTapConfig::Custom(&always_none),
3232                tap_hold_interval: 0,
3233            }),
3234        ]]];
3235        let mut layout = Layout::new(LAYERS);
3236        assert_eq!(CustomEvent::NoEvent, layout.tick());
3237        assert_keys(&[], layout.keycodes());
3238
3239        // Custom handler always taps
3240        layout.event(Press(0, 0));
3241        assert_eq!(CustomEvent::NoEvent, layout.tick());
3242        assert_keys(&[], layout.keycodes());
3243        assert_eq!(CustomEvent::NoEvent, layout.tick());
3244        assert_keys(&[Kb0], layout.keycodes());
3245
3246        // nothing more
3247        layout.event(Release(0, 0));
3248        assert_eq!(CustomEvent::NoEvent, layout.tick());
3249        assert_keys(&[], layout.keycodes());
3250
3251        // Custom handler always holds
3252        layout.event(Press(0, 1));
3253        assert_eq!(CustomEvent::NoEvent, layout.tick());
3254        assert_keys(&[], layout.keycodes());
3255        assert_eq!(CustomEvent::NoEvent, layout.tick());
3256        assert_keys(&[Kb3], layout.keycodes());
3257
3258        // nothing more
3259        layout.event(Release(0, 1));
3260        assert_eq!(CustomEvent::NoEvent, layout.tick());
3261        assert_keys(&[], layout.keycodes());
3262
3263        // Custom handler always prevents any event
3264        layout.event(Press(0, 2));
3265        assert_eq!(CustomEvent::NoEvent, layout.tick());
3266        assert_keys(&[], layout.keycodes());
3267
3268        // even timeout does not trigger
3269        for _ in 0..200 {
3270            assert_eq!(CustomEvent::NoEvent, layout.tick());
3271            assert_keys(&[], layout.keycodes());
3272        }
3273
3274        assert_eq!(CustomEvent::NoEvent, layout.tick());
3275        assert_keys(&[], layout.keycodes());
3276
3277        // nothing more
3278        layout.event(Release(0, 2));
3279        assert_eq!(CustomEvent::NoEvent, layout.tick());
3280        assert_keys(&[], layout.keycodes());
3281
3282        // Custom handler timeout fallback
3283        layout.event(Press(0, 3));
3284        assert_eq!(CustomEvent::NoEvent, layout.tick());
3285        assert_keys(&[], layout.keycodes());
3286
3287        for _ in 0..199 {
3288            assert_eq!(CustomEvent::NoEvent, layout.tick());
3289            assert_keys(&[], layout.keycodes());
3290        }
3291
3292        assert_eq!(CustomEvent::NoEvent, layout.tick());
3293        assert_keys(&[Kb7], layout.keycodes());
3294    }
3295
3296    #[test]
3297    fn tap_hold_interval() {
3298        static LAYERS: Layers<2, 1> = &[[[
3299            HoldTap(&HoldTapAction {
3300                on_press_reset_timeout_to: None,
3301                require_prior_idle: None,
3302                timeout: 200,
3303                hold: k(LAlt),
3304                timeout_action: k(LAlt),
3305                tap: k(Space),
3306                config: HoldTapConfig::Default,
3307                tap_hold_interval: 200,
3308            }),
3309            k(Enter),
3310        ]]];
3311        let mut layout = Layout::new(LAYERS);
3312
3313        // press and release the HT key, expect tap action
3314        assert_eq!(CustomEvent::NoEvent, layout.tick());
3315        assert_keys(&[], layout.keycodes());
3316        layout.event(Press(0, 0));
3317        assert_eq!(CustomEvent::NoEvent, layout.tick());
3318        assert_keys(&[], layout.keycodes());
3319        layout.event(Release(0, 0));
3320        assert_eq!(CustomEvent::NoEvent, layout.tick());
3321        assert_keys(&[Space], layout.keycodes());
3322        assert_eq!(CustomEvent::NoEvent, layout.tick());
3323        assert_keys(&[], layout.keycodes());
3324
3325        // press again within tap_hold_interval, tap action should be in keycode immediately
3326        layout.event(Press(0, 0));
3327        assert_eq!(CustomEvent::NoEvent, layout.tick());
3328        assert_keys(&[Space], layout.keycodes());
3329
3330        // tap action should continue to be in keycodes even after timeout
3331        for _ in 0..300 {
3332            assert_eq!(CustomEvent::NoEvent, layout.tick());
3333            assert_keys(&[Space], layout.keycodes());
3334        }
3335        layout.event(Release(0, 0));
3336        assert_eq!(CustomEvent::NoEvent, layout.tick());
3337        assert_keys(&[], layout.keycodes());
3338
3339        // Press again. This is outside the tap_hold_interval window, so should result in hold
3340        // action.
3341        layout.event(Press(0, 0));
3342        for _ in 0..200 {
3343            assert_eq!(CustomEvent::NoEvent, layout.tick());
3344            assert_keys(&[], layout.keycodes());
3345        }
3346        assert_eq!(CustomEvent::NoEvent, layout.tick());
3347        assert_keys(&[LAlt], layout.keycodes());
3348        layout.event(Release(0, 0));
3349        assert_eq!(CustomEvent::NoEvent, layout.tick());
3350        assert_keys(&[], layout.keycodes());
3351    }
3352
3353    #[test]
3354    fn tap_hold_interval_interleave() {
3355        static LAYERS: Layers<3, 1> = &[[[
3356            HoldTap(&HoldTapAction {
3357                on_press_reset_timeout_to: None,
3358                require_prior_idle: None,
3359                timeout: 200,
3360                hold: k(LAlt),
3361                timeout_action: k(LAlt),
3362                tap: k(Space),
3363                config: HoldTapConfig::Default,
3364                tap_hold_interval: 200,
3365            }),
3366            k(Enter),
3367            HoldTap(&HoldTapAction {
3368                on_press_reset_timeout_to: None,
3369                require_prior_idle: None,
3370                timeout: 200,
3371                hold: k(LAlt),
3372                timeout_action: k(LAlt),
3373                tap: k(Enter),
3374                config: HoldTapConfig::Default,
3375                tap_hold_interval: 200,
3376            }),
3377        ]]];
3378        let mut layout = Layout::new(LAYERS);
3379
3380        // press and release the HT key, expect tap action
3381        assert_eq!(CustomEvent::NoEvent, layout.tick());
3382        assert_keys(&[], layout.keycodes());
3383        layout.event(Press(0, 0));
3384        assert_eq!(CustomEvent::NoEvent, layout.tick());
3385        assert_keys(&[], layout.keycodes());
3386        layout.event(Release(0, 0));
3387        assert_eq!(CustomEvent::NoEvent, layout.tick());
3388        assert_keys(&[Space], layout.keycodes());
3389        assert_eq!(CustomEvent::NoEvent, layout.tick());
3390        assert_keys(&[], layout.keycodes());
3391
3392        // press a different key in between
3393        layout.event(Press(0, 1));
3394        assert_eq!(CustomEvent::NoEvent, layout.tick());
3395        assert_keys(&[Enter], layout.keycodes());
3396        layout.event(Release(0, 1));
3397        assert_eq!(CustomEvent::NoEvent, layout.tick());
3398        assert_keys(&[], layout.keycodes());
3399
3400        // press HT key again, should result in hold action
3401        layout.event(Press(0, 0));
3402        for _ in 0..200 {
3403            assert_eq!(CustomEvent::NoEvent, layout.tick());
3404            assert_keys(&[], layout.keycodes());
3405        }
3406        assert_eq!(CustomEvent::NoEvent, layout.tick());
3407        assert_keys(&[LAlt], layout.keycodes());
3408        layout.event(Release(0, 0));
3409        assert_eq!(CustomEvent::NoEvent, layout.tick());
3410        assert_keys(&[], layout.keycodes());
3411
3412        // press HT key, press+release diff key, release HT key
3413        assert_eq!(CustomEvent::NoEvent, layout.tick());
3414        assert_keys(&[], layout.keycodes());
3415        layout.event(Press(0, 0));
3416        assert_eq!(CustomEvent::NoEvent, layout.tick());
3417        assert_keys(&[], layout.keycodes());
3418        layout.event(Press(0, 1));
3419        assert_eq!(CustomEvent::NoEvent, layout.tick());
3420        assert_keys(&[], layout.keycodes());
3421        layout.event(Release(0, 1));
3422        assert_eq!(CustomEvent::NoEvent, layout.tick());
3423        assert_keys(&[], layout.keycodes());
3424        layout.event(Release(0, 0));
3425        assert_eq!(CustomEvent::NoEvent, layout.tick());
3426        assert_keys(&[Space], layout.keycodes());
3427        assert_eq!(CustomEvent::NoEvent, layout.tick());
3428        assert_keys(&[Enter, Space], layout.keycodes());
3429        assert_eq!(CustomEvent::NoEvent, layout.tick());
3430        assert_keys(&[Space], layout.keycodes());
3431        assert_eq!(CustomEvent::NoEvent, layout.tick());
3432        assert_keys(&[], layout.keycodes());
3433
3434        // press HT key again, should result in hold action
3435        layout.event(Press(0, 0));
3436        for _ in 0..200 {
3437            assert_eq!(CustomEvent::NoEvent, layout.tick());
3438            assert_keys(&[], layout.keycodes());
3439        }
3440        assert_eq!(CustomEvent::NoEvent, layout.tick());
3441        assert_keys(&[LAlt], layout.keycodes());
3442        layout.event(Release(0, 0));
3443        assert_eq!(CustomEvent::NoEvent, layout.tick());
3444        assert_keys(&[], layout.keycodes());
3445
3446        // press HT key, press+release diff (HT) key, release HT key
3447        assert_eq!(CustomEvent::NoEvent, layout.tick());
3448        assert_keys(&[], layout.keycodes());
3449        layout.event(Press(0, 0));
3450        assert_eq!(CustomEvent::NoEvent, layout.tick());
3451        assert_keys(&[], layout.keycodes());
3452        layout.event(Press(0, 2));
3453        assert_eq!(CustomEvent::NoEvent, layout.tick());
3454        assert_keys(&[], layout.keycodes());
3455        layout.event(Release(0, 2));
3456        assert_eq!(CustomEvent::NoEvent, layout.tick());
3457        assert_keys(&[], layout.keycodes());
3458        layout.event(Release(0, 0));
3459        assert_eq!(CustomEvent::NoEvent, layout.tick());
3460        assert_keys(&[Space], layout.keycodes());
3461        assert_eq!(CustomEvent::NoEvent, layout.tick());
3462        assert_keys(&[Space], layout.keycodes());
3463        assert_eq!(CustomEvent::NoEvent, layout.tick());
3464        assert_keys(&[Enter, Space], layout.keycodes());
3465        assert_eq!(CustomEvent::NoEvent, layout.tick());
3466        assert_keys(&[Space], layout.keycodes());
3467        assert_eq!(CustomEvent::NoEvent, layout.tick());
3468        assert_keys(&[], layout.keycodes());
3469
3470        // press HT key again, should result in hold action
3471        layout.event(Press(0, 0));
3472        for _ in 0..200 {
3473            assert_eq!(CustomEvent::NoEvent, layout.tick());
3474            assert_keys(&[], layout.keycodes());
3475        }
3476        assert_eq!(CustomEvent::NoEvent, layout.tick());
3477        assert_keys(&[LAlt], layout.keycodes());
3478    }
3479
3480    #[test]
3481    fn tap_hold_interval_short_hold() {
3482        static LAYERS: Layers<1, 1> = &[[[HoldTap(&HoldTapAction {
3483            on_press_reset_timeout_to: None,
3484            require_prior_idle: None,
3485            timeout: 50,
3486            hold: k(LAlt),
3487            timeout_action: k(LAlt),
3488            tap: k(Space),
3489            config: HoldTapConfig::Default,
3490            tap_hold_interval: 200,
3491        })]]];
3492        let mut layout = Layout::new(LAYERS);
3493
3494        // press and hold the HT key, expect hold action
3495        assert_eq!(CustomEvent::NoEvent, layout.tick());
3496        assert_keys(&[], layout.keycodes());
3497        layout.event(Press(0, 0));
3498        for _ in 0..50 {
3499            assert_eq!(CustomEvent::NoEvent, layout.tick());
3500            assert_keys(&[], layout.keycodes());
3501        }
3502        assert_eq!(CustomEvent::NoEvent, layout.tick());
3503        assert_keys(&[LAlt], layout.keycodes());
3504        layout.event(Release(0, 0));
3505        assert_eq!(CustomEvent::NoEvent, layout.tick());
3506        assert_keys(&[], layout.keycodes());
3507
3508        // press and hold the HT key, expect hold action, even though it's within the
3509        // tap_hold_interval
3510        assert_eq!(CustomEvent::NoEvent, layout.tick());
3511        assert_keys(&[], layout.keycodes());
3512        layout.event(Press(0, 0));
3513        for _ in 0..50 {
3514            assert_eq!(CustomEvent::NoEvent, layout.tick());
3515            assert_keys(&[], layout.keycodes());
3516        }
3517        assert_eq!(CustomEvent::NoEvent, layout.tick());
3518        assert_keys(&[LAlt], layout.keycodes());
3519        layout.event(Release(0, 0));
3520        assert_eq!(CustomEvent::NoEvent, layout.tick());
3521        assert_keys(&[], layout.keycodes());
3522    }
3523
3524    #[test]
3525    fn tap_hold_interval_different_hold() {
3526        static LAYERS: Layers<2, 1> = &[[[
3527            HoldTap(&HoldTapAction {
3528                on_press_reset_timeout_to: None,
3529                require_prior_idle: None,
3530                timeout: 50,
3531                hold: k(LAlt),
3532                timeout_action: k(LAlt),
3533                tap: k(Space),
3534                config: HoldTapConfig::Default,
3535                tap_hold_interval: 200,
3536            }),
3537            HoldTap(&HoldTapAction {
3538                on_press_reset_timeout_to: None,
3539                require_prior_idle: None,
3540                timeout: 200,
3541                hold: k(RAlt),
3542                timeout_action: k(RAlt),
3543                tap: k(Enter),
3544                config: HoldTapConfig::Default,
3545                tap_hold_interval: 200,
3546            }),
3547        ]]];
3548        let mut layout = Layout::new(LAYERS);
3549
3550        // press HT1, press HT2, release HT1 after hold timeout, release HT2, press HT2
3551        layout.event(Press(0, 0));
3552        layout.event(Press(0, 1));
3553        for _ in 0..50 {
3554            assert_eq!(CustomEvent::NoEvent, layout.tick());
3555            assert_keys(&[], layout.keycodes());
3556        }
3557        assert_eq!(CustomEvent::NoEvent, layout.tick());
3558        assert_keys(&[LAlt], layout.keycodes());
3559        layout.event(Release(0, 0));
3560        assert_eq!(CustomEvent::NoEvent, layout.tick());
3561        assert_keys(&[LAlt], layout.keycodes());
3562        layout.event(Release(0, 1));
3563        assert_eq!(CustomEvent::NoEvent, layout.tick());
3564        assert_keys(&[LAlt, Enter], layout.keycodes());
3565        assert_eq!(CustomEvent::NoEvent, layout.tick());
3566        assert_keys(&[Enter], layout.keycodes());
3567        // press HT2 again, should result in tap action
3568        layout.event(Press(0, 1));
3569        assert_eq!(CustomEvent::NoEvent, layout.tick());
3570        assert_keys(&[], layout.keycodes());
3571
3572        for _ in 0..300 {
3573            assert_eq!(CustomEvent::NoEvent, layout.tick());
3574            assert_keys(&[Enter], layout.keycodes());
3575        }
3576    }
3577
3578    #[test]
3579    fn one_shot() {
3580        static LAYERS: Layers<3, 1> = &[[[
3581            OneShot(&crate::action::OneShot {
3582                timeout: 100,
3583                action: &k(LShift),
3584                end_config: OneShotEndConfig::EndOnFirstPress,
3585            }),
3586            k(A),
3587            k(B),
3588        ]]];
3589        let mut layout = Layout::new(LAYERS);
3590        layout.oneshot.pause_input_processing_delay = 1;
3591
3592        // Test:
3593        // 1. press one-shot
3594        // 2. release one-shot
3595        // 3. press A within timeout
3596        // 4. press B within timeout
3597        // 5. release A, B
3598        layout.event(Press(0, 0));
3599        for _ in 0..25 {
3600            assert_eq!(CustomEvent::NoEvent, layout.tick());
3601            assert_keys(&[LShift], layout.keycodes());
3602        }
3603        layout.event(Release(0, 0));
3604        for _ in 0..25 {
3605            assert_eq!(CustomEvent::NoEvent, layout.tick());
3606            assert_keys(&[LShift], layout.keycodes());
3607        }
3608        layout.event(Press(0, 1));
3609        layout.event(Press(0, 2));
3610        assert_eq!(CustomEvent::NoEvent, layout.tick());
3611        assert_keys(&[A, LShift], layout.keycodes());
3612        assert_eq!(CustomEvent::NoEvent, layout.tick());
3613        assert_keys(&[A, B], layout.keycodes());
3614        layout.event(Release(0, 1));
3615        layout.event(Release(0, 2));
3616        assert_eq!(CustomEvent::NoEvent, layout.tick());
3617        assert_keys(&[B], layout.keycodes());
3618        assert_eq!(CustomEvent::NoEvent, layout.tick());
3619        assert_keys(&[], layout.keycodes());
3620
3621        // Test:
3622        // 1. press one-shot
3623        // 2. release one-shot
3624        // 3. press A after timeout
3625        // 4. release A
3626        layout.event(Press(0, 0));
3627        for _ in 0..25 {
3628            assert_eq!(CustomEvent::NoEvent, layout.tick());
3629            assert_keys(&[LShift], layout.keycodes());
3630        }
3631        layout.event(Release(0, 0));
3632        for _ in 0..75 {
3633            assert_eq!(CustomEvent::NoEvent, layout.tick());
3634            assert_keys(&[LShift], layout.keycodes());
3635        }
3636        assert_eq!(CustomEvent::NoEvent, layout.tick());
3637        assert_keys(&[], layout.keycodes());
3638        assert_eq!(CustomEvent::NoEvent, layout.tick());
3639        assert_keys(&[], layout.keycodes());
3640        layout.event(Press(0, 1));
3641        assert_eq!(CustomEvent::NoEvent, layout.tick());
3642        assert_keys(&[A], layout.keycodes());
3643        layout.event(Release(0, 1));
3644        assert_eq!(CustomEvent::NoEvent, layout.tick());
3645        assert_keys(&[], layout.keycodes());
3646
3647        // Test:
3648        // 1. press one-shot
3649        // 2. press A
3650        // 3. release A
3651        // 4. release one-shot
3652        layout.event(Press(0, 0));
3653        for _ in 0..25 {
3654            assert_eq!(CustomEvent::NoEvent, layout.tick());
3655            assert_keys(&[LShift], layout.keycodes());
3656        }
3657        layout.event(Press(0, 1));
3658        assert_eq!(CustomEvent::NoEvent, layout.tick());
3659        assert_keys(&[LShift, A], layout.keycodes());
3660        layout.event(Release(0, 1));
3661        assert_eq!(CustomEvent::NoEvent, layout.tick());
3662        assert_keys(&[LShift], layout.keycodes());
3663        layout.event(Release(0, 0));
3664        assert_eq!(CustomEvent::NoEvent, layout.tick());
3665        assert_keys(&[], layout.keycodes());
3666
3667        // Test:
3668        // 1. press one-shot
3669        // 2. press A after timeout
3670        // 3. release A
3671        // 4. release one-shot
3672        layout.event(Press(0, 0));
3673        for _ in 0..200 {
3674            assert_eq!(CustomEvent::NoEvent, layout.tick());
3675            assert_keys(&[LShift], layout.keycodes());
3676        }
3677        assert_eq!(CustomEvent::NoEvent, layout.tick());
3678        assert_keys(&[LShift], layout.keycodes());
3679        layout.event(Press(0, 1));
3680        assert_eq!(CustomEvent::NoEvent, layout.tick());
3681        assert_keys(&[LShift, A], layout.keycodes());
3682        layout.event(Release(0, 1));
3683        assert_eq!(CustomEvent::NoEvent, layout.tick());
3684        assert_keys(&[LShift], layout.keycodes());
3685        layout.event(Release(0, 0));
3686        assert_eq!(CustomEvent::NoEvent, layout.tick());
3687        assert_keys(&[], layout.keycodes());
3688    }
3689
3690    #[test]
3691    fn one_shot_end_press_or_repress() {
3692        static LAYERS: Layers<3, 1> = &[[[
3693            OneShot(&crate::action::OneShot {
3694                timeout: 100,
3695                action: &k(LShift),
3696                end_config: OneShotEndConfig::EndOnFirstPressOrRepress,
3697            }),
3698            k(A),
3699            k(B),
3700        ]]];
3701        let mut layout = Layout::new(LAYERS);
3702        layout.oneshot.pause_input_processing_delay = 1;
3703
3704        // Test:
3705        // 1. press one-shot
3706        // 2. release one-shot
3707        // 3. press A within timeout
3708        // 4. press B within timeout
3709        // 5. release A, B
3710        layout.event(Press(0, 0));
3711        for _ in 0..25 {
3712            assert_eq!(CustomEvent::NoEvent, layout.tick());
3713            assert_keys(&[LShift], layout.keycodes());
3714        }
3715        layout.event(Release(0, 0));
3716        for _ in 0..25 {
3717            assert_eq!(CustomEvent::NoEvent, layout.tick());
3718            assert_keys(&[LShift], layout.keycodes());
3719        }
3720        layout.event(Press(0, 1));
3721        layout.event(Press(0, 2));
3722        assert_eq!(CustomEvent::NoEvent, layout.tick());
3723        assert_keys(&[A, LShift], layout.keycodes());
3724        assert_eq!(CustomEvent::NoEvent, layout.tick());
3725        assert_keys(&[A, B], layout.keycodes());
3726        layout.event(Release(0, 1));
3727        layout.event(Release(0, 2));
3728        assert_eq!(CustomEvent::NoEvent, layout.tick());
3729        assert_keys(&[B], layout.keycodes());
3730        assert_eq!(CustomEvent::NoEvent, layout.tick());
3731        assert_keys(&[], layout.keycodes());
3732
3733        // Test:
3734        // 1. press one-shot
3735        // 2. release one-shot
3736        // 3. press A after timeout
3737        // 4. release A
3738        layout.event(Press(0, 0));
3739        for _ in 0..25 {
3740            assert_eq!(CustomEvent::NoEvent, layout.tick());
3741            assert_keys(&[LShift], layout.keycodes());
3742        }
3743        layout.event(Release(0, 0));
3744        for _ in 0..75 {
3745            assert_eq!(CustomEvent::NoEvent, layout.tick());
3746            assert_keys(&[LShift], layout.keycodes());
3747        }
3748        assert_eq!(CustomEvent::NoEvent, layout.tick());
3749        assert_keys(&[], layout.keycodes());
3750        assert_eq!(CustomEvent::NoEvent, layout.tick());
3751        assert_keys(&[], layout.keycodes());
3752        layout.event(Press(0, 1));
3753        assert_eq!(CustomEvent::NoEvent, layout.tick());
3754        assert_keys(&[A], layout.keycodes());
3755        layout.event(Release(0, 1));
3756        assert_eq!(CustomEvent::NoEvent, layout.tick());
3757        assert_keys(&[], layout.keycodes());
3758
3759        // Test:
3760        // 1. press one-shot
3761        // 2. press A
3762        // 3. release A
3763        // 4. release one-shot
3764        layout.event(Press(0, 0));
3765        for _ in 0..25 {
3766            assert_eq!(CustomEvent::NoEvent, layout.tick());
3767            assert_keys(&[LShift], layout.keycodes());
3768        }
3769        layout.event(Press(0, 1));
3770        assert_eq!(CustomEvent::NoEvent, layout.tick());
3771        assert_keys(&[LShift, A], layout.keycodes());
3772        layout.event(Release(0, 1));
3773        assert_eq!(CustomEvent::NoEvent, layout.tick());
3774        assert_keys(&[LShift], layout.keycodes());
3775        layout.event(Release(0, 0));
3776        assert_eq!(CustomEvent::NoEvent, layout.tick());
3777        assert_keys(&[], layout.keycodes());
3778
3779        // Test:
3780        // 1. press one-shot
3781        // 2. press A after timeout
3782        // 3. release A
3783        // 4. release one-shot
3784        layout.event(Press(0, 0));
3785        for _ in 0..200 {
3786            assert_eq!(CustomEvent::NoEvent, layout.tick());
3787            assert_keys(&[LShift], layout.keycodes());
3788        }
3789        assert_eq!(CustomEvent::NoEvent, layout.tick());
3790        assert_keys(&[LShift], layout.keycodes());
3791        layout.event(Press(0, 1));
3792        assert_eq!(CustomEvent::NoEvent, layout.tick());
3793        assert_keys(&[LShift, A], layout.keycodes());
3794        layout.event(Release(0, 1));
3795        assert_eq!(CustomEvent::NoEvent, layout.tick());
3796        assert_keys(&[LShift], layout.keycodes());
3797        layout.event(Release(0, 0));
3798        assert_eq!(CustomEvent::NoEvent, layout.tick());
3799        assert_keys(&[], layout.keycodes());
3800
3801        // Test:
3802        // 1. press one-shot
3803        // 2. release one-shot
3804        // 3. press one-shot within timeout
3805        // 4. release one-shot quickly - should end
3806        layout.event(Press(0, 0));
3807        assert_eq!(CustomEvent::NoEvent, layout.tick());
3808        assert_keys(&[LShift], layout.keycodes());
3809        layout.event(Release(0, 0));
3810        assert_eq!(CustomEvent::NoEvent, layout.tick());
3811        assert_keys(&[LShift], layout.keycodes());
3812        layout.event(Press(0, 0));
3813        assert_eq!(CustomEvent::NoEvent, layout.tick());
3814        assert_keys(&[LShift], layout.keycodes());
3815        layout.event(Release(0, 0));
3816        assert_eq!(CustomEvent::NoEvent, layout.tick());
3817        assert_keys(&[], layout.keycodes());
3818
3819        // Test:
3820        // 1. press one-shot
3821        // 2. release one-shot
3822        // 3. press one-shot within timeout
3823        // 4. release one-shot after timeout
3824        layout.event(Press(0, 0));
3825        assert_eq!(CustomEvent::NoEvent, layout.tick());
3826        assert_keys(&[LShift], layout.keycodes());
3827        layout.event(Release(0, 0));
3828        assert_eq!(CustomEvent::NoEvent, layout.tick());
3829        assert_keys(&[LShift], layout.keycodes());
3830        layout.event(Press(0, 0));
3831        assert_eq!(CustomEvent::NoEvent, layout.tick());
3832        assert_keys(&[LShift], layout.keycodes());
3833        assert_eq!(CustomEvent::NoEvent, layout.tick());
3834        assert_keys(&[LShift], layout.keycodes());
3835        for _ in 0..200 {
3836            assert_eq!(CustomEvent::NoEvent, layout.tick());
3837            assert_keys(&[LShift], layout.keycodes());
3838        }
3839        layout.event(Release(0, 0));
3840        assert_eq!(CustomEvent::NoEvent, layout.tick());
3841        assert_keys(&[], layout.keycodes());
3842    }
3843
3844    #[test]
3845    fn one_shot_end_on_release() {
3846        static LAYERS: Layers<3, 1> = &[[[
3847            OneShot(&crate::action::OneShot {
3848                timeout: 100,
3849                action: &k(LShift),
3850                end_config: OneShotEndConfig::EndOnFirstRelease,
3851            }),
3852            k(A),
3853            k(B),
3854        ]]];
3855        let mut layout = Layout::new(LAYERS);
3856
3857        // Test:
3858        // 1. press one-shot
3859        // 2. release one-shot
3860        // 3. press A within timeout
3861        // 4. press B within timeout
3862        // 5. release A, B
3863        layout.event(Press(0, 0));
3864        for _ in 0..25 {
3865            assert_eq!(CustomEvent::NoEvent, layout.tick());
3866            assert_keys(&[LShift], layout.keycodes());
3867        }
3868        layout.event(Release(0, 0));
3869        for _ in 0..25 {
3870            assert_eq!(CustomEvent::NoEvent, layout.tick());
3871            assert_keys(&[LShift], layout.keycodes());
3872        }
3873        layout.event(Press(0, 1));
3874        layout.event(Press(0, 2));
3875        assert_eq!(CustomEvent::NoEvent, layout.tick());
3876        assert_keys(&[A, LShift], layout.keycodes());
3877        assert_eq!(CustomEvent::NoEvent, layout.tick());
3878        assert_keys(&[A, B, LShift], layout.keycodes());
3879        layout.event(Release(0, 1));
3880        layout.event(Release(0, 2));
3881        assert_eq!(CustomEvent::NoEvent, layout.tick());
3882        assert_keys(&[B, LShift], layout.keycodes());
3883        assert_eq!(CustomEvent::NoEvent, layout.tick());
3884        assert_keys(&[], layout.keycodes());
3885
3886        // Test:
3887        // 1. press one-shot
3888        // 2. release one-shot
3889        // 3. press A after timeout
3890        // 4. release A
3891        layout.event(Press(0, 0));
3892        for _ in 0..25 {
3893            assert_eq!(CustomEvent::NoEvent, layout.tick());
3894            assert_keys(&[LShift], layout.keycodes());
3895        }
3896        layout.event(Release(0, 0));
3897        for _ in 0..75 {
3898            assert_eq!(CustomEvent::NoEvent, layout.tick());
3899            assert_keys(&[LShift], layout.keycodes());
3900        }
3901        assert_eq!(CustomEvent::NoEvent, layout.tick());
3902        assert_keys(&[], layout.keycodes());
3903        assert_eq!(CustomEvent::NoEvent, layout.tick());
3904        assert_keys(&[], layout.keycodes());
3905        layout.event(Press(0, 1));
3906        assert_eq!(CustomEvent::NoEvent, layout.tick());
3907        assert_keys(&[A], layout.keycodes());
3908        layout.event(Release(0, 1));
3909        assert_eq!(CustomEvent::NoEvent, layout.tick());
3910        assert_keys(&[], layout.keycodes());
3911
3912        // Test:
3913        // 1. press one-shot
3914        // 2. press A
3915        // 3. release A
3916        // 4. release one-shot
3917        layout.event(Press(0, 0));
3918        for _ in 0..25 {
3919            assert_eq!(CustomEvent::NoEvent, layout.tick());
3920            assert_keys(&[LShift], layout.keycodes());
3921        }
3922        layout.event(Press(0, 1));
3923        assert_eq!(CustomEvent::NoEvent, layout.tick());
3924        assert_keys(&[LShift, A], layout.keycodes());
3925        layout.event(Release(0, 1));
3926        assert_eq!(CustomEvent::NoEvent, layout.tick());
3927        assert_keys(&[LShift], layout.keycodes());
3928        layout.event(Release(0, 0));
3929        assert_eq!(CustomEvent::NoEvent, layout.tick());
3930        assert_keys(&[], layout.keycodes());
3931
3932        // Test:
3933        // 1. press one-shot
3934        // 2. press A after timeout
3935        // 3. release A
3936        // 4. release one-shot
3937        layout.event(Press(0, 0));
3938        for _ in 0..200 {
3939            assert_eq!(CustomEvent::NoEvent, layout.tick());
3940            assert_keys(&[LShift], layout.keycodes());
3941        }
3942        assert_eq!(CustomEvent::NoEvent, layout.tick());
3943        assert_keys(&[LShift], layout.keycodes());
3944        layout.event(Press(0, 1));
3945        assert_eq!(CustomEvent::NoEvent, layout.tick());
3946        assert_keys(&[LShift, A], layout.keycodes());
3947        layout.event(Release(0, 1));
3948        assert_eq!(CustomEvent::NoEvent, layout.tick());
3949        assert_keys(&[LShift], layout.keycodes());
3950        layout.event(Release(0, 0));
3951        assert_eq!(CustomEvent::NoEvent, layout.tick());
3952        assert_keys(&[], layout.keycodes());
3953
3954        // Test:
3955        // 3. press A
3956        // 1. press one-shot
3957        // 2. release one-shot
3958        // 3. release A
3959        // 4. press B within timeout
3960        // 5. release B
3961        layout.event(Press(0, 1));
3962        assert_eq!(CustomEvent::NoEvent, layout.tick());
3963        assert_keys(&[A], layout.keycodes());
3964        layout.event(Press(0, 0));
3965        for _ in 0..25 {
3966            assert_eq!(CustomEvent::NoEvent, layout.tick());
3967            assert_keys(&[A, LShift], layout.keycodes());
3968        }
3969        layout.event(Release(0, 0));
3970        for _ in 0..25 {
3971            assert_eq!(CustomEvent::NoEvent, layout.tick());
3972            assert_keys(&[A, LShift], layout.keycodes());
3973        }
3974        layout.event(Release(0, 1));
3975        assert_eq!(CustomEvent::NoEvent, layout.tick());
3976        assert_keys(&[LShift], layout.keycodes());
3977        assert_eq!(CustomEvent::NoEvent, layout.tick());
3978        assert_keys(&[LShift], layout.keycodes());
3979        layout.event(Press(0, 2));
3980        assert_eq!(CustomEvent::NoEvent, layout.tick());
3981        assert_keys(&[B, LShift], layout.keycodes());
3982        layout.event(Release(0, 2));
3983        assert_eq!(CustomEvent::NoEvent, layout.tick());
3984        assert_keys(&[LShift], layout.keycodes());
3985        assert_eq!(CustomEvent::NoEvent, layout.tick());
3986        assert_keys(&[], layout.keycodes());
3987    }
3988
3989    #[test]
3990    fn one_shot_multi() {
3991        static LAYERS: Layers<4, 1> = &[
3992            [[
3993                OneShot(&crate::action::OneShot {
3994                    timeout: 100,
3995                    action: &k(LShift),
3996                    end_config: OneShotEndConfig::EndOnFirstPress,
3997                }),
3998                OneShot(&crate::action::OneShot {
3999                    timeout: 100,
4000                    action: &k(LCtrl),
4001                    end_config: OneShotEndConfig::EndOnFirstPress,
4002                }),
4003                OneShot(&crate::action::OneShot {
4004                    timeout: 100,
4005                    action: &Layer(1),
4006                    end_config: OneShotEndConfig::EndOnFirstPress,
4007                }),
4008                NoOp,
4009            ]],
4010            [[k(A), k(B), k(C), k(D)]],
4011        ];
4012        let mut layout = Layout::new(LAYERS);
4013        layout.oneshot.pause_input_processing_delay = 1;
4014
4015        layout.event(Press(0, 0));
4016        layout.event(Release(0, 0));
4017        for _ in 0..90 {
4018            assert_eq!(CustomEvent::NoEvent, layout.tick());
4019            assert_keys(&[LShift], layout.keycodes());
4020        }
4021        layout.event(Press(0, 1));
4022        for _ in 0..90 {
4023            assert_eq!(CustomEvent::NoEvent, layout.tick());
4024            assert_keys(&[LShift, LCtrl], layout.keycodes());
4025        }
4026        assert_eq!(layout.current_layer(), 0);
4027        layout.event(Press(0, 2));
4028        layout.event(Release(0, 2));
4029        for _ in 0..90 {
4030            assert_eq!(CustomEvent::NoEvent, layout.tick());
4031            assert_keys(&[LShift, LCtrl], layout.keycodes());
4032            assert_eq!(layout.current_layer(), 1);
4033        }
4034        layout.event(Press(0, 3));
4035        layout.event(Release(0, 3));
4036        assert_eq!(CustomEvent::NoEvent, layout.tick());
4037        assert_keys(&[LShift, LCtrl, D], layout.keycodes());
4038        assert_eq!(layout.current_layer(), 1);
4039        assert_eq!(CustomEvent::NoEvent, layout.tick());
4040        assert_keys(&[LCtrl], layout.keycodes());
4041        assert_eq!(layout.current_layer(), 0);
4042        layout.event(Release(0, 1));
4043        assert_eq!(CustomEvent::NoEvent, layout.tick());
4044        assert_keys(&[], layout.keycodes());
4045    }
4046
4047    #[test]
4048    fn one_shot_tap_hold() {
4049        static LAYERS: Layers<3, 1> = &[
4050            [[
4051                OneShot(&crate::action::OneShot {
4052                    timeout: 200,
4053                    action: &k(LShift),
4054                    end_config: OneShotEndConfig::EndOnFirstPress,
4055                }),
4056                HoldTap(&HoldTapAction {
4057                    on_press_reset_timeout_to: None,
4058                    require_prior_idle: None,
4059                    timeout: 100,
4060                    hold: k(LAlt),
4061                    timeout_action: k(LAlt),
4062                    tap: k(Space),
4063                    config: HoldTapConfig::Default,
4064                    tap_hold_interval: 0,
4065                }),
4066                NoOp,
4067            ]],
4068            [[k(A), k(B), k(C)]],
4069        ];
4070        let mut layout = Layout::new(LAYERS);
4071        layout.oneshot.pause_input_processing_delay = 1;
4072
4073        layout.event(Press(0, 0));
4074        layout.event(Release(0, 0));
4075        for _ in 0..90 {
4076            assert_eq!(CustomEvent::NoEvent, layout.tick());
4077            assert_keys(&[LShift], layout.keycodes());
4078        }
4079        layout.event(Press(0, 1));
4080        for _ in 0..90 {
4081            assert_eq!(CustomEvent::NoEvent, layout.tick());
4082            assert_keys(&[LShift], layout.keycodes());
4083        }
4084        layout.event(Release(0, 1));
4085        assert_eq!(CustomEvent::NoEvent, layout.tick());
4086        assert_keys(&[LShift, Space], layout.keycodes());
4087        assert_eq!(CustomEvent::NoEvent, layout.tick());
4088        assert_keys(&[], layout.keycodes());
4089
4090        layout.event(Press(0, 0));
4091        layout.event(Release(0, 0));
4092        for _ in 0..90 {
4093            assert_eq!(CustomEvent::NoEvent, layout.tick());
4094            assert_keys(&[LShift], layout.keycodes());
4095        }
4096        layout.event(Press(0, 1));
4097        for _ in 0..100 {
4098            assert_eq!(CustomEvent::NoEvent, layout.tick());
4099            assert_keys(&[LShift], layout.keycodes());
4100        }
4101        assert_eq!(CustomEvent::NoEvent, layout.tick());
4102        assert_keys(&[LShift, LAlt], layout.keycodes());
4103        assert_eq!(CustomEvent::NoEvent, layout.tick());
4104        assert_keys(&[LAlt], layout.keycodes());
4105        layout.event(Release(0, 1));
4106        assert_eq!(CustomEvent::NoEvent, layout.tick());
4107        assert_keys(&[], layout.keycodes());
4108    }
4109
4110    #[test]
4111    fn tap_dance_uneager() {
4112        static LAYERS: Layers<2, 2> = &[[
4113            [
4114                TapDance(&crate::action::TapDance {
4115                    timeout: 100,
4116                    actions: &[
4117                        &k(LShift),
4118                        &OneShot(&crate::action::OneShot {
4119                            timeout: 100,
4120                            action: &k(LCtrl),
4121                            end_config: OneShotEndConfig::EndOnFirstPress,
4122                        }),
4123                        &HoldTap(&HoldTapAction {
4124                            on_press_reset_timeout_to: None,
4125                            require_prior_idle: None,
4126                            timeout: 100,
4127                            hold: k(LAlt),
4128                            timeout_action: k(LAlt),
4129                            tap: k(Space),
4130                            config: HoldTapConfig::Default,
4131                            tap_hold_interval: 0,
4132                        }),
4133                    ],
4134                    config: TapDanceConfig::Lazy,
4135                }),
4136                k(A),
4137            ],
4138            [k(B), k(C)],
4139        ]];
4140        let mut layout = Layout::new(LAYERS);
4141
4142        // Test: tap-dance first key, timeout
4143        layout.event(Press(0, 0));
4144        for _ in 0..100 {
4145            assert_eq!(CustomEvent::NoEvent, layout.tick());
4146            assert_keys(&[], layout.keycodes());
4147        }
4148        assert_eq!(CustomEvent::NoEvent, layout.tick());
4149        assert_keys(&[LShift], layout.keycodes());
4150        layout.event(Release(0, 0));
4151        assert_eq!(CustomEvent::NoEvent, layout.tick());
4152        assert_keys(&[], layout.keycodes());
4153
4154        // Test: tap-dance first key, press another key
4155        layout.event(Press(0, 0));
4156        assert_eq!(CustomEvent::NoEvent, layout.tick());
4157        assert_keys(&[], layout.keycodes());
4158        layout.event(Press(0, 1));
4159        assert_eq!(CustomEvent::NoEvent, layout.tick());
4160        assert_keys(&[LShift], layout.keycodes());
4161        layout.event(Release(0, 0));
4162        assert_keys(&[LShift], layout.keycodes());
4163        layout.event(Release(0, 1));
4164        assert_eq!(CustomEvent::NoEvent, layout.tick());
4165        assert_keys(&[LShift, A], layout.keycodes());
4166        assert_eq!(CustomEvent::NoEvent, layout.tick());
4167        assert_keys(&[A], layout.keycodes());
4168        assert_eq!(CustomEvent::NoEvent, layout.tick());
4169        assert_keys(&[], layout.keycodes());
4170
4171        // Test: tap-dance second key, timeout
4172        layout.event(Press(0, 0));
4173        assert_eq!(CustomEvent::NoEvent, layout.tick());
4174        assert_keys(&[], layout.keycodes());
4175        layout.event(Release(0, 0));
4176        for _ in 0..50 {
4177            assert_eq!(CustomEvent::NoEvent, layout.tick());
4178            assert_keys(&[], layout.keycodes());
4179        }
4180        layout.event(Press(0, 0));
4181        assert_eq!(CustomEvent::NoEvent, layout.tick());
4182        assert_keys(&[], layout.keycodes());
4183        layout.event(Release(0, 0));
4184        for _ in 0..99 {
4185            assert_eq!(CustomEvent::NoEvent, layout.tick());
4186            assert_keys(&[], layout.keycodes());
4187        }
4188        for _ in 0..100 {
4189            assert_eq!(CustomEvent::NoEvent, layout.tick());
4190            assert_keys(&[LCtrl], layout.keycodes());
4191        }
4192        assert_eq!(CustomEvent::NoEvent, layout.tick());
4193        assert_keys(&[], layout.keycodes());
4194
4195        // Test: tap-dance third key, timeout, tap
4196        layout.event(Press(0, 0));
4197        assert_eq!(CustomEvent::NoEvent, layout.tick());
4198        assert_keys(&[], layout.keycodes());
4199        layout.event(Release(0, 0));
4200        for _ in 0..50 {
4201            assert_eq!(CustomEvent::NoEvent, layout.tick());
4202            assert_keys(&[], layout.keycodes());
4203        }
4204        layout.event(Press(0, 0));
4205        assert_eq!(CustomEvent::NoEvent, layout.tick());
4206        assert_keys(&[], layout.keycodes());
4207        layout.event(Release(0, 0));
4208        for _ in 0..50 {
4209            assert_eq!(CustomEvent::NoEvent, layout.tick());
4210            assert_keys(&[], layout.keycodes());
4211        }
4212        layout.event(Press(0, 0));
4213        assert_eq!(CustomEvent::NoEvent, layout.tick());
4214        assert_keys(&[], layout.keycodes());
4215        layout.event(Release(0, 0));
4216        assert_eq!(CustomEvent::NoEvent, layout.tick());
4217        assert_keys(&[Space], layout.keycodes());
4218        assert_eq!(CustomEvent::NoEvent, layout.tick());
4219        assert_keys(&[], layout.keycodes());
4220
4221        // Test: tap-dance third key, timeout, hold
4222        layout.event(Press(0, 0));
4223        assert_eq!(CustomEvent::NoEvent, layout.tick());
4224        assert_keys(&[], layout.keycodes());
4225        layout.event(Release(0, 0));
4226        for _ in 0..50 {
4227            assert_eq!(CustomEvent::NoEvent, layout.tick());
4228            assert_keys(&[], layout.keycodes());
4229        }
4230        layout.event(Press(0, 0));
4231        assert_eq!(CustomEvent::NoEvent, layout.tick());
4232        assert_keys(&[], layout.keycodes());
4233        layout.event(Release(0, 0));
4234        for _ in 0..50 {
4235            assert_eq!(CustomEvent::NoEvent, layout.tick());
4236            assert_keys(&[], layout.keycodes());
4237        }
4238        layout.event(Press(0, 0));
4239        for _ in 0..100 {
4240            assert_eq!(CustomEvent::NoEvent, layout.tick());
4241            assert_keys(&[], layout.keycodes());
4242        }
4243        for _ in 0..200 {
4244            assert_eq!(CustomEvent::NoEvent, layout.tick());
4245            assert_keys(&[LAlt], layout.keycodes());
4246        }
4247        layout.event(Release(0, 0));
4248        assert_eq!(CustomEvent::NoEvent, layout.tick());
4249        assert_keys(&[], layout.keycodes());
4250    }
4251
4252    #[test]
4253    fn tap_dance_eager() {
4254        static LAYERS: Layers<2, 2> = &[[
4255            [
4256                TapDance(&crate::action::TapDance {
4257                    timeout: 100,
4258                    actions: &[&k(Kb1), &k(Kb2), &k(Kb3)],
4259                    config: TapDanceConfig::Eager,
4260                }),
4261                k(A),
4262            ],
4263            [k(B), k(C)],
4264        ]];
4265        let mut layout = Layout::new(LAYERS);
4266
4267        // Test: tap-dance-eager first key
4268        layout.event(Press(0, 0));
4269        assert_eq!(CustomEvent::NoEvent, layout.tick());
4270        assert_keys(&[Kb1], layout.keycodes());
4271        for _ in 0..200 {
4272            assert_eq!(CustomEvent::NoEvent, layout.tick());
4273            assert_keys(&[Kb1], layout.keycodes());
4274        }
4275        layout.event(Release(0, 0));
4276        assert_eq!(CustomEvent::NoEvent, layout.tick());
4277        assert_keys(&[], layout.keycodes());
4278
4279        // Test: tap-dance-eager first key, press another key
4280        layout.event(Press(0, 0));
4281        assert_eq!(CustomEvent::NoEvent, layout.tick());
4282        assert_keys(&[Kb1], layout.keycodes());
4283        layout.event(Press(0, 1));
4284        assert_eq!(CustomEvent::NoEvent, layout.tick());
4285        assert_keys(&[Kb1, A], layout.keycodes());
4286        layout.event(Release(0, 0));
4287        assert_keys(&[Kb1, A], layout.keycodes());
4288        layout.event(Release(0, 1));
4289        assert_eq!(CustomEvent::NoEvent, layout.tick());
4290        assert_keys(&[A], layout.keycodes());
4291        assert_eq!(CustomEvent::NoEvent, layout.tick());
4292        assert_keys(&[], layout.keycodes());
4293
4294        // Test: tap-dance second key
4295        layout.event(Press(0, 0));
4296        assert_eq!(CustomEvent::NoEvent, layout.tick());
4297        assert_keys(&[Kb1], layout.keycodes());
4298        layout.event(Release(0, 0));
4299        for _ in 0..50 {
4300            assert_eq!(CustomEvent::NoEvent, layout.tick());
4301            assert_keys(&[], layout.keycodes());
4302        }
4303        layout.event(Press(0, 0));
4304        assert_eq!(CustomEvent::NoEvent, layout.tick());
4305        assert_keys(&[Kb2], layout.keycodes());
4306        layout.event(Release(0, 0));
4307        for _ in 0..99 {
4308            assert_eq!(CustomEvent::NoEvent, layout.tick());
4309            assert_keys(&[], layout.keycodes());
4310        }
4311        assert_eq!(CustomEvent::NoEvent, layout.tick());
4312        assert_keys(&[], layout.keycodes());
4313
4314        // Test: tap-dance third key
4315        layout.event(Press(0, 0));
4316        assert_eq!(CustomEvent::NoEvent, layout.tick());
4317        assert_keys(&[Kb1], layout.keycodes());
4318        layout.event(Release(0, 0));
4319        for _ in 0..50 {
4320            assert_eq!(CustomEvent::NoEvent, layout.tick());
4321            assert_keys(&[], layout.keycodes());
4322        }
4323        layout.event(Press(0, 0));
4324        assert_eq!(CustomEvent::NoEvent, layout.tick());
4325        assert_keys(&[Kb2], layout.keycodes());
4326        layout.event(Release(0, 0));
4327        for _ in 0..50 {
4328            assert_eq!(CustomEvent::NoEvent, layout.tick());
4329            assert_keys(&[], layout.keycodes());
4330        }
4331        layout.event(Press(0, 0));
4332        assert_eq!(CustomEvent::NoEvent, layout.tick());
4333        assert_keys(&[Kb3], layout.keycodes());
4334        layout.event(Release(0, 0));
4335        assert_eq!(CustomEvent::NoEvent, layout.tick());
4336        assert_keys(&[], layout.keycodes());
4337    }
4338
4339    #[test]
4340    fn release_state() {
4341        static LAYERS: Layers<2, 1> = &[
4342            [[
4343                MultipleActions(&(&[KeyCode(LCtrl), Layer(1)] as _)),
4344                MultipleActions(&(&[KeyCode(LAlt), Layer(1)] as _)),
4345            ]],
4346            [[
4347                MultipleActions(
4348                    &(&[ReleaseState(ReleasableState::KeyCode(LAlt)), KeyCode(Space)] as _),
4349                ),
4350                ReleaseState(ReleasableState::Layer(1)),
4351            ]],
4352        ];
4353
4354        let mut layout = Layout::new(LAYERS);
4355
4356        layout.event(Press(0, 1));
4357        assert_eq!(CustomEvent::NoEvent, layout.tick());
4358        assert_keys(&[LAlt], layout.keycodes());
4359        assert_eq!(1, layout.current_layer());
4360        layout.event(Press(0, 0));
4361        assert_eq!(CustomEvent::NoEvent, layout.tick());
4362        assert_keys(&[Space], layout.keycodes());
4363        layout.event(Release(0, 0));
4364        assert_eq!(CustomEvent::NoEvent, layout.tick());
4365        assert_keys(&[], layout.keycodes());
4366        layout.event(Release(0, 1));
4367        assert_eq!(CustomEvent::NoEvent, layout.tick());
4368        assert_keys(&[], layout.keycodes());
4369
4370        layout.event(Press(0, 0));
4371        assert_eq!(CustomEvent::NoEvent, layout.tick());
4372        assert_keys(&[LCtrl], layout.keycodes());
4373        assert_eq!(1, layout.current_layer());
4374        layout.event(Press(0, 1));
4375        assert_eq!(CustomEvent::NoEvent, layout.tick());
4376        assert_eq!(0, layout.current_layer());
4377        assert_keys(&[LCtrl], layout.keycodes());
4378        layout.event(Release(0, 1));
4379        assert_eq!(CustomEvent::NoEvent, layout.tick());
4380        assert_keys(&[LCtrl], layout.keycodes());
4381        layout.event(Release(0, 0));
4382        assert_eq!(CustomEvent::NoEvent, layout.tick());
4383        assert_keys(&[], layout.keycodes());
4384    }
4385
4386    #[test]
4387    fn test_chord() {
4388        const GROUP: ChordsGroup<core::convert::Infallible> = ChordsGroup {
4389            coords: &[((0, 2), 1), ((0, 3), 2), ((0, 4), 4), ((0, 5), 8)],
4390            chords: &[
4391                (1, &KeyCode(Kb1)),
4392                (2, &KeyCode(Kb2)),
4393                (4, &KeyCode(Kb3)),
4394                (8, &KeyCode(Kb4)),
4395                (3, &KeyCode(Kb5)),
4396                (11, &KeyCode(Kb6)),
4397            ],
4398            timeout: 100,
4399        };
4400        static LAYERS: Layers<6, 1> = &[[[
4401            NoOp,
4402            NoOp,
4403            Chords(&GROUP),
4404            Chords(&GROUP),
4405            Chords(&GROUP),
4406            Chords(&GROUP),
4407        ]]];
4408
4409        let mut layout = Layout::new(LAYERS);
4410        layout.event(Press(0, 2));
4411        // timeout on non-terminal chord
4412        for _ in 0..50 {
4413            assert_eq!(CustomEvent::NoEvent, layout.tick());
4414            assert_keys(&[], layout.keycodes());
4415        }
4416        layout.event(Press(0, 3));
4417        for _ in 0..49 {
4418            assert_eq!(CustomEvent::NoEvent, layout.tick());
4419            assert_keys(&[], layout.keycodes());
4420        }
4421        assert_eq!(CustomEvent::NoEvent, layout.tick());
4422        assert_keys(&[Kb5], layout.keycodes());
4423        layout.event(Release(0, 2));
4424        assert_eq!(CustomEvent::NoEvent, layout.tick());
4425        assert_keys(&[Kb5], layout.keycodes());
4426        layout.event(Release(0, 3));
4427        assert_eq!(CustomEvent::NoEvent, layout.tick());
4428        assert_keys(&[], layout.keycodes());
4429
4430        // timeout on terminal chord with no action associated
4431        // combo like (h j k) -> (h j) (k)
4432        layout.event(Press(0, 2));
4433        for _ in 0..50 {
4434            assert_eq!(CustomEvent::NoEvent, layout.tick());
4435            assert_keys(&[], layout.keycodes());
4436        }
4437        layout.event(Press(0, 3));
4438        for _ in 0..30 {
4439            assert_eq!(CustomEvent::NoEvent, layout.tick());
4440            assert_keys(&[], layout.keycodes());
4441        }
4442        layout.event(Press(0, 4));
4443        for _ in 0..20 {
4444            assert_eq!(CustomEvent::NoEvent, layout.tick());
4445            assert_keys(&[], layout.keycodes());
4446        }
4447        assert_eq!(CustomEvent::NoEvent, layout.tick());
4448        assert_keys(&[Kb5], layout.keycodes());
4449        assert_eq!(CustomEvent::NoEvent, layout.tick());
4450        assert_keys(&[Kb5, Kb3], layout.keycodes());
4451        layout.event(Release(0, 2));
4452        assert_eq!(CustomEvent::NoEvent, layout.tick());
4453        assert_keys(&[Kb3], layout.keycodes());
4454        layout.event(Release(0, 3));
4455        assert_eq!(CustomEvent::NoEvent, layout.tick());
4456        assert_keys(&[Kb3], layout.keycodes());
4457        layout.event(Release(0, 4));
4458        assert_eq!(CustomEvent::NoEvent, layout.tick());
4459        assert_keys(&[], layout.keycodes());
4460
4461        // release terminal chord with no action associated
4462        // combo like (h j k) -> (h j) (k)
4463        layout.event(Press(0, 2));
4464        for _ in 0..50 {
4465            assert_eq!(CustomEvent::NoEvent, layout.tick());
4466            assert_keys(&[], layout.keycodes());
4467        }
4468        layout.event(Press(0, 3));
4469        for _ in 0..30 {
4470            assert_eq!(CustomEvent::NoEvent, layout.tick());
4471            assert_keys(&[], layout.keycodes());
4472        }
4473        layout.event(Press(0, 4));
4474        assert_eq!(CustomEvent::NoEvent, layout.tick());
4475        assert_keys(&[], layout.keycodes());
4476        layout.event(Release(0, 4));
4477        assert_eq!(CustomEvent::NoEvent, layout.tick());
4478        assert_keys(&[], layout.keycodes());
4479        assert_eq!(CustomEvent::NoEvent, layout.tick());
4480        assert_keys(&[Kb5], layout.keycodes());
4481        assert_eq!(CustomEvent::NoEvent, layout.tick());
4482        assert_keys(&[Kb5, Kb3], layout.keycodes());
4483        assert_eq!(CustomEvent::NoEvent, layout.tick());
4484        assert_keys(&[Kb5], layout.keycodes());
4485        layout.event(Release(0, 2));
4486        layout.event(Release(0, 3));
4487        assert_eq!(CustomEvent::NoEvent, layout.tick());
4488        assert_keys(&[], layout.keycodes());
4489        assert_eq!(CustomEvent::NoEvent, layout.tick());
4490        assert_keys(&[], layout.keycodes());
4491
4492        // release terminal chord with no action associated
4493        // Test combo like (h j k l) -> (h) (j k l)
4494        layout.event(Press(0, 4));
4495        layout.event(Press(0, 2));
4496        layout.event(Press(0, 3));
4497        layout.event(Press(0, 5));
4498        assert_eq!(CustomEvent::NoEvent, layout.tick());
4499        assert_keys(&[], layout.keycodes());
4500        for _ in 0..30 {
4501            assert_eq!(CustomEvent::NoEvent, layout.tick());
4502            assert_keys(&[], layout.keycodes());
4503        }
4504        layout.event(Release(0, 2));
4505        assert_eq!(CustomEvent::NoEvent, layout.tick());
4506        assert_keys(&[], layout.keycodes());
4507        assert_eq!(CustomEvent::NoEvent, layout.tick());
4508        assert_keys(&[Kb3], layout.keycodes());
4509        assert_eq!(CustomEvent::NoEvent, layout.tick());
4510        assert_keys(&[Kb3, Kb6], layout.keycodes());
4511        assert_eq!(CustomEvent::NoEvent, layout.tick());
4512        assert_keys(&[Kb3], layout.keycodes());
4513    }
4514
4515    #[test]
4516    fn test_chord_normalkey_order() {
4517        const GROUP: ChordsGroup<core::convert::Infallible> = ChordsGroup {
4518            coords: &[((0, 2), 1), ((0, 3), 2), ((0, 4), 4), ((0, 5), 8)],
4519            chords: &[
4520                (1, &KeyCode(Kb1)),
4521                (2, &KeyCode(Kb2)),
4522                (4, &KeyCode(Kb3)),
4523                (8, &KeyCode(Kb4)),
4524                (3, &KeyCode(Kb5)),
4525                (11, &KeyCode(Kb6)),
4526            ],
4527            timeout: 100,
4528        };
4529        static LAYERS: Layers<6, 1> = &[[[
4530            NoOp,
4531            k(A),
4532            Chords(&GROUP),
4533            Chords(&GROUP),
4534            Chords(&GROUP),
4535            Chords(&GROUP),
4536        ]]];
4537
4538        let mut layout = Layout::new(LAYERS);
4539        layout.event(Press(0, 2));
4540        // timeout on non-terminal chord
4541        for _ in 0..50 {
4542            assert_eq!(CustomEvent::NoEvent, layout.tick());
4543            assert_keys(&[], layout.keycodes());
4544        }
4545        layout.event(Press(0, 1));
4546        assert_eq!(CustomEvent::NoEvent, layout.tick());
4547        assert_keys(&[Kb1], layout.keycodes());
4548        assert_eq!(CustomEvent::NoEvent, layout.tick());
4549        assert_keys(&[Kb1, A], layout.keycodes());
4550        layout.event(Release(0, 1));
4551        assert_eq!(CustomEvent::NoEvent, layout.tick());
4552        assert_keys(&[Kb1], layout.keycodes());
4553        layout.event(Release(0, 2));
4554        assert_eq!(CustomEvent::NoEvent, layout.tick());
4555        assert_keys(&[], layout.keycodes());
4556    }
4557
4558    #[test]
4559    fn test_chord_multi_waiting_decomposition() {
4560        const GROUP: ChordsGroup<core::convert::Infallible> = ChordsGroup {
4561            coords: &[((0, 0), 1), ((0, 1), 2)],
4562            chords: &[
4563                (
4564                    1,
4565                    &HoldTap(&HoldTapAction {
4566                        on_press_reset_timeout_to: None,
4567                        require_prior_idle: None,
4568                        timeout: 100,
4569                        hold: k(A),
4570                        timeout_action: k(A),
4571                        tap: k(Kb1),
4572                        config: HoldTapConfig::Default,
4573                        tap_hold_interval: 0,
4574                    }),
4575                ),
4576                (
4577                    2,
4578                    &HoldTap(&HoldTapAction {
4579                        on_press_reset_timeout_to: None,
4580                        require_prior_idle: None,
4581                        timeout: 100,
4582                        hold: k(B),
4583                        timeout_action: k(B),
4584                        tap: k(Kb2),
4585                        config: HoldTapConfig::Default,
4586                        tap_hold_interval: 0,
4587                    }),
4588                ),
4589            ],
4590            timeout: 100,
4591        };
4592        static LAYERS: Layers<2, 1> = &[[[Chords(&GROUP), Chords(&GROUP)]]];
4593
4594        let mut layout = Layout::new(LAYERS);
4595        layout.quick_tap_hold_timeout = true;
4596        layout.event(Press(0, 0));
4597        layout.event(Press(0, 1));
4598        // Why does this take 103 ticks?
4599        // 0: chord begin
4600        // 1: chord decompose
4601        // 2: action queue dequeue
4602        // 3: action queue dequeue
4603        // 4-103: timeout ticks
4604        for _ in 0..102 {
4605            assert_eq!(CustomEvent::NoEvent, layout.tick());
4606            assert_keys(&[], layout.keycodes());
4607        }
4608        assert_eq!(CustomEvent::NoEvent, layout.tick());
4609        assert_keys(&[A, B], layout.keycodes());
4610        layout.event(Release(0, 0));
4611        layout.event(Release(0, 1));
4612        assert_eq!(CustomEvent::NoEvent, layout.tick());
4613        assert_keys(&[B], layout.keycodes());
4614        assert_eq!(CustomEvent::NoEvent, layout.tick());
4615        assert_keys(&[], layout.keycodes());
4616    }
4617
4618    #[test]
4619    fn test_fork() {
4620        static LAYERS: Layers<2, 1> = &[[[
4621            Fork(&ForkConfig {
4622                left: k(Kb1),
4623                right: k(Kb2),
4624                right_triggers: &[Space],
4625            }),
4626            k(Space),
4627        ]]];
4628        let mut layout = Layout::new(LAYERS);
4629
4630        layout.event(Press(0, 0));
4631        assert_eq!(CustomEvent::NoEvent, layout.tick());
4632        assert_keys(&[Kb1], layout.keycodes());
4633        layout.event(Release(0, 0));
4634        assert_eq!(CustomEvent::NoEvent, layout.tick());
4635        assert_keys(&[], layout.keycodes());
4636
4637        layout.event(Press(0, 1));
4638        layout.event(Press(0, 0));
4639        assert_eq!(CustomEvent::NoEvent, layout.tick());
4640        assert_keys(&[Space], layout.keycodes());
4641        assert_eq!(CustomEvent::NoEvent, layout.tick());
4642        assert_keys(&[Space, Kb2], layout.keycodes());
4643        layout.event(Release(0, 1));
4644        layout.event(Release(0, 0));
4645        assert_eq!(CustomEvent::NoEvent, layout.tick());
4646        assert_keys(&[Kb2], layout.keycodes());
4647        assert_eq!(CustomEvent::NoEvent, layout.tick());
4648        assert_keys(&[], layout.keycodes());
4649    }
4650
4651    #[test]
4652    fn test_repeat() {
4653        static LAYERS: Layers<5, 1> = &[
4654            [[
4655                k(A),
4656                MultipleKeyCodes(&[LShift, B].as_slice()),
4657                Repeat,
4658                MultipleActions(&[k(C), k(D)].as_slice()),
4659                Layer(1),
4660            ]],
4661            [[
4662                k(E),
4663                MultipleKeyCodes(&[LShift, F].as_slice()),
4664                Repeat,
4665                MultipleActions(&[k(G), k(H)].as_slice()),
4666                Layer(1),
4667            ]],
4668        ];
4669        let mut layout = Layout::new(LAYERS);
4670
4671        // Press a key
4672        layout.event(Press(0, 0));
4673        assert_eq!(CustomEvent::NoEvent, layout.tick());
4674        assert_keys(&[A], layout.keycodes());
4675        layout.event(Release(0, 0));
4676        assert_eq!(CustomEvent::NoEvent, layout.tick());
4677        assert_keys(&[], layout.keycodes());
4678
4679        // Repeat it, should be the same
4680        layout.event(Press(0, 2));
4681        assert_eq!(CustomEvent::NoEvent, layout.tick());
4682        assert_keys(&[A], layout.keycodes());
4683        layout.event(Release(0, 2));
4684        assert_eq!(CustomEvent::NoEvent, layout.tick());
4685        assert_keys(&[], layout.keycodes());
4686
4687        // Press a chord
4688        layout.event(Press(0, 1));
4689        assert_eq!(CustomEvent::NoEvent, layout.tick());
4690        assert_keys(&[LShift, B], layout.keycodes());
4691        layout.event(Release(0, 1));
4692        assert_eq!(CustomEvent::NoEvent, layout.tick());
4693        assert_keys(&[], layout.keycodes());
4694
4695        // Repeat it, should be the same
4696        layout.event(Press(0, 2));
4697        assert_eq!(CustomEvent::NoEvent, layout.tick());
4698        assert_keys(&[LShift, B], layout.keycodes());
4699        layout.event(Release(0, 2));
4700        assert_eq!(CustomEvent::NoEvent, layout.tick());
4701        assert_keys(&[], layout.keycodes());
4702
4703        // Press a multiple action
4704        layout.event(Press(0, 3));
4705        assert_eq!(CustomEvent::NoEvent, layout.tick());
4706        assert_keys(&[C, D], layout.keycodes());
4707        layout.event(Release(0, 3));
4708        assert_eq!(CustomEvent::NoEvent, layout.tick());
4709        assert_keys(&[], layout.keycodes());
4710
4711        // Repeat it, should be the same
4712        layout.event(Press(0, 2));
4713        assert_eq!(CustomEvent::NoEvent, layout.tick());
4714        assert_keys(&[C, D], layout.keycodes());
4715        layout.event(Release(0, 2));
4716        assert_eq!(CustomEvent::NoEvent, layout.tick());
4717        assert_keys(&[], layout.keycodes());
4718
4719        // Go to a different layer and press a key
4720        layout.event(Press(0, 4));
4721        assert_eq!(CustomEvent::NoEvent, layout.tick());
4722        assert_keys(&[], layout.keycodes());
4723        layout.event(Press(0, 0));
4724        assert_eq!(CustomEvent::NoEvent, layout.tick());
4725        assert_keys(&[E], layout.keycodes());
4726        layout.event(Release(0, 4));
4727        assert_eq!(CustomEvent::NoEvent, layout.tick());
4728        assert_keys(&[E], layout.keycodes());
4729        layout.event(Release(0, 0));
4730        assert_eq!(CustomEvent::NoEvent, layout.tick());
4731        assert_keys(&[], layout.keycodes());
4732
4733        // Repeat, should be the same as the other layer
4734        layout.event(Press(0, 2));
4735        assert_eq!(CustomEvent::NoEvent, layout.tick());
4736        assert_keys(&[E], layout.keycodes());
4737        layout.event(Release(0, 2));
4738        assert_eq!(CustomEvent::NoEvent, layout.tick());
4739        assert_keys(&[], layout.keycodes());
4740
4741        // Activate the layer action and press repeat there, should still be the same action
4742        layout.event(Press(0, 4));
4743        assert_eq!(CustomEvent::NoEvent, layout.tick());
4744        assert_keys(&[], layout.keycodes());
4745        layout.event(Press(0, 2));
4746        assert_eq!(CustomEvent::NoEvent, layout.tick());
4747        assert_keys(&[E], layout.keycodes());
4748        layout.event(Release(0, 2));
4749        assert_eq!(CustomEvent::NoEvent, layout.tick());
4750        assert_keys(&[], layout.keycodes());
4751        layout.event(Release(0, 4));
4752        assert_eq!(CustomEvent::NoEvent, layout.tick());
4753        assert_keys(&[], layout.keycodes());
4754    }
4755
4756    #[test]
4757    fn test_clear_multiple_keycodes() {
4758        static LAYERS: Layers<2, 1> = &[[[k(A), MultipleKeyCodes(&[LCtrl, Enter].as_slice())]]];
4759        let mut layout = Layout::new(LAYERS);
4760        layout.event(Press(0, 1));
4761        assert_eq!(CustomEvent::NoEvent, layout.tick());
4762        assert_keys(&[LCtrl, Enter], layout.keycodes());
4763        // Cancel chord keys on next keypress.
4764        layout.event(Press(0, 0));
4765        assert_eq!(CustomEvent::NoEvent, layout.tick());
4766        assert_keys(&[A], layout.keycodes());
4767    }
4768
4769    // Tests the new Trans behavior.
4770    // https://github.com/jtroo/kanata/issues/738
4771    #[test]
4772    fn test_trans_in_stacked_held_layers() {
4773        static LAYERS: Layers<4, 1> = &[
4774            [[Layer(1), NoOp, NoOp, k(A)]],
4775            [[NoOp, Layer(2), NoOp, k(B)]],
4776            [[NoOp, NoOp, Layer(3), Trans]],
4777            [[NoOp, NoOp, NoOp, Trans]],
4778        ];
4779        let mut layout = Layout::new(LAYERS);
4780
4781        // change to layer 2
4782        layout.event(Press(0, 0));
4783        assert_eq!(CustomEvent::NoEvent, layout.tick());
4784        assert_keys(&[], layout.keycodes());
4785        // change to layer 3
4786        layout.event(Press(0, 1));
4787        assert_eq!(CustomEvent::NoEvent, layout.tick());
4788        assert_keys(&[], layout.keycodes());
4789        // change to layer 4
4790        layout.event(Press(0, 2));
4791        assert_eq!(CustomEvent::NoEvent, layout.tick());
4792        assert_keys(&[], layout.keycodes());
4793        // pressing Trans should press a key in layer 2, compared to previous behavior,
4794        // where a key in layer 1 would be pressed
4795        layout.event(Press(0, 3));
4796        assert_eq!(CustomEvent::NoEvent, layout.tick());
4797        assert_keys(&[B], layout.keycodes());
4798        layout.event(Release(0, 3));
4799        assert_eq!(CustomEvent::NoEvent, layout.tick());
4800        assert_keys(&[], layout.keycodes());
4801    }
4802
4803    #[test]
4804    fn test_trans_in_action_on_first_layer() {
4805        static DEFSRC_LAYER: [Action; 2] = [NoOp, k(X)];
4806        static LAYERS: Layers<2, 1> = &[
4807            [[Layer(1), Trans]],
4808            [[NoOp, MultipleActions(&[Trans].as_slice())]],
4809        ];
4810        let mut layout = Layout::new_with_trans_action_settings(&DEFSRC_LAYER, LAYERS, true, true);
4811
4812        layout.event(Press(0, 0));
4813        assert_eq!(CustomEvent::NoEvent, layout.tick());
4814        assert_keys(&[], layout.keycodes());
4815        layout.event(Press(0, 1));
4816        assert_eq!(CustomEvent::NoEvent, layout.tick());
4817        assert_keys(&[X], layout.keycodes());
4818        layout.event(Release(0, 1));
4819        assert_eq!(CustomEvent::NoEvent, layout.tick());
4820        assert_keys(&[], layout.keycodes());
4821    }
4822
4823    #[test]
4824    fn test_trans_in_taphold_tap() {
4825        static LAYERS: Layers<3, 1> = &[
4826            [[Layer(1), NoOp, k(A)]],
4827            [[NoOp, Layer(2), k(B)]],
4828            [[
4829                NoOp,
4830                NoOp,
4831                HoldTap(&HoldTapAction {
4832                    on_press_reset_timeout_to: None,
4833                    require_prior_idle: None,
4834                    timeout: 50,
4835                    hold: k(Space),
4836                    timeout_action: k(Space),
4837                    tap: Trans,
4838                    config: HoldTapConfig::Default,
4839                    tap_hold_interval: 200,
4840                }),
4841            ]],
4842        ];
4843        let mut layout = Layout::new(LAYERS);
4844
4845        layout.event(Press(0, 0));
4846        assert_eq!(CustomEvent::NoEvent, layout.tick());
4847        assert_keys(&[], layout.keycodes());
4848        layout.event(Press(0, 1));
4849        assert_eq!(CustomEvent::NoEvent, layout.tick());
4850        assert_keys(&[], layout.keycodes());
4851        layout.event(Press(0, 2)); // press th
4852        for _ in 0..10 {
4853            assert_eq!(CustomEvent::NoEvent, layout.tick());
4854            assert_keys(&[], layout.keycodes());
4855        }
4856        layout.event(Release(0, 2)); // release th
4857        assert_eq!(CustomEvent::NoEvent, layout.tick());
4858        assert_keys(&[B], layout.keycodes()); // B is resolved from Trans
4859        assert_eq!(CustomEvent::NoEvent, layout.tick());
4860        assert_keys(&[], layout.keycodes());
4861        // test tap action repeat
4862        layout.event(Press(0, 2));
4863        for _ in 0..30 {
4864            assert_eq!(CustomEvent::NoEvent, layout.tick());
4865            assert_keys(&[B], layout.keycodes());
4866        }
4867        layout.event(Release(0, 2));
4868        assert_eq!(CustomEvent::NoEvent, layout.tick());
4869        assert_keys(&[], layout.keycodes());
4870    }
4871
4872    #[test]
4873    fn test_trans_in_taphold_hold() {
4874        static LAYERS: Layers<3, 1> = &[
4875            [[Layer(1), NoOp, k(A)]],
4876            [[NoOp, Layer(2), k(B)]],
4877            [[
4878                NoOp,
4879                NoOp,
4880                HoldTap(&HoldTapAction {
4881                    on_press_reset_timeout_to: None,
4882                    require_prior_idle: None,
4883                    timeout: 50,
4884                    hold: Trans,
4885                    timeout_action: Trans,
4886                    tap: k(Space),
4887                    config: HoldTapConfig::Default,
4888                    tap_hold_interval: 200,
4889                }),
4890            ]],
4891        ];
4892        let mut layout = Layout::new(LAYERS);
4893
4894        layout.event(Press(0, 0));
4895        assert_eq!(CustomEvent::NoEvent, layout.tick());
4896        assert_keys(&[], layout.keycodes());
4897        layout.event(Press(0, 1));
4898        assert_eq!(CustomEvent::NoEvent, layout.tick());
4899        assert_keys(&[], layout.keycodes());
4900        layout.event(Press(0, 2)); // press th
4901        for _ in 0..50 {
4902            assert_eq!(CustomEvent::NoEvent, layout.tick());
4903            assert_keys(&[], layout.keycodes());
4904        }
4905        for _ in 0..70 {
4906            assert_eq!(CustomEvent::NoEvent, layout.tick());
4907            assert_keys(&[B], layout.keycodes()); // B is resolved from Trans
4908        }
4909        layout.event(Release(0, 2)); // release th
4910        assert_eq!(CustomEvent::NoEvent, layout.tick());
4911        assert_keys(&[], layout.keycodes());
4912    }
4913
4914    #[test]
4915    fn test_trans_in_tapdance_lazy() {
4916        static LAYERS: Layers<3, 1> = &[
4917            [[Layer(1), NoOp, k(A)]],
4918            [[NoOp, Layer(2), k(B)]],
4919            [[
4920                NoOp,
4921                NoOp,
4922                TapDance(&crate::action::TapDance {
4923                    timeout: 100,
4924                    actions: &[&Trans, &k(X)],
4925                    config: TapDanceConfig::Lazy,
4926                }),
4927            ]],
4928        ];
4929        let mut layout = Layout::new(LAYERS);
4930
4931        layout.event(Press(0, 0));
4932        assert_eq!(CustomEvent::NoEvent, layout.tick());
4933        assert_keys(&[], layout.keycodes());
4934        layout.event(Press(0, 1));
4935        assert_eq!(CustomEvent::NoEvent, layout.tick());
4936        assert_keys(&[], layout.keycodes());
4937        layout.event(Press(0, 2));
4938        for _ in 0..10 {
4939            assert_eq!(CustomEvent::NoEvent, layout.tick());
4940            assert_keys(&[], layout.keycodes());
4941        }
4942        layout.event(Release(0, 2));
4943        for _ in 0..90 {
4944            assert_eq!(CustomEvent::NoEvent, layout.tick());
4945            assert_keys(&[], layout.keycodes());
4946        }
4947        assert_eq!(CustomEvent::NoEvent, layout.tick());
4948        assert_keys(&[B], layout.keycodes());
4949        assert_eq!(CustomEvent::NoEvent, layout.tick());
4950        assert_keys(&[], layout.keycodes());
4951    }
4952
4953    #[test]
4954    fn test_trans_in_tapdance_eager() {
4955        static LAYERS: Layers<3, 1> = &[
4956            [[Layer(1), NoOp, k(A)]],
4957            [[NoOp, Layer(2), k(B)]],
4958            [[
4959                NoOp,
4960                NoOp,
4961                TapDance(&crate::action::TapDance {
4962                    timeout: 100,
4963                    actions: &[&Trans, &k(X)],
4964                    config: TapDanceConfig::Eager,
4965                }),
4966            ]],
4967        ];
4968        let mut layout = Layout::new(LAYERS);
4969
4970        layout.event(Press(0, 0));
4971        assert_eq!(CustomEvent::NoEvent, layout.tick());
4972        assert_keys(&[], layout.keycodes());
4973        layout.event(Press(0, 1));
4974        assert_eq!(CustomEvent::NoEvent, layout.tick());
4975        assert_keys(&[], layout.keycodes());
4976        layout.event(Press(0, 2));
4977        for _ in 0..10 {
4978            assert_eq!(CustomEvent::NoEvent, layout.tick());
4979            assert_keys(&[B], layout.keycodes());
4980        }
4981        layout.event(Release(0, 2));
4982        assert_eq!(CustomEvent::NoEvent, layout.tick());
4983        assert_keys(&[], layout.keycodes());
4984    }
4985
4986    #[test]
4987    fn test_trans_in_multi() {
4988        static LAYERS: Layers<3, 1> = &[
4989            [[Layer(1), NoOp, k(A)]],
4990            [[NoOp, Layer(2), k(B)]],
4991            [[NoOp, NoOp, MultipleActions(&[Trans, k(X)].as_slice())]],
4992        ];
4993        let mut layout = Layout::new(LAYERS);
4994
4995        layout.event(Press(0, 0));
4996        assert_eq!(CustomEvent::NoEvent, layout.tick());
4997        assert_keys(&[], layout.keycodes());
4998        layout.event(Press(0, 1));
4999        assert_eq!(CustomEvent::NoEvent, layout.tick());
5000        assert_keys(&[], layout.keycodes());
5001        layout.event(Press(0, 2));
5002        for _ in 0..10 {
5003            assert_eq!(CustomEvent::NoEvent, layout.tick());
5004            assert_keys(&[B, X], layout.keycodes());
5005        }
5006        layout.event(Release(0, 2));
5007        assert_eq!(CustomEvent::NoEvent, layout.tick());
5008        assert_keys(&[], layout.keycodes());
5009    }
5010
5011    #[test]
5012    fn test_trans_in_chords() {
5013        const GROUP: ChordsGroup<core::convert::Infallible> = ChordsGroup {
5014            coords: &[((0, 2), 1), ((0, 3), 2)],
5015            chords: &[(1, &Trans), (2, &Trans), (3, &KeyCode(X))],
5016            timeout: 100,
5017        };
5018        static LAYERS: Layers<4, 1> = &[
5019            [[Layer(1), NoOp, k(A), k(B)]],
5020            [[NoOp, Layer(2), k(C), k(D)]],
5021            [[NoOp, NoOp, Chords(&GROUP), Chords(&GROUP)]],
5022        ];
5023        let mut layout = Layout::new(LAYERS);
5024
5025        layout.event(Press(0, 0));
5026        assert_eq!(CustomEvent::NoEvent, layout.tick());
5027        assert_keys(&[], layout.keycodes());
5028        layout.event(Press(0, 1));
5029        assert_eq!(CustomEvent::NoEvent, layout.tick());
5030        assert_keys(&[], layout.keycodes());
5031        layout.event(Press(0, 2));
5032        for _ in 0..10 {
5033            assert_eq!(CustomEvent::NoEvent, layout.tick());
5034            assert_keys(&[], layout.keycodes());
5035        }
5036        layout.event(Release(0, 2));
5037        assert_eq!(CustomEvent::NoEvent, layout.tick());
5038        assert_keys(&[C], layout.keycodes());
5039        assert_eq!(CustomEvent::NoEvent, layout.tick());
5040        assert_keys(&[], layout.keycodes());
5041    }
5042
5043    #[test]
5044    fn test_trans_in_fork() {
5045        static LAYERS: Layers<3, 1> = &[
5046            [[Layer(1), NoOp, k(A)]],
5047            [[NoOp, Layer(2), k(B)]],
5048            [[
5049                NoOp,
5050                NoOp,
5051                Fork(&ForkConfig {
5052                    left: Trans,
5053                    right: Trans,
5054                    right_triggers: &[Space],
5055                }),
5056            ]],
5057        ];
5058        let mut layout = Layout::new(LAYERS);
5059
5060        layout.event(Press(0, 0));
5061        assert_eq!(CustomEvent::NoEvent, layout.tick());
5062        assert_keys(&[], layout.keycodes());
5063        layout.event(Press(0, 1));
5064        assert_eq!(CustomEvent::NoEvent, layout.tick());
5065        assert_keys(&[], layout.keycodes());
5066        layout.event(Press(0, 2));
5067        assert_eq!(CustomEvent::NoEvent, layout.tick());
5068        assert_keys(&[B], layout.keycodes());
5069        layout.event(Release(0, 2));
5070        assert_eq!(CustomEvent::NoEvent, layout.tick());
5071        assert_keys(&[], layout.keycodes());
5072    }
5073
5074    #[test]
5075    fn test_trans_in_switch() {
5076        static LAYERS: Layers<3, 1> = &[
5077            [[Layer(1), NoOp, k(A)]],
5078            [[NoOp, Layer(2), k(B)]],
5079            [[
5080                NoOp,
5081                NoOp,
5082                Switch(&switch::Switch {
5083                    cases: &[(&[], &Trans, BreakOrFallthrough::Break)],
5084                    init_fn: None,
5085                    callbacks: &[],
5086                }),
5087            ]],
5088        ];
5089        let mut layout = Layout::new(LAYERS);
5090        layout.trans_resolution_behavior_v2 = true;
5091
5092        layout.event(Press(0, 0));
5093        assert_eq!(CustomEvent::NoEvent, layout.tick());
5094        assert_keys(&[], layout.keycodes());
5095        layout.event(Press(0, 1));
5096        assert_eq!(CustomEvent::NoEvent, layout.tick());
5097        assert_keys(&[], layout.keycodes());
5098
5099        layout.event(Press(0, 2));
5100        assert_eq!(CustomEvent::NoEvent, layout.tick());
5101        assert_keys(&[B], layout.keycodes());
5102
5103        layout.event(Release(0, 2));
5104        assert_eq!(CustomEvent::NoEvent, layout.tick());
5105        assert_keys(&[], layout.keycodes());
5106    }
5107
5108    #[test]
5109    fn test_multiple_taphold_trans() {
5110        static LAYERS: Layers<4, 1> = &[
5111            [[Layer(1), NoOp, NoOp, k(A)]],
5112            [[
5113                NoOp,
5114                Layer(2),
5115                NoOp,
5116                HoldTap(&HoldTapAction {
5117                    on_press_reset_timeout_to: None,
5118                    require_prior_idle: None,
5119                    timeout: 50,
5120                    hold: k(B),
5121                    timeout_action: k(B),
5122                    tap: Trans,
5123                    config: HoldTapConfig::Default,
5124                    tap_hold_interval: 200,
5125                }),
5126            ]],
5127            [[
5128                NoOp,
5129                NoOp,
5130                Layer(3),
5131                HoldTap(&HoldTapAction {
5132                    on_press_reset_timeout_to: None,
5133                    require_prior_idle: None,
5134                    timeout: 50,
5135                    hold: k(C),
5136                    timeout_action: k(C),
5137                    tap: Trans,
5138                    config: HoldTapConfig::Default,
5139                    tap_hold_interval: 200,
5140                }),
5141            ]],
5142            [[
5143                NoOp,
5144                NoOp,
5145                NoOp,
5146                HoldTap(&HoldTapAction {
5147                    on_press_reset_timeout_to: None,
5148                    require_prior_idle: None,
5149                    timeout: 50,
5150                    hold: k(D),
5151                    timeout_action: k(D),
5152                    tap: Trans,
5153                    config: HoldTapConfig::Default,
5154                    tap_hold_interval: 200,
5155                }),
5156            ]],
5157        ];
5158        let mut layout = Layout::new(LAYERS);
5159
5160        layout.event(Press(0, 0));
5161        assert_eq!(CustomEvent::NoEvent, layout.tick());
5162        assert_keys(&[], layout.keycodes());
5163        layout.event(Press(0, 1));
5164        assert_eq!(CustomEvent::NoEvent, layout.tick());
5165        assert_keys(&[], layout.keycodes());
5166        layout.event(Press(0, 2));
5167        assert_eq!(CustomEvent::NoEvent, layout.tick());
5168        assert_keys(&[], layout.keycodes());
5169        layout.event(Press(0, 3));
5170        assert_eq!(CustomEvent::NoEvent, layout.tick());
5171        assert_keys(&[], layout.keycodes());
5172        layout.event(Release(0, 3));
5173        assert_eq!(CustomEvent::NoEvent, layout.tick());
5174        assert_keys(&[], layout.keycodes());
5175        layout.event(Release(0, 3));
5176        assert_eq!(CustomEvent::NoEvent, layout.tick());
5177        assert_keys(&[A], layout.keycodes());
5178    }
5179
5180    #[test]
5181    fn trans_in_multi_works_with_all_trans_settings() {
5182        let permutations: &[(bool, bool)] =
5183            &[(false, false), (false, true), (true, false), (true, true)];
5184
5185        for &(trans_v2, delegate_to_1st) in permutations {
5186            static DEFSRC_LAYER: [Action; 3] = [NoOp, NoOp, k(X)];
5187            static LAYERS: Layers<3, 1> = &[
5188                [[
5189                    Layer(1),
5190                    DefaultLayer(1),
5191                    MultipleActions(&[Trans, k(Y)].as_slice()),
5192                ]],
5193                [[NoOp, Layer(2), k(B)]],
5194                [[NoOp, NoOp, Trans]],
5195            ];
5196            for &do_layer_switch in &[false, true] {
5197                let mut layout = Layout::new_with_trans_action_settings(
5198                    &DEFSRC_LAYER,
5199                    LAYERS,
5200                    trans_v2,
5201                    delegate_to_1st,
5202                );
5203
5204                layout.event(Press(0, 2));
5205                assert_eq!(CustomEvent::NoEvent, layout.tick());
5206                assert_keys(&[X, Y], layout.keycodes());
5207                layout.event(Release(0, 2));
5208                assert_eq!(CustomEvent::NoEvent, layout.tick());
5209                assert_keys(&[], layout.keycodes());
5210
5211                if do_layer_switch {
5212                    layout.event(Press(0, 1));
5213                    assert_eq!(CustomEvent::NoEvent, layout.tick());
5214                    assert_keys(&[], layout.keycodes());
5215                    layout.event(Release(0, 1));
5216                    assert_eq!(CustomEvent::NoEvent, layout.tick());
5217                    assert_keys(&[], layout.keycodes());
5218                    assert_eq!(layout.default_layer, 1);
5219                } else {
5220                    layout.event(Press(0, 0));
5221                    assert_eq!(CustomEvent::NoEvent, layout.tick());
5222                    assert_keys(&[], layout.keycodes());
5223                }
5224
5225                layout.event(Press(0, 2));
5226                assert_eq!(CustomEvent::NoEvent, layout.tick());
5227                assert_keys(&[B], layout.keycodes());
5228                layout.event(Release(0, 2));
5229                assert_eq!(CustomEvent::NoEvent, layout.tick());
5230                assert_keys(&[], layout.keycodes());
5231
5232                layout.event(Press(0, 1));
5233                assert_eq!(CustomEvent::NoEvent, layout.tick());
5234                assert_keys(&[], layout.keycodes());
5235                layout.event(Press(0, 2));
5236                assert_eq!(CustomEvent::NoEvent, layout.tick());
5237                assert_keys(
5238                    match (trans_v2, delegate_to_1st) {
5239                        (false, false) => &[X],
5240                        (false, true) => &[X, Y],
5241                        (true, _) => &[B],
5242                    },
5243                    layout.keycodes(),
5244                );
5245                layout.event(Release(0, 2));
5246                assert_eq!(CustomEvent::NoEvent, layout.tick());
5247                assert_keys(&[], layout.keycodes());
5248            }
5249        }
5250    }
5251
5252    #[cfg(feature = "tap_hold_tracker")]
5253    #[test]
5254    fn hold_activated_is_set_on_hold_timeout() {
5255        static LAYERS: Layers<1, 1> = &[[[HoldTap(&HoldTapAction {
5256            timeout: 5,
5257            hold: k(LAlt),
5258            timeout_action: k(LAlt),
5259            tap: k(Space),
5260            config: HoldTapConfig::Default,
5261            tap_hold_interval: 0,
5262            on_press_reset_timeout_to: None,
5263            require_prior_idle: None,
5264        })]]];
5265        let mut layout = Layout::new(LAYERS);
5266        // Nothing set initially.
5267        assert!(layout.tap_hold_tracker.take_hold_activated().is_none());
5268
5269        layout.event(Press(0, 0));
5270        for _ in 0..6 {
5271            let _ = layout.tick();
5272        }
5273        // Hold action should be active.
5274        assert_keys(&[LAlt], layout.keycodes());
5275
5276        // Flag should be set exactly once.
5277        let info = layout
5278            .tap_hold_tracker
5279            .take_hold_activated()
5280            .expect("hold_activated should be set");
5281        assert_eq!(info.coord, (0, 0));
5282        assert!(layout.tap_hold_tracker.take_hold_activated().is_none());
5283    }
5284
5285    #[cfg(feature = "tap_hold_tracker")]
5286    #[test]
5287    fn tap_activated_is_set_on_tap_release() {
5288        static LAYERS: Layers<2, 1> = &[[[
5289            HoldTap(&HoldTapAction {
5290                timeout: 200,
5291                hold: k(LAlt),
5292                timeout_action: k(LAlt),
5293                tap: k(Space),
5294                config: HoldTapConfig::Default,
5295                tap_hold_interval: 0,
5296                on_press_reset_timeout_to: None,
5297                require_prior_idle: None,
5298            }),
5299            k(A),
5300        ]]];
5301        let mut layout = Layout::new(LAYERS);
5302        assert!(layout.tap_hold_tracker.take_tap_activated().is_none());
5303
5304        // Quick press and release triggers tap.
5305        layout.event(Press(0, 0));
5306        let _ = layout.tick();
5307        layout.event(Release(0, 0));
5308        let _ = layout.tick();
5309
5310        assert_keys(&[Space], layout.keycodes());
5311        let info = layout
5312            .tap_hold_tracker
5313            .take_tap_activated()
5314            .expect("tap_activated should be set");
5315        assert_eq!(info.coord, (0, 0));
5316        assert!(layout.tap_hold_tracker.take_tap_activated().is_none());
5317    }
5318
5319    #[cfg(feature = "tap_hold_tracker")]
5320    #[test]
5321    fn hold_activated_is_set_on_permissive_hold() {
5322        static LAYERS: Layers<2, 1> = &[[[
5323            HoldTap(&HoldTapAction {
5324                timeout: 200,
5325                hold: k(LAlt),
5326                timeout_action: k(LAlt),
5327                tap: k(Space),
5328                config: HoldTapConfig::PermissiveHold,
5329                tap_hold_interval: 0,
5330                on_press_reset_timeout_to: None,
5331                require_prior_idle: None,
5332            }),
5333            k(A),
5334        ]]];
5335        let mut layout = Layout::new(LAYERS);
5336        assert!(layout.tap_hold_tracker.take_hold_activated().is_none());
5337
5338        // PermissiveHold: press hold-tap key, press another key, release it => hold.
5339        layout.event(Press(0, 0));
5340        let _ = layout.tick();
5341        layout.event(Press(0, 1));
5342        let _ = layout.tick();
5343        layout.event(Release(0, 1));
5344        let _ = layout.tick();
5345
5346        assert_keys(&[LAlt], layout.keycodes());
5347        let info = layout
5348            .tap_hold_tracker
5349            .take_hold_activated()
5350            .expect("hold_activated should be set via waiting_into_hold");
5351        assert_eq!(info.coord, (0, 0));
5352        assert!(layout.tap_hold_tracker.take_tap_activated().is_none());
5353    }
5354
5355    #[cfg(feature = "tap_hold_tracker")]
5356    #[test]
5357    fn hold_activated_is_set_on_hold_on_other_key_press() {
5358        static LAYERS: Layers<2, 1> = &[[[
5359            HoldTap(&HoldTapAction {
5360                timeout: 200,
5361                hold: k(LAlt),
5362                timeout_action: k(LAlt),
5363                tap: k(Space),
5364                config: HoldTapConfig::HoldOnOtherKeyPress,
5365                tap_hold_interval: 0,
5366                on_press_reset_timeout_to: None,
5367                require_prior_idle: None,
5368            }),
5369            k(A),
5370        ]]];
5371        let mut layout = Layout::new(LAYERS);
5372        assert!(layout.tap_hold_tracker.take_hold_activated().is_none());
5373
5374        // HoldOnOtherKeyPress: press hold-tap key, then press another key => hold.
5375        layout.event(Press(0, 0));
5376        let _ = layout.tick();
5377        layout.event(Press(0, 1));
5378        let _ = layout.tick();
5379
5380        assert_keys(&[LAlt], layout.keycodes());
5381        let info = layout
5382            .tap_hold_tracker
5383            .take_hold_activated()
5384            .expect("hold_activated should be set via waiting_into_hold");
5385        assert_eq!(info.coord, (0, 0));
5386        assert!(layout.tap_hold_tracker.take_tap_activated().is_none());
5387    }
5388
5389    #[test]
5390    fn chord_does_not_set_tap_hold_activated() {
5391        const GROUP: ChordsGroup<core::convert::Infallible> = ChordsGroup {
5392            coords: &[((0, 0), 1), ((0, 1), 2)],
5393            chords: &[(3, &KeyCode(Kb5))],
5394            timeout: 100,
5395        };
5396        static LAYERS: Layers<2, 1> = &[[[Chords(&GROUP), Chords(&GROUP)]]];
5397
5398        let mut layout = Layout::new(LAYERS);
5399        layout.event(Press(0, 0));
5400        for _ in 0..50 {
5401            let _ = layout.tick();
5402        }
5403        layout.event(Press(0, 1));
5404        for _ in 0..50 {
5405            let _ = layout.tick();
5406        }
5407        assert_keys(&[Kb5], layout.keycodes());
5408        // Chord resolution must not set tap or hold activated flags.
5409        assert!(layout.tap_hold_tracker.take_hold_activated().is_none());
5410        assert!(layout.tap_hold_tracker.take_tap_activated().is_none());
5411    }
5412
5413    #[test]
5414    fn tap_dance_does_not_set_tap_hold_activated() {
5415        static LAYERS: Layers<2, 1> = &[[[
5416            TapDance(&crate::action::TapDance {
5417                timeout: 100,
5418                actions: &[&k(LShift), &k(LCtrl)],
5419                config: TapDanceConfig::Lazy,
5420            }),
5421            k(A),
5422        ]]];
5423
5424        let mut layout = Layout::new(LAYERS);
5425        // Single tap, wait for timeout.
5426        layout.event(Press(0, 0));
5427        for _ in 0..101 {
5428            let _ = layout.tick();
5429        }
5430        assert_keys(&[LShift], layout.keycodes());
5431        // Tap-dance resolution must not set tap or hold activated flags.
5432        assert!(layout.tap_hold_tracker.take_hold_activated().is_none());
5433        assert!(layout.tap_hold_tracker.take_tap_activated().is_none());
5434    }
5435}