use crate::{Key, MouseButton};
use std::mem::size_of;
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Mutex, OnceLock, mpsc};
use windows::Win32::Foundation::{LPARAM, LRESULT, POINT, WPARAM};
use windows::Win32::UI::Input::KeyboardAndMouse::{
GetAsyncKeyState, INPUT, INPUT_0, INPUT_KEYBOARD, INPUT_MOUSE, KEYBD_EVENT_FLAGS, KEYBDINPUT,
KEYEVENTF_EXTENDEDKEY, KEYEVENTF_KEYUP, KEYEVENTF_UNICODE, MOUSEEVENTF_HWHEEL,
MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP,
MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP, MOUSEEVENTF_WHEEL, MOUSEEVENTF_XDOWN,
MOUSEEVENTF_XUP, MOUSEINPUT, SendInput, VIRTUAL_KEY,
};
use windows::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, GetCursorPos, GetMessageW, MSG, MSLLHOOKSTRUCT, SetCursorPos,
SetWindowsHookExW, UnhookWindowsHookEx, WH_MOUSE_LL, WM_MOUSEHWHEEL, WM_MOUSEWHEEL,
};
const KEY_COUNT: usize = 256;
const KEY_DOWN_MASK: i16 = i16::MIN;
const WHEEL_DELTA: i32 = 120;
static KEY_TRANSITIONS: OnceLock<Mutex<TransitionState>> = OnceLock::new();
static MOUSE_TRANSITIONS: OnceLock<Mutex<TransitionState>> = OnceLock::new();
static SCROLL_LISTENER_STARTED: OnceLock<bool> = OnceLock::new();
static HORIZONTAL_SCROLL_DELTA: AtomicI32 = AtomicI32::new(0);
static VERTICAL_SCROLL_DELTA: AtomicI32 = AtomicI32::new(0);
#[derive(Clone)]
struct TransitionState {
last_pressed_check: [bool; KEY_COUNT],
last_released_check: [bool; KEY_COUNT],
}
impl TransitionState {
const fn new() -> Self {
Self {
last_pressed_check: [false; KEY_COUNT],
last_released_check: [false; KEY_COUNT],
}
}
fn pressed(&mut self, virtual_key: u16, is_down: bool) -> bool {
let previous = &mut self.last_pressed_check[usize::from(virtual_key)];
let transitioned = is_down && !*previous;
*previous = is_down;
transitioned
}
fn released(&mut self, virtual_key: u16, is_down: bool) -> bool {
let previous = &mut self.last_released_check[usize::from(virtual_key)];
let transitioned = !is_down && *previous;
*previous = is_down;
transitioned
}
}
pub(crate) fn key_pressed(key: Key) -> bool {
pressed(&KEY_TRANSITIONS, key_virtual_key(key))
}
pub(crate) fn key_down(key: Key) -> bool {
virtual_key_down(key_virtual_key(key))
}
pub(crate) fn key_released(key: Key) -> bool {
released(&KEY_TRANSITIONS, key_virtual_key(key))
}
pub(crate) fn mouse_pressed(button: MouseButton) -> bool {
pressed(&MOUSE_TRANSITIONS, mouse_virtual_key(button))
}
pub(crate) fn mouse_down(button: MouseButton) -> bool {
virtual_key_down(mouse_virtual_key(button))
}
pub(crate) fn mouse_released(button: MouseButton) -> bool {
released(&MOUSE_TRANSITIONS, mouse_virtual_key(button))
}
fn pressed(state: &OnceLock<Mutex<TransitionState>>, virtual_key: u16) -> bool {
let mut state = state
.get_or_init(|| Mutex::new(TransitionState::new()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let is_down = virtual_key_down(virtual_key);
state.pressed(virtual_key, is_down)
}
fn released(state: &OnceLock<Mutex<TransitionState>>, virtual_key: u16) -> bool {
let mut state = state
.get_or_init(|| Mutex::new(TransitionState::new()))
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let is_down = virtual_key_down(virtual_key);
state.released(virtual_key, is_down)
}
fn virtual_key_down(virtual_key: u16) -> bool {
unsafe { GetAsyncKeyState(i32::from(virtual_key)) & KEY_DOWN_MASK != 0 }
}
pub(crate) fn send_key(key: Key, key_up: bool) -> bool {
send_inputs(&[keyboard_input(key, key_up)])
}
pub(crate) fn tap_key(key: Key) -> bool {
send_inputs(&[keyboard_input(key, false), keyboard_input(key, true)])
}
pub(crate) fn type_text(text: &str) -> bool {
let utf16: Vec<u16> = text.encode_utf16().collect();
let mut inputs = Vec::with_capacity(utf16.len() * 2);
for code_unit in utf16 {
inputs.push(unicode_input(code_unit, false));
inputs.push(unicode_input(code_unit, true));
}
send_inputs(&inputs)
}
fn keyboard_input(key: Key, key_up: bool) -> INPUT {
let mut flags = if is_extended_key(key) {
KEYEVENTF_EXTENDEDKEY
} else {
KEYBD_EVENT_FLAGS::default()
};
if key_up {
flags |= KEYEVENTF_KEYUP;
}
INPUT {
r#type: INPUT_KEYBOARD,
Anonymous: INPUT_0 {
ki: KEYBDINPUT {
wVk: VIRTUAL_KEY(key_virtual_key(key)),
dwFlags: flags,
..Default::default()
},
},
}
}
fn unicode_input(code_unit: u16, key_up: bool) -> INPUT {
INPUT {
r#type: INPUT_KEYBOARD,
Anonymous: INPUT_0 {
ki: KEYBDINPUT {
wScan: code_unit,
dwFlags: if key_up {
KEYEVENTF_UNICODE | KEYEVENTF_KEYUP
} else {
KEYEVENTF_UNICODE
},
..Default::default()
},
},
}
}
pub(crate) fn cursor_position() -> Option<(i32, i32)> {
let mut point = POINT::default();
if unsafe { GetCursorPos(&mut point) }.is_ok() {
Some((point.x, point.y))
} else {
None
}
}
pub(crate) fn set_cursor_position(x: i32, y: i32) -> bool {
unsafe { SetCursorPos(x, y) }.is_ok()
}
pub(crate) fn send_mouse_button(button: MouseButton, button_up: bool) -> bool {
send_inputs(&[mouse_button_input(button, button_up)])
}
pub(crate) fn click_mouse(button: MouseButton, count: usize) -> bool {
let mut inputs = Vec::with_capacity(count * 2);
for _ in 0..count {
inputs.push(mouse_button_input(button, false));
inputs.push(mouse_button_input(button, true));
}
send_inputs(&inputs)
}
pub(crate) fn scroll_mouse_vertical(steps: i32) -> bool {
scroll_mouse(steps, MOUSEEVENTF_WHEEL)
}
pub(crate) fn scroll_mouse_horizontal(steps: i32) -> bool {
scroll_mouse(steps, MOUSEEVENTF_HWHEEL)
}
fn scroll_mouse(
steps: i32,
flags: windows::Win32::UI::Input::KeyboardAndMouse::MOUSE_EVENT_FLAGS,
) -> bool {
let distance = steps.saturating_mul(WHEEL_DELTA);
let input = INPUT {
r#type: INPUT_MOUSE,
Anonymous: INPUT_0 {
mi: MOUSEINPUT {
mouseData: distance as u32,
dwFlags: flags,
..Default::default()
},
},
};
send_inputs(&[input])
}
pub(crate) fn take_scroll_delta() -> Option<(i32, i32)> {
if !*SCROLL_LISTENER_STARTED.get_or_init(start_scroll_listener) {
return None;
}
Some((
HORIZONTAL_SCROLL_DELTA.swap(0, Ordering::Relaxed),
VERTICAL_SCROLL_DELTA.swap(0, Ordering::Relaxed),
))
}
fn start_scroll_listener() -> bool {
let (sender, receiver) = mpsc::sync_channel(1);
if std::thread::Builder::new()
.name("inputkit-mouse-hook".into())
.spawn(move || run_scroll_listener(sender))
.is_err()
{
return false;
}
receiver.recv().unwrap_or(false)
}
fn run_scroll_listener(started: mpsc::SyncSender<bool>) {
let hook = match unsafe { SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook), None, 0) } {
Ok(hook) => hook,
Err(_) => {
let _ = started.send(false);
return;
}
};
if started.send(true).is_err() {
let _ = unsafe { UnhookWindowsHookEx(hook) };
return;
}
let mut message = MSG::default();
while unsafe { GetMessageW(&mut message, None, 0, 0) }.0 > 0 {}
let _ = unsafe { UnhookWindowsHookEx(hook) };
}
unsafe extern "system" fn mouse_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code >= 0 && (wparam.0 as u32 == WM_MOUSEWHEEL || wparam.0 as u32 == WM_MOUSEHWHEEL) {
let event = unsafe { &*(lparam.0 as *const MSLLHOOKSTRUCT) };
let delta = (event.mouseData >> 16) as u16 as i16 as i32;
let accumulator = if wparam.0 as u32 == WM_MOUSEWHEEL {
&VERTICAL_SCROLL_DELTA
} else {
&HORIZONTAL_SCROLL_DELTA
};
add_scroll_delta(accumulator, delta);
}
unsafe { CallNextHookEx(None, code, wparam, lparam) }
}
fn add_scroll_delta(accumulator: &AtomicI32, delta: i32) {
let _ = accumulator.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
Some(current.saturating_add(delta))
});
}
fn mouse_button_input(button: MouseButton, button_up: bool) -> INPUT {
let (mouse_data, down_flag, up_flag) = match button {
MouseButton::Left => (0, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP),
MouseButton::Right => (0, MOUSEEVENTF_RIGHTDOWN, MOUSEEVENTF_RIGHTUP),
MouseButton::Middle => (0, MOUSEEVENTF_MIDDLEDOWN, MOUSEEVENTF_MIDDLEUP),
MouseButton::X1 => (1, MOUSEEVENTF_XDOWN, MOUSEEVENTF_XUP),
MouseButton::X2 => (2, MOUSEEVENTF_XDOWN, MOUSEEVENTF_XUP),
};
INPUT {
r#type: INPUT_MOUSE,
Anonymous: INPUT_0 {
mi: MOUSEINPUT {
mouseData: mouse_data,
dwFlags: if button_up { up_flag } else { down_flag },
..Default::default()
},
},
}
}
fn send_inputs(inputs: &[INPUT]) -> bool {
unsafe { SendInput(inputs, size_of::<INPUT>() as i32) == inputs.len() as u32 }
}
const fn key_virtual_key(key: Key) -> u16 {
match key {
Key::A => 0x41,
Key::B => 0x42,
Key::C => 0x43,
Key::D => 0x44,
Key::E => 0x45,
Key::F => 0x46,
Key::G => 0x47,
Key::H => 0x48,
Key::I => 0x49,
Key::J => 0x4A,
Key::K => 0x4B,
Key::L => 0x4C,
Key::M => 0x4D,
Key::N => 0x4E,
Key::O => 0x4F,
Key::P => 0x50,
Key::Q => 0x51,
Key::R => 0x52,
Key::S => 0x53,
Key::T => 0x54,
Key::U => 0x55,
Key::V => 0x56,
Key::W => 0x57,
Key::X => 0x58,
Key::Y => 0x59,
Key::Z => 0x5A,
Key::Num0 => 0x30,
Key::Num1 => 0x31,
Key::Num2 => 0x32,
Key::Num3 => 0x33,
Key::Num4 => 0x34,
Key::Num5 => 0x35,
Key::Num6 => 0x36,
Key::Num7 => 0x37,
Key::Num8 => 0x38,
Key::Num9 => 0x39,
Key::Backspace => 0x08,
Key::Tab => 0x09,
Key::Enter => 0x0D,
Key::Escape => 0x1B,
Key::Space => 0x20,
Key::Home => 0x24,
Key::End => 0x23,
Key::PageUp => 0x21,
Key::PageDown => 0x22,
Key::Insert => 0x2D,
Key::Delete => 0x2E,
Key::Shift => 0x10,
Key::LeftShift => 0xA0,
Key::RightShift => 0xA1,
Key::Control => 0x11,
Key::LeftControl => 0xA2,
Key::RightControl => 0xA3,
Key::Alt => 0x12,
Key::LeftAlt => 0xA4,
Key::RightAlt => 0xA5,
Key::LeftWindows => 0x5B,
Key::RightWindows => 0x5C,
Key::Menu => 0x5D,
Key::CapsLock => 0x14,
Key::NumLock => 0x90,
Key::ScrollLock => 0x91,
Key::PrintScreen => 0x2C,
Key::Pause => 0x13,
Key::Left => 0x25,
Key::Up => 0x26,
Key::Right => 0x27,
Key::Down => 0x28,
Key::F1 => 0x70,
Key::F2 => 0x71,
Key::F3 => 0x72,
Key::F4 => 0x73,
Key::F5 => 0x74,
Key::F6 => 0x75,
Key::F7 => 0x76,
Key::F8 => 0x77,
Key::F9 => 0x78,
Key::F10 => 0x79,
Key::F11 => 0x7A,
Key::F12 => 0x7B,
Key::F13 => 0x7C,
Key::F14 => 0x7D,
Key::F15 => 0x7E,
Key::F16 => 0x7F,
Key::F17 => 0x80,
Key::F18 => 0x81,
Key::F19 => 0x82,
Key::F20 => 0x83,
Key::F21 => 0x84,
Key::F22 => 0x85,
Key::F23 => 0x86,
Key::F24 => 0x87,
Key::Numpad0 => 0x60,
Key::Numpad1 => 0x61,
Key::Numpad2 => 0x62,
Key::Numpad3 => 0x63,
Key::Numpad4 => 0x64,
Key::Numpad5 => 0x65,
Key::Numpad6 => 0x66,
Key::Numpad7 => 0x67,
Key::Numpad8 => 0x68,
Key::Numpad9 => 0x69,
Key::NumpadMultiply => 0x6A,
Key::NumpadAdd => 0x6B,
Key::NumpadSubtract => 0x6D,
Key::NumpadDecimal => 0x6E,
Key::NumpadDivide => 0x6F,
Key::NumpadSeparator => 0x6C,
Key::Semicolon => 0xBA,
Key::Equals => 0xBB,
Key::Comma => 0xBC,
Key::Minus => 0xBD,
Key::Period => 0xBE,
Key::Slash => 0xBF,
Key::Backtick => 0xC0,
Key::LeftBracket => 0xDB,
Key::Backslash => 0xDC,
Key::RightBracket => 0xDD,
Key::Quote => 0xDE,
Key::VolumeMute => 0xAD,
Key::VolumeDown => 0xAE,
Key::VolumeUp => 0xAF,
Key::MediaNext => 0xB0,
Key::MediaPrevious => 0xB1,
Key::MediaStop => 0xB2,
Key::MediaPlayPause => 0xB3,
Key::BrowserBack => 0xA6,
Key::BrowserForward => 0xA7,
Key::BrowserRefresh => 0xA8,
Key::BrowserStop => 0xA9,
Key::BrowserSearch => 0xAA,
Key::BrowserFavorites => 0xAB,
Key::BrowserHome => 0xAC,
Key::LaunchMail => 0xB4,
Key::LaunchMediaPlayer => 0xB5,
Key::LaunchApp1 => 0xB6,
Key::LaunchApp2 => 0xB7,
Key::Sleep => 0x5F,
}
}
const fn mouse_virtual_key(button: MouseButton) -> u16 {
match button {
MouseButton::Left => 0x01,
MouseButton::Right => 0x02,
MouseButton::Middle => 0x04,
MouseButton::X1 => 0x05,
MouseButton::X2 => 0x06,
}
}
const fn is_extended_key(key: Key) -> bool {
matches!(
key,
Key::RightControl
| Key::RightAlt
| Key::LeftWindows
| Key::RightWindows
| Key::Menu
| Key::PrintScreen
| Key::NumLock
| Key::Insert
| Key::Delete
| Key::Home
| Key::End
| Key::PageUp
| Key::PageDown
| Key::Up
| Key::Down
| Key::Left
| Key::Right
| Key::NumpadDivide
| Key::VolumeMute
| Key::VolumeDown
| Key::VolumeUp
| Key::MediaNext
| Key::MediaPrevious
| Key::MediaStop
| Key::MediaPlayPause
| Key::BrowserBack
| Key::BrowserForward
| Key::BrowserRefresh
| Key::BrowserStop
| Key::BrowserSearch
| Key::BrowserFavorites
| Key::BrowserHome
| Key::LaunchMail
| Key::LaunchMediaPlayer
| Key::LaunchApp1
| Key::LaunchApp2
| Key::Sleep
)
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicI32, Ordering};
use super::{TransitionState, add_scroll_delta, is_extended_key, key_virtual_key};
use crate::Key;
const A: u16 = 0x41;
#[test]
fn pressed_only_reports_the_up_to_down_transition() {
let mut state = TransitionState::new();
assert!(!state.pressed(A, false));
assert!(state.pressed(A, true));
assert!(!state.pressed(A, true));
assert!(!state.pressed(A, false));
assert!(state.pressed(A, true));
}
#[test]
fn released_only_reports_the_down_to_up_transition() {
let mut state = TransitionState::new();
assert!(!state.released(A, false));
assert!(!state.released(A, true));
assert!(!state.released(A, true));
assert!(state.released(A, false));
assert!(!state.released(A, false));
}
#[test]
fn pressed_and_released_checks_track_independently() {
let mut state = TransitionState::new();
assert!(state.pressed(A, true));
assert!(!state.released(A, true));
assert!(state.released(A, false));
assert!(!state.pressed(A, false));
}
#[test]
fn side_specific_modifiers_have_distinct_virtual_keys() {
assert_ne!(
key_virtual_key(Key::LeftShift),
key_virtual_key(Key::RightShift)
);
assert_ne!(
key_virtual_key(Key::LeftControl),
key_virtual_key(Key::RightControl)
);
assert_ne!(
key_virtual_key(Key::LeftAlt),
key_virtual_key(Key::RightAlt)
);
}
#[test]
fn right_side_extended_modifiers_are_marked_extended() {
assert!(!is_extended_key(Key::LeftControl));
assert!(is_extended_key(Key::RightControl));
assert!(!is_extended_key(Key::LeftAlt));
assert!(is_extended_key(Key::RightAlt));
}
#[test]
fn accumulated_scroll_delta_saturates_instead_of_wrapping() {
let accumulator = AtomicI32::new(i32::MAX - 10);
add_scroll_delta(&accumulator, 120);
assert_eq!(accumulator.load(Ordering::Relaxed), i32::MAX);
}
}