rmk-macro 0.7.1

Proc-macro crate of RMK
Documentation
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
//! Initialize default keymap from config
use std::collections::HashMap;

use proc_macro2::{Ident, TokenStream as TokenStream2};
use quote::{format_ident, quote};
use rmk_config::{KEYCODE_ALIAS, KeyboardTomlConfig, MorseProfile};

use crate::behavior::expand_profile_name;

/// Read the default keymap setting in `keyboard.toml` and add as a `get_default_keymap` function
/// Also add `get_default_encoder_map`
pub(crate) fn expand_default_keymap(keyboard_config: &KeyboardTomlConfig) -> TokenStream2 {
    let profiles = &keyboard_config
        .get_behavior_config()
        .unwrap()
        .morse
        .and_then(|m| m.profiles);
    let num_encoder = keyboard_config
        .get_board_config()
        .unwrap()
        .get_num_encoder()
        .iter()
        .sum();

    let (layout, _) = keyboard_config.get_layout_config().unwrap();

    let mut layers = vec![];
    let mut encoder_map = vec![];

    for layer in &layout.keymap {
        layers.push(expand_layer(layer.clone(), profiles));
    }

    for encoder_layer in &layout.encoder_map {
        encoder_map.push(expand_encoder_layer(encoder_layer.clone(), num_encoder, profiles));
    }
    encoder_map.resize(
        layout.keymap.len(),
        quote! { [::rmk::encoder!(::rmk::k!(No), ::rmk::k!(No)); NUM_ENCODER] },
    );

    quote! {
        pub const fn get_default_keymap() -> [[[::rmk::types::action::KeyAction; COL]; ROW]; NUM_LAYER] {
            [#(#layers), *]
        }

        pub const fn get_default_encoder_map() -> [[::rmk::types::action::EncoderAction; NUM_ENCODER]; NUM_LAYER] {
            [#(#encoder_map), *]
        }
    }
}

/// Expand a layer for keymap
fn expand_layer(layer: Vec<Vec<String>>, profiles: &Option<HashMap<String, MorseProfile>>) -> TokenStream2 {
    let mut rows = vec![];
    for row in layer {
        rows.push(expand_row(row, profiles));
    }
    quote! { [#(#rows), *] }
}

/// Expand a row for keymap
fn expand_row(row: Vec<String>, profiles: &Option<HashMap<String, MorseProfile>>) -> TokenStream2 {
    let mut keys = vec![];
    for key in row {
        keys.push(parse_key(key, profiles));
    }
    quote! { [#(#keys), *] }
}

/// Expand a layer for encoder map
fn expand_encoder_layer(
    encoder_layer: Vec<[String; 2]>,
    num_encoder: usize,
    profiles: &Option<HashMap<String, MorseProfile>>,
) -> TokenStream2 {
    let mut encoders = vec![];

    for encoder in encoder_layer {
        let cw_action = parse_key(encoder[0].clone(), profiles);
        let ccw_action = parse_key(encoder[1].clone(), profiles);
        encoders.push(quote! { ::rmk::encoder!(#cw_action, #ccw_action) });
    }

    // Make sure it configures correct number of encoders
    encoders.resize(num_encoder, quote! { ::rmk::encoder!(::rmk::k!(No), ::rmk::k!(No)) });

    quote! { [#(#encoders), *] }
}

struct ModifierCombinationMacro {
    right: bool,
    gui: bool,
    alt: bool,
    shift: bool,
    ctrl: bool,
}
impl ModifierCombinationMacro {
    fn new() -> Self {
        Self {
            right: false,
            gui: false,
            alt: false,
            shift: false,
            ctrl: false,
        }
    }
    fn is_empty(&self) -> bool {
        !(self.gui || self.alt || self.shift || self.ctrl)
    }
}
// Allows to use `#modifiers` in the quote
impl quote::ToTokens for ModifierCombinationMacro {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let right = self.right;
        let gui = self.gui;
        let alt = self.alt;
        let shift = self.shift;
        let ctrl = self.ctrl;

        tokens.extend(quote! {
            ::rmk::types::modifier::ModifierCombination::new_from(#right, #gui, #alt, #shift, #ctrl)
        });
    }
}

/// Get modifier combination, in types of mod1 | mod2 | ...
fn parse_modifiers(modifiers_str: &str) -> ModifierCombinationMacro {
    let mut combination = ModifierCombinationMacro::new();
    let tokens = modifiers_str.split_terminator("|");
    tokens.for_each(|w| {
        let w = w.trim();
        let key = match KEYCODE_ALIAS.get(w.to_lowercase().as_str()) {
            Some(k) => *k,
            None => w,
        };
        match key {
            "LShift" => combination.shift = true,
            "LCtrl" => combination.ctrl = true,
            "LAlt" => combination.alt = true,
            "LGui" => combination.gui = true,
            "RShift" => {
                combination.right = true;
                combination.shift = true;
            }
            "RCtrl" => {
                combination.right = true;
                combination.ctrl = true;
            }
            "RAlt" => {
                combination.right = true;
                combination.alt = true;
            }
            "RGui" => {
                combination.right = true;
                combination.gui = true;
            }
            _ => (),
        }
    });
    combination
}

/// Parse the key string at a single position
pub(crate) fn parse_key(key: String, profiles: &Option<HashMap<String, MorseProfile>>) -> TokenStream2 {
    if !key.is_empty() && (key.trim_start_matches("_").is_empty() || key.to_lowercase() == "trns") {
        return quote! { ::rmk::a!(Transparent) };
    } else if !key.is_empty() && key == "No" {
        return quote! { ::rmk::a!(No) };
    }

    match key {
        s if s.to_lowercase().starts_with("wm(") => {
            let prefix = s.get(0..3).unwrap();
            if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
                let keys: Vec<&str> = internal
                    .split_terminator(",")
                    .map(|w| w.trim())
                    .filter(|w| !w.is_empty())
                    .collect();
                if keys.len() != 2 {
                    panic!(
                        "\n❌ keyboard.toml: WM(key, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }

                let ident = get_key_with_alias(keys[0].to_string());

                let modifiers = parse_modifiers(keys[1]);

                if modifiers.is_empty() {
                    panic!(
                        "\n❌ keyboard.toml: modifier in WM(layer, modifier) is not valid! Please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                quote! {
                    ::rmk::wm!(#ident, #modifiers)
                }
            } else {
                panic!(
                    "\n❌ keyboard.toml: WM(layer, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
        }
        s if s.to_lowercase().starts_with("mo(") => {
            let layer = get_number(s.clone(), s.get(0..3).unwrap(), ")");
            quote! {
                ::rmk::mo!(#layer)
            }
        }
        s if s.to_lowercase().starts_with("osl(") => {
            let layer = get_number(s.clone(), s.get(0..4).unwrap(), ")");
            quote! {
                ::rmk::osl!(#layer)
            }
        }
        s if s.to_lowercase().starts_with("osm(") => {
            let prefix = s.get(0..4).unwrap();
            if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
                let modifiers = parse_modifiers(internal);

                if modifiers.is_empty() {
                    panic!(
                        "\n❌ keyboard.toml: modifier in OSM(modifier) is not valid! Please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                quote! {
                    ::rmk::osm!(#modifiers)
                }
            } else {
                panic!(
                    "\n❌ keyboard.toml: OSM(modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
        }
        s if s.to_lowercase().starts_with("lm(") => {
            let prefix = s.get(0..3).unwrap();
            if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
                let keys: Vec<&str> = internal
                    .split_terminator(",")
                    .map(|w| w.trim())
                    .filter(|w| !w.is_empty())
                    .collect();
                if keys.len() != 2 {
                    panic!(
                        "\n❌ keyboard.toml: LM(layer, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                let layer = keys[0].parse::<u8>().unwrap();

                let modifiers = parse_modifiers(keys[1]);

                if modifiers.is_empty() {
                    panic!(
                        "\n❌ keyboard.toml: modifier in LM(layer, modifier) is not valid! Please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                quote! {
                    ::rmk::lm!(#layer, #modifiers)
                }
            } else {
                panic!(
                    "\n❌ keyboard.toml: LM(layer, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
        }
        s if s.to_lowercase().starts_with("lt(") => {
            let prefix = s.get(0..3).unwrap();
            let keys: Vec<&str> = s
                .trim_start_matches(prefix)
                .trim_end_matches(")")
                .split_terminator(",")
                .map(|w| w.trim())
                .filter(|w| !w.is_empty())
                .collect();
            if keys.len() < 2 || keys.len() > 3 {
                panic!(
                    "\n❌ keyboard.toml: LT(layer, key) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
            let layer = keys[0].parse::<u8>().unwrap();
            let key = get_key_with_alias(keys[1].to_string());

            if keys.len() == 3 {
                let profile = expand_profile_name(keys[2], profiles);
                quote! { ::rmk::ltp!(#layer, #key, #profile) }
            } else {
                quote! { ::rmk::lt!(#layer, #key) }
            }
        }
        s if s.to_lowercase().starts_with("tt(") => {
            let layer = get_number(s.clone(), s.get(0..3).unwrap(), ")");
            quote! {
                ::rmk::tt!(#layer)
            }
        }
        s if s.to_lowercase().starts_with("tg(") => {
            let layer = get_number(s.clone(), s.get(0..3).unwrap(), ")");
            quote! {
                ::rmk::tg!(#layer)
            }
        }
        s if s.to_lowercase().starts_with("to(") => {
            let layer = get_number(s.clone(), s.get(0..3).unwrap(), ")");
            quote! {
                ::rmk::to!(#layer)
            }
        }
        s if s.to_lowercase().starts_with("df(") => {
            let layer = get_number(s.clone(), s.get(0..3).unwrap(), ")");
            quote! {
                ::rmk::df!(#layer)
            }
        }
        s if s.to_lowercase().starts_with("mt(") => {
            let prefix = s.get(0..3).unwrap();
            if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
                let keys: Vec<&str> = internal
                    .split_terminator(",")
                    .map(|w| w.trim())
                    .filter(|w| !w.is_empty())
                    .collect();
                if keys.len() < 2 || keys.len() > 3 {
                    panic!(
                        "\n❌ keyboard.toml: MT(key, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                let ident = get_key_with_alias(keys[0].to_string());
                let modifiers = parse_modifiers(keys[1]);

                if modifiers.is_empty() {
                    panic!(
                        "\n❌ keyboard.toml: modifier in MT(key, modifier) is not valid! Please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                if keys.len() == 3 {
                    let profile = expand_profile_name(keys[2], profiles);
                    quote! { ::rmk::mtp!(#ident, #modifiers, #profile) }
                } else {
                    quote! { ::rmk::mt!(#ident, #modifiers) }
                }
            } else {
                panic!(
                    "\n❌ keyboard.toml: MT(key, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
        }
        s if s.to_lowercase().starts_with("macro(") => {
            let number = get_number(s.clone(), s.get(0..6).unwrap(), ")");
            quote! {
                ::rmk::macros!(#number)
            }
        }
        // s if s.to_lowercase().starts_with("hrm(") => {
        //     let prefix = s.get(0..4).unwrap();
        //     if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
        //         let keys: Vec<&str> = internal
        //             .split_terminator(",")
        //             .map(|w| w.trim())
        //             .filter(|w| !w.is_empty())
        //             .collect();
        //         if keys.len() != 2 {
        //             panic!(
        //                 "\n❌ keyboard.toml: HRM(key, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
        //             );
        //         }
        //         let ident = get_key_with_alias(keys[0].to_string());
        //         let modifiers = parse_modifiers(keys[1]);

        //         if modifiers.is_empty() {
        //             panic!(
        //                 "\n❌ keyboard.toml: modifier in HRM(key, modifier) is not valid! Please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
        //             );
        //         }
        //         quote! {
        //             ::rmk::hrm!(#ident, #modifiers)
        //         }
        //     } else {
        //         panic!(
        //             "\n❌ keyboard.toml: HRM(key, modifier) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
        //         );
        //     }
        // }
        s if s.to_lowercase().starts_with("th(") => {
            let prefix = s.get(0..3).unwrap();
            if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
                let keys: Vec<&str> = internal
                    .split_terminator(",")
                    .map(|w| w.trim())
                    .filter(|w| !w.is_empty())
                    .collect();
                if keys.len() < 2 || keys.len() > 3 {
                    panic!(
                        "\n❌ keyboard.toml: TH(key_tap, key_hold) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                let ident1 = get_key_with_alias(keys[0].to_string());
                let ident2 = get_key_with_alias(keys[1].to_string());

                if keys.len() == 3 {
                    let profile = expand_profile_name(keys[2], profiles);
                    quote! { ::rmk::thp!(#ident1, #ident2, #profile) }
                } else {
                    quote! { ::rmk::th!(#ident1, #ident2) }
                }
            } else {
                panic!(
                    "\n❌ keyboard.toml: TH(key_tap, key_hold) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
        }
        s if s.to_lowercase().starts_with("shifted(") => {
            let prefix = s.get(0..8).unwrap();
            if let Some(internal) = s.trim_start_matches(prefix).strip_suffix(")") {
                if internal.is_empty() {
                    panic!(
                        "\n❌ keyboard.toml: SHIFTED(key) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                    );
                }
                let key = get_key_with_alias(internal.to_string());
                quote! { ::rmk::shifted!(#key) }
            } else {
                panic!(
                    "\n❌ keyboard.toml: SHIFTED(key) invalid, please check the documentation: https://rmk.rs/docs/features/configuration/layout.html"
                );
            }
        }
        s if s.to_lowercase().starts_with("td(") => {
            let index = get_number(s.clone(), s.get(0..3).unwrap(), ")");
            quote! {
                ::rmk::td!(#index)
            }
        }
        s if s.to_lowercase().starts_with("m(") => {
            let index = get_number(s.clone(), s.get(0..2).unwrap(), ")");
            quote! {
                ::rmk::m!(#index)
            }
        }
        _ => {
            let ident = get_key_with_alias(key);
            quote! { ::rmk::k!(#ident) }
        }
    }
}

/// Parse the string literal like `MO(1)`, `OSL(1)`, `TD(0)`, etc, get the number in it.
/// The caller should pass the trimmed prefix and suffix
fn get_number(key: String, prefix: &str, suffix: &str) -> u8 {
    let layer_str = key.trim_start_matches(prefix).trim_end_matches(suffix);
    layer_str.parse::<u8>().unwrap()
}

pub(crate) fn get_key_with_alias(key: String) -> Ident {
    let key = match KEYCODE_ALIAS.get(key.to_lowercase().as_str()) {
        Some(k) => *k,
        None => key.as_str(),
    };
    format_ident!("{}", key)
}