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;
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;
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();
pub(super) static WATCHING: AtomicBool = AtomicBool::new(false);
pub struct Keys;
impl Keys {
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 || {
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;
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) }
});
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) {
unsafe { PostThreadMessageW(thread, WM_APP_ACTIVE, usize::from(active), 0) };
}
}
pub fn set_active(active: bool) {
if ACTIVE.swap(active, Ordering::Relaxed) != active {
Self::post_active(active);
}
}
pub fn set_watching(watching: bool) {
WATCHING.store(watching, Ordering::Relaxed);
}
}
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())
}
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];
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]));
}
}
unsafe { CallNextHookEx(0, code, wparam, lparam) }
}