use std::sync::mpsc;
use winit::event_loop::EventLoopProxy;
use super::win32::{GetCurrentThreadId, GetMessageW, Msg, PostThreadMessageW, RegisterHotKey, UnregisterHotKey};
use crate::terminal::events::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;
#[link(name = "user32")]
unsafe extern "system" {
fn PeekMessageW(msg: *mut Msg, hwnd: isize, min: u32, max: u32, remove: u32) -> i32;
}
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,
};
(mods != 0).then_some((mods, vk))
}
pub struct Hotkey {
thread: u32,
}
impl Hotkey {
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 || {
unsafe {
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);
}
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)");
}
Some(Hotkey { thread })
}
pub fn clear(&self) {
unsafe { PostThreadMessageW(self.thread, WM_APP_CLEAR, 0, 0) };
}
pub fn change(&self, text: &str) -> bool {
let Some((mods, vk)) = parse(text) else { return false };
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() {
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:?}");
}
}
}