Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.8 KB
Raw Blame
//! The keyboard layout data of platform/keyboardLayout (IKeyboardLayoutInfo, IMacLinuxKeyboardMapping) as
//! native-keymap's keyboard_mac.mm reads it: the current input source and, per DOM key code, the characters of
//! UCKeyTranslate without modifiers, with Shift, with Option (AltGr) and with Shift+Option.

use serde_json::{Value, json};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "linux")]
pub use linux::{current_key_event, current_layout_info, current_raw_mapping, xkb_key_code};
#[cfg(target_os = "macos")]
pub use macos::{current_key_event, current_layout_info, current_raw_mapping};
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "windows")]
pub use windows::{current_key_event, current_layout_info, current_raw_mapping};

/// The DOM codes with a macOS virtual key code, in the order of chromium's dom_code_data.inc that native-keymap
/// walks (and so the order of the mapping's keys).
#[cfg(target_os = "macos")]
const MAC_KEY_CODES: [(&str, u16); 119] = [
    ("KeyA", 0), ("KeyB", 11), ("KeyC", 8), ("KeyD", 2), ("KeyE", 14), ("KeyF", 3), ("KeyG", 5),
    ("KeyH", 4), ("KeyI", 34), ("KeyJ", 38), ("KeyK", 40), ("KeyL", 37), ("KeyM", 46), ("KeyN", 45),
    ("KeyO", 31), ("KeyP", 35), ("KeyQ", 12), ("KeyR", 15), ("KeyS", 1), ("KeyT", 17), ("KeyU", 32),
    ("KeyV", 9), ("KeyW", 13), ("KeyX", 7), ("KeyY", 16), ("KeyZ", 6), ("Digit1", 18), ("Digit2", 19),
    ("Digit3", 20), ("Digit4", 21), ("Digit5", 23), ("Digit6", 22), ("Digit7", 26), ("Digit8", 28), ("Digit9", 25),
    ("Digit0", 29), ("Enter", 36), ("Escape", 53), ("Backspace", 51), ("Tab", 48), ("Space", 49), ("Minus", 27),
    ("Equal", 24), ("BracketLeft", 33), ("BracketRight", 30), ("Backslash", 42), ("Semicolon", 41), ("Quote", 39), ("Backquote", 50),
    ("Comma", 43), ("Period", 47), ("Slash", 44), ("CapsLock", 57), ("F1", 122), ("F2", 120), ("F3", 99),
    ("F4", 118), ("F5", 96), ("F6", 97), ("F7", 98), ("F8", 100), ("F9", 101), ("F10", 109),
    ("F11", 103), ("F12", 111), ("Insert", 114), ("Home", 115), ("PageUp", 116), ("Delete", 117), ("End", 119),
    ("PageDown", 121), ("ArrowRight", 124), ("ArrowLeft", 123), ("ArrowDown", 125), ("ArrowUp", 126), ("NumLock", 71), ("NumpadDivide", 75),
    ("NumpadMultiply", 67), ("NumpadSubtract", 78), ("NumpadAdd", 69), ("NumpadEnter", 76), ("Numpad1", 83), ("Numpad2", 84), ("Numpad3", 85),
    ("Numpad4", 86), ("Numpad5", 87), ("Numpad6", 88), ("Numpad7", 89), ("Numpad8", 91), ("Numpad9", 92), ("Numpad0", 82),
    ("NumpadDecimal", 65), ("IntlBackslash", 10), ("ContextMenu", 110), ("NumpadEqual", 81), ("F13", 105), ("F14", 107), ("F15", 113),
    ("F16", 106), ("F17", 64), ("F18", 79), ("F19", 80), ("F20", 90), ("AudioVolumeMute", 74), ("AudioVolumeUp", 72),
    ("AudioVolumeDown", 73), ("NumpadComma", 95), ("IntlRo", 94), ("IntlYen", 93), ("Lang1", 104), ("Lang2", 102), ("ControlLeft", 59),
    ("ShiftLeft", 56), ("AltLeft", 58), ("MetaLeft", 55), ("ControlRight", 62), ("ShiftRight", 60), ("AltRight", 61), ("MetaRight", 54),
];

/// The macOS virtual key code of a DOM code, compared case-insensitively.
#[cfg(target_os = "macos")]
pub fn mac_key_code(dom_code: &str) -> Option<u16> {
    MAC_KEY_CODES.iter().find(|(code, _)| code.eq_ignore_ascii_case(dom_code)).map(|(_, key_code)| *key_code)
}

/// A native key down: its DOM `code` and modifiers, as `StandardKeyboardEvent` reads them.
#[derive(Clone, Copy, Debug)]
pub struct KeyEvent {
    pub code: &'static str,
    pub ctrl: bool,
    pub shift: bool,
    pub alt: bool,
    pub meta: bool,
}

/// `std::iscntrl` of macOS's libc on a UTF-16 unit: C0, DEL and C1.
#[cfg(any(target_os = "macos", test))]
fn is_control(character: char) -> bool {
    matches!(character, '\0'..='\x1f' | '\x7f'..='\u{9f}')
}

/// keybindingService.ts `_dumpDebugInfoJSON`, the text of Developer: Inspect Key Mappings (JSON).
pub fn dump_debug_info_json() -> String {
    stringify(&json!({ "layout": current_layout_info(), "rawMapping": current_raw_mapping() }))
}

/// keybindingService.ts `_dumpDebugInfo`, the text of Developer: Inspect Key Mappings: the layout, the keybindings
/// as the layout resolves them, the keyboard mapper's tables and the raw key map.
pub fn dump_debug_info(mapper: Option<&crate::keyboard_mapper::KeyboardMapper>, resolved_keybindings: &str) -> String {
    let mapper_info = mapper.map_or("FallbackKeyboardMapper dispatching on keyCode".into(), |mapper| mapper.dump_debug_info());
    let (layout, raw) = (stringify(&current_layout_info()), stringify(&current_raw_mapping()));
    format!("Layout info:\n{layout}\n\n{resolved_keybindings}\n\n{mapper_info}\n\nRaw mapping:\n{raw}")
}

/// `JSON.stringify(value, null, '\t')`.
fn stringify(value: &Value) -> String {
    let mut text = Vec::new();
    let mut serializer = serde_json::Serializer::with_formatter(&mut text, serde_json::ser::PrettyFormatter::with_indent(b"\t"));
    serde::Serialize::serialize(value, &mut serializer).expect("JSON values serialize");
    String::from_utf8(text).expect("serde_json writes UTF-8")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(target_os = "macos")]
    #[test]
    fn raw_mapping_has_every_dom_code_with_its_four_characters() {
        let mapping = current_raw_mapping();
        let mapping = mapping.as_object().expect("an object");
        assert_eq!(mapping.keys().map(String::as_str).collect::<Vec<_>>(), MAC_KEY_CODES.map(|(code, _)| code));
        assert_eq!(mapping["ShiftLeft"], json!({ "value": "", "valueIsDeadKey": false, "withShift": "", "withShiftIsDeadKey": false, "withAltGr": "", "withAltGrIsDeadKey": false, "withShiftAltGr": "", "withShiftAltGrIsDeadKey": false }));
        assert_eq!(mapping["Space"]["value"], " ");
    }

    /// libtest runs tests on many threads: without the lock, the first TIS calls of the process aborted it with
    /// no message (macOS 26 and 27) about 1 run in 5 with 2 threads and every run with 8.
    #[cfg(target_os = "macos")]
    #[test]
    fn layout_reads_from_many_threads_at_once_do_not_abort() {
        let threads: Vec<_> = (0..8).map(|_| std::thread::spawn(|| (current_layout_info(), current_raw_mapping()))).collect();
        for thread in threads {
            assert_eq!(thread.join().unwrap().1["Space"]["value"], " ");
        }
    }

    /// Without an X display native-keymap gives no layout and an empty map; Xvfb starts with the `evdev` rules and
    /// the `us` layout.
    #[cfg(target_os = "linux")]
    #[test]
    fn layout_and_raw_mapping_come_from_the_x_server() {
        if std::env::var_os("DISPLAY").is_none() {
            assert_eq!((current_layout_info(), current_raw_mapping()), (Value::Null, json!({})));
            return;
        }
        let layout = current_layout_info();
        assert_eq!((&layout["rules"], &layout["layout"], &layout["group"]), (&json!("evdev"), &json!("us"), &json!(0)));
        let mapping = current_raw_mapping();
        assert_eq!(mapping["KeyA"], json!({ "value": "a", "withShift": "A", "withAltGr": "a", "withShiftAltGr": "A", "withLevel5": "a", "withLevel3Level5": "a" }));
        assert_eq!(mapping["Digit1"]["withShift"], "!");
        assert_eq!(mapping["ShiftLeft"]["value"], "");
    }

    #[test]
    fn inspect_key_mappings_shows_the_scan_code_mapper_tables() {
        let mapper = crate::keyboard_mapper::KeyboardMapper::new(false, &crate::keyboard_mapper::tests::raw_mapping("mac_de_ch"), false);
        let text = dump_debug_info(Some(&mapper), "resolved");
        assert!(text.contains(&format!("\n\nresolved\n\n{}\n\nRaw mapping:\n", mapper.dump_debug_info())), "{text}");
        assert!(dump_debug_info(None, "resolved").contains("\n\nFallbackKeyboardMapper dispatching on keyCode\n\n"));
    }

    #[test]
    fn control_characters_are_left_out_as_iscntrl() {
        assert!(is_control('\r') && is_control('\x7f') && is_control('\u{85}'));
        assert!(!is_control(' ') && !is_control('a') && !is_control('\u{a0}'));
    }
}