Skip to main content

gasm_host/
keymap.rs

1//! Keyboard layouts: the same text format as the web player (`gasm-host.js`
2//! `parseKeymap`). A line per binding: `<pad 1-4> <button> <key code>...`, where key
3//! codes are W3C `KeyboardEvent.code` names (winit's `KeyCode` uses the same names).
4//! Keyboard bindings for pad N >= 2 apply while fewer than N gamepads are connected.
5
6use winit::keyboard::KeyCode;
7
8pub use crate::keys::KEY_CODES;
9
10pub const DEFAULT_KEYMAP: &str = include_str!("default-keymap.txt");
11pub const BUTTONS: [&str; 12] = ["a", "b", "x", "y", "l", "r", "select", "start", "up", "down", "left", "right"];
12
13/// (key, zero-based pad, button bit)
14pub type Keymap = Vec<(KeyCode, usize, u32)>;
15
16pub fn parse(text: &str) -> Result<Keymap, String> {
17    let mut map = Vec::new();
18    let mut errors = Vec::new();
19    for (i, raw) in text.lines().enumerate() {
20        let line = raw.split('#').next().unwrap_or("").trim();
21        if line.is_empty() {
22            continue;
23        }
24        let mut parts = line.split_whitespace();
25        let (pad, button) = (parts.next(), parts.next());
26        let keys: Vec<&str> = parts.collect();
27        let pad = pad.and_then(|p| p.parse::<usize>().ok()).filter(|p| (1..=4).contains(p));
28        let bit = button.and_then(|b| BUTTONS.iter().position(|n| n.eq_ignore_ascii_case(b)));
29        let (Some(pad), Some(bit), false) = (pad, bit, keys.is_empty()) else {
30            errors.push(format!("line {}: expected \"<pad 1-4> <button> <key>...\", got {line:?}", i + 1));
31            continue;
32        };
33        for k in keys {
34            match key_from_code(normalize(k)) {
35                Some(KeyCode::Escape) => errors.push(format!("line {}: Escape is reserved (quit)", i + 1)),
36                Some(code) => map.push((code, pad - 1, 1u32 << bit)),
37                None => errors.push(format!("line {}: unknown key code {k:?}", i + 1)),
38            }
39        }
40    }
41    if errors.is_empty() { Ok(map) } else { Err(errors.join("\n")) }
42}
43
44/// Pads from held keys; keyboard pad N (zero-based n >= 1) only while `gamepads <= n`.
45pub fn pads(map: &Keymap, held: &std::collections::HashSet<KeyCode>, gamepads: usize) -> [u32; 4] {
46    let mut pads = [0u32; 4];
47    for (key, pad, bit) in map {
48        if held.contains(key) && (*pad == 0 || gamepads <= *pad) {
49            pads[*pad] |= bit;
50        }
51    }
52    pads
53}
54
55macro_rules! codes {
56    ($($name:ident),* $(,)?) => {
57        /// W3C KeyboardEvent.code name -> winit KeyCode.
58        pub fn key_from_code(s: &str) -> Option<KeyCode> {
59            match s { $(stringify!($name) => Some(KeyCode::$name),)* _ => None }
60        }
61    };
62}
63
64codes!(
65    KeyA, KeyB, KeyC, KeyD, KeyE, KeyF, KeyG, KeyH, KeyI, KeyJ, KeyK, KeyL, KeyM,
66    KeyN, KeyO, KeyP, KeyQ, KeyR, KeyS, KeyT, KeyU, KeyV, KeyW, KeyX, KeyY, KeyZ,
67    Digit0, Digit1, Digit2, Digit3, Digit4, Digit5, Digit6, Digit7, Digit8, Digit9,
68    ArrowUp, ArrowDown, ArrowLeft, ArrowRight,
69    Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9,
70    NumpadAdd, NumpadSubtract, NumpadMultiply, NumpadDivide, NumpadDecimal, NumpadEnter, NumpadEqual, NumpadComma,
71    F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
72    Space, Enter, Tab, Backspace, Escape, CapsLock,
73    ShiftLeft, ShiftRight, ControlLeft, ControlRight, AltLeft, AltRight, SuperLeft, SuperRight,
74    Comma, Period, Slash, Semicolon, Quote, BracketLeft, BracketRight, Backslash, Minus, Equal, Backquote, IntlBackslash,
75    Insert, Delete, Home, End, PageUp, PageDown,
76    F13, F14, F15, F16, F17, F18, F19, F20, F21, F22, F23, F24,
77    PrintScreen, ScrollLock, Pause, NumLock, ContextMenu, IntlRo, IntlYen,
78);
79
80/// GASM_KEY_* code of a winit key (0 if it has none).
81pub fn gasm_key(code: KeyCode) -> u16 {
82    use std::sync::OnceLock;
83    static MAP: OnceLock<Vec<(KeyCode, u16)>> = OnceLock::new();
84    MAP.get_or_init(|| {
85        KEY_CODES.iter().enumerate().skip(1).filter_map(|(i, n)| key_from_code(normalize(n)).map(|k| (k, i as u16))).collect()
86    })
87    .iter()
88    .find(|(k, _)| *k == code)
89    .map_or(0, |(_, i)| *i)
90}
91
92/// Browser names for keys whose winit name differs.
93pub fn normalize(s: &str) -> &str {
94    match s { "MetaLeft" | "OSLeft" => "SuperLeft", "MetaRight" | "OSRight" => "SuperRight", other => other }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100    use std::collections::HashSet;
101
102    #[test]
103    fn default_keymap_parses_and_two_players_share_a_keyboard() {
104        let map = parse(DEFAULT_KEYMAP).unwrap();
105        let held: HashSet<_> = [KeyCode::KeyX, KeyCode::KeyL, KeyCode::ControlRight].into();
106        let p = pads(&map, &held, 0);
107        assert_eq!(p[0], 1 << 0); // X = A on pad 1
108        assert_eq!(p[1], (1 << 11) | (1 << 7)); // L = right, RCtrl = start on pad 2
109        assert_eq!(pads(&map, &held, 2)[1], 0); // two gamepads: keyboard player 2 off
110        assert!(parse("1 jump KeyX").is_err());
111        assert!(parse("5 a KeyX").is_err());
112        assert!(parse("1 a Escape").is_err());
113    }
114}