rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Rustimal's pane shortcuts and clicks while a program has the keyboard.

use super::*;

pub(super) const WH_MOUSE_LL: i32 = 14;

pub(super) const WM_LBUTTONDOWN: usize = 0x0201;

pub(super) const WM_RBUTTONDOWN: usize = 0x0204;

pub(super) const WM_MBUTTONDOWN: usize = 0x0207;

pub(super) const WM_HOTKEY: u32 = 0x0312;

/// Tell the thread to register (`wparam` 1) or let go of (0) the chords.
pub(super) const WM_APP_ACTIVE: u32 = 0x8002;

pub(super) const MOD_ALT: u32 = 1;

pub(super) const MOD_CONTROL: u32 = 2;

pub(super) const MOD_SHIFT: u32 = 4;

pub(super) const MOD_NOREPEAT: u32 = 0x4000;

/// The chords to hand back, as `(modifiers, key, action id)`.
pub(super) static CHORDS: Mutex<Vec<(u32, u32, &'static str)>> = Mutex::new(Vec::new());

pub(super) static PROXY: Mutex<Option<EventLoopProxy<UserEvent>>> = Mutex::new(None);

pub(super) static ACTIVE: AtomicBool = AtomicBool::new(false);

pub(super) static THREAD: OnceLock<u32> = OnceLock::new();

/// Whether there is a hosted program at all, for the mouse hook to look at clicks.
pub(super) static WATCHING: AtomicBool = AtomicBool::new(false);

pub struct Keys;

impl Keys {
    /// Hand the pane shortcuts back to rustimal while a hosted program has the keyboard.
    pub fn install(proxy: &EventLoopProxy<UserEvent>, chords: BTreeMap<String, &'static str>) {
        let table = chords
            .into_iter()
            .filter_map(|(chord, action)| {
                let (mods, key) = chord.rsplit_once('+').map_or(("", chord.as_str()), |(m, k)| (m, k));
                let flags = mods.split('+').fold(0, |all, m| {
                    all | match m {
                        "ctrl" => MOD_CONTROL,
                        "alt" => MOD_ALT,
                        "shift" => MOD_SHIFT,
                        _ => 0,
                    }
                });
                Some((flags, vk_of(key)?, action))
            })
            .collect();
        if let Ok(mut all) = CHORDS.lock() {
            *all = table;
        }
        if let Ok(mut slot) = PROXY.lock() {
            *slot = Some(proxy.clone());
        }
        THREAD.get_or_init(|| {
            let (sender, receiver) = std::sync::mpsc::channel();
            let started = std::thread::Builder::new().name("host-keys".into()).spawn(move || {
                // SAFETY: the thread's own message queue, hot keys and mouse hook; it waits
                // for messages (what they are reported through) for as long as rustimal runs.
                unsafe {
                    let _ = sender.send(GetCurrentThreadId());
                    SetWindowsHookExW(WH_MOUSE_LL, mouse_hook, 0, 0);
                    let mut message = Msg::empty();
                    let mut registered: Vec<i32> = Vec::new();
                    while GetMessageW(&mut message, 0, 0, 0) > 0 {
                        match message.message {
                            WM_APP_ACTIVE => {
                                for id in registered.drain(..) {
                                    UnregisterHotKey(0, id);
                                }
                                if message.wparam == 1
                                    && let Ok(all) = CHORDS.lock()
                                {
                                    for (i, &(mods, vk, _)) in all.iter().enumerate() {
                                        let id = i as i32 + 1;
                                        // One that is taken by another program is left out.
                                        if RegisterHotKey(0, id, mods | MOD_NOREPEAT, vk) != 0 {
                                            registered.push(id);
                                        }
                                    }
                                }
                            }
                            WM_HOTKEY => {
                                let action = CHORDS.lock().ok().and_then(|all| {
                                    all.get((message.wparam).wrapping_sub(1)).map(|&(_, _, action)| action)
                                });
                                if let Some(action) = action
                                    && let Ok(slot) = PROXY.lock()
                                    && let Some(proxy) = slot.as_ref()
                                {
                                    let _ = proxy.send_event(UserEvent::HostKey(action.to_string()));
                                }
                            }
                            _ => {}
                        }
                    }
                }
            });
            if started.is_err() { 0 } else { receiver.recv_timeout(Duration::from_secs(2)).unwrap_or(0) }
        });
        // The chords may have changed (a new keymap): register them again if they are in use.
        if ACTIVE.load(Ordering::Relaxed) {
            Self::post_active(true);
        }
    }

    pub(super) fn post_active(active: bool) {
        if let Some(&thread) = THREAD.get().filter(|&&t| t != 0) {
            // SAFETY: posts a message to our own thread.
            unsafe { PostThreadMessageW(thread, WM_APP_ACTIVE, usize::from(active), 0) };
        }
    }

    /// Whether a hosted program has the keyboard (the chords are only registered then).
    pub fn set_active(active: bool) {
        if ACTIVE.swap(active, Ordering::Relaxed) != active {
            Self::post_active(active);
        }
    }

    /// Whether there are hosted programs, so that clicks on them are reported.
    pub fn set_watching(watching: bool) {
        WATCHING.store(watching, Ordering::Relaxed);
    }
}

/// The virtual key for a chord's key, the other way round from [`key_name`].
pub(super) fn vk_of(key: &str) -> Option<u32> {
    (0..=0xFFu32).find(|&vk| key_name(vk).as_deref() == Some(key))
}

pub(super) fn key_name(vk: u32) -> Option<String> {
    let named = match vk {
        0x41..=0x5A => return Some(((vk as u8 - 0x41 + b'a') as char).to_string()),
        0x30..=0x39 => return Some(((vk as u8 - 0x30 + b'0') as char).to_string()),
        0x70..=0x7B => return Some(format!("f{}", vk - 0x6F)),
        0x25 => "left",
        0x26 => "up",
        0x27 => "right",
        0x28 => "down",
        0x21 => "pageup",
        0x22 => "pagedown",
        0x23 => "end",
        0x24 => "home",
        0x2D => "insert",
        0x2E => "delete",
        0x09 => "tab",
        0x0D => "enter",
        0x1B => "escape",
        0x20 => "space",
        0x08 => "backspace",
        0xBB => "=",
        0xBC => ",",
        0xBD => "-",
        0xBE => ".",
        0xBA => ";",
        0xBF => "/",
        0xC0 => "`",
        0xDB => "[",
        0xDC => "\\",
        0xDD => "]",
        0xDE => "'",
        _ => return None,
    };
    Some(named.to_string())
}

/// Tells rustimal where a button went down. A click in a program never reaches rustimal's
/// own window, and some programs (Chromium's) don't take the keyboard by being clicked.
pub(super) unsafe extern "system" fn mouse_hook(code: i32, wparam: usize, lparam: isize) -> isize {
    if code == 0
        && WATCHING.load(Ordering::Relaxed)
        && matches!(wparam, WM_LBUTTONDOWN | WM_RBUTTONDOWN | WM_MBUTTONDOWN)
    {
        let mut at = [0i32; 2];
        // SAFETY: the point is where the position goes.
        unsafe { GetCursorPos(&mut at) };
        if let Ok(slot) = PROXY.lock()
            && let Some(proxy) = slot.as_ref()
        {
            let _ = proxy.send_event(UserEvent::HostClick(at[0], at[1]));
        }
    }
    // SAFETY: passes on what was given.
    unsafe { CallNextHookEx(0, code, wparam, lparam) }
}