-
Notifications
You must be signed in to change notification settings - Fork 145
/
Copy pathlayout.rs
3605 lines (3426 loc) · 139 KB
/
layout.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Layout management.
/// A procedural macro to generate [Layers](type.Layers.html)
/// ## Syntax
/// Items inside the macro are converted to Actions as such:
/// - [`Action::KeyCode`]: Idents are automatically understood as keycodes: `A`, `RCtrl`, `Space`
/// - Punctuation, numbers and other literals that aren't special to the rust parser are converted
/// to KeyCodes as well: `,` becomes `KeyCode::Commma`, `2` becomes `KeyCode::Kb2`, `/` becomes `KeyCode::Slash`
/// - Characters which require shifted keys are converted to `Action::MultipleKeyCodes(&[LShift, <character>])`:
/// `!` becomes `Action::MultipleKeyCodes(&[LShift, Kb1])` etc
/// - Characters special to the rust parser (parentheses, brackets, braces, quotes, apostrophes, underscores, backslashes and backticks)
/// left alone cause parsing errors and as such have to be enclosed by apostrophes: `'['` becomes `KeyCode::LBracket`,
/// `'\''` becomes `KeyCode::Quote`, `'\\'` becomes `KeyCode::BSlash`
/// - [`Action::NoOp`]: Lowercase `n`
/// - [`Action::Trans`]: Lowercase `t`
/// - [`Action::Layer`]: A number in parentheses: `(1)`, `(4 - 2)`, `(0x4u8 as usize)`
/// - [`Action::MultipleActions`]: Actions in brackets: `[LCtrl S]`, `[LAlt LCtrl C]`, `[(2) B {Action::NoOp}]`
/// - Other `Action`s: anything in braces (`{}`) is copied unchanged to the final layout - `{ Action::Custom(42) }`
/// simply becomes `Action::Custom(42)`
///
/// **Important note**: comma (`,`) is a keycode on its own, and can't be used to separate keycodes as one would have
/// to do when not using a macro.
pub use kanata_keyberon_macros::*;
use crate::key_code::KeyCode;
use crate::{action::*, multikey_buffer::MultiKeyBuffer};
use arraydeque::ArrayDeque;
use heapless::Vec;
use State::*;
/// The coordinate type.
pub type KCoord = (u8, u16);
/// The Layers type.
///
/// `Layers` type is an array of layers which contain the description
/// of actions on the switch matrix. For example `layers[1][2][3]`
/// corresponds to the key on the first layer, row 2, column 3.
/// The generic parameters are in order: the number of columns, rows and layers,
/// and the type contained in custom actions.
pub type Layers<'a, const C: usize, const R: usize, const L: usize, T = core::convert::Infallible> =
[[[Action<'a, T>; C]; R]; L];
const QUEUE_SIZE: usize = 32;
/// The current event queue.
///
/// Events can be retrieved by iterating over this struct and calling [Queued::event].
type Queue = ArrayDeque<[Queued; QUEUE_SIZE], arraydeque::behavior::Wrapping>;
/// A list of queued press events. Used for special handling of potentially multiple press events
/// that occur during a Waiting event.
type PressedQueue = ArrayDeque<[KCoord; QUEUE_SIZE]>;
/// The maximum number of actions that can be activated concurrently via chord decomposition or
/// activation of multiple switch cases using fallthrough.
pub const ACTION_QUEUE_LEN: usize = 8;
/// The queue is currently only used for chord decomposition when a longer chord does not result in
/// an action, but splitting it into smaller chords would. The buffer size of 8 should be more than
/// enough for real world usage, but if one wanted to be extra safe, this should be ChordKeys::BITS
/// since that should guarantee that all potentially queueable actions can fit.
type ActionQueue<'a, T> =
ArrayDeque<[QueuedAction<'a, T>; ACTION_QUEUE_LEN], arraydeque::behavior::Wrapping>;
type QueuedAction<'a, T> = Option<(KCoord, &'a Action<'a, T>)>;
/// The layout manager. It takes `Event`s and `tick`s as input, and
/// generate keyboard reports.
pub struct Layout<'a, const C: usize, const R: usize, const L: usize, T = core::convert::Infallible>
where
T: 'a + std::fmt::Debug,
{
pub layers: &'a [[[Action<'a, T>; C]; R]; L],
pub default_layer: usize,
/// Key states.
pub states: Vec<State<'a, T>, 64>,
pub waiting: Option<WaitingState<'a, T>>,
pub tap_dance_eager: Option<TapDanceEagerState<'a, T>>,
pub queue: Queue,
pub oneshot: OneShotState,
pub last_press_tracker: LastPressTracker,
pub active_sequences: ArrayDeque<[SequenceState<'a, T>; 4], arraydeque::behavior::Wrapping>,
pub action_queue: ActionQueue<'a, T>,
pub rpt_action: Option<&'a Action<'a, T>>,
pub historical_keys: ArrayDeque<[KeyCode; 8], arraydeque::behavior::Wrapping>,
pub quick_tap_hold_timeout: bool,
rpt_multikey_key_buffer: MultiKeyBuffer<'a, T>,
}
/// An event on the key matrix.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Event {
/// Press event with coordinates (i, j).
Press(u8, u16),
/// Release event with coordinates (i, j).
Release(u8, u16),
}
impl Event {
/// Returns the coordinates (i, j) of the event.
pub fn coord(self) -> KCoord {
match self {
Event::Press(i, j) => (i, j),
Event::Release(i, j) => (i, j),
}
}
/// Transforms the coordinates of the event.
///
/// # Example
///
/// ```
/// # use kanata_keyberon::layout::Event;
/// assert_eq!(
/// Event::Press(3, 10),
/// Event::Press(3, 1).transform(|i, j| (i, 11 - j)),
/// );
/// ```
pub fn transform(self, f: impl FnOnce(u8, u16) -> KCoord) -> Self {
match self {
Event::Press(i, j) => {
let (i, j) = f(i, j);
Event::Press(i, j)
}
Event::Release(i, j) => {
let (i, j) = f(i, j);
Event::Release(i, j)
}
}
}
/// Returns `true` if the event is a key press.
pub fn is_press(self) -> bool {
match self {
Event::Press(..) => true,
Event::Release(..) => false,
}
}
/// Returns `true` if the event is a key release.
pub fn is_release(self) -> bool {
match self {
Event::Release(..) => true,
Event::Press(..) => false,
}
}
}
/// Event from custom action.
#[derive(Debug, Default, PartialEq, Eq)]
pub enum CustomEvent<'a, T: 'a> {
/// No custom action.
#[default]
NoEvent,
/// The given custom action key is pressed.
Press(&'a T),
/// The given custom action key is released.
Release(&'a T),
}
impl<'a, T> CustomEvent<'a, T> {
/// Update an event according to a new event.
///
///The event can only be modified in the order `NoEvent < Press <
/// Release`
fn update(&mut self, e: Self) {
use CustomEvent::*;
match (&e, &self) {
(Release(_), NoEvent) | (Release(_), Press(_)) => *self = e,
(Press(_), NoEvent) => *self = e,
_ => (),
}
}
}
/// Metadata about normal key flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct NormalKeyFlags(u16);
const NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION: u16 = 0x0001;
impl NormalKeyFlags {
pub fn clear_on_next_action(self) -> bool {
(self.0 & NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION) == NORMAL_KEY_FLAG_CLEAR_ON_NEXT_ACTION
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum State<'a, T: 'a> {
NormalKey {
keycode: KeyCode,
coord: KCoord,
flags: NormalKeyFlags,
},
LayerModifier {
value: usize,
coord: KCoord,
},
Custom {
value: &'a T,
coord: KCoord,
},
FakeKey {
keycode: KeyCode,
}, // Fake key event for sequences
RepeatingSequence {
sequence: &'a &'a [SequenceEvent<'a, T>],
coord: KCoord,
},
SeqCustomPending(&'a T),
SeqCustomActive(&'a T),
Tombstone,
}
impl<'a, T> Copy for State<'a, T> {}
impl<'a, T> Clone for State<'a, T> {
fn clone(&self) -> Self {
*self
}
}
impl<'a, T: 'a> State<'a, T> {
fn keycode(&self) -> Option<KeyCode> {
match self {
NormalKey { keycode, .. } => Some(*keycode),
FakeKey { keycode } => Some(*keycode),
_ => None,
}
}
fn keycode_in_coords(&self, coords: &OneShotCoords) -> Option<KeyCode> {
match self {
NormalKey { keycode, coord, .. } => {
if coords.contains(coord) {
Some(*keycode)
} else {
None
}
}
_ => None,
}
}
fn tick(&self) -> Option<Self> {
Some(*self)
}
/// Returns None if the key has been released and Some otherwise.
pub fn release(&self, c: KCoord, custom: &mut CustomEvent<'a, T>) -> Option<Self> {
match *self {
NormalKey { coord, .. }
| LayerModifier { coord, .. }
| RepeatingSequence { coord, .. }
if coord == c =>
{
None
}
Custom { value, coord } if coord == c => {
custom.update(CustomEvent::Release(value));
None
}
_ => Some(*self),
}
}
pub fn release_state(&self, s: ReleasableState) -> Option<Self> {
match (*self, s) {
(NormalKey { keycode: k1, .. }, ReleasableState::KeyCode(k2)) => {
if k1 == k2 {
None
} else {
Some(*self)
}
}
(LayerModifier { value: l1, .. }, ReleasableState::Layer(l2)) => {
if l1 == l2 {
None
} else {
Some(*self)
}
}
_ => Some(*self),
}
}
fn seq_release(&self, kc: KeyCode) -> Option<Self> {
match *self {
FakeKey { keycode, .. } if keycode == kc => None,
_ => Some(*self),
}
}
fn get_layer(&self) -> Option<usize> {
match self {
LayerModifier { value, .. } => Some(*value),
_ => None,
}
}
}
#[derive(Copy, Clone, Debug)]
struct TapDanceState<'a, T: 'a> {
actions: &'a [&'a Action<'a, T>],
timeout: u16,
num_taps: u16,
}
#[derive(Copy, Clone, Debug)]
pub struct TapDanceEagerState<'a, T: 'a> {
coord: KCoord,
actions: &'a [&'a Action<'a, T>],
timeout: u16,
orig_timeout: u16,
num_taps: u16,
}
impl<'a, T> TapDanceEagerState<'a, T> {
fn tick(&mut self) {
self.timeout = self.timeout.saturating_sub(1);
}
fn is_expired(&self) -> bool {
self.timeout == 0 || usize::from(self.num_taps) >= self.actions.len()
}
fn set_expired(&mut self) {
self.timeout = 0;
}
fn incr_taps(&mut self) {
self.num_taps += 1;
self.timeout = self.orig_timeout;
}
}
#[derive(Debug)]
enum WaitingConfig<'a, T: 'a + std::fmt::Debug> {
HoldTap(HoldTapConfig<'a>),
TapDance(TapDanceState<'a, T>),
Chord(&'a ChordsGroup<'a, T>),
}
#[derive(Debug)]
pub struct WaitingState<'a, T: 'a + std::fmt::Debug> {
coord: KCoord,
timeout: u16,
delay: u16,
ticks: u16,
hold: &'a Action<'a, T>,
tap: &'a Action<'a, T>,
timeout_action: &'a Action<'a, T>,
config: WaitingConfig<'a, T>,
}
/// Actions that can be triggered for a key configured for HoldTap.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum WaitingAction {
/// Trigger the holding event.
Hold,
/// Trigger the tapping event.
Tap,
/// Trigger the timeout event.
Timeout,
/// Drop this event. It will act as if no key was pressed.
NoOp,
}
impl<'a, T: std::fmt::Debug> WaitingState<'a, T> {
fn tick(
&mut self,
queued: &mut Queue,
action_queue: &mut ActionQueue<'a, T>,
) -> Option<(WaitingAction, Option<PressedQueue>)> {
self.timeout = self.timeout.saturating_sub(1);
self.ticks = self.ticks.saturating_add(1);
let mut pq = None;
let (ret, cfg_change) = match self.config {
WaitingConfig::HoldTap(htc) => (self.handle_hold_tap(htc, queued), None),
WaitingConfig::TapDance(ref tds) => {
let (ret, num_taps) =
self.handle_tap_dance(tds.num_taps, tds.actions.len(), queued);
// Due to ownership issues, handle_tap_dance can't contain all of the necessary
// logic.
if ret.is_some() {
let idx = core::cmp::min(num_taps.into(), tds.actions.len()).saturating_sub(1);
self.tap = tds.actions[idx];
}
if num_taps > tds.num_taps {
self.timeout = tds.timeout;
}
(
ret,
Some(WaitingConfig::TapDance(TapDanceState { num_taps, ..*tds })),
)
}
WaitingConfig::Chord(config) => {
if let Some((ret, action, cpq)) = self.handle_chord(config, queued, action_queue) {
self.tap = action;
pq = Some(cpq);
(Some(ret), None)
} else {
(None, None)
}
}
};
if let Some(cfg) = cfg_change {
self.config = cfg;
}
ret.map(|v| (v, pq))
}
fn handle_hold_tap(&mut self, cfg: HoldTapConfig, queued: &Queue) -> Option<WaitingAction> {
let mut skip_timeout = false;
match cfg {
HoldTapConfig::Default => (),
HoldTapConfig::HoldOnOtherKeyPress => {
if queued.iter().any(|s| s.event.is_press()) {
return Some(WaitingAction::Hold);
}
}
HoldTapConfig::PermissiveHold => {
let mut queued = queued.iter();
while let Some(q) = queued.next() {
if q.event.is_press() {
let (i, j) = q.event.coord();
let target = Event::Release(i, j);
if queued.clone().any(|q| q.event == target) {
return Some(WaitingAction::Hold);
}
}
}
}
HoldTapConfig::Custom(func) => {
let (waiting_action, local_skip) = (func)(QueuedIter(queued.iter()));
if waiting_action.is_some() {
return waiting_action;
} else {
skip_timeout = local_skip;
}
}
}
if let Some(&Queued { since, .. }) = queued
.iter()
.find(|s| self.is_corresponding_release(&s.event))
{
if self.timeout > self.delay.saturating_sub(since) {
Some(WaitingAction::Tap)
} else {
Some(WaitingAction::Timeout)
}
} else if self.timeout == 0 && (!skip_timeout) {
Some(WaitingAction::Timeout)
} else {
None
}
}
fn handle_tap_dance(
&self,
num_taps: u16,
max_taps: usize,
queued: &mut Queue,
) -> (Option<WaitingAction>, u16) {
// Evict events with the same coordinates except for the final release. E.g. if 3 taps have
// occurred, this will remove all `Press` events and 2 `Release` events. This is done so
// that the state machine processes the entire tap dance sequence as a single press and
// single release regardless of how many taps were actually done.
let evict_same_coord_events = |num_taps: u16, queued: &mut Queue| {
let mut releases_to_remove = num_taps.saturating_sub(1);
queued.retain(|s| {
let mut do_retain = true;
if self.is_corresponding_release(&s.event) {
if releases_to_remove > 0 {
do_retain = false;
releases_to_remove = releases_to_remove.saturating_sub(1)
}
} else if self.is_corresponding_press(&s.event) {
do_retain = false;
}
do_retain
});
};
if self.timeout == 0 || usize::from(num_taps) >= max_taps {
evict_same_coord_events(num_taps, queued);
return (Some(WaitingAction::Tap), num_taps);
}
// Get the number of sequential taps for this tap-dance key. If a different key was
// pressed, activate a tap-dance action.
match queued.iter().try_fold(1, |same_tap_count, s| {
if self.is_corresponding_press(&s.event) {
Ok(same_tap_count + 1)
} else if matches!(s.event, Event::Press(..)) {
Err((same_tap_count, ()))
} else {
Ok(same_tap_count)
}
}) {
Ok(num_taps) => (None, num_taps),
Err((num_taps, _)) => {
evict_same_coord_events(num_taps, queued);
(Some(WaitingAction::Tap), num_taps)
}
}
}
fn handle_chord(
&mut self,
config: &'a ChordsGroup<'a, T>,
queued: &mut Queue,
action_queue: &mut ActionQueue<'a, T>,
) -> Option<(WaitingAction, &'a Action<'a, T>, PressedQueue)> {
// need to keep track of how many Press events we handled so we can filter them out later
let mut handled_press_events = 0;
let start_chord_coord = self.coord;
let mut released_coord = None;
// Compute the set of chord keys that are currently pressed
// `Ok` when chording mode may continue
// `Err` when it should end for various reasons
let active = queued
.iter()
.try_fold(config.get_keys(self.coord).unwrap_or(0), |active, s| {
if self.delay.saturating_sub(s.since) > self.timeout {
Ok(active)
} else if let Some(chord_keys) = config.get_keys(s.event.coord()) {
match s.event {
Event::Press(_, _) => {
handled_press_events += 1;
Ok(active | chord_keys)
}
Event::Release(i, j) => {
// release chord quickly by changing the coordinate to the released
// key, to be consistent with chord decomposition behaviour.
released_coord = Some((i, j));
Err(active)
}
}
} else if matches!(s.event, Event::Press(..)) {
Err(active) // pressed a non-chord key, abort
} else {
Ok(active)
}
})
.and_then(|active| {
if self.timeout.saturating_sub(self.delay) == 0 {
Err(active) // timeout expired, abort
} else {
Ok(active)
}
});
let res = match active {
Ok(active) => {
// Chording mode still active, only trigger action if it's unambiguous
if let Some(action) = config.get_chord_if_unambiguous(active) {
if let Some(coord) = released_coord {
self.coord = coord;
}
(WaitingAction::Tap, action)
} else {
return None; // nothing to do yet, we'll check back later
}
}
Err(active) => {
// Abort chording mode. Trigger a chord action if there is one.
if let Some(action) = config.get_chord(active) {
if let Some(coord) = released_coord {
self.coord = coord;
}
(WaitingAction::Tap, action)
} else {
self.decompose_chord_into_action_queue(config, queued, action_queue);
(WaitingAction::NoOp, &Action::NoOp)
}
}
};
let mut pq = PressedQueue::new();
let _ = pq.push_back(start_chord_coord);
// Return all press events that were logically handled by this chording event
queued.retain(|s| {
if self.delay.saturating_sub(s.since) > self.timeout {
true
} else if matches!(s.event, Event::Press(i, j) if config.get_keys((i, j)).is_some())
&& handled_press_events > 0
{
handled_press_events -= 1;
let _ = pq.push_back(s.event().coord());
false
} else {
true
}
});
Some((res.0, res.1, pq))
}
fn decompose_chord_into_action_queue(
&mut self,
config: &'a ChordsGroup<'a, T>,
queued: &mut Queue,
action_queue: &mut ActionQueue<'a, T>,
) {
let mut chord_key_order = [0u32; ChordKeys::BITS as usize];
// Default to the initial coordinate. But if a key is released early (before the timeout
// occurs), use that key for action releases. That way the chord is released as early as
// possible.
let mut action_queue_coord = self.coord;
let starting_mask = config.get_keys(self.coord).unwrap_or(0);
let mut mask_bits_set = 1;
chord_key_order[0] = starting_mask;
let _ = queued.iter().try_fold(starting_mask, |active, s| {
if self.delay.saturating_sub(s.since) > self.timeout {
Ok(active)
} else if let Some(chord_keys) = config.get_keys(s.event.coord()) {
match s.event {
Event::Press(_, _) => {
if active | chord_keys != active {
chord_key_order[mask_bits_set] = chord_keys;
mask_bits_set += 1;
}
Ok(active | chord_keys)
}
Event::Release(i, j) => {
action_queue_coord = (i, j);
Err(active) // released a chord key, abort
}
}
} else if matches!(s.event, Event::Press(..)) {
Err(active) // pressed a non-chord key, abort
} else {
Ok(active)
}
});
let len = mask_bits_set;
let chord_keys = &chord_key_order[0..len];
// Compute actions using the following description:
//
// Let's say we have a chord group with keys (h j k l). The full set (h j k l) is not
// defined with an action, but the user has pressed all of h, j, k, l in the listed order,
// so now kanata needs to break down the combo. How should it work?
//
// Figuratively "release" keys in reverse-temporal order until a valid chord is found. So
// first, l is figuratively released, and if (h j k) is a valid chord, that action will
// activate. If (l) by itself is valid that then activates after (h j k) is finished.
//
// In the case that (h j k) is not a chord, instead activate (h j). If that is a valid
// chord, then try to activate (k l) together, and if not, evaluate (k), then (l).
//
// If (h j) is not a valid chord, try to activate (h). Then try to activate (j k l). If
// that is invalid, try (j k), then (j). If (j k) is valid, try (l). If (j) is valid, try
// (k l). If (k l) is invalid, try (k) then (l).
//
// The possible executions, listed in descending order of priority (first listed has
// highest execution priority) are:
// (h j k l)
// (h j k) (l)
// (h j) (k l)
// (h j) (k) (l)
// (h) (j k l)
// (h) (j k) (l)
// (h) (j) (k l)
// (h) (j) (k) (l)
let mut start = 0;
let mut end = len;
while start < len {
let sub_chord = &chord_keys[start..end];
let chord_mask = sub_chord
.iter()
.copied()
.reduce(|acc, e| acc | e)
.unwrap_or(0);
if let Some(action) = config.get_chord(chord_mask) {
let _ = action_queue.push_back(Some((action_queue_coord, action)));
} else {
end -= 1;
// shrink from end until something is found, or have checked up to and including
// the individual start key.
while end > start {
let sub_chord = &chord_keys[start..end];
let chord_mask = sub_chord
.iter()
.copied()
.reduce(|acc, e| acc | e)
.unwrap_or(0);
if let Some(action) = config.get_chord(chord_mask) {
let _ = action_queue.push_back(Some((action_queue_coord, action)));
break;
}
end -= 1;
}
}
start = if end <= start { start + 1 } else { end };
end = len;
}
}
fn is_corresponding_release(&self, event: &Event) -> bool {
matches!(event, Event::Release(i, j) if (*i, *j) == self.coord)
}
fn is_corresponding_press(&self, event: &Event) -> bool {
matches!(event, Event::Press(i, j) if (*i, *j) == self.coord)
}
}
type OneShotCoords = ArrayDeque<[KCoord; ONE_SHOT_MAX_ACTIVE], arraydeque::behavior::Wrapping>;
#[derive(Debug, Copy, Clone)]
pub struct SequenceState<'a, T: 'a> {
cur_event: Option<SequenceEvent<'a, T>>,
delay: u32, // Keeps track of SequenceEvent::Delay time remaining
tapped: Option<KeyCode>, // Keycode of a key that should be released at the next tick
remaining_events: &'a [SequenceEvent<'a, T>],
}
type OneShotKeys = [KCoord; ONE_SHOT_MAX_ACTIVE];
type ReleasedOneShotKeys = Vec<KCoord, ONE_SHOT_MAX_ACTIVE>;
/// Contains the state of one shot keys that are currently active.
pub struct OneShotState {
/// KCoordinates of one shot keys that are active
pub keys: ArrayDeque<OneShotKeys, arraydeque::behavior::Wrapping>,
/// KCoordinates of one shot keys that have been released
pub released_keys: ArrayDeque<OneShotKeys, arraydeque::behavior::Wrapping>,
/// Used to keep track of already-pressed keys for the release variants.
pub other_pressed_keys: ArrayDeque<OneShotKeys, arraydeque::behavior::Wrapping>,
/// Timeout (ms) after which all one shot keys expire
pub timeout: u16,
/// Contains the end config of the most recently pressed one shot key
pub end_config: OneShotEndConfig,
/// Marks if release of the one shot keys should be done on the next tick
pub release_on_next_tick: bool,
/// The number of ticks to delay the release of the one-shot activation
/// for EndOnFirstPress(OrRepress).
/// This used to not exist and effectively be 1 (1ms),
/// but that is too short for some environments.
/// When too short, applications or desktop environments process
/// the key release before the next press,
/// even if temporally the release was sent after.
pub on_press_release_delay: u16,
/// If on_press_release_delay is used, this will be >0,
/// meaning input processing should be paused to prevent extra presses
/// from coming in while OneShot has not yet been released.
///
/// May also be reused for other purposes...
pub pause_input_processing_ticks: u16,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
enum OneShotHandlePressKey {
OneShotKey(KCoord),
Other(KCoord),
}
impl OneShotState {
fn tick(&mut self) -> Option<ReleasedOneShotKeys> {
if self.keys.is_empty() {
return None;
}
self.timeout = self.timeout.saturating_sub(1);
if self.release_on_next_tick || self.timeout == 0 {
self.release_on_next_tick = false;
self.timeout = 0;
self.pause_input_processing_ticks = 0;
self.keys.clear();
self.other_pressed_keys.clear();
Some(self.released_keys.drain(..).collect())
} else {
None
}
}
fn handle_press(&mut self, key: OneShotHandlePressKey) -> OneShotCoords {
let mut oneshot_coords = ArrayDeque::new();
if self.keys.is_empty() {
return oneshot_coords;
}
match key {
OneShotHandlePressKey::OneShotKey(pressed_coord) => {
if matches!(
self.end_config,
OneShotEndConfig::EndOnFirstReleaseOrRepress
| OneShotEndConfig::EndOnFirstPressOrRepress
) && self.keys.contains(&pressed_coord)
{
self.release_on_next_tick = true;
oneshot_coords.extend(self.keys.iter().copied());
}
self.released_keys.retain(|coord| *coord != pressed_coord);
}
OneShotHandlePressKey::Other(pressed_coord) => {
if matches!(
self.end_config,
OneShotEndConfig::EndOnFirstPress | OneShotEndConfig::EndOnFirstPressOrRepress
) {
self.timeout = core::cmp::min(self.on_press_release_delay, self.timeout);
self.pause_input_processing_ticks = self.on_press_release_delay;
} else {
let _ = self.other_pressed_keys.push_back(pressed_coord);
}
oneshot_coords.extend(self.keys.iter().copied());
}
};
oneshot_coords
}
/// Returns true if the caller should handle the release normally and false otherwise.
/// The second value in the tuple represents an overflow of released one shot keys and should
/// be released is it is `Some`.
fn handle_release(&mut self, (i, j): KCoord) -> (bool, Option<KCoord>) {
if self.keys.is_empty() {
return (true, None);
}
if !self.keys.contains(&(i, j)) {
if matches!(
self.end_config,
OneShotEndConfig::EndOnFirstRelease | OneShotEndConfig::EndOnFirstReleaseOrRepress
) && self.other_pressed_keys.contains(&(i, j))
{
self.release_on_next_tick = true;
}
(true, None)
} else {
// delay release for one shot keys
(false, self.released_keys.push_back((i, j)))
}
}
}
/// An iterator over the currently queued events.
///
/// Events can be retrieved by iterating over this struct and calling [Queued::event].
#[derive(Clone)]
pub struct QueuedIter<'a>(arraydeque::Iter<'a, Queued>);
impl<'a> Iterator for QueuedIter<'a> {
type Item = &'a Queued;
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// An event, waiting in a queue to be processed.
#[derive(Debug, Copy, Clone)]
pub struct Queued {
event: Event,
since: u16,
}
impl From<Event> for Queued {
fn from(event: Event) -> Self {
Queued { event, since: 0 }
}
}
impl Queued {
fn tick(&mut self) {
self.since = self.since.saturating_add(1);
}
/// Get the [Event] from this object.
pub fn event(&self) -> Event {
self.event
}
}
#[derive(Default)]
pub struct LastPressTracker {
pub coord: KCoord,
pub tap_hold_timeout: u16,
}
impl LastPressTracker {
fn tick(&mut self) {
self.tap_hold_timeout = self.tap_hold_timeout.saturating_sub(1);
}
}
impl<'a, const C: usize, const R: usize, const L: usize, T: 'a + Copy + std::fmt::Debug>
Layout<'a, C, R, L, T>
{
/// Creates a new `Layout` object.
pub fn new(layers: &'a [[[Action<T>; C]; R]; L]) -> Self {
Self {
layers,
default_layer: 0,
states: Vec::new(),
waiting: None,
tap_dance_eager: None,
queue: ArrayDeque::new(),
oneshot: OneShotState {
timeout: 0,
end_config: OneShotEndConfig::EndOnFirstPress,
keys: ArrayDeque::new(),
released_keys: ArrayDeque::new(),
other_pressed_keys: ArrayDeque::new(),
release_on_next_tick: false,
on_press_release_delay: 0,
pause_input_processing_ticks: 0,
},
last_press_tracker: Default::default(),
active_sequences: ArrayDeque::new(),
action_queue: ArrayDeque::new(),
rpt_action: None,
historical_keys: ArrayDeque::new(),
rpt_multikey_key_buffer: unsafe { MultiKeyBuffer::new() },
quick_tap_hold_timeout: false,
}
}
/// Iterates on the key codes of the current state.
pub fn keycodes(&self) -> impl Iterator<Item = KeyCode> + Clone + '_ {
self.states.iter().filter_map(State::keycode)
}
fn waiting_into_hold(&mut self) -> CustomEvent<'a, T> {
if let Some(w) = &self.waiting {
let hold = w.hold;
let coord = w.coord;
let delay = match w.config {
WaitingConfig::HoldTap(..) | WaitingConfig::Chord(_) => w.delay + w.ticks,
WaitingConfig::TapDance(_) => 0,
};
self.waiting = None;
if coord == self.last_press_tracker.coord {
self.last_press_tracker.tap_hold_timeout = 0;
}
self.do_action(hold, coord, delay, false)
} else {
CustomEvent::NoEvent
}
}
fn waiting_into_tap(&mut self, pq: Option<PressedQueue>) -> CustomEvent<'a, T> {
if let Some(w) = &self.waiting {
let tap = w.tap;
let coord = w.coord;
let delay = match w.config {
WaitingConfig::HoldTap(..) | WaitingConfig::Chord(_) => w.delay + w.ticks,
WaitingConfig::TapDance(_) => 0,
};
self.waiting = None;
let ret = self.do_action(tap, coord, delay, false);
if let Some(pq) = pq {
match tap {
Action::KeyCode(_)
| Action::MultipleKeyCodes(_)
| Action::OneShot(_)
| Action::Layer(_) => {
// The current intent of this block is to ensure that simple actions like
// key presses or layer-while-held remain pressed as long as a single key from
// the input chord remains held. The behaviour of these actions is correct in
// the case of repeating do_action, so there is currently no harm in doing
// this. Other action types are more problematic though.
for other_coord in pq.iter().copied() {
self.do_action(tap, other_coord, delay, false);
}
}
Action::MultipleActions(acs) => {
// Like above block, but for the same simple actions within MultipleActions
for ac in acs.iter() {
if matches!(
ac,
Action::KeyCode(_)
| Action::MultipleKeyCodes(_)
| Action::OneShot(_)
| Action::Layer(_)
) {
for other_coord in pq.iter().copied() {
self.do_action(ac, other_coord, delay, false);
}
}
}
}
_ => {}
}
}
// Similar issue happens for the quick tap-hold tap as with on-press release;
// the rapidity of the release can cause issues. See on_press_release_delay
// comments for more detail.
self.oneshot.pause_input_processing_ticks = self.oneshot.on_press_release_delay;
ret
} else {
CustomEvent::NoEvent
}
}
fn waiting_into_timeout(&mut self) -> CustomEvent<'a, T> {
if let Some(w) = &self.waiting {
let timeout_action = w.timeout_action;
let coord = w.coord;
let delay = match w.config {
WaitingConfig::HoldTap(..) | WaitingConfig::Chord(_) => w.delay + w.ticks,
WaitingConfig::TapDance(_) => 0,
};
self.waiting = None;
if coord == self.last_press_tracker.coord {
self.last_press_tracker.tap_hold_timeout = 0;
}
self.do_action(timeout_action, coord, delay, false)
} else {
CustomEvent::NoEvent
}
}
fn drop_waiting(&mut self) -> CustomEvent<'a, T> {
self.waiting = None;