-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathmod.rs
executable file
·3524 lines (3304 loc) · 127 KB
/
mod.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
//! This parses the configuration language to create a `kanata_keyberon::layout::Layout` as well as
//! associated metadata to help with processing.
//!
//! How the configuration maps to keyberon:
//!
//! If the mapped keys are defined as:
//!
//! (defsrc
//! esc 1 2 3 4
//! )
//!
//! and the layers are:
//!
//! (deflayer one
//! _ a s d _
//! )
//!
//! (deflayer two
//! _ a o e _
//! )
//!
//! Then the keyberon layers will be as follows:
//!
//! (xx means unimportant and _ means transparent)
//!
//! layers[0] = { xx, esc, a, s, d, 4, xx... }
//! layers[1] = { xx, _ , a, s, d, _, xx... }
//! layers[2] = { xx, esc, a, o, e, 4, xx... }
//! layers[3] = { xx, _ , a, o, e, _, xx... }
//!
//! Note that this example isn't practical, but `(defsrc esc 1 2 3 4)` is used because these keys
//! are at the beginning of the array. The column index for layers is the numerical value of
//! the key from `keys::OsCode`.
//!
//! In addition, there are two versions of each layer. One version delegates transparent entries to
//! the key defined in defsrc, while the other keeps them as actually transparent. This is to match
//! the behaviour in kmonad.
//!
//! The specific values in example above applies to Linux, but the same logic applies to Windows.
pub mod sexpr;
pub(crate) mod alloc;
use alloc::*;
mod key_override;
use crate::sequences::*;
use kanata_keyberon::chord::ChordsV2;
pub use key_override::*;
mod custom_tap_hold;
use custom_tap_hold::*;
pub mod layer_opts;
use layer_opts::*;
pub mod list_actions;
use list_actions::*;
mod defcfg;
pub use defcfg::*;
mod deftemplate;
pub use deftemplate::*;
mod switch;
pub use switch::*;
use crate::custom_action::*;
use crate::keys::*;
use crate::layers::*;
mod error;
pub use error::*;
mod chord;
use chord::*;
mod fake_key;
use fake_key::*;
pub use fake_key::{FAKE_KEY_ROW, NORMAL_KEY_ROW};
mod platform;
use platform::*;
mod is_a_button;
use is_a_button::*;
mod key_outputs;
pub use key_outputs::*;
mod permutations;
use permutations::*;
mod str_ext;
pub use str_ext::*;
use crate::trie::Trie;
use anyhow::anyhow;
use std::cell::Cell;
use std::collections::hash_map::Entry;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Arc;
type HashSet<T> = rustc_hash::FxHashSet<T>;
type HashMap<K, V> = rustc_hash::FxHashMap<K, V>;
use kanata_keyberon::action::*;
use kanata_keyberon::key_code::*;
use kanata_keyberon::layout::*;
use sexpr::*;
#[cfg(test)]
mod tests;
#[cfg(test)]
pub use sexpr::parse;
#[macro_export]
macro_rules! bail {
($err:expr $(,)?) => {
return Err(ParseError::from(anyhow::anyhow!($err)))
};
($fmt:expr, $($arg:tt)*) => {
return Err(ParseError::from(anyhow::anyhow!($fmt, $($arg)*)))
};
}
#[macro_export]
macro_rules! bail_expr {
($expr:expr, $fmt:expr $(,)?) => {
return Err(ParseError::from_expr($expr, format!($fmt)))
};
($expr:expr, $fmt:expr, $($arg:tt)*) => {
return Err(ParseError::from_expr($expr, format!($fmt, $($arg)*)))
};
}
#[macro_export]
macro_rules! err_expr {
($expr:expr, $fmt:expr $(,)?) => {
Err(ParseError::from_expr($expr, format!($fmt)))
};
($expr:expr, $fmt:expr, $($arg:tt)*) => {
Err(ParseError::from_expr($expr, format!($fmt, $($arg)*)))
};
}
#[macro_export]
macro_rules! bail_span {
($expr:expr, $fmt:expr $(,)?) => {
return Err(ParseError::from_spanned($expr, format!($fmt)))
};
($expr:expr, $fmt:expr, $($arg:tt)*) => {
return Err(ParseError::from_spanned($expr, format!($fmt, $($arg)*)))
};
}
#[macro_export]
macro_rules! err_span {
($expr:expr, $fmt:expr $(,)?) => {
Err(ParseError::from_spanned($expr, format!($fmt)))
};
($expr:expr, $fmt:expr, $($arg:tt)*) => {
Err(ParseError::from_spanned($expr, format!($fmt, $($arg)*)))
};
}
#[macro_export]
macro_rules! anyhow_expr {
($expr:expr, $fmt:expr $(,)?) => {
ParseError::from_expr($expr, format!($fmt))
};
($expr:expr, $fmt:expr, $($arg:tt)*) => {
ParseError::from_expr($expr, format!($fmt, $($arg)*))
};
}
#[macro_export]
macro_rules! anyhow_span {
($expr:expr, $fmt:expr $(,)?) => {
ParseError::from_spanned($expr, format!($fmt))
};
($expr:expr, $fmt:expr, $($arg:tt)*) => {
ParseError::from_spanned($expr, format!($fmt, $($arg)*))
};
}
pub struct FileContentProvider<'a> {
/// A function to load content of a file from a filepath.
/// Optionally, it could implement caching and a mechanism preventing "file" and "./file"
/// from loading twice.
get_file_content_fn: &'a mut dyn FnMut(&Path) -> std::result::Result<String, String>,
}
impl<'a> FileContentProvider<'a> {
pub fn new(
get_file_content_fn: &'a mut impl FnMut(&Path) -> std::result::Result<String, String>,
) -> Self {
Self {
get_file_content_fn,
}
}
pub fn get_file_content(&mut self, filename: &Path) -> std::result::Result<String, String> {
(self.get_file_content_fn)(filename)
}
}
pub type KanataCustom = &'static &'static [&'static CustomAction];
pub type KanataAction = Action<'static, KanataCustom>;
type KLayout = Layout<'static, KEYS_IN_ROW, 2, KanataCustom>;
type TapHoldCustomFunc =
fn(
&[OsCode],
&Allocations,
) -> &'static (dyn Fn(QueuedIter) -> (Option<WaitingAction>, bool) + Send + Sync);
pub type BorrowedKLayout<'a> = Layout<'a, KEYS_IN_ROW, 2, &'a &'a [&'a CustomAction]>;
pub type KeySeqsToFKeys = Trie;
pub struct KanataLayout {
layout: KLayout,
_allocations: Arc<Allocations>,
}
impl KanataLayout {
fn new(layout: KLayout, a: Arc<Allocations>) -> Self {
Self {
layout,
_allocations: a,
}
}
/// bm stands for borrow mut.
pub fn bm(&mut self) -> &mut BorrowedKLayout {
// shrink the lifetime
unsafe { std::mem::transmute(&mut self.layout) }
}
/// b stands for borrow.
pub fn b(&self) -> &BorrowedKLayout {
// shrink the lifetime
unsafe { std::mem::transmute(&self.layout) }
}
}
pub struct Cfg {
/// The list of keys that kanata should be processing. Keys that are missing from `mapped_keys`
/// that are received from the OS input mechanism will be forwarded to OS output mechanism
/// without going through kanata's processing.
pub mapped_keys: MappedKeys,
/// The potential outputs for a physical key position. The intention behind this is for sending
/// key repeats.
pub key_outputs: KeyOutputs,
/// Layer info used for printing to the logs.
pub layer_info: Vec<LayerInfo>,
/// Configuration items in `defcfg`.
pub options: CfgOptions,
/// The keyberon layout state machine struct.
pub layout: KanataLayout,
/// Sequences defined in `defseq`.
pub sequences: KeySeqsToFKeys,
/// Overrides defined in `defoverrides`.
pub overrides: Overrides,
/// Mapping of fake key name to its column in the fake key row.
pub fake_keys: HashMap<String, usize>,
/// The maximum value of switch's key-timing item in the configuration.
pub switch_max_key_timing: u16,
}
/// Parse a new configuration from a file.
pub fn new_from_file(p: &Path) -> MResult<Cfg> {
parse_cfg(p)
}
pub fn new_from_str(cfg_text: &str) -> MResult<Cfg> {
let mut s = ParserState::default();
let icfg = parse_cfg_raw_string(
cfg_text,
&mut s,
&PathBuf::from("configuration"),
&mut FileContentProvider {
get_file_content_fn: &mut |_| Err("include is not supported".into()),
},
DEF_LOCAL_KEYS,
Err("environment variables are not supported".into()),
)?;
let (layers, allocations) = icfg.klayers.get();
let key_outputs = create_key_outputs(&layers, &icfg.overrides, &icfg.chords_v2);
let switch_max_key_timing = s.switch_max_key_timing.get();
let mut layout = KanataLayout::new(
Layout::new_with_trans_action_settings(
s.a.sref(s.defsrc_layer),
layers,
icfg.options.trans_resolution_behavior_v2,
icfg.options.delegate_to_first_layer,
),
allocations,
);
layout.bm().chords_v2 = icfg.chords_v2;
layout.bm().quick_tap_hold_timeout = icfg.options.concurrent_tap_hold;
layout.bm().oneshot.on_press_release_delay = icfg.options.rapid_event_delay;
let mut fake_keys: HashMap<String, usize> = s
.virtual_keys
.iter()
.map(|(k, v)| (k.clone(), v.0))
.collect();
fake_keys.shrink_to_fit();
log::info!("config file is valid");
Ok(Cfg {
options: icfg.options,
mapped_keys: icfg.mapped_keys,
layer_info: icfg.layer_info,
key_outputs,
layout,
sequences: icfg.sequences,
overrides: icfg.overrides,
fake_keys,
switch_max_key_timing,
})
}
pub type MappedKeys = HashSet<OsCode>;
#[derive(Debug)]
pub struct LayerInfo {
pub name: String,
pub cfg_text: String,
pub icon: Option<String>,
}
#[allow(clippy::type_complexity)] // return type is not pub
fn parse_cfg(p: &Path) -> MResult<Cfg> {
let mut s = ParserState::default();
let icfg = parse_cfg_raw(p, &mut s)?;
let (layers, allocations) = icfg.klayers.get();
let key_outputs = create_key_outputs(&layers, &icfg.overrides, &icfg.chords_v2);
let switch_max_key_timing = s.switch_max_key_timing.get();
let mut layout = KanataLayout::new(
Layout::new_with_trans_action_settings(
s.a.sref(s.defsrc_layer),
layers,
icfg.options.trans_resolution_behavior_v2,
icfg.options.delegate_to_first_layer,
),
allocations,
);
layout.bm().chords_v2 = icfg.chords_v2;
layout.bm().quick_tap_hold_timeout = icfg.options.concurrent_tap_hold;
layout.bm().oneshot.on_press_release_delay = icfg.options.rapid_event_delay;
let mut fake_keys: HashMap<String, usize> = s
.virtual_keys
.iter()
.map(|(k, v)| (k.clone(), v.0))
.collect();
fake_keys.shrink_to_fit();
log::info!("config file is valid");
Ok(Cfg {
options: icfg.options,
mapped_keys: icfg.mapped_keys,
layer_info: icfg.layer_info,
key_outputs,
layout,
sequences: icfg.sequences,
overrides: icfg.overrides,
fake_keys,
switch_max_key_timing,
})
}
#[cfg(all(
not(feature = "interception_driver"),
any(
not(feature = "win_llhook_read_scancodes"),
not(feature = "win_sendinput_send_scancodes")
),
target_os = "windows"
))]
const DEF_LOCAL_KEYS: &str = "deflocalkeys-win";
#[cfg(all(
feature = "win_llhook_read_scancodes",
feature = "win_sendinput_send_scancodes",
target_os = "windows"
))]
const DEF_LOCAL_KEYS: &str = "deflocalkeys-winiov2";
#[cfg(all(feature = "interception_driver", target_os = "windows"))]
const DEF_LOCAL_KEYS: &str = "deflocalkeys-wintercept";
#[cfg(target_os = "macos")]
const DEF_LOCAL_KEYS: &str = "deflocalkeys-macos";
#[cfg(any(target_os = "linux", target_os = "unknown"))]
const DEF_LOCAL_KEYS: &str = "deflocalkeys-linux";
#[derive(Debug)]
pub struct IntermediateCfg {
pub options: CfgOptions,
pub mapped_keys: MappedKeys,
pub layer_info: Vec<LayerInfo>,
pub klayers: KanataLayers,
pub sequences: KeySeqsToFKeys,
pub overrides: Overrides,
pub chords_v2: Option<ChordsV2<'static, KanataCustom>>,
}
// A snapshot of enviroment variables, or an error message with an explanation
// why env vars are not not supported.
pub type EnvVars = std::result::Result<Vec<(String, String)>, String>;
#[allow(clippy::type_complexity)] // return type is not pub
fn parse_cfg_raw(p: &Path, s: &mut ParserState) -> MResult<IntermediateCfg> {
const INVALID_PATH_ERROR: &str = "The provided config file path is not valid";
let mut loaded_files: HashSet<PathBuf> = HashSet::default();
let mut get_file_content_fn_impl = |filepath: &Path| {
// Make the include paths relative to main config file instead of kanata executable.
let filepath_relative_to_loaded_kanata_cfg = if filepath.is_absolute() {
filepath.to_owned()
} else {
let relative_main_cfg_file_dir = p.parent().ok_or(INVALID_PATH_ERROR)?;
relative_main_cfg_file_dir.join(filepath)
};
let abs_filepath: PathBuf = filepath_relative_to_loaded_kanata_cfg
.canonicalize()
.map_err(|e| {
format!(
"Failed to resolve relative path: {}: {}",
filepath_relative_to_loaded_kanata_cfg.to_string_lossy(),
e
)
})?;
// Forbid loading the same file multiple times.
// This prevents a potential recursive infinite loop of includes
// (if includes within includes were to be allowed).
if !loaded_files.insert(abs_filepath.clone()) {
return Err("The provided config file was already included before".to_string());
};
std::fs::read_to_string(abs_filepath.to_str().ok_or(INVALID_PATH_ERROR)?)
.map_err(|e| format!("Failed to include file: {e}"))
};
let mut file_content_provider = FileContentProvider::new(&mut get_file_content_fn_impl);
// `get_file_content_fn_impl` already uses CWD of the main config path,
// so we need to provide only the name, not the whole path.
let cfg_file_name: PathBuf = p
.file_name()
.ok_or_else(|| miette::miette!(INVALID_PATH_ERROR))?
.into();
let text = file_content_provider
.get_file_content(&cfg_file_name)
.map_err(|e| miette::miette!(e))?;
let env_vars: EnvVars = Ok(std::env::vars().collect());
parse_cfg_raw_string(
&text,
s,
p,
&mut file_content_provider,
DEF_LOCAL_KEYS,
env_vars,
)
.map_err(|e| e.into())
}
fn expand_includes(
xs: Vec<TopLevel>,
file_content_provider: &mut FileContentProvider,
) -> Result<Vec<TopLevel>> {
let include_is_first_atom = gen_first_atom_filter("include");
xs.iter().try_fold(Vec::new(), |mut acc, spanned_exprs| {
if include_is_first_atom(&&spanned_exprs.t) {
let mut exprs =
check_first_expr(spanned_exprs.t.iter(), "include").expect("can't fail");
let expr = exprs.next().ok_or(anyhow_span!(
spanned_exprs,
"Every include block must contain exactly one filepath"
))?;
let spanned_filepath = match expr {
SExpr::Atom(filepath) => filepath,
SExpr::List(_) => {
bail_expr!(expr, "Filepath cannot be a list")
}
};
if let Some(expr) = exprs.next() {
bail_expr!(
expr,
"Multiple filepaths are not allowed in include blocks. If you want to include multiple files, create a new include block for each of them."
)
};
let include_file_path = spanned_filepath.t.trim_atom_quotes();
let file_content = file_content_provider.get_file_content(Path::new(include_file_path))
.map_err(|e| anyhow_span!(spanned_filepath, "{e}"))?;
let tree = sexpr::parse(&file_content, include_file_path)?;
acc.extend(tree);
Ok(acc)
} else {
acc.push(spanned_exprs.clone());
Ok(acc)
}
})
}
const DEFLAYER: &str = "deflayer";
const DEFLAYER_MAPPED: &str = "deflayermap";
const DEFLOCALKEYS_VARIANTS: &[&str] = &[
"deflocalkeys-win",
"deflocalkeys-winiov2",
"deflocalkeys-wintercept",
"deflocalkeys-linux",
"deflocalkeys-macos",
];
#[derive(Debug, Clone)]
pub struct LspHintInactiveCode {
pub span: Span,
pub reason: String,
}
#[allow(clippy::type_complexity)] // return type is not pub
pub fn parse_cfg_raw_string(
text: &str,
s: &mut ParserState,
cfg_path: &Path,
file_content_provider: &mut FileContentProvider,
def_local_keys_variant_to_apply: &str,
env_vars: EnvVars,
) -> Result<IntermediateCfg> {
let mut lsp_hint_inactive_code: Vec<LspHintInactiveCode> = vec![];
let spanned_root_exprs = sexpr::parse(text, &cfg_path.to_string_lossy())
.and_then(|xs| expand_includes(xs, file_content_provider))
.and_then(|xs| {
filter_platform_specific_cfg(
xs,
def_local_keys_variant_to_apply,
&mut lsp_hint_inactive_code,
)
})
.and_then(|xs| filter_env_specific_cfg(xs, &env_vars, &mut lsp_hint_inactive_code))
.and_then(expand_templates)?;
if let Some(spanned) = spanned_root_exprs
.iter()
.find(gen_first_atom_filter_spanned("include"))
{
bail_span!(spanned, "Nested includes are not allowed.")
}
let root_exprs: Vec<_> = spanned_root_exprs.iter().map(|t| t.t.clone()).collect();
error_on_unknown_top_level_atoms(&spanned_root_exprs)?;
let mut local_keys: Option<HashMap<String, OsCode>> = None;
clear_custom_str_oscode_mapping();
for def_local_keys_variant in DEFLOCALKEYS_VARIANTS {
if let Some((result, span)) = spanned_root_exprs
.iter()
.find(gen_first_atom_filter_spanned(def_local_keys_variant))
.map(|x| {
(
parse_deflocalkeys(def_local_keys_variant, &x.t),
x.span.clone(),
)
})
{
let mapping = result?;
if def_local_keys_variant == &def_local_keys_variant_to_apply {
assert!(
local_keys.is_none(),
">1 mutually exclusive deflocalkeys variants were parsed"
);
local_keys = Some(mapping);
} else {
lsp_hint_inactive_code.push(LspHintInactiveCode {
span,
reason: format!(
"Another localkeys variant is currently active: {def_local_keys_variant_to_apply}"
),
})
}
}
if let Some(spanned) = spanned_root_exprs
.iter()
.filter(gen_first_atom_filter_spanned(def_local_keys_variant))
.nth(1)
{
bail_span!(
spanned,
"Only one {def_local_keys_variant} is allowed, found more. Delete the extras."
)
}
}
replace_custom_str_oscode_mapping(&local_keys.unwrap_or_default());
let cfg = root_exprs
.iter()
.find(gen_first_atom_filter("defcfg"))
.map(|cfg| parse_defcfg(cfg))
.transpose()?
.unwrap_or_default();
if let Some(spanned) = spanned_root_exprs
.iter()
.filter(gen_first_atom_filter_spanned("defcfg"))
.nth(1)
{
bail_span!(
spanned,
"Only one defcfg is allowed, found more. Delete the extras."
)
}
let src_expr = root_exprs
.iter()
.find(gen_first_atom_filter("defsrc"))
.ok_or_else(|| anyhow!("Exactly one defsrc must exist; found none"))?;
if let Some(spanned) = spanned_root_exprs
.iter()
.filter(gen_first_atom_filter_spanned("defsrc"))
.nth(1)
{
bail_span!(
spanned,
"Exactly one defsrc is allowed, found more. Delete the extras."
)
}
let (mut mapped_keys, mapping_order) = parse_defsrc(src_expr, &cfg)?;
let var_exprs = root_exprs
.iter()
.filter(gen_first_atom_filter("defvar"))
.collect::<Vec<_>>();
parse_vars(&var_exprs, s)?;
let deflayer_labels = [DEFLAYER, DEFLAYER_MAPPED];
let deflayer_spanned_filter = |exprs: &&Spanned<Vec<SExpr>>| -> bool {
if exprs.t.is_empty() {
return false;
}
if let SExpr::Atom(atom) = &exprs.t[0] {
deflayer_labels.contains(&atom.t.as_str())
} else {
false
}
};
let layer_exprs = spanned_root_exprs
.iter()
.filter(deflayer_spanned_filter)
.cloned()
.map(|e| match e.t[0].atom(None).unwrap() {
DEFLAYER => SpannedLayerExprs::DefsrcMapping(e.clone()),
DEFLAYER_MAPPED => SpannedLayerExprs::CustomMapping(e.clone()),
_ => unreachable!(),
})
.collect::<Vec<_>>();
if layer_exprs.is_empty() {
bail!("No deflayer expressions exist. At least one layer must be defined.")
}
let (layer_idxs, layer_icons) = parse_layer_indexes(&layer_exprs, mapping_order.len(), s)?;
let mut sorted_idxs: Vec<(&String, &usize)> =
layer_idxs.iter().map(|tuple| (tuple.0, tuple.1)).collect();
sorted_idxs.sort_by_key(|f| f.1);
#[allow(clippy::needless_collect)]
// Clippy suggests using the sorted_idxs iter directly and manipulating it
// to produce the layer_names vec when creating Vec<LayerInfo> below
let layer_names = sorted_idxs
.into_iter()
.map(|(name, _)| (*name).clone())
.collect::<Vec<_>>();
let deflayer_filter = |exprs: &&Vec<SExpr>| -> bool {
if exprs.is_empty() {
return false;
}
if let SExpr::Atom(atom) = &exprs[0] {
deflayer_labels.contains(&atom.t.as_str())
} else {
false
}
};
let layer_strings = spanned_root_exprs
.iter()
.filter(|expr| deflayer_filter(&&expr.t))
.map(|expr| expr.span.file_content()[expr.span.clone()].to_string())
.collect::<Vec<_>>();
let layer_info: Vec<LayerInfo> = layer_names
.into_iter()
.zip(layer_strings)
.map(|(name, cfg_text)| LayerInfo {
name: name.clone(),
cfg_text,
icon: layer_icons.get(&name).unwrap_or(&None).clone(),
})
.collect();
let defsrc_layer = create_defsrc_layer();
let deflayer_filter = |exprs: &&Vec<SExpr>| -> bool {
if exprs.is_empty() {
return false;
}
if let SExpr::Atom(atom) = &exprs[0] {
deflayer_labels.contains(&atom.t.as_str())
} else {
false
}
};
let layer_exprs = root_exprs
.iter()
.filter(deflayer_filter)
.cloned()
.map(|e| match e[0].atom(None).unwrap() {
DEFLAYER => LayerExprs::DefsrcMapping(e.clone()),
DEFLAYER_MAPPED => LayerExprs::CustomMapping(e.clone()),
_ => unreachable!(),
})
.collect::<Vec<_>>();
*s = ParserState {
a: s.a.clone(),
layer_exprs,
layer_idxs,
mapping_order,
defsrc_layer,
is_cmd_enabled: {
#[cfg(feature = "cmd")]
{
if cfg.enable_cmd {
log::warn!("DANGER! cmd action is enabled.");
true
} else {
false
}
}
#[cfg(not(feature = "cmd"))]
{
log::info!("NOTE: kanata was compiled to never allow cmd");
false
}
},
delegate_to_first_layer: cfg.delegate_to_first_layer,
default_sequence_timeout: cfg.sequence_timeout,
default_sequence_input_mode: cfg.sequence_input_mode,
block_unmapped_keys: cfg.block_unmapped_keys,
lsp_hint_inactive_code,
vars: s.vars.clone(),
..Default::default()
};
let chords_exprs = spanned_root_exprs
.iter()
.filter(gen_first_atom_filter_spanned("defchords"))
.collect::<Vec<_>>();
parse_chord_groups(&chords_exprs, s)?;
let fake_keys_exprs = root_exprs
.iter()
.filter(gen_first_atom_filter("deffakekeys"))
.collect::<Vec<_>>();
parse_fake_keys(&fake_keys_exprs, s)?;
let vkeys_exprs = root_exprs
.iter()
.filter(gen_first_atom_filter("defvirtualkeys"))
.collect::<Vec<_>>();
parse_virtual_keys(&vkeys_exprs, s)?;
let sequence_exprs = root_exprs
.iter()
.filter(gen_first_atom_filter("defseq"))
.collect::<Vec<_>>();
let sequences = parse_sequences(&sequence_exprs, s)?;
let alias_exprs = spanned_root_exprs
.iter()
.filter(gen_first_atom_start_filter_spanned("defalias"))
.collect::<Vec<_>>();
parse_aliases(&alias_exprs, s, &env_vars)?;
let mut klayers = parse_layers(s, &mut mapped_keys, &cfg)?;
resolve_chord_groups(&mut klayers, s)?;
let layers = s.a.bref_slice(klayers);
s.layers = layers;
let override_exprs = root_exprs
.iter()
.filter(gen_first_atom_filter("defoverrides"))
.collect::<Vec<_>>();
let overrides = match override_exprs.len() {
0 => Overrides::new(&[]),
1 => parse_overrides(override_exprs[0], s)?,
_ => {
let spanned = spanned_root_exprs
.iter()
.filter(gen_first_atom_filter_spanned("defoverrides"))
.nth(1)
.expect("> 2 overrides");
bail_span!(
spanned,
"Only one defoverrides allowed, found more. Delete the extras."
)
}
};
s.trans_forbidden_reason = Some("Transparent action is forbidden within chordsv2");
let chords_v2_exprs = root_exprs
.iter()
.filter(gen_first_atom_filter("defchordsv2-experimental"))
.collect::<Vec<_>>();
let chords_v2 = match chords_v2_exprs.len() {
0 => None,
1 => {
let cfks = parse_defchordv2(chords_v2_exprs[0], s)?;
Some(ChordsV2::new(cfks, cfg.chords_v2_min_idle))
}
_ => {
let spanned = spanned_root_exprs
.iter()
.filter(gen_first_atom_filter_spanned("defchordsv2-experimental"))
.nth(1)
.expect("> 2 overrides");
bail_span!(
spanned,
"Only one defchordsv2 allowed, found more.\nDelete the extras."
)
}
};
s.trans_forbidden_reason = None;
if chords_v2.is_some() && !cfg.concurrent_tap_hold {
return Err(anyhow!(
"With defchordsv2 defined, concurrent-tap-hold in defcfg must be true.\n\
It is currently false or unspecified."
)
.into());
}
let klayers = unsafe { KanataLayers::new(layers, s.a.clone()) };
Ok(IntermediateCfg {
options: cfg,
mapped_keys,
layer_info,
klayers,
sequences,
overrides,
chords_v2,
})
}
fn error_on_unknown_top_level_atoms(exprs: &[Spanned<Vec<SExpr>>]) -> Result<()> {
for expr in exprs {
expr.t
.first()
.ok_or_else(|| {
anyhow_span!(
expr,
"Found empty list as a configuration item, you should delete this"
)
})?
.atom(None)
.map(|a| match a {
"defcfg"
| "defalias"
| "defaliasenvcond"
| "defsrc"
| DEFLAYER
| DEFLAYER_MAPPED
| "defoverrides"
| "deflocalkeys-macos"
| "deflocalkeys-linux"
| "deflocalkeys-win"
| "deflocalkeys-winiov2"
| "deflocalkeys-wintercept"
| "deffakekeys"
| "defvirtualkeys"
| "defchords"
| "defvar"
| "deftemplate"
| "defchordsv2-experimental"
| "defseq" => Ok(()),
_ => err_span!(expr, "Found unknown configuration item"),
})
.ok_or_else(|| {
anyhow_expr!(
expr.t.first().expect("not empty"),
"Invalid: found list as first item in a configuration item"
)
})??;
}
Ok(())
}
/// Return a closure that filters a root expression by the content of the first element. The
/// closure returns true if the first element is an atom that matches the input `a` and false
/// otherwise.
fn gen_first_atom_filter(a: &str) -> impl Fn(&&Vec<SExpr>) -> bool {
let a = a.to_owned();
move |expr| {
if expr.is_empty() {
return false;
}
if let SExpr::Atom(atom) = &expr[0] {
atom.t == a
} else {
false
}
}
}
/// Return a closure that filters a root expression by the content of the first element. The
/// closure returns true if the first element is an atom that starts with the input `a` and false
/// otherwise.
fn gen_first_atom_start_filter_spanned(a: &str) -> impl Fn(&&Spanned<Vec<SExpr>>) -> bool {
let a = a.to_owned();
move |expr| {
if expr.t.is_empty() {
return false;
}
if let SExpr::Atom(atom) = &expr.t[0] {
atom.t.starts_with(&a)
} else {
false
}
}
}
/// Return a closure that filters a root expression by the content of the first element. The
/// closure returns true if the first element is an atom that matches the input `a` and false
/// otherwise.
fn gen_first_atom_filter_spanned(a: &str) -> impl Fn(&&Spanned<Vec<SExpr>>) -> bool {
let a = a.to_owned();
move |expr| {
if expr.t.is_empty() {
return false;
}
if let SExpr::Atom(atom) = &expr.t[0] {
atom.t == a
} else {
false
}
}
}
/// Consumes the first element and returns the rest of the iterator. Returns `Ok` if the first
/// element is an atom and equals `expected_first`.
fn check_first_expr<'a>(
mut exprs: impl Iterator<Item = &'a SExpr>,
expected_first: &str,
) -> Result<impl Iterator<Item = &'a SExpr>> {
let first_atom = exprs
.next()
.ok_or_else(|| anyhow!("Passed empty list to {expected_first}"))?
.atom(None)
.ok_or_else(|| anyhow!("First entry is expected to be an atom for {expected_first}"))?;
if first_atom != expected_first {
bail!("Passed non-{expected_first} expression to {expected_first}: {first_atom}");
}
Ok(exprs)
}
/// Parse custom keys from an expression starting with deflocalkeys.
fn parse_deflocalkeys(
def_local_keys_variant: &str,
expr: &[SExpr],
) -> Result<HashMap<String, OsCode>> {
let mut localkeys = HashMap::default();
let mut exprs = check_first_expr(expr.iter(), def_local_keys_variant)?;
// Read k-v pairs from the configuration
while let Some(key_expr) = exprs.next() {
let key = key_expr.atom(None).ok_or_else(|| {
anyhow_expr!(key_expr, "No lists are allowed in {def_local_keys_variant}")
})?;
if localkeys.contains_key(key) {
bail_expr!(
key_expr,
"Duplicate {key} found in {def_local_keys_variant}"
);
}
let osc = match exprs.next() {
Some(v) => v
.atom(None)
.ok_or_else(|| anyhow_expr!(v, "No lists are allowed in {def_local_keys_variant}"))
.and_then(|osc| {
osc.parse::<u16>().map_err(|_| {
anyhow_expr!(v, "Unknown number in {def_local_keys_variant}: {osc}")
})
})
.and_then(|osc| {
OsCode::from_u16(osc).ok_or_else(|| {
anyhow_expr!(v, "Unknown number in {def_local_keys_variant}: {osc}")
})