inputkit 0.1.0

Keyboard and mouse input automation for Windows
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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);
    }
}