Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

24.0 KB
Raw Blame
use serde::{Deserialize, Serialize};
use tauri::ipc::Channel;

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "camelCase")]
pub struct NativeOsHotkeyBinding {
    pub code: String,
    pub ctrl: bool,
    pub shift: bool,
    pub alt: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NativeOsHotkeyEvent {
    pub phase: String, // "keydown" | "keyup"
    pub code: String,
    pub key: String,
    pub ctrl_key: bool,
    pub meta_key: bool,
    pub shift_key: bool,
    pub alt_key: bool,
    pub repeat: bool,
    pub is_recording: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OsHotkeyStatus {
    pub supported: bool,
    pub active: bool,
    pub registered_count: usize,
    pub recording: bool,
}

/// Converts a standard DOM KeyboardEvent.code into one or more Windows Virtual-Key codes.
pub fn dom_code_to_vks(code: &str) -> Vec<u32> {
    if let Some(ch) = code.strip_prefix("Key") {
        if ch.len() == 1 {
            let b = ch.as_bytes()[0];
            if b.is_ascii_uppercase() {
                return vec![b as u32];
            }
        }
    }
    if let Some(d) = code.strip_prefix("Digit") {
        if d.len() == 1 {
            let b = d.as_bytes()[0];
            if b.is_ascii_digit() {
                return vec![b as u32];
            }
        }
    }
    if let Some(d) = code.strip_prefix("Numpad") {
        if d.len() == 1 {
            let b = d.as_bytes()[0];
            if b.is_ascii_digit() {
                return vec![0x60 + (b - b'0') as u32];
            }
        }
        return match d {
            "Add" => vec![0x6B],
            "Subtract" => vec![0x6D],
            "Enter" => vec![0x0D],
            _ => vec![],
        };
    }
    if let Some(fn_num) = code.strip_prefix('F') {
        if let Ok(n) = fn_num.parse::<u32>() {
            if (1..=12).contains(&n) {
                return vec![0x70 + (n - 1)];
            }
        }
    }

    match code {
        "BracketLeft" => vec![0xDB],
        "BracketRight" => vec![0xDD],
        "Comma" => vec![0xBC],
        "Period" => vec![0xBE],
        "Slash" => vec![0xBF],
        "Backslash" => vec![0xDC],
        "Semicolon" => vec![0xBA],
        "Quote" => vec![0xDE],
        "Backquote" => vec![0xC0],
        "Equal" => vec![0xBB],
        "Minus" => vec![0xBD],
        "Tab" => vec![0x09],
        "Space" => vec![0x20],
        "Enter" => vec![0x0D],
        "Escape" => vec![0x1B],
        "Delete" => vec![0x2E],
        "Backspace" => vec![0x08],
        "ArrowUp" => vec![0x26],
        "ArrowDown" => vec![0x28],
        "ArrowLeft" => vec![0x25],
        "ArrowRight" => vec![0x27],
        "Home" => vec![0x24],
        "End" => vec![0x23],
        "PageUp" => vec![0x21],
        "PageDown" => vec![0x22],
        _ => vec![],
    }
}

/// Converts a Windows Virtual-Key code into canonical DOM (code, key) pair.
pub fn vk_to_dom_code_and_key(vk: u32, is_extended: bool) -> Option<(&'static str, &'static str)> {
    match vk {
        0x41 => Some(("KeyA", "a")),
        0x42 => Some(("KeyB", "b")),
        0x43 => Some(("KeyC", "c")),
        0x44 => Some(("KeyD", "d")),
        0x45 => Some(("KeyE", "e")),
        0x46 => Some(("KeyF", "f")),
        0x47 => Some(("KeyG", "g")),
        0x48 => Some(("KeyH", "h")),
        0x49 => Some(("KeyI", "i")),
        0x4A => Some(("KeyJ", "j")),
        0x4B => Some(("KeyK", "k")),
        0x4C => Some(("KeyL", "l")),
        0x4D => Some(("KeyM", "m")),
        0x4E => Some(("KeyN", "n")),
        0x4F => Some(("KeyO", "o")),
        0x50 => Some(("KeyP", "p")),
        0x51 => Some(("KeyQ", "q")),
        0x52 => Some(("KeyR", "r")),
        0x53 => Some(("KeyS", "s")),
        0x54 => Some(("KeyT", "t")),
        0x55 => Some(("KeyU", "u")),
        0x56 => Some(("KeyV", "v")),
        0x57 => Some(("KeyW", "w")),
        0x58 => Some(("KeyX", "x")),
        0x59 => Some(("KeyY", "y")),
        0x5A => Some(("KeyZ", "z")),
        0x30 => Some(("Digit0", "0")),
        0x31 => Some(("Digit1", "1")),
        0x32 => Some(("Digit2", "2")),
        0x33 => Some(("Digit3", "3")),
        0x34 => Some(("Digit4", "4")),
        0x35 => Some(("Digit5", "5")),
        0x36 => Some(("Digit6", "6")),
        0x37 => Some(("Digit7", "7")),
        0x38 => Some(("Digit8", "8")),
        0x39 => Some(("Digit9", "9")),
        0x60 => Some(("Numpad0", "0")),
        0x61 => Some(("Numpad1", "1")),
        0x62 => Some(("Numpad2", "2")),
        0x63 => Some(("Numpad3", "3")),
        0x64 => Some(("Numpad4", "4")),
        0x65 => Some(("Numpad5", "5")),
        0x66 => Some(("Numpad6", "6")),
        0x67 => Some(("Numpad7", "7")),
        0x68 => Some(("Numpad8", "8")),
        0x69 => Some(("Numpad9", "9")),
        0x6B => Some(("NumpadAdd", "+")),
        0x6D => Some(("NumpadSubtract", "-")),
        0x70 => Some(("F1", "F1")),
        0x71 => Some(("F2", "F2")),
        0x72 => Some(("F3", "F3")),
        0x73 => Some(("F4", "F4")),
        0x74 => Some(("F5", "F5")),
        0x75 => Some(("F6", "F6")),
        0x76 => Some(("F7", "F7")),
        0x77 => Some(("F8", "F8")),
        0x78 => Some(("F9", "F9")),
        0x79 => Some(("F10", "F10")),
        0x7A => Some(("F11", "F11")),
        0x7B => Some(("F12", "F12")),
        0xDB => Some(("BracketLeft", "[")),
        0xDD => Some(("BracketRight", "]")),
        0xBC => Some(("Comma", ",")),
        0xBE => Some(("Period", ".")),
        0xBF => Some(("Slash", "/")),
        0xDC => Some(("Backslash", "\\")),
        0xBA => Some(("Semicolon", ";")),
        0xDE => Some(("Quote", "'")),
        0xC0 => Some(("Backquote", "`")),
        0xBB => Some(("Equal", "=")),
        0xBD => Some(("Minus", "-")),
        0x09 => Some(("Tab", "Tab")),
        0x20 => Some(("Space", " ")),
        0x0D => Some((if is_extended { "NumpadEnter" } else { "Enter" }, "Enter")),
        0x1B => Some(("Escape", "Escape")),
        0x2E => Some(("Delete", "Delete")),
        0x08 => Some(("Backspace", "Backspace")),
        0x26 => Some(("ArrowUp", "ArrowUp")),
        0x28 => Some(("ArrowDown", "ArrowDown")),
        0x25 => Some(("ArrowLeft", "ArrowLeft")),
        0x27 => Some(("ArrowRight", "ArrowRight")),
        0x24 => Some(("Home", "Home")),
        0x23 => Some(("End", "End")),
        0x21 => Some(("PageUp", "PageUp")),
        0x22 => Some(("PageDown", "PageDown")),
        _ => None,
    }
}

#[cfg(target_os = "windows")]
mod win_impl {
    use super::*;
    use std::collections::HashSet;
    use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU32, Ordering};
    use std::sync::{mpsc, LazyLock, Mutex, RwLock};
    use std::thread::JoinHandle;
    use windows_sys::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
    use windows_sys::Win32::System::Threading::GetCurrentThreadId;
    use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
        GetAsyncKeyState, SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_KEYUP,
        VK_CONTROL, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN, VK_MENU, VK_RCONTROL, VK_RMENU,
        VK_RSHIFT, VK_RWIN, VK_SHIFT,
    };
    use windows_sys::Win32::UI::WindowsAndMessaging::{
        CallNextHookEx, DispatchMessageW, GetAncestor, GetForegroundWindow, GetMessageW,
        PostThreadMessageW, SetWindowsHookExW, TranslateMessage, UnhookWindowsHookEx, GA_ROOT,
        HHOOK, KBDLLHOOKSTRUCT, LLKHF_EXTENDED, LLKHF_INJECTED, MSG, WH_KEYBOARD_LL, WM_KEYDOWN,
        WM_KEYUP, WM_QUIT, WM_SYSKEYDOWN, WM_SYSKEYUP,
    };

    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    struct VkBinding {
        vk: u32,
        ctrl: bool,
        shift: bool,
        alt: bool,
    }

    static MAIN_HWND: AtomicIsize = AtomicIsize::new(0);
    static RECORDING_MODE: AtomicBool = AtomicBool::new(false);
    static HOOK_RUNNING: AtomicBool = AtomicBool::new(false);
    static HOOK_THREAD_ID: AtomicU32 = AtomicU32::new(0);
    static WIN_DOWN: AtomicBool = AtomicBool::new(false);
    static WIN_COMBO_CONSUMED: AtomicBool = AtomicBool::new(false);

    static BINDINGS: LazyLock<RwLock<HashSet<VkBinding>>> =
        LazyLock::new(|| RwLock::new(HashSet::new()));
    static CONSUMED_VKS: LazyLock<Mutex<HashSet<u32>>> =
        LazyLock::new(|| Mutex::new(HashSet::new()));
    static EVENT_TX: LazyLock<Mutex<Option<mpsc::Sender<NativeOsHotkeyEvent>>>> =
        LazyLock::new(|| Mutex::new(None));
    static CHANNEL_SINK: LazyLock<Mutex<Option<Channel<NativeOsHotkeyEvent>>>> =
        LazyLock::new(|| Mutex::new(None));
    static HOOK_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =
        LazyLock::new(|| Mutex::new(None));
    static DISPATCH_THREAD: LazyLock<Mutex<Option<JoinHandle<()>>>> =
        LazyLock::new(|| Mutex::new(None));

    fn is_pure_modifier_vk(vk: u32) -> bool {
        matches!(
            vk as u16,
            VK_LWIN
                | VK_RWIN
                | VK_CONTROL
                | VK_LCONTROL
                | VK_RCONTROL
                | VK_SHIFT
                | VK_LSHIFT
                | VK_RSHIFT
                | VK_MENU
                | VK_LMENU
                | VK_RMENU
        )
    }

    fn is_our_window_foreground() -> bool {
        let main_raw = MAIN_HWND.load(Ordering::Relaxed);
        if main_raw == 0 {
            return false;
        }
        let main_hwnd = main_raw as HWND;
        unsafe {
            let fg = GetForegroundWindow();
            if fg.is_null() {
                return false;
            }
            if fg == main_hwnd {
                return true;
            }
            GetAncestor(fg, GA_ROOT) == main_hwnd
        }
    }

    fn is_vk_pressed(vk: u16) -> bool {
        unsafe { (GetAsyncKeyState(vk as i32) as u16 & 0x8000) != 0 }
    }

    /// Injects a harmless unassigned virtual key (0xE8) so Windows Shell treats the Win hold
    /// as a completed key chord rather than a lone Win tap (preventing the Start Menu popup).
    fn suppress_start_menu_tap() {
        unsafe {
            let inputs: [INPUT; 2] = [
                INPUT {
                    r#type: INPUT_KEYBOARD,
                    Anonymous: INPUT_0 {
                        ki: KEYBDINPUT {
                            wVk: 0xE8,
                            wScan: 0,
                            dwFlags: 0,
                            time: 0,
                            dwExtraInfo: 0,
                        },
                    },
                },
                INPUT {
                    r#type: INPUT_KEYBOARD,
                    Anonymous: INPUT_0 {
                        ki: KEYBDINPUT {
                            wVk: 0xE8,
                            wScan: 0,
                            dwFlags: KEYEVENTF_KEYUP,
                            time: 0,
                            dwExtraInfo: 0,
                        },
                    },
                },
            ];
            let _ = SendInput(
                inputs.len() as u32,
                inputs.as_ptr(),
                std::mem::size_of::<INPUT>() as i32,
            );
        }
    }

    fn emit_async(event: NativeOsHotkeyEvent) {
        if let Ok(guard) = EVENT_TX.try_lock() {
            if let Some(tx) = guard.as_ref() {
                let _ = tx.send(event);
            }
        }
    }

    unsafe extern "system" fn ll_keyboard_proc(
        n_code: i32,
        w_param: WPARAM,
        l_param: LPARAM,
    ) -> LRESULT {
        if n_code < 0 || l_param == 0 {
            return CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param);
        }

        let consume = std::panic::catch_unwind(|| -> bool {
            let kb = &*(l_param as *const KBDLLHOOKSTRUCT);
            // Never intercept injected keys (including our own 0xE8 Start Menu suppressor)
            if (kb.flags & LLKHF_INJECTED) != 0 {
                return false;
            }

            let msg = w_param as u32;
            let is_down = msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN;
            let is_up = msg == WM_KEYUP || msg == WM_SYSKEYUP;
            if !is_down && !is_up {
                return false;
            }

            let vk = kb.vkCode;
            let is_extended = (kb.flags & LLKHF_EXTENDED) != 0;

            // Track Win key physical press/release cleanly without ever swallowing Win keyup
            if vk == VK_LWIN as u32 || vk == VK_RWIN as u32 {
                if is_down {
                    if !WIN_DOWN.swap(true, Ordering::SeqCst) {
                        WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);
                    }
                } else {
                    WIN_DOWN.store(false, Ordering::SeqCst);
                    WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);
                }
                return false;
            }

            // Release previously consumed key cleanly even if focus changed mid-hold
            if is_up {
                let was_consumed = CONSUMED_VKS
                    .try_lock()
                    .map(|mut set| set.remove(&vk))
                    .unwrap_or(false);
                if was_consumed {
                    if let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) {
                        emit_async(NativeOsHotkeyEvent {
                            phase: "keyup".to_string(),
                            code: code.to_string(),
                            key: key.to_string(),
                            ctrl_key: is_vk_pressed(VK_CONTROL),
                            meta_key: WIN_DOWN.load(Ordering::Relaxed)
                                || is_vk_pressed(VK_LWIN)
                                || is_vk_pressed(VK_RWIN),
                            shift_key: is_vk_pressed(VK_SHIFT),
                            alt_key: is_vk_pressed(VK_MENU),
                            repeat: false,
                            is_recording: RECORDING_MODE.load(Ordering::Relaxed),
                        });
                    }
                    return true;
                }
                return false;
            }

            // Only evaluate keydowns when Win key is actively held AND Ink Studio is foreground
            let win_held =
                WIN_DOWN.load(Ordering::Relaxed) || is_vk_pressed(VK_LWIN) || is_vk_pressed(VK_RWIN);
            if !win_held || is_pure_modifier_vk(vk) || !is_our_window_foreground() {
                return false;
            }

            let ctrl = is_vk_pressed(VK_CONTROL);
            let shift = is_vk_pressed(VK_SHIFT);
            let alt = is_vk_pressed(VK_MENU);

            // Never fight Windows Lock Screen (Win+L without extra modifiers)
            if vk == 0x4C && !ctrl && !shift && !alt {
                return false;
            }

            let Some((code, key)) = vk_to_dom_code_and_key(vk, is_extended) else {
                return false;
            };

            let is_recording = RECORDING_MODE.load(Ordering::Relaxed);
            let matched = if is_recording {
                // Do not capture bare Escape when recording; let user cancel
                vk != 0x1B
            } else {
                BINDINGS
                    .try_read()
                    .map(|set| set.contains(&VkBinding { vk, ctrl, shift, alt }))
                    .unwrap_or(false)
            };

            if !matched {
                return false;
            }

            let is_repeat = CONSUMED_VKS
                .try_lock()
                .map(|mut set| !set.insert(vk))
                .unwrap_or(false);

            if !WIN_COMBO_CONSUMED.swap(true, Ordering::SeqCst) {
                suppress_start_menu_tap();
            }

            emit_async(NativeOsHotkeyEvent {
                phase: "keydown".to_string(),
                code: code.to_string(),
                key: key.to_string(),
                ctrl_key: ctrl,
                meta_key: true,
                shift_key: shift,
                alt_key: alt,
                repeat: is_repeat,
                is_recording,
            });

            true
        })
        .unwrap_or(false);

        if consume {
            1
        } else {
            CallNextHookEx(std::ptr::null_mut(), n_code, w_param, l_param)
        }
    }

    fn ensure_hook_running() -> Result<(), String> {
        if HOOK_RUNNING.load(Ordering::SeqCst) {
            return Ok(());
        }

        let (tx, rx) = mpsc::channel::<NativeOsHotkeyEvent>();
        if let Ok(mut guard) = EVENT_TX.lock() {
            *guard = Some(tx);
        }

        let dispatch_handle = std::thread::Builder::new()
            .name("inkstudio-os-hotkey-dispatch".to_string())
            .spawn(move || {
                while let Ok(ev) = rx.recv() {
                    if let Ok(sink) = CHANNEL_SINK.lock() {
                        if let Some(ch) = sink.as_ref() {
                            let _ = ch.send(ev);
                        }
                    }
                }
            })
            .map_err(|e| format!("Failed to spawn OS hotkey dispatch thread: {}", e))?;

        if let Ok(mut guard) = DISPATCH_THREAD.lock() {
            *guard = Some(dispatch_handle);
        }

        let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();
        let hook_handle = std::thread::Builder::new()
            .name("inkstudio-os-hotkeys".to_string())
            .spawn(move || unsafe {
                let tid = GetCurrentThreadId();
                HOOK_THREAD_ID.store(tid, Ordering::SeqCst);

                let hook: HHOOK =
                    SetWindowsHookExW(WH_KEYBOARD_LL, Some(ll_keyboard_proc), std::ptr::null_mut(), 0);
                if hook.is_null() {
                    HOOK_THREAD_ID.store(0, Ordering::SeqCst);
                    let _ = ready_tx.send(Err("Failed to install WH_KEYBOARD_LL hook".to_string()));
                    return;
                }

                HOOK_RUNNING.store(true, Ordering::SeqCst);
                let _ = ready_tx.send(Ok(()));

                let mut msg: MSG = std::mem::zeroed();
                while GetMessageW(&mut msg, std::ptr::null_mut(), 0, 0) > 0 {
                    TranslateMessage(&msg);
                    DispatchMessageW(&msg);
                }

                UnhookWindowsHookEx(hook);
                HOOK_RUNNING.store(false, Ordering::SeqCst);
                HOOK_THREAD_ID.store(0, Ordering::SeqCst);
                WIN_DOWN.store(false, Ordering::SeqCst);
                WIN_COMBO_CONSUMED.store(false, Ordering::SeqCst);
                if let Ok(mut consumed) = CONSUMED_VKS.lock() {
                    consumed.clear();
                }
            })
            .map_err(|e| format!("Failed to spawn OS hotkey hook thread: {}", e))?;

        match ready_rx.recv() {
            Ok(Ok(())) => {
                if let Ok(mut guard) = HOOK_THREAD.lock() {
                    *guard = Some(hook_handle);
                }
                Ok(())
            }
            Ok(Err(err)) => {
                let _ = hook_handle.join();
                stop();
                Err(err)
            }
            Err(_) => {
                let _ = hook_handle.join();
                stop();
                Err("OS hotkey hook thread exited unexpectedly".to_string())
            }
        }
    }

    pub fn sync(
        window: &tauri::WebviewWindow,
        bindings: Vec<NativeOsHotkeyBinding>,
        recording: bool,
        channel: Channel<NativeOsHotkeyEvent>,
    ) -> Result<OsHotkeyStatus, String> {
        let hwnd = window
            .hwnd()
            .map_err(|e| format!("Failed to acquire main HWND: {}", e))?;
        MAIN_HWND.store(hwnd.0 as isize, Ordering::SeqCst);

        if let Ok(mut sink) = CHANNEL_SINK.lock() {
            *sink = Some(channel);
        }

        let mut vk_set = HashSet::new();
        for b in &bindings {
            for vk in dom_code_to_vks(&b.code) {
                vk_set.insert(VkBinding {
                    vk,
                    ctrl: b.ctrl,
                    shift: b.shift,
                    alt: b.alt,
                });
            }
        }
        let count = vk_set.len();

        if let Ok(mut guard) = BINDINGS.write() {
            *guard = vk_set;
        }
        RECORDING_MODE.store(recording, Ordering::SeqCst);

        if count == 0 && !recording {
            stop_hook_only();
            return Ok(OsHotkeyStatus {
                supported: true,
                active: false,
                registered_count: 0,
                recording: false,
            });
        }

        ensure_hook_running()?;

        Ok(OsHotkeyStatus {
            supported: true,
            active: HOOK_RUNNING.load(Ordering::SeqCst),
            registered_count: count,
            recording,
        })
    }

    fn stop_hook_only() {
        RECORDING_MODE.store(false, Ordering::SeqCst);
        let tid = HOOK_THREAD_ID.load(Ordering::SeqCst);
        if tid != 0 {
            unsafe {
                let _ = PostThreadMessageW(tid, WM_QUIT, 0, 0);
            }
        }
        if let Ok(mut guard) = HOOK_THREAD.lock() {
            if let Some(handle) = guard.take() {
                let _ = handle.join();
            }
        }
        if let Ok(mut guard) = EVENT_TX.lock() {
            *guard = None;
        }
        if let Ok(mut guard) = DISPATCH_THREAD.lock() {
            if let Some(handle) = guard.take() {
                let _ = handle.join();
            }
        }
        HOOK_RUNNING.store(false, Ordering::SeqCst);
    }

    pub fn stop() {
        stop_hook_only();
        if let Ok(mut guard) = BINDINGS.write() {
            guard.clear();
        }
        if let Ok(mut sink) = CHANNEL_SINK.lock() {
            *sink = None;
        }
        MAIN_HWND.store(0, Ordering::SeqCst);
    }
}

#[cfg(not(target_os = "windows"))]
mod fallback_impl {
    use super::*;

    pub fn sync(
        _window: &tauri::WebviewWindow,
        _bindings: Vec<NativeOsHotkeyBinding>,
        _recording: bool,
        _channel: Channel<NativeOsHotkeyEvent>,
    ) -> Result<OsHotkeyStatus, String> {
        Ok(OsHotkeyStatus {
            supported: false,
            active: false,
            registered_count: 0,
            recording: false,
        })
    }

    pub fn stop() {}
}

pub fn sync_os_hotkeys(
    window: &tauri::WebviewWindow,
    bindings: Vec<NativeOsHotkeyBinding>,
    recording: bool,
    channel: Channel<NativeOsHotkeyEvent>,
) -> Result<OsHotkeyStatus, String> {
    #[cfg(target_os = "windows")]
    {
        win_impl::sync(window, bindings, recording, channel)
    }
    #[cfg(not(target_os = "windows"))]
    {
        fallback_impl::sync(window, bindings, recording, channel)
    }
}

pub fn stop_os_hotkeys() {
    #[cfg(target_os = "windows")]
    win_impl::stop();
    #[cfg(not(target_os = "windows"))]
    fallback_impl::stop();
}

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

    #[test]
    fn test_dom_code_vk_roundtrip() {
        let cases = [
            ("KeyA", 0x41u32, "a"),
            ("KeyQ", 0x51, "q"),
            ("KeyZ", 0x5A, "z"),
            ("Digit0", 0x30, "0"),
            ("Digit9", 0x39, "9"),
            ("Numpad1", 0x61, "1"),
            ("F1", 0x70, "F1"),
            ("F12", 0x7B, "F12"),
            ("BracketLeft", 0xDB, "["),
            ("BracketRight", 0xDD, "]"),
            ("Comma", 0xBC, ","),
            ("Period", 0xBE, "."),
            ("Space", 0x20, " "),
            ("Delete", 0x2E, "Delete"),
            ("ArrowLeft", 0x25, "ArrowLeft"),
        ];

        for (code, expected_vk, expected_key) in cases {
            let vks = dom_code_to_vks(code);
            assert_eq!(vks, vec![expected_vk], "dom_code_to_vks failed for {}", code);
            let mapped = vk_to_dom_code_and_key(expected_vk, false);
            assert_eq!(
                mapped,
                Some((code, expected_key)),
                "vk_to_dom_code_and_key failed for 0x{:X}",
                expected_vk
            );
        }
    }

    #[test]
    fn test_numpad_enter_extended_flag() {
        assert_eq!(vk_to_dom_code_and_key(0x0D, false), Some(("Enter", "Enter")));
        assert_eq!(
            vk_to_dom_code_and_key(0x0D, true),
            Some(("NumpadEnter", "Enter"))
        );
    }

    #[test]
    fn test_unknown_dom_codes_return_empty() {
        assert!(dom_code_to_vks("UnknownKey").is_empty());
        assert!(dom_code_to_vks("MetaLeft").is_empty());
        assert_eq!(vk_to_dom_code_and_key(0x5B, false), None);
    }
}