-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathlayout.rs
1251 lines (1176 loc) · 43.7 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.
///
/// ## Usage example:
/// Example layout for a 12x4 split keyboard:
/// ```
/// use keyberon::action::Action;
/// use keyberon::layout::Layers;
/// static DLAYER: Action = Action::DefaultLayer(5);
///
/// pub static LAYERS: Layers<12, 4, 2> = keyberon::layout::layout! {
/// {
/// [ Tab Q W E R T Y U I O P BSpace ]
/// [ LCtrl A S D F G H J K L ; Quote ]
/// [ LShift Z X C V B N M , . / Escape ]
/// [ n n LGui {DLAYER} Space Escape BSpace Enter (1) RAlt n n ]
/// }
/// {
/// [ Tab 1 2 3 4 5 6 7 8 9 0 BSpace ]
/// [ LCtrl ! @ # $ % ^ & * '(' ')' - ]
/// [ LShift n n n n n n n n n n [LAlt A]]
/// [ n n LGui (2) t t t t t RAlt n n ]
/// }
/// // ...
/// };
/// ```
pub use keyberon_macros::*;
use crate::action::{Action, HoldTapAction, HoldTapConfig};
use crate::key_code::KeyCode;
use arraydeque::ArrayDeque;
use heapless::Vec;
use State::*;
/// 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<
const C: usize,
const R: usize,
const L: usize,
T = core::convert::Infallible,
K = KeyCode,
> = [[[Action<T, K>; C]; R]; L];
/// The current event stack.
///
/// Events can be retrieved by iterating over this struct and calling [Stacked::event].
type Stack = ArrayDeque<Stacked, 32, arraydeque::behavior::Wrapping>;
/// The layout manager. It takes `Event`s and `tick`s as input, and
/// generate keyboard reports.
pub struct Layout<
const C: usize,
const R: usize,
const L: usize,
T = core::convert::Infallible,
K = KeyCode,
> where
T: 'static,
K: 'static + Copy,
{
layers: &'static [[[Action<T, K>; C]; R]; L],
default_layer: usize,
states: Vec<State<T, K>, 64>,
waiting: Option<WaitingState<T, K>>,
stacked: Stack,
tap_hold_tracker: TapHoldTracker,
}
/// An event on the key matrix.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Event {
/// Press event with coordinates (i, j).
Press(u8, u8),
/// Release event with coordinates (i, j).
Release(u8, u8),
}
impl Event {
/// Returns the coordinates (i, j) of the event.
pub fn coord(self) -> (u8, u8) {
match self {
Event::Press(i, j) => (i, j),
Event::Release(i, j) => (i, j),
}
}
/// Transforms the coordinates of the event.
///
/// # Example
///
/// ```
/// # use 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, u8) -> (u8, u8)) -> 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, PartialEq, Eq, Default)]
pub enum CustomEvent<T: 'static> {
/// No custom action.
#[default]
NoEvent,
/// The given custom action key is pressed.
Press(&'static T),
/// The given custom action key is released.
Release(&'static T),
}
impl<T> CustomEvent<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,
_ => (),
}
}
}
#[derive(Debug, Eq, PartialEq)]
enum State<T: 'static, K: 'static + Copy> {
NormalKey { keycode: K, coord: (u8, u8) },
LayerModifier { value: usize, coord: (u8, u8) },
Custom { value: &'static T, coord: (u8, u8) },
}
impl<T: 'static, K: 'static + Copy> Copy for State<T, K> {}
impl<T: 'static, K: 'static + Copy> Clone for State<T, K> {
fn clone(&self) -> Self {
*self
}
}
impl<T: 'static, K: 'static + Copy> State<T, K> {
fn keycode(&self) -> Option<K> {
match self {
NormalKey { keycode, .. } => Some(*keycode),
_ => None,
}
}
fn tick(&self) -> Option<Self> {
Some(*self)
}
fn release(&self, c: (u8, u8), custom: &mut CustomEvent<T>) -> Option<Self> {
match *self {
NormalKey { coord, .. } | LayerModifier { coord, .. } if coord == c => None,
Custom { value, coord } if coord == c => {
custom.update(CustomEvent::Release(value));
None
}
_ => Some(*self),
}
}
fn get_layer(&self) -> Option<usize> {
match self {
LayerModifier { value, .. } => Some(*value),
_ => None,
}
}
}
#[derive(Debug)]
struct WaitingState<T: 'static, K: 'static> {
coord: (u8, u8),
timeout: u16,
delay: u16,
hold: &'static Action<T, K>,
tap: &'static Action<T, K>,
config: HoldTapConfig,
}
/// 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,
/// Drop this event. It will act as if no key was pressed.
NoOp,
}
impl<T, K> WaitingState<T, K> {
fn tick(&mut self, stacked: &Stack) -> Option<WaitingAction> {
self.timeout = self.timeout.saturating_sub(1);
match self.config {
HoldTapConfig::Default => (),
HoldTapConfig::HoldOnOtherKeyPress => {
if stacked.iter().any(|s| s.event.is_press()) {
return Some(WaitingAction::Hold);
}
}
HoldTapConfig::PermissiveHold => {
for (x, s) in stacked.iter().enumerate() {
if s.event.is_press() {
let (i, j) = s.event.coord();
let target = Event::Release(i, j);
if stacked.iter().skip(x + 1).any(|s| s.event == target) {
return Some(WaitingAction::Hold);
}
}
}
}
HoldTapConfig::Custom(func) => {
if let waiting_action @ Some(_) = (func)(StackedIter(stacked.iter())) {
return waiting_action;
}
}
}
if let Some(&Stacked { since, .. }) = stacked
.iter()
.find(|s| self.is_corresponding_release(&s.event))
{
if self.timeout + since >= self.delay {
Some(WaitingAction::Tap)
} else {
Some(WaitingAction::Hold)
}
} else if self.timeout == 0 {
Some(WaitingAction::Hold)
} else {
None
}
}
fn is_corresponding_release(&self, event: &Event) -> bool {
matches!(event, Event::Release(i, j) if (*i, *j) == self.coord)
}
}
/// An iterator over the currently stacked events.
///
/// Events can be retrieved by iterating over this struct and calling [Stacked::event].
pub struct StackedIter<'a>(arraydeque::Iter<'a, Stacked>);
impl<'a> Iterator for StackedIter<'a> {
type Item = &'a Stacked;
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 stack to be processed.
#[derive(Debug)]
pub struct Stacked {
event: Event,
since: u16,
}
impl From<Event> for Stacked {
fn from(event: Event) -> Self {
Stacked { event, since: 0 }
}
}
impl Stacked {
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)]
struct TapHoldTracker {
coord: (u8, u8),
timeout: u16,
}
impl TapHoldTracker {
fn tick(&mut self) {
self.timeout = self.timeout.saturating_sub(1);
}
}
impl<const C: usize, const R: usize, const L: usize, T: 'static, K: 'static + Copy>
Layout<C, R, L, T, K>
{
/// Creates a new `Layout` object.
pub fn new(layers: &'static [[[Action<T, K>; C]; R]; L]) -> Self {
Self {
layers,
default_layer: 0,
states: Vec::new(),
waiting: None,
stacked: ArrayDeque::new(),
tap_hold_tracker: Default::default(),
}
}
/// Iterates on the key codes of the current state.
pub fn keycodes(&self) -> impl Iterator<Item = K> + '_ {
self.states.iter().filter_map(State::keycode)
}
fn waiting_into_hold(&mut self) -> CustomEvent<T> {
if let Some(w) = &self.waiting {
let hold = w.hold;
let coord = w.coord;
self.waiting = None;
if coord == self.tap_hold_tracker.coord {
self.tap_hold_tracker.timeout = 0;
}
self.do_action(hold, coord, 0)
} else {
CustomEvent::NoEvent
}
}
fn waiting_into_tap(&mut self) -> CustomEvent<T> {
if let Some(w) = &self.waiting {
let tap = w.tap;
let coord = w.coord;
self.waiting = None;
self.do_action(tap, coord, 0)
} else {
CustomEvent::NoEvent
}
}
fn drop_waiting(&mut self) -> CustomEvent<T> {
self.waiting = None;
CustomEvent::NoEvent
}
/// A time event.
///
/// This method must be called regularly, typically every millisecond.
///
/// Returns the corresponding `CustomEvent`, allowing to manage
/// custom actions thanks to the `Action::Custom` variant.
pub fn tick(&mut self) -> CustomEvent<T> {
self.states = self.states.iter().filter_map(State::tick).collect();
self.stacked.iter_mut().for_each(Stacked::tick);
self.tap_hold_tracker.tick();
match &mut self.waiting {
Some(w) => match w.tick(&self.stacked) {
Some(WaitingAction::Hold) => self.waiting_into_hold(),
Some(WaitingAction::Tap) => self.waiting_into_tap(),
Some(WaitingAction::NoOp) => self.drop_waiting(),
None => CustomEvent::NoEvent,
},
None => match self.stacked.pop_front() {
Some(s) => self.unstack(s),
None => CustomEvent::NoEvent,
},
}
}
fn unstack(&mut self, stacked: Stacked) -> CustomEvent<T> {
use Event::*;
match stacked.event {
Release(i, j) => {
let mut custom = CustomEvent::NoEvent;
self.states = self
.states
.iter()
.filter_map(|s| s.release((i, j), &mut custom))
.collect();
custom
}
Press(i, j) => {
let action = self.press_as_action((i, j), self.current_layer());
self.do_action(action, (i, j), stacked.since)
}
}
}
/// Register a key event.
pub fn event(&mut self, event: Event) {
if let Some(stacked) = self.stacked.push_back(event.into()) {
self.waiting_into_hold();
self.unstack(stacked);
}
}
fn press_as_action(&self, coord: (u8, u8), layer: usize) -> &'static Action<T, K> {
use crate::action::Action::*;
let action = self
.layers
.get(layer)
.and_then(|l| l.get(coord.0 as usize))
.and_then(|l| l.get(coord.1 as usize));
match action {
None => &NoOp,
Some(Trans) => {
if layer != self.default_layer {
self.press_as_action(coord, self.default_layer)
} else {
&NoOp
}
}
Some(action) => action,
}
}
fn do_action(
&mut self,
action: &'static Action<T, K>,
coord: (u8, u8),
delay: u16,
) -> CustomEvent<T> {
assert!(self.waiting.is_none());
use Action::*;
match action {
NoOp | Trans => (),
HoldTap(HoldTapAction {
timeout,
hold,
tap,
config,
tap_hold_interval,
}) => {
if *tap_hold_interval == 0
|| coord != self.tap_hold_tracker.coord
|| self.tap_hold_tracker.timeout == 0
{
let waiting: WaitingState<T, K> = WaitingState {
coord,
timeout: *timeout,
delay,
hold,
tap,
config: *config,
};
self.waiting = Some(waiting);
self.tap_hold_tracker.timeout = *tap_hold_interval;
} else {
self.tap_hold_tracker.timeout = 0;
self.do_action(tap, coord, delay);
}
// Need to set tap_hold_tracker coord AFTER the checks.
self.tap_hold_tracker.coord = coord;
}
&KeyCode(keycode) => {
self.tap_hold_tracker.coord = coord;
let _ = self.states.push(NormalKey { coord, keycode });
}
&MultipleKeyCodes(v) => {
self.tap_hold_tracker.coord = coord;
for &keycode in *v {
let _ = self.states.push(NormalKey { coord, keycode });
}
}
&MultipleActions(v) => {
self.tap_hold_tracker.coord = coord;
let mut custom = CustomEvent::NoEvent;
for action in *v {
custom.update(self.do_action(action, coord, delay));
}
return custom;
}
&Layer(value) => {
self.tap_hold_tracker.coord = coord;
let _ = self.states.push(LayerModifier { value, coord });
}
DefaultLayer(value) => {
self.tap_hold_tracker.coord = coord;
self.set_default_layer(*value);
}
Custom(value) => {
self.tap_hold_tracker.coord = coord;
if self.states.push(State::Custom { value, coord }).is_ok() {
return CustomEvent::Press(value);
}
}
}
CustomEvent::NoEvent
}
/// Obtain the index of the current active layer
pub fn current_layer(&self) -> usize {
self.states
.iter()
.rev()
.find_map(State::get_layer)
.unwrap_or(self.default_layer)
}
/// Sets the default layer for the layout
pub fn set_default_layer(&mut self, value: usize) {
if value < self.layers.len() {
self.default_layer = value
}
}
}
#[cfg(test)]
mod test {
extern crate std;
use super::{Event::*, Layout, *};
use crate::action::Action::*;
use crate::action::HoldTapConfig;
use crate::action::{k, l, m};
use crate::key_code::KeyCode;
use crate::key_code::KeyCode::*;
use std::collections::BTreeSet;
#[track_caller]
fn assert_keys(expected: &[KeyCode], iter: impl Iterator<Item = KeyCode>) {
let expected: BTreeSet<_> = expected.iter().copied().collect();
let tested = iter.collect();
assert_eq!(expected, tested);
}
#[test]
fn basic_hold_tap() {
static LAYERS: Layers<2, 1, 2> = [
[[
HoldTap(&HoldTapAction {
timeout: 200,
hold: l(1),
tap: k(Space),
config: HoldTapConfig::Default,
tap_hold_interval: 0,
}),
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(LCtrl),
tap: k(Enter),
config: HoldTapConfig::Default,
tap_hold_interval: 0,
}),
]],
[[Trans, m(&[LCtrl, Enter].as_slice())]],
];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Release(0, 0));
for _ in 0..197 {
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LCtrl], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LCtrl], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LCtrl, Space], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LCtrl], layout.keycodes());
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
#[test]
fn hold_tap_interleaved_timeout() {
static LAYERS: Layers<2, 1, 1> = [[[
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(LAlt),
tap: k(Space),
config: HoldTapConfig::Default,
tap_hold_interval: 0,
}),
HoldTap(&HoldTapAction {
timeout: 20,
hold: k(LCtrl),
tap: k(Enter),
config: HoldTapConfig::Default,
tap_hold_interval: 0,
}),
]]];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 1));
for _ in 0..15 {
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Space], layout.keycodes());
for _ in 0..10 {
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Space], layout.keycodes());
}
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Space, LCtrl], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LCtrl], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
#[test]
fn hold_on_press() {
static LAYERS: Layers<2, 1, 1> = [[[
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(LAlt),
tap: k(Space),
config: HoldTapConfig::HoldOnOtherKeyPress,
tap_hold_interval: 0,
}),
k(Enter),
]]];
let mut layout = Layout::new(&LAYERS);
// Press another key before timeout
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt, Enter], layout.keycodes());
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Enter], layout.keycodes());
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// Press another key after timeout
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 0));
for _ in 0..200 {
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt], layout.keycodes());
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt, Enter], layout.keycodes());
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Enter], layout.keycodes());
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
#[test]
fn permissive_hold() {
static LAYERS: Layers<2, 1, 1> = [[[
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(LAlt),
tap: k(Space),
config: HoldTapConfig::PermissiveHold,
tap_hold_interval: 0,
}),
k(Enter),
]]];
let mut layout = Layout::new(&LAYERS);
// Press and release another key before timeout
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt, Enter], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LAlt], layout.keycodes());
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
#[test]
fn stacked_hold_tap() {
static LAYERS: Layers<2, 1, 1> = [[[
k(Enter),
HoldTap(&HoldTapAction {
timeout: 10,
hold: k(LAlt),
tap: k(Space),
config: HoldTapConfig::Default,
tap_hold_interval: 0,
}),
]]];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
// Push 2 events in a row, without ticking:
// Press/Release attached to a HoldTap
layout.event(Press(0, 1));
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(CustomEvent::NoEvent, layout.tick());
}
#[test]
fn multiple_actions() {
static LAYERS: Layers<2, 1, 2> = [
[[MultipleActions(&[l(1), k(LShift)].as_slice()), k(F)]],
[[Trans, k(E)]],
];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LShift], layout.keycodes());
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LShift, E], layout.keycodes());
layout.event(Release(0, 1));
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[LShift], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
#[test]
fn custom() {
static LAYERS: Layers<1, 1, 1, u8> = [[[Action::Custom(42)]]];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// Custom event
layout.event(Press(0, 0));
assert_eq!(CustomEvent::Press(&42), layout.tick());
assert_keys(&[], layout.keycodes());
// nothing more
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// release custom
layout.event(Release(0, 0));
assert_eq!(CustomEvent::Release(&42), layout.tick());
assert_keys(&[], layout.keycodes());
}
#[test]
fn multiple_layers() {
static LAYERS: Layers<2, 1, 4> = [
[[l(1), l(2)]],
[[k(A), l(3)]],
[[l(0), k(B)]],
[[k(C), k(D)]],
];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(0, layout.current_layer());
assert_keys(&[], layout.keycodes());
// press L1
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(1, layout.current_layer());
assert_keys(&[], layout.keycodes());
// press L3 on L1
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(3, layout.current_layer());
assert_keys(&[], layout.keycodes());
// release L1, still on l3
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(3, layout.current_layer());
assert_keys(&[], layout.keycodes());
// press and release C on L3
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[C], layout.keycodes());
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// release L3, back to L0
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(0, layout.current_layer());
assert_keys(&[], layout.keycodes());
// back to empty, going to L2
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(2, layout.current_layer());
assert_keys(&[], layout.keycodes());
// and press the L0 key on L2
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(0, layout.current_layer());
assert_keys(&[], layout.keycodes());
// release the L0, back to L2
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(2, layout.current_layer());
assert_keys(&[], layout.keycodes());
// release the L2, back to L0
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_eq!(0, layout.current_layer());
assert_keys(&[], layout.keycodes());
}
#[test]
fn custom_handler() {
fn always_tap(_: StackedIter) -> Option<WaitingAction> {
Some(WaitingAction::Tap)
}
fn always_hold(_: StackedIter) -> Option<WaitingAction> {
Some(WaitingAction::Hold)
}
fn always_nop(_: StackedIter) -> Option<WaitingAction> {
Some(WaitingAction::NoOp)
}
fn always_none(_: StackedIter) -> Option<WaitingAction> {
None
}
static LAYERS: Layers<4, 1, 1> = [[[
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(Kb1),
tap: k(Kb0),
config: HoldTapConfig::Custom(always_tap),
tap_hold_interval: 0,
}),
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(Kb3),
tap: k(Kb2),
config: HoldTapConfig::Custom(always_hold),
tap_hold_interval: 0,
}),
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(Kb5),
tap: k(Kb4),
config: HoldTapConfig::Custom(always_nop),
tap_hold_interval: 0,
}),
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(Kb7),
tap: k(Kb6),
config: HoldTapConfig::Custom(always_none),
tap_hold_interval: 0,
}),
]]];
let mut layout = Layout::new(&LAYERS);
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// Custom handler always taps
layout.event(Press(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Kb0], layout.keycodes());
// nothing more
layout.event(Release(0, 0));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// Custom handler always holds
layout.event(Press(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Kb3], layout.keycodes());
// nothing more
layout.event(Release(0, 1));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// Custom handler always prevents any event
layout.event(Press(0, 2));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// even timeout does not trigger
for _ in 0..200 {
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// nothing more
layout.event(Release(0, 2));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
// Custom handler timeout fallback
layout.event(Press(0, 3));
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
for _ in 0..199 {
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[], layout.keycodes());
}
assert_eq!(CustomEvent::NoEvent, layout.tick());
assert_keys(&[Kb7], layout.keycodes());
}
#[test]
fn tap_hold_interval() {
static LAYERS: Layers<2, 1, 1> = [[[
HoldTap(&HoldTapAction {
timeout: 200,
hold: k(LAlt),
tap: k(Space),
config: HoldTapConfig::Default,
tap_hold_interval: 200,
}),
k(Enter),
]]];
let mut layout = Layout::new(&LAYERS);