rustimal 0.4.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! A global hotkey that shows and hides rustimal from anywhere (`hotkey = "ctrl+alt+space"`).
//!
//! A background thread registers the key with Windows and turns each press into a
//! `UserEvent::Hotkey` for the app. The key can be changed while running.

use std::sync::mpsc;

use winit::event_loop::EventLoopProxy;

use crate::pane::UserEvent;

const MOD_ALT: u32 = 0x1;
const MOD_CONTROL: u32 = 0x2;
const MOD_SHIFT: u32 = 0x4;
const MOD_WIN: u32 = 0x8;
const MOD_NOREPEAT: u32 = 0x4000;
const WM_HOTKEY: u32 = 0x0312;
const WM_APP: u32 = 0x8000;
const WM_APP_CLEAR: u32 = WM_APP + 1;
const PM_NOREMOVE: u32 = 0;
const HOTKEY_ID: i32 = 1;

#[repr(C)]
struct Msg {
    hwnd: isize,
    message: u32,
    wparam: usize,
    lparam: isize,
    time: u32,
    pt_x: i32,
    pt_y: i32,
}

#[link(name = "user32")]
unsafe extern "system" {
    fn RegisterHotKey(hwnd: isize, id: i32, modifiers: u32, vk: u32) -> i32;
    fn UnregisterHotKey(hwnd: isize, id: i32) -> i32;
    fn GetMessageW(msg: *mut Msg, hwnd: isize, min: u32, max: u32) -> i32;
    fn PeekMessageW(msg: *mut Msg, hwnd: isize, min: u32, max: u32, remove: u32) -> i32;
    fn PostThreadMessageW(thread: u32, msg: u32, wparam: usize, lparam: isize) -> i32;
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn GetCurrentThreadId() -> u32;
}

/// Turn `ctrl+alt+space`, `win+shift+f12` and the like into Windows modifiers and a virtual-key
/// code. Letters and digits, F1-F12, the usual named keys and a few symbols (US layout) work.
pub fn parse(text: &str) -> Option<(u32, u32)> {
    let text = text.trim().to_lowercase();
    let (mods_part, key) = match text.rsplit_once('+') {
        Some((m, k)) if !k.is_empty() => (m, k.trim()),
        _ if !text.is_empty() && !text.ends_with('+') => ("", text.as_str()),
        _ => return None,
    };
    let mut mods = 0;
    for m in mods_part.split('+').map(str::trim).filter(|m| !m.is_empty()) {
        mods |= match m {
            "ctrl" | "control" => MOD_CONTROL,
            "alt" => MOD_ALT,
            "shift" => MOD_SHIFT,
            "win" | "super" | "meta" => MOD_WIN,
            _ => return None,
        };
    }
    let vk = match key {
        "space" => 0x20,
        "enter" | "return" => 0x0D,
        "tab" => 0x09,
        "escape" | "esc" => 0x1B,
        "backspace" => 0x08,
        "insert" => 0x2D,
        "delete" | "del" => 0x2E,
        "home" => 0x24,
        "end" => 0x23,
        "pageup" => 0x21,
        "pagedown" => 0x22,
        "left" => 0x25,
        "up" => 0x26,
        "right" => 0x27,
        "down" => 0x28,
        "`" => 0xC0,
        "-" => 0xBD,
        "=" => 0xBB,
        "," => 0xBC,
        "." => 0xBE,
        "/" => 0xBF,
        ";" => 0xBA,
        "'" => 0xDE,
        "[" => 0xDB,
        "]" => 0xDD,
        "\\" => 0xDC,
        k if k.len() == 1 && k.as_bytes()[0].is_ascii_alphanumeric() => k.as_bytes()[0].to_ascii_uppercase() as u32,
        k if k.starts_with('f') && k[1..].parse::<u32>().is_ok_and(|n| (1..=12).contains(&n)) => {
            0x70 + k[1..].parse::<u32>().unwrap() - 1
        }
        _ => return None,
    };
    // A bare key with no modifier would take that key away from every program.
    (mods != 0).then_some((mods, vk))
}

/// The running hotkey thread.
pub struct Hotkey {
    thread: u32,
}

impl Hotkey {
    /// Start listening for `text`. Returns `None` if it can't be read or registered.
    pub fn start(text: &str, proxy: EventLoopProxy<UserEvent>) -> Option<Hotkey> {
        let (mods, vk) = parse(text).or_else(|| {
            log::warn!("can't read the hotkey '{text}'");
            None
        })?;
        let (tx, rx) = mpsc::channel();
        std::thread::spawn(move || {
            // SAFETY: plain user32 calls on this thread, with a correctly sized MSG.
            unsafe {
                // Make sure this thread has a message queue before anyone posts to it.
                let mut msg: Msg = std::mem::zeroed();
                PeekMessageW(&mut msg, 0, 0, 0, PM_NOREMOVE);
                let ok = RegisterHotKey(0, HOTKEY_ID, mods | MOD_NOREPEAT, vk) != 0;
                let _ = tx.send((GetCurrentThreadId(), ok));
                while GetMessageW(&mut msg, 0, 0, 0) > 0 {
                    match msg.message {
                        WM_HOTKEY => {
                            let _ = proxy.send_event(UserEvent::Hotkey);
                        }
                        // Change the key: modifiers in wparam, virtual key in lparam.
                        WM_APP => {
                            UnregisterHotKey(0, HOTKEY_ID);
                            if RegisterHotKey(0, HOTKEY_ID, msg.wparam as u32 | MOD_NOREPEAT, msg.lparam as u32) == 0 {
                                log::warn!("could not register the new hotkey (another program may use it)");
                            }
                        }
                        WM_APP_CLEAR => {
                            UnregisterHotKey(0, HOTKEY_ID);
                        }
                        _ => {}
                    }
                }
            }
        });
        let (thread, ok) = rx.recv().ok()?;
        if !ok {
            log::warn!("could not register the hotkey '{text}' (another program may use it)");
        }
        // Keep going even if it failed: a later change of key may work.
        Some(Hotkey { thread })
    }

    /// Stop listening.
    pub fn clear(&self) {
        // SAFETY: posting a thread message with plain integers.
        unsafe { PostThreadMessageW(self.thread, WM_APP_CLEAR, 0, 0) };
    }

    /// Switch to another key. Returns false if it can't be read.
    pub fn change(&self, text: &str) -> bool {
        let Some((mods, vk)) = parse(text) else { return false };
        // SAFETY: posting a thread message with plain integers.
        unsafe { PostThreadMessageW(self.thread, WM_APP, mods as usize, vk as isize) != 0 }
    }
}

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

    #[test]
    fn hotkeys_parse_to_windows_codes() {
        assert_eq!(parse("ctrl+alt+space"), Some((MOD_CONTROL | MOD_ALT, 0x20)));
        assert_eq!(parse("Win+Shift+F12"), Some((MOD_WIN | MOD_SHIFT, 0x7B)));
        assert_eq!(parse("ctrl+t"), Some((MOD_CONTROL, b'T' as u32)));
        assert_eq!(parse("ctrl+5"), Some((MOD_CONTROL, b'5' as u32)));
        assert_eq!(parse("alt+`"), Some((MOD_ALT, 0xC0)));
        assert_eq!(parse("ctrl+shift+pageup"), Some((MOD_CONTROL | MOD_SHIFT, 0x21)));
        assert_eq!(parse("ctrl+f1"), Some((MOD_CONTROL, 0x70)));
    }

    #[test]
    fn bad_hotkeys_are_refused() {
        // A key with no modifier would be taken from every program.
        assert_eq!(parse("space"), None);
        assert_eq!(parse("f5"), None);
        for bad in ["", "ctrl+", "ctrl+nope", "hyper+x", "ctrl+f13", "ctrl+ab", "+"] {
            assert_eq!(parse(bad), None, "{bad:?}");
        }
    }
}