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
use super::error::*;
use super::sexpr::SExpr;
use super::HashSet;
use crate::cfg::check_first_expr;
use crate::custom_action::*;
#[allow(unused)]
use crate::{anyhow_expr, anyhow_span, bail, bail_expr};

#[derive(Debug)]
pub struct CfgOptions {
    pub process_unmapped_keys: bool,
    pub enable_cmd: bool,
    pub sequence_timeout: u16,
    pub sequence_input_mode: SequenceInputMode,
    pub sequence_backtrack_modcancel: bool,
    pub log_layer_changes: bool,
    pub delegate_to_first_layer: bool,
    pub movemouse_inherit_accel_state: bool,
    pub movemouse_smooth_diagonals: bool,
    pub dynamic_macro_max_presses: u16,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_dev: Vec<String>,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_dev_names_include: Option<Vec<String>>,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_dev_names_exclude: Option<Vec<String>>,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_continue_if_no_devs_found: bool,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_unicode_u_code: crate::keys::OsCode,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_unicode_termination: UnicodeTermination,
    #[cfg(any(target_os = "linux", target_os = "unknown"))]
    pub linux_x11_repeat_delay_rate: Option<KeyRepeatSettings>,
    #[cfg(any(target_os = "windows", target_os = "unknown"))]
    pub windows_altgr: AltGrBehaviour,
    #[cfg(any(
        all(feature = "interception_driver", target_os = "windows"),
        target_os = "unknown"
    ))]
    pub windows_interception_mouse_hwid: Option<[u8; HWID_ARR_SZ]>,
}

impl Default for CfgOptions {
    fn default() -> Self {
        Self {
            process_unmapped_keys: false,
            enable_cmd: false,
            sequence_timeout: 1000,
            sequence_input_mode: SequenceInputMode::HiddenSuppressed,
            sequence_backtrack_modcancel: true,
            log_layer_changes: true,
            delegate_to_first_layer: false,
            movemouse_inherit_accel_state: false,
            movemouse_smooth_diagonals: false,
            dynamic_macro_max_presses: 128,
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            linux_dev: vec![],
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            linux_dev_names_include: None,
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            linux_dev_names_exclude: None,
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            linux_continue_if_no_devs_found: false,
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            // historically was the only option, so make KEY_U the default
            linux_unicode_u_code: crate::keys::OsCode::KEY_U,
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            // historically was the only option, so make Enter the default
            linux_unicode_termination: UnicodeTermination::Enter,
            #[cfg(any(target_os = "linux", target_os = "unknown"))]
            linux_x11_repeat_delay_rate: None,
            #[cfg(any(target_os = "windows", target_os = "unknown"))]
            windows_altgr: AltGrBehaviour::default(),
            #[cfg(any(
                all(feature = "interception_driver", target_os = "windows"),
                target_os = "unknown"
            ))]
            windows_interception_mouse_hwid: None,
        }
    }
}

/// Parse configuration entries from an expression starting with defcfg.
pub fn parse_defcfg(expr: &[SExpr]) -> Result<CfgOptions> {
    let mut seen_keys = HashSet::default();
    let mut cfg = CfgOptions::default();
    let mut exprs = check_first_expr(expr.iter(), "defcfg")?;
    // Read k-v pairs from the configuration
    loop {
        let key = match exprs.next() {
            Some(k) => k,
            None => return Ok(cfg),
        };
        let val = match exprs.next() {
            Some(v) => v,
            None => bail_expr!(key, "Found a defcfg option missing a value"),
        };
        match (&key, &val) {
            (SExpr::Atom(k), SExpr::Atom(v)) => {
                if !seen_keys.insert(&k.t) {
                    bail_expr!(key, "Duplicate defcfg option {}", k.t);
                }
                match k.t.as_str() {
                    k @ "sequence-timeout" => {
                        cfg.sequence_timeout = parse_cfg_val_u16(val, k, true)?;
                    }
                    "sequence-input-mode" => {
                        cfg.sequence_input_mode =
                            SequenceInputMode::try_from_str(&v.t.trim_matches('"'))
                                .map_err(|e| anyhow_expr!(val, "{}", e.to_string()))?;
                    }
                    k @ "dynamic-macro-max-presses" => {
                        cfg.dynamic_macro_max_presses = parse_cfg_val_u16(val, k, false)?;
                    }
                    "linux-dev" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            let paths = v.t.trim_matches('"');
                            cfg.linux_dev = parse_colon_separated_text(paths);
                        }
                    }
                    "linux-dev-names-include" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            let paths = v.t.trim_matches('"');
                            cfg.linux_dev_names_include = Some(parse_colon_separated_text(paths));
                        }
                    }
                    "linux-dev-names-exclude" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            let paths = v.t.trim_matches('"');
                            cfg.linux_dev_names_exclude = Some(parse_colon_separated_text(paths));
                        }
                    }
                    _k @ "linux-unicode-u-code" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            cfg.linux_unicode_u_code = crate::keys::str_to_oscode(
                                v.t.trim_matches('"'),
                            )
                            .ok_or_else(|| anyhow_expr!(val, "unknown code for {_k}: {}", v.t))?;
                        }
                    }
                    _k @ "linux-unicode-termination" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            cfg.linux_unicode_termination = match v.t.trim_matches('"') {
                                "enter" => UnicodeTermination::Enter,
                                "space" => UnicodeTermination::Space,
                                "enter-space" => UnicodeTermination::EnterSpace,
                                "space-enter" => UnicodeTermination::SpaceEnter,
                                _ => bail_expr!(
                                    val,
                                    "{_k} got {}. It accepts: enter|space|enter-space|space-enter",
                                    v.t
                                ),
                            }
                        }
                    }
                    "linux-x11-repeat-delay-rate" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            let delay_rate = v.t.trim_matches('"').split(',').collect::<Vec<_>>();
                            const ERRMSG: &str = "Invalid value for linux-x11-repeat-delay-rate.\nExpected two numbers 0-65535 separated by a comma, e.g. 200,25";
                            if delay_rate.len() != 2 {
                                bail_expr!(val, "{}", ERRMSG)
                            }
                            cfg.linux_x11_repeat_delay_rate = Some(KeyRepeatSettings {
                                delay: match str::parse::<u16>(delay_rate[0]) {
                                    Ok(delay) => delay,
                                    Err(_) => bail_expr!(val, "{}", ERRMSG),
                                },
                                rate: match str::parse::<u16>(delay_rate[1]) {
                                    Ok(rate) => rate,
                                    Err(_) => bail_expr!(val, "{}", ERRMSG),
                                },
                            });
                        }
                    }
                    _k @ "windows-altgr" => {
                        #[cfg(any(target_os = "windows", target_os = "unknown"))]
                        {
                            const CANCEL: &str = "cancel-lctl-press";
                            const ADD: &str = "add-lctl-release";
                            cfg.windows_altgr = match v.t.trim_matches('"') {
                                CANCEL => AltGrBehaviour::CancelLctlPress,
                                ADD => AltGrBehaviour::AddLctlRelease,
                                _ => bail_expr!(
                                    val,
                                    "Invalid value for {_k}: {}. Valid values are {},{}",
                                    v.t,
                                    CANCEL,
                                    ADD
                                ),
                            }
                        }
                    }
                    _k @ "windows-interception-mouse-hwid" => {
                        #[cfg(any(
                            all(feature = "interception_driver", target_os = "windows"),
                            target_os = "unknown"
                        ))]
                        {
                            let hwid = v.t.trim_matches('"');
                            log::trace!("win hwid: {hwid}");
                            let hwid_vec = hwid
                                .split(',')
                                .try_fold(vec![], |mut hwid_bytes, hwid_byte| {
                                    hwid_byte.trim_matches(' ').parse::<u8>().map(|b| {
                                        hwid_bytes.push(b);
                                        hwid_bytes
                                    })
                                }).map_err(|_| anyhow_expr!(val, "{_k} format is invalid. It should consist of integers separated by commas"))?;
                            let hwid_slice = hwid_vec.iter().copied().enumerate()
                                .try_fold([0u8; HWID_ARR_SZ], |mut hwid, idx_byte| {
                                    let (i, b) = idx_byte;
                                    if i > HWID_ARR_SZ {
                                        bail_expr!(val, "{_k} is too long; it should be up to {HWID_ARR_SZ} 8-bit unsigned integers")
                                    }
                                    hwid[i] = b;
                                    Ok(hwid)
                            });
                            cfg.windows_interception_mouse_hwid = Some(hwid_slice?);
                        }
                    }

                    "process-unmapped-keys" => {
                        cfg.process_unmapped_keys = parse_defcfg_val_bool(val, &k.t)?
                    }
                    "danger-enable-cmd" => cfg.enable_cmd = parse_defcfg_val_bool(val, &k.t)?,
                    "sequence-backtrack-modcancel" => {
                        cfg.sequence_backtrack_modcancel = parse_defcfg_val_bool(val, &k.t)?
                    }
                    "log-layer-changes" => {
                        cfg.log_layer_changes = parse_defcfg_val_bool(val, &k.t)?
                    }
                    "delegate-to-first-layer" => {
                        cfg.delegate_to_first_layer = parse_defcfg_val_bool(val, &k.t)?;
                        if cfg.delegate_to_first_layer {
                            log::info!("delegating transparent keys on other layers to first defined layer");
                        }
                    }
                    "linux-continue-if-no-devs-found" => {
                        #[cfg(any(target_os = "linux", target_os = "unknown"))]
                        {
                            cfg.linux_continue_if_no_devs_found = parse_defcfg_val_bool(val, &k.t)?
                        }
                    }
                    "movemouse-smooth-diagonals" => {
                        cfg.movemouse_smooth_diagonals = parse_defcfg_val_bool(val, &k.t)?
                    }
                    "movemouse-inherit-accel-state" => {
                        cfg.movemouse_inherit_accel_state = parse_defcfg_val_bool(val, &k.t)?
                    }
                    _ => bail_expr!(key, "Unknown defcfg option {}", &k.t),
                };
            }
            (SExpr::List(_), _) => {
                bail_expr!(key, "Lists are not allowed in defcfg");
            }
            (_, SExpr::List(_)) => {
                bail_expr!(val, "Lists are not allowed in defcfg");
            }
        }
    }
}

pub const FALSE_VALUES: [&str; 3] = ["no", "false", "0"];
pub const TRUE_VALUES: [&str; 3] = ["yes", "true", "1"];
pub const BOOLEAN_VALUES: [&str; 6] = ["yes", "true", "1", "no", "false", "0"];

fn parse_defcfg_val_bool(expr: &SExpr, label: &str) -> Result<bool> {
    match &expr {
        SExpr::Atom(v) => {
            let val = v.t.trim_matches('"').to_ascii_lowercase();
            if TRUE_VALUES.contains(&val.as_str()) {
                Ok(true)
            } else if FALSE_VALUES.contains(&val.as_str()) {
                Ok(false)
            } else {
                bail_expr!(
                    expr,
                    "The value for {label} must be one of: {}",
                    BOOLEAN_VALUES.join(", ")
                );
            }
        }
        SExpr::List(_) => {
            bail_expr!(
                expr,
                "The value for {label} cannot be a list, it must be one of: {}",
                BOOLEAN_VALUES.join(", "),
            )
        }
    }
}

fn parse_cfg_val_u16(expr: &SExpr, label: &str, exclude_zero: bool) -> Result<u16> {
    let start = if exclude_zero { 1 } else { 0 };
    match &expr {
        SExpr::Atom(v) => Ok(str::parse::<u16>(&v.t.trim_matches('"'))
            .ok()
            .and_then(|u| {
                if exclude_zero && u == 0 {
                    None
                } else {
                    Some(u)
                }
            })
            .ok_or_else(|| anyhow_expr!(expr, "{label} must be {start}-65535"))?),
        SExpr::List(_) => {
            bail_expr!(
                expr,
                "The value for {label} cannot be a list, it must be a number {start}-65535",
            )
        }
    }
}

pub fn parse_colon_separated_text(paths: &str) -> Vec<String> {
    let mut all_paths = vec![];
    let mut full_dev_path = String::new();
    let mut dev_path_iter = paths.split(':').peekable();
    while let Some(dev_path) = dev_path_iter.next() {
        if dev_path.ends_with('\\') && dev_path_iter.peek().is_some() {
            full_dev_path.push_str(dev_path.trim_end_matches('\\'));
            full_dev_path.push(':');
            continue;
        } else {
            full_dev_path.push_str(dev_path);
        }
        all_paths.push(full_dev_path.clone());
        full_dev_path.clear();
    }
    all_paths.shrink_to_fit();
    all_paths
}

#[cfg(any(target_os = "linux", target_os = "unknown"))]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct KeyRepeatSettings {
    pub delay: u16,
    pub rate: u16,
}

#[cfg(any(target_os = "linux", target_os = "unknown"))]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum UnicodeTermination {
    Enter,
    Space,
    SpaceEnter,
    EnterSpace,
}

#[cfg(any(target_os = "windows", target_os = "unknown"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AltGrBehaviour {
    DoNothing,
    CancelLctlPress,
    AddLctlRelease,
}

#[cfg(any(target_os = "windows", target_os = "unknown"))]
impl Default for AltGrBehaviour {
    fn default() -> Self {
        Self::DoNothing
    }
}

#[cfg(any(
    all(feature = "interception_driver", target_os = "windows"),
    target_os = "unknown"
))]
pub const HWID_ARR_SZ: usize = 128;