Repository navigation
Expand file tree
/
Copy pathwindows_input.rs
More file actions
1823 lines (1726 loc) · 64.8 KB
/
Copy pathwindows_input.rs
File metadata and controls
1823 lines (1726 loc) · 64.8 KB
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::ptr;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use color_eyre::eyre::{Result, eyre};
use windows_sys::Win32::Foundation::{LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::System::SystemInformation::GetTickCount;
use windows_sys::Win32::System::Threading::GetCurrentThreadId;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{
GetAsyncKeyState, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT, KEYEVENTF_EXTENDEDKEY,
KEYEVENTF_KEYUP, SendInput, VK_CONTROL, VK_ESCAPE, VK_LCONTROL, VK_LMENU, VK_LSHIFT, VK_LWIN,
VK_MENU, VK_RCONTROL, VK_RETURN, VK_RMENU, VK_RSHIFT, VK_RWIN, VK_SHIFT, VK_SPACE, VK_TAB,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{
CallNextHookEx, GetMessageW, HC_ACTION, KBDLLHOOKSTRUCT, LLKHF_EXTENDED, MSG, MSLLHOOKSTRUCT,
PM_NOREMOVE, PeekMessageW, PostThreadMessageW, SetWindowsHookExW, UnhookWindowsHookEx,
WH_KEYBOARD_LL, WH_MOUSE_LL, WM_KEYDOWN, WM_KEYUP, WM_QUIT, WM_SYSKEYDOWN, WM_SYSKEYUP,
};
use crate::app_settings::{HotkeyBinding, HotkeyKey, HotkeyModifiers, ModifierSide};
use crate::audio::CaptureInstant;
use crate::dictation::ShortcutMode;
/// The focused application's executable stem (e.g. "chrome"), lowercased,
/// for per-application dictation modes and history entries.
pub fn foreground_process_stem() -> Option<String> {
use windows_sys::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
let window = unsafe { GetForegroundWindow() };
let path = window_process_path(window)?;
Some(path.file_stem()?.to_string_lossy().to_lowercase())
}
/// The executable of the process that owns `window`.
pub fn window_process_path(
window: windows_sys::Win32::Foundation::HWND,
) -> Option<std::path::PathBuf> {
use windows_sys::Win32::Foundation::CloseHandle;
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::GetWindowThreadProcessId;
if window.is_null() {
return None;
}
unsafe {
let mut pid = 0_u32;
GetWindowThreadProcessId(window, &mut pid);
if pid == 0 {
return None;
}
let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
if process.is_null() {
return None;
}
let mut buffer = [0_u16; 1024];
let mut length = buffer.len() as u32;
let ok = QueryFullProcessImageNameW(process, 0, buffer.as_mut_ptr(), &mut length);
CloseHandle(process);
if ok == 0 {
return None;
}
Some(String::from_utf16_lossy(&buffer[..length as usize]).into())
}
}
/// A shortcut as the keyboard hook matches it: the chord's modifier keys,
/// each with its side, and the named key. Settings store it as a portable
/// `HotkeyBinding`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct WindowsHotkey {
pub control: Option<ModifierSide>,
pub windows: Option<ModifierSide>,
pub alt: Option<ModifierSide>,
pub shift: Option<ModifierSide>,
pub key: Option<String>,
}
impl Default for WindowsHotkey {
fn default() -> Self {
Self {
control: Some(ModifierSide::Either),
windows: None,
alt: None,
shift: None,
key: Some("space".into()),
}
}
}
/// Windows names Command the Windows key and Option Alt; keys go by name.
impl From<&HotkeyBinding> for WindowsHotkey {
fn from(binding: &HotkeyBinding) -> Self {
Self {
control: binding.modifiers.control,
windows: binding.modifiers.command,
alt: binding.modifiers.option,
shift: binding.modifiers.shift,
key: binding.key.as_ref().map(HotkeyKey::name),
}
}
}
impl From<&WindowsHotkey> for HotkeyBinding {
fn from(hotkey: &WindowsHotkey) -> Self {
Self {
modifiers: hotkey.modifiers(),
key: hotkey.key.as_deref().map(HotkeyKey::named),
}
}
}
impl WindowsHotkey {
fn modifiers(&self) -> HotkeyModifiers {
HotkeyModifiers {
control: self.control,
option: self.alt,
shift: self.shift,
command: self.windows,
function: false,
}
}
pub fn validate(&self) -> Result<()> {
let modifier_count = self.modifiers().count();
let Some(key) = self.key.as_deref() else {
if modifier_count == 0 {
return Err(eyre!(
"Windows dictation shortcuts require a key or a modifier"
));
}
return Ok(());
};
if key.trim().is_empty() {
return Err(eyre!("Windows dictation shortcut key cannot be empty"));
}
crate::windows_input::virtual_key(key)?;
let function_key = key
.strip_prefix('f')
.or_else(|| key.strip_prefix('F'))
.and_then(|number| number.parse::<u8>().ok())
.is_some_and(|number| (1..=24).contains(&number));
if !function_key && HotkeyKey::mouse_number(key).is_none() && modifier_count == 0 {
return Err(eyre!(
"Windows dictation shortcuts require a modifier or a function key"
));
}
Ok(())
}
pub fn label(&self) -> String {
HotkeyBinding::from(self).keycaps().join("+")
}
/// Releasing Alt or Windows pressed alone opens the menu bar or Start,
/// so a modifier-only shortcut holding either masks its release.
fn masks_release(&self) -> bool {
self.key.is_none() && (self.alt.is_some() || self.windows.is_some())
}
}
/// `dwExtraInfo` on every event Hex injects, so its own hook skips them: a
/// paste's Ctrl must never press a Ctrl-alone shortcut.
pub(crate) const HEX_INJECTED: usize = 0x4845_5821;
/// Unassigned, so pressing it between an Alt or Windows press and release
/// keeps the menu bar and Start closed, as AutoHotkey and PowerToys do.
const MASK_KEY: u16 = 0xE8;
/// What the hook does with an event.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Disposition {
Pass,
Suppress,
/// Swallow this Alt or Windows release and replay it after the mask key.
Mask,
}
const EVENT_CAPACITY: usize = 16;
const MAX_EVENT_DELAY_MS: u32 = 60_000;
const DOUBLE_TAP_WINDOW_MS: u32 = 300;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HotkeyAction {
Start,
Finish,
Cancel,
PasteLast,
/// The Annotate key went down, and came up (`CaptureUp`).
Capture,
CaptureUp,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HotkeyEvent {
pub action: HotkeyAction,
/// Dictate without processing's shortcut owns the capture.
pub raw: bool,
timestamp_ms: u32,
}
impl HotkeyEvent {
pub fn occurred_at(self, captured_through: CaptureInstant) -> CaptureInstant {
self.occurred_at_with(unsafe { GetTickCount() }, captured_through)
}
fn occurred_at_with(
self,
observed_at_ms: u32,
captured_through: CaptureInstant,
) -> CaptureInstant {
let delay = observed_at_ms
.wrapping_sub(self.timestamp_ms)
.min(MAX_EVENT_DELAY_MS);
captured_through
.checked_sub(Duration::from_millis(u64::from(delay)))
.unwrap_or(CaptureInstant::ZERO)
}
}
struct CallbackState {
events: SyncSender<HotkeyEvent>,
errors: mpsc::Sender<String>,
binding: WindowsHotkey,
trigger_vk: Option<u32>,
paste_last: Option<WindowsHotkey>,
paste_trigger_vk: Option<u32>,
/// Dictate without processing, while it is bound.
raw: Option<WindowsHotkey>,
raw_trigger_vk: Option<u32>,
raw_trigger_down: bool,
annotate: Option<WindowsHotkey>,
annotate_trigger_vk: Option<u32>,
annotate_trigger_down: bool,
/// Escape went down to stop Annotate's drawing; its release is ours too.
drawing_escape_down: bool,
modifiers: ModifierState,
side_down: SideDownTimes,
trigger_down: bool,
paste_trigger_down: bool,
escape_down: bool,
double_tap_enabled: bool,
double_tap_only: bool,
/// Pass the dictation key on to other apps instead of consuming it.
share_trigger: bool,
capture: CaptureState,
dirty: bool,
/// A modifier-only shortcut with Alt or Windows was pressed with no
/// other key since, so its release would open the menu bar or Start.
mask_release: bool,
}
#[derive(Default)]
struct CaptureState {
active: bool,
locked: bool,
second_tap: bool,
recording: bool,
last_release_ms: Option<u32>,
/// Every press acts as the second tap of a double-tap: releasing it
/// locks the capture, and the next press finishes it.
toggle: bool,
/// The raw shortcut, not the dictation one, owns this capture (or the
/// last one).
raw: bool,
}
impl CaptureState {
/// Whether the other shortcut owns a capture in progress.
fn owned_by_other(&self, raw: bool) -> bool {
self.raw != raw && (self.active || self.locked)
}
/// Hands an idle capture to one shortcut; a tap of the other one never
/// counts toward its double tap.
fn claim(&mut self, raw: bool) {
if self.raw != raw && !self.active && !self.locked {
self.raw = raw;
self.last_release_ms = None;
}
}
fn press(
&mut self,
double_tap_enabled: bool,
double_tap_only: bool,
timestamp_ms: u32,
) -> Option<HotkeyAction> {
if self.locked {
self.locked = false;
self.recording = false;
self.last_release_ms = None;
return Some(HotkeyAction::Finish);
}
if self.active {
return None;
}
self.active = true;
let double_tapped = self
.last_release_ms
.take()
.is_some_and(|released| timestamp_ms.wrapping_sub(released) < DOUBLE_TAP_WINDOW_MS);
self.second_tap = self.toggle || (double_tap_enabled && double_tapped);
if double_tap_only && !self.second_tap {
// Double-tap-only: the first tap arms the window silently;
// recording waits for the second tap.
self.recording = false;
return None;
}
self.recording = true;
Some(HotkeyAction::Start)
}
fn release(&mut self, double_tap_enabled: bool, timestamp_ms: u32) -> Option<HotkeyAction> {
if !self.active {
return None;
}
self.active = false;
if self.second_tap {
self.second_tap = false;
self.locked = true;
self.last_release_ms = None;
return None;
}
self.last_release_ms = double_tap_enabled.then_some(timestamp_ms);
if !self.recording {
// Releasing an armed-but-silent first tap emits nothing.
return None;
}
self.recording = false;
Some(HotkeyAction::Finish)
}
/// Another key joined a held modifier-only shortcut: it was a chord
/// meant for another application. Only a recording capture reports
/// it, since a bare cancel also cancels the newest unfinished job.
fn interrupt(&mut self) -> Option<HotkeyAction> {
if !self.active {
return None;
}
let recording = self.recording;
self.active = false;
self.second_tap = false;
self.recording = false;
self.last_release_ms = None;
recording.then_some(HotkeyAction::Cancel)
}
fn cancel(&mut self) -> Option<HotkeyAction> {
if !self.active && !self.locked {
return None;
}
self.active = false;
self.locked = false;
self.second_tap = false;
self.recording = false;
self.last_release_ms = None;
Some(HotkeyAction::Cancel)
}
}
#[derive(Default)]
struct ModifierState {
left_control: bool,
right_control: bool,
left_windows: bool,
right_windows: bool,
left_alt: bool,
right_alt: bool,
left_shift: bool,
right_shift: bool,
}
static CALLBACK_STATE: Mutex<Option<CallbackState>> = Mutex::new(None);
/// While a settings-pane chord capture runs, the hook must neither act on
/// nor suppress anything: acting would fire real dictations/pastes from
/// the chord being recorded, and suppression would hide the current
/// binding's keys from `GetAsyncKeyState`, making it impossible to
/// re-record the same chord. macOS suspends its hotkey handling the same
/// way during capture.
static CAPTURE_INHIBIT: AtomicBool = AtomicBool::new(false);
/// Turns hook processing off (true) or back on (false) for the duration
/// of a chord capture. Entering a capture also cancels any in-flight
/// dictation hold, like the macOS capture flow.
pub(crate) fn set_capture_inhibited(inhibited: bool) {
CAPTURE_INHIBIT.store(inhibited, Ordering::Relaxed);
if !inhibited {
return;
}
let mut guard = CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner());
if let Some(state) = guard.as_mut() {
let now = unsafe { GetTickCount() };
state.trigger_down = false;
state.paste_trigger_down = false;
state.raw_trigger_down = false;
if let Some(action) = state.capture.cancel() {
send_event(state, action, now);
}
}
}
/// Whether this app owns the foreground window; chord capture only
/// listens while it does, so keystrokes typed into other applications
/// can never rebind a shortcut.
pub(crate) fn app_is_foreground() -> bool {
use windows_sys::Win32::System::Threading::GetCurrentProcessId;
use windows_sys::Win32::UI::WindowsAndMessaging::{
GetForegroundWindow, GetWindowThreadProcessId,
};
unsafe {
let foreground = GetForegroundWindow();
if foreground.is_null() {
return false;
}
let mut process_id = 0;
GetWindowThreadProcessId(foreground, &mut process_id);
process_id == GetCurrentProcessId()
}
}
pub struct WindowsHotkeyMonitor {
pub events: Receiver<HotkeyEvent>,
pub errors: Receiver<String>,
thread_id: u32,
worker: Option<JoinHandle<()>>,
}
impl WindowsHotkeyMonitor {
#[allow(clippy::too_many_arguments)]
pub fn start(
binding: WindowsHotkey,
paste_last: Option<WindowsHotkey>,
raw: Option<WindowsHotkey>,
annotate: Option<WindowsHotkey>,
double_tap_enabled: bool,
double_tap_only: bool,
shortcut_mode: ShortcutMode,
share_trigger: bool,
) -> Result<Self> {
binding.validate()?;
let trigger_vk = binding.key.as_deref().map(virtual_key).transpose()?;
let paste_trigger_vk = chord_virtual_key(paste_last.as_ref(), "Paste Last")?;
let raw_trigger_vk = chord_virtual_key(raw.as_ref(), "Dictate without processing")?;
let annotate_trigger_vk = chord_virtual_key(annotate.as_ref(), "Annotate")?;
let label = binding.label();
let (event_sender, events) = mpsc::sync_channel(EVENT_CAPACITY);
let (error_sender, errors) = mpsc::channel();
let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
let state = CallbackState {
events: event_sender,
errors: error_sender,
binding,
trigger_vk,
paste_last,
paste_trigger_vk,
raw,
raw_trigger_vk,
raw_trigger_down: false,
annotate,
annotate_trigger_vk,
annotate_trigger_down: false,
drawing_escape_down: false,
modifiers: ModifierState::default(),
side_down: SideDownTimes::default(),
trigger_down: false,
paste_trigger_down: false,
escape_down: false,
double_tap_enabled,
double_tap_only,
share_trigger,
capture: CaptureState {
toggle: shortcut_mode == ShortcutMode::Toggle,
..CaptureState::default()
},
dirty: false,
mask_release: false,
};
let worker = thread::Builder::new()
.name("windows-hotkey".into())
.spawn(move || run_hook(state, ready_sender))?;
let thread_id = ready_receiver
.recv_timeout(Duration::from_secs(2))
.map_err(|_| eyre!("timed out installing the Windows {label} keyboard hook"))?
.map_err(|error| eyre!(error))?;
Ok(Self {
events,
errors,
thread_id,
worker: Some(worker),
})
}
}
fn chord_virtual_key(binding: Option<&WindowsHotkey>, name: &str) -> Result<Option<u32>> {
binding
.map(|binding| {
binding.validate()?;
binding
.key
.as_deref()
.ok_or_else(|| eyre!("{name} requires a non-modifier key"))
.and_then(virtual_key)
})
.transpose()
}
impl Drop for WindowsHotkeyMonitor {
fn drop(&mut self) {
let posted = unsafe { PostThreadMessageW(self.thread_id, WM_QUIT, 0, 0) };
if posted == 0 {
tracing::warn!(
error = %std::io::Error::last_os_error(),
"could not stop Windows hotkey message loop"
);
}
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
fn run_hook(mut initial: CallbackState, ready: SyncSender<Result<u32, String>>) {
let thread_id = unsafe { GetCurrentThreadId() };
let mut message = MSG::default();
unsafe {
PeekMessageW(&mut message, ptr::null_mut(), 0, 0, PM_NOREMOVE);
}
let errors = initial.errors.clone();
initial.modifiers = ModifierState::current();
{
let mut state = CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner());
if state.is_some() {
let _ = ready.send(Err("the Windows keyboard hook is already active".into()));
return;
}
*state = Some(initial);
}
let hook =
unsafe { SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook), ptr::null_mut(), 0) };
if hook.is_null() {
CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner())
.take();
let _ = ready.send(Err(format!(
"could not install the Windows keyboard hook: {}",
std::io::Error::last_os_error()
)));
return;
}
let mouse = unsafe { SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook), ptr::null_mut(), 0) };
if mouse.is_null() {
let error = std::io::Error::last_os_error();
unsafe {
UnhookWindowsHookEx(hook);
}
CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner())
.take();
let _ = ready.send(Err(format!(
"could not install the Windows mouse hook: {error}"
)));
return;
}
if ready.send(Ok(thread_id)).is_err() {
unsafe {
UnhookWindowsHookEx(hook);
UnhookWindowsHookEx(mouse);
}
CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner())
.take();
return;
}
loop {
let status = unsafe { GetMessageW(&mut message, ptr::null_mut(), 0, 0) };
if status == 0 {
break;
}
if status == -1 {
let _ = errors.send(format!(
"Windows hotkey message loop failed: {}",
std::io::Error::last_os_error()
));
break;
}
}
unsafe {
UnhookWindowsHookEx(hook);
UnhookWindowsHookEx(mouse);
}
CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner())
.take();
}
unsafe extern "system" fn keyboard_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code != HC_ACTION as i32 {
return unsafe { CallNextHookEx(ptr::null_mut(), code, wparam, lparam) };
}
let is_down = matches!(wparam as u32, WM_KEYDOWN | WM_SYSKEYDOWN);
let is_up = matches!(wparam as u32, WM_KEYUP | WM_SYSKEYUP);
if !is_down && !is_up {
return unsafe { CallNextHookEx(ptr::null_mut(), code, wparam, lparam) };
}
let event = unsafe { &*(lparam as *const KBDLLHOOKSTRUCT) };
if event.dwExtraInfo == HEX_INJECTED {
return unsafe { CallNextHookEx(ptr::null_mut(), code, wparam, lparam) };
}
match process_button(event.vkCode, is_down, event.time) {
Disposition::Pass => unsafe { CallNextHookEx(ptr::null_mut(), code, wparam, lparam) },
Disposition::Suppress => 1,
Disposition::Mask if replay_masked_release(event) => 1,
// Windows refused the injection (an elevated foreground window):
// let the release through rather than leave the key held.
Disposition::Mask => unsafe { CallNextHookEx(ptr::null_mut(), code, wparam, lparam) },
}
}
/// Taps the mask key, then replays the swallowed release, so the system
/// sees a chord instead of Alt or Windows alone.
fn replay_masked_release(release: &KBDLLHOOKSTRUCT) -> bool {
let extended = if release.flags & LLKHF_EXTENDED != 0 {
KEYEVENTF_EXTENDEDKEY
} else {
0
};
let input = |vk: u16, scan: u16, flags: u32| INPUT {
r#type: INPUT_KEYBOARD,
Anonymous: INPUT_0 {
ki: KEYBDINPUT {
wVk: vk,
wScan: scan,
dwFlags: flags,
time: 0,
dwExtraInfo: HEX_INJECTED,
},
},
};
let inputs = [
input(MASK_KEY, 0, 0),
input(MASK_KEY, 0, KEYEVENTF_KEYUP),
input(
release.vkCode as u16,
release.scanCode as u16,
KEYEVENTF_KEYUP | extended,
),
];
let sent = unsafe {
SendInput(
inputs.len() as u32,
inputs.as_ptr(),
size_of::<INPUT>() as i32,
)
};
sent as usize == inputs.len()
}
fn mouse_message(message: u32, data: u32) -> Option<(u32, bool)> {
use windows_sys::Win32::UI::WindowsAndMessaging::{
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MBUTTONDOWN, WM_MBUTTONUP, WM_RBUTTONDOWN, WM_RBUTTONUP,
WM_XBUTTONDOWN, WM_XBUTTONUP,
};
let (button, down) = match message {
WM_LBUTTONDOWN => (0x01, true),
WM_LBUTTONUP => (0x01, false),
WM_RBUTTONDOWN => (0x02, true),
WM_RBUTTONUP => (0x02, false),
WM_MBUTTONDOWN => (0x04, true),
WM_MBUTTONUP => (0x04, false),
WM_XBUTTONDOWN | WM_XBUTTONUP => (
match data >> 16 {
1 => 0x05,
2 => 0x06,
_ => return None,
},
message == WM_XBUTTONDOWN,
),
_ => return None,
};
Some((button, down))
}
unsafe extern "system" fn mouse_hook(code: i32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
if code == HC_ACTION as i32 {
// SAFETY: Windows supplies a live MSLLHOOKSTRUCT for this callback.
let event = unsafe { &*(lparam as *const MSLLHOOKSTRUCT) };
if crate::capture_host::wants_input() {
report_pointer(wparam as u32, event);
}
if let Some((vk, down)) = mouse_message(wparam as u32, event.mouseData)
&& process_button(vk, down, event.time) != Disposition::Pass
{
return 1;
}
}
unsafe { CallNextHookEx(ptr::null_mut(), code, wparam, lparam) }
}
/// What a recording Annotate capture takes from the mouse hook: every move,
/// click, and wheel turn, in physical screen pixels as the engine's Windows
/// target frames are. The event still reaches the app beneath.
fn report_pointer(message: u32, event: &MSLLHOOKSTRUCT) {
use crate::capture_host::{Tapped, report_input};
use scrawl_capture::hosted_input::HostInput;
use windows_sys::Win32::UI::WindowsAndMessaging::{
LLMHF_INJECTED, WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEHWHEEL, WM_MOUSEMOVE, WM_MOUSEWHEEL,
WM_RBUTTONDOWN, WM_RBUTTONUP,
};
if event.flags & LLMHF_INJECTED != 0 {
return;
}
let (x, y) = (f64::from(event.pt.x), f64::from(event.pt.y));
let modifiers = held_modifiers();
// One notch is 120 in the high word, signed; up and right are positive.
let notches = f64::from((event.mouseData >> 16) as i16) / 120.0;
let input = match message {
WM_MOUSEMOVE => HostInput::Moved { x, y, modifiers },
WM_LBUTTONDOWN | WM_LBUTTONUP | WM_RBUTTONDOWN | WM_RBUTTONUP => HostInput::Button {
down: matches!(message, WM_LBUTTONDOWN | WM_RBUTTONDOWN),
right: matches!(message, WM_RBUTTONDOWN | WM_RBUTTONUP),
x,
y,
modifiers,
},
WM_MOUSEWHEEL => HostInput::Scroll {
x,
y,
dx: 0.0,
dy: notches,
},
WM_MOUSEHWHEEL => HostInput::Scroll {
x,
y,
dx: notches,
dy: 0.0,
},
_ => return,
};
report_input(CaptureInstant::now(), Tapped::Pointer(input));
}
/// A modifier changed while an Annotate capture records: Shift alone inks.
/// `held` includes the change, which the async key state does not yet.
fn report_modifiers(held: &ModifierState) {
use crate::capture_host::{Tapped, report_input};
use scrawl_capture::hosted_input::HostInput;
let mut point = windows_sys::Win32::Foundation::POINT { x: 0, y: 0 };
// SAFETY: `point` is a valid POINT to fill.
unsafe { windows_sys::Win32::UI::WindowsAndMessaging::GetCursorPos(&mut point) };
report_input(
CaptureInstant::now(),
Tapped::Pointer(HostInput::ModifiersChanged {
x: f64::from(point.x),
y: f64::from(point.y),
modifiers: scrawl_capture::hosted_input::Modifiers {
command: held.left_windows || held.right_windows,
control: held.left_control || held.right_control,
option: held.left_alt || held.right_alt,
shift: held.left_shift || held.right_shift,
},
}),
);
}
/// The modifiers held now, as the engine names them: the Windows key is its
/// Command, Alt its Option.
fn held_modifiers() -> scrawl_capture::hosted_input::Modifiers {
scrawl_capture::hosted_input::Modifiers {
command: key_down(VK_LWIN) || key_down(VK_RWIN),
control: key_down(VK_CONTROL),
option: key_down(VK_MENU),
shift: key_down(VK_SHIFT),
}
}
// Both low-level hooks feed exactly the same capture and suppression rules.
fn process_button(vk: u32, is_down: bool, time: u32) -> Disposition {
let is_up = !is_down;
let mut suppressed = false;
let mut mask = false;
{
let mut guard = CALLBACK_STATE
.lock()
.unwrap_or_else(|error| error.into_inner());
if let Some(state) = guard.as_mut() {
// The hook never sees a release that lands on another desktop,
// such as the Windows key of Win+L or the modifiers of
// Ctrl+Alt+Delete, so tracked modifiers stayed held after
// unlocking and Ctrl+Space no longer matched. Re-read them on
// every event: the asynchronous key state does not include this
// event yet, so `update` applies it on top.
state.modifiers = ModifierState::current();
let modifier_event = state.modifiers.update(vk, is_down);
state.side_down.update(vk, is_down, time);
// During a chord capture the hook only tracks modifier state;
// it neither triggers actions nor suppresses keys, so the
// capture can observe every key through GetAsyncKeyState.
if CAPTURE_INHIBIT.load(Ordering::Relaxed) {
state.mask_release = false;
return Disposition::Pass;
}
if !modifier_event && is_down {
state.mask_release = false;
}
if modifier_event && crate::capture_host::wants_input() {
report_modifiers(&state.modifiers);
}
let annotate_event = state.annotate_trigger_vk == Some(vk)
&& (state.annotate_trigger_down
|| (is_down
&& !state.capture.active
&& !state.capture.locked
&& !state.dirty
&& state
.annotate
.as_ref()
.is_some_and(|binding| state.modifiers.matches(binding))));
if annotate_event {
if is_down && !state.annotate_trigger_down {
state.annotate_trigger_down = true;
send_event(state, HotkeyAction::Capture, time);
} else if is_up && state.annotate_trigger_down {
state.annotate_trigger_down = false;
send_event(state, HotkeyAction::CaptureUp, time);
}
return Disposition::Suppress;
}
// Escape stops Annotate's drawing, never its recording, when no
// dictation takes it.
if vk == u32::from(VK_ESCAPE)
&& !state.capture.active
&& !state.capture.locked
&& (state.drawing_escape_down || (is_down && crate::capture_host::exit_drawing()))
{
state.drawing_escape_down = is_down;
return Disposition::Suppress;
}
// Dictate without processing: a key chord, held, locked, and
// finished like the dictation key, owning the capture it starts.
let raw_event = state.raw_trigger_vk == Some(vk)
&& (state.raw_trigger_down
|| (is_down
&& !state.dirty
&& !state.capture.owned_by_other(true)
&& state
.raw
.as_ref()
.is_some_and(|binding| state.modifiers.matches(binding))));
if raw_event {
if is_down && !state.raw_trigger_down {
state.raw_trigger_down = true;
state.capture.claim(true);
let was_locked = state.capture.locked;
if let Some(action) =
state
.capture
.press(state.double_tap_enabled, state.double_tap_only, time)
{
if was_locked {
state.dirty = true;
}
send_event(state, action, time);
}
} else if is_up && state.raw_trigger_down {
state.raw_trigger_down = false;
if let Some(action) = state.capture.release(state.double_tap_enabled, time) {
send_event(state, action, time);
}
if state.dirty
&& !state
.raw
.as_ref()
.is_some_and(|binding| state.modifiers.any_required_down(binding))
{
state.dirty = false;
}
}
return Disposition::Suppress;
}
let paste_event = state.paste_trigger_vk == Some(vk)
&& (state.paste_trigger_down
|| (is_down
&& !state.capture.active
&& !state.capture.locked
&& !state.dirty
&& state
.paste_last
.as_ref()
.is_some_and(|binding| state.modifiers.matches(binding))));
if paste_event {
suppressed = true;
if is_down && !state.paste_trigger_down {
state.paste_trigger_down = true;
send_event(state, HotkeyAction::PasteLast, time);
} else if is_up {
state.paste_trigger_down = false;
}
} else if state.trigger_vk == Some(vk) {
if is_down {
if state.trigger_down {
suppressed = !state.share_trigger;
} else if !state.dirty
&& !state.capture.owned_by_other(false)
&& state.modifiers.matches(&state.binding)
{
state.trigger_down = true;
suppressed = !state.share_trigger;
state.capture.claim(false);
let was_locked = state.capture.locked;
if let Some(action) = state.capture.press(
state.double_tap_enabled,
state.double_tap_only,
time,
) {
if was_locked {
state.dirty = true;
}
send_event(state, action, time);
}
}
} else if state.trigger_down {
state.trigger_down = false;
suppressed = !state.share_trigger;
if let Some(action) = state.capture.release(state.double_tap_enabled, time) {
send_event(state, action, time);
}
if state.dirty && !state.modifiers.any_required_down(&state.binding) {
state.dirty = false;
}
}
} else if vk == u32::from(VK_ESCAPE) {
if is_down && (state.capture.active || state.capture.locked) {
state.dirty = true;
state.escape_down = true;
suppressed = true;
if let Some(action) = state.capture.cancel() {
send_event(state, action, time);
}
} else if is_up && state.escape_down {
state.escape_down = false;
suppressed = true;
// Escape is not a modifier, so the modifier path never
// sees this release; without clearing here, the next
// Ctrl+Space after a cancel was ignored.
if !state.modifiers.any_required_down(&state.binding) {
state.dirty = false;
}
}
} else if !modifier_event {
// A key or button joining a held modifier-only shortcut makes
// a chord meant for another application, such as Alt+Tab.
if is_down
&& state.trigger_vk.is_none()
&& state.capture.active
&& !state.capture.raw
{
state.dirty = true;
if let Some(action) = state.capture.interrupt() {
send_event(state, action, time);
}
}
} else {
if is_up
&& state.mask_release
&& matches!(vk as u16, VK_LMENU | VK_RMENU | VK_MENU | VK_LWIN | VK_RWIN)
{
state.mask_release = false;
mask = !state.share_trigger;
}
if state.trigger_vk.is_none()
&& state.capture.locked
&& !state.capture.raw
&& !state.dirty
&& is_down
&& state.modifiers.matches(&state.binding)
&& state.side_down.together(&state.binding)
{
// Only a modifier-only shortcut finishes on a modifier
// press. A key chord such as Ctrl+Space finishes on its
// key, so resting a finger on Ctrl never ends a locked
// or toggled capture.
if let Some(action) =
state
.capture