Repository navigation
Expand file tree
/
Copy pathsuppression.rs
More file actions
6120 lines (5813 loc) · 225 KB
/
Copy pathsuppression.rs
File metadata and controls
6120 lines (5813 loc) · 225 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::collections::{HashMap, HashSet, VecDeque};
use std::ffi::c_void;
use std::ptr;
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver, Sender, SyncSender};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::Duration;
use color_eyre::eyre::{Result, eyre};
#[cfg(test)]
use crate::app_settings::HotkeyBinding;
use crate::app_settings::{HOTKEY_MODIFIERS_MASK, RuntimeHotkey, RuntimeHotkeys};
use crate::audio::CaptureInstant;
use crate::dictation::{BOTH_SIDES_WINDOW, MINIMUM_HOLD_DURATION};
const DOUBLE_TAP_WINDOW: Duration = MINIMUM_HOLD_DURATION;
const ESCAPE_KEY_CODE: u16 = 53;
/// The key code the Globe (Fn) key reports in its own key events.
const GLOBE_KEY_CODE: u16 = 179;
const EVENT_LEFT_MOUSE_DOWN: u32 = 1;
const EVENT_LEFT_MOUSE_UP: u32 = 2;
const EVENT_RIGHT_MOUSE_DOWN: u32 = 3;
const EVENT_RIGHT_MOUSE_UP: u32 = 4;
const EVENT_KEY_DOWN: u32 = 10;
const EVENT_KEY_UP: u32 = 11;
const EVENT_FLAGS_CHANGED: u32 = 12;
const EVENT_OTHER_MOUSE_DOWN: u32 = 25;
const EVENT_OTHER_MOUSE_UP: u32 = 26;
const EVENT_LEFT_MOUSE_DRAGGED: u32 = 6;
const EVENT_RIGHT_MOUSE_DRAGGED: u32 = 7;
const EVENT_OTHER_MOUSE_DRAGGED: u32 = 27;
const MOUSE_EVENT_BUTTON_NUMBER: u32 = 3;
#[cfg(hex_capture)]
const EVENT_MOUSE_MOVED: u32 = 5;
#[cfg(hex_capture)]
const EVENT_SCROLL_WHEEL: u32 = 22;
#[cfg(hex_capture)]
const KEYBOARD_EVENT_AUTOREPEAT: u32 = 8;
#[cfg(hex_capture)]
const SCROLL_WHEEL_DELTA_AXIS_1: u32 = 11;
#[cfg(hex_capture)]
const SCROLL_WHEEL_DELTA_AXIS_2: u32 = 12;
const EVENT_TAP_DISABLED_BY_TIMEOUT: u32 = u32::MAX - 1;
const EVENT_TAP_DISABLED_BY_USER_INPUT: u32 = u32::MAX;
const KEYBOARD_EVENT_KEYCODE: u32 = 9;
const EVENT_SOURCE_USER_DATA: u32 = 42;
// Assistive keyboards inject downstream of HID; observe them alongside hardware input.
const ANNOTATED_SESSION_EVENT_TAP: u32 = 2;
// Another app's global shortcut (Carbon hotkeys such as a window manager's
// Option-1) consumes its key before the session, so only HID sees that press.
const HID_EVENT_TAP: u32 = 0;
const HEAD_INSERT_EVENT_TAP: u32 = 0;
const DEFAULT_EVENT_TAP: u32 = 0;
const LISTEN_ONLY_EVENT_TAP: u32 = 1;
const HID_SYSTEM_STATE: u32 = 1;
const COMBINED_SESSION_STATE: u32 = 0;
const STALE_KEY_NEUTRAL_DURATION: Duration = Duration::from_millis(100);
const PHYSICAL_KEY_DOWN_HISTORY: usize = 8;
type EventRef = *mut c_void;
type EventTapCallback = unsafe extern "C" fn(
proxy: *mut c_void,
event_type: u32,
event: EventRef,
user_info: *mut c_void,
) -> EventRef;
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
fn CGEventSourceFlagsState(state_id: u32) -> u64;
fn CGEventSourceKeyState(state_id: u32, key: u16) -> bool;
fn CGEventSourceButtonState(state_id: u32, button: u32) -> bool;
fn CGEventTapCreate(
tap: u32,
place: u32,
options: u32,
events_of_interest: u64,
callback: EventTapCallback,
user_info: *mut c_void,
) -> *mut c_void;
fn CGEventTapEnable(tap: *mut c_void, enable: bool);
fn CGEventTapIsEnabled(tap: *mut c_void) -> bool;
fn CGEventGetFlags(event: EventRef) -> u64;
fn CGEventGetTimestamp(event: EventRef) -> u64;
fn CGEventGetIntegerValueField(event: EventRef, field: u32) -> i64;
#[cfg(hex_capture)]
fn CGEventGetLocation(event: EventRef) -> CgPoint;
#[cfg(hex_capture)]
fn CGEventKeyboardGetUnicodeString(
event: EventRef,
max_length: usize,
actual_length: *mut usize,
buffer: *mut u16,
);
}
#[cfg(hex_capture)]
#[repr(C)]
#[derive(Clone, Copy)]
struct CgPoint {
x: f64,
y: f64,
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFMachPortCreateRunLoopSource(
allocator: *const c_void,
port: *mut c_void,
order: isize,
) -> *mut c_void;
fn CFRunLoopAddSource(run_loop: *mut c_void, source: *mut c_void, mode: *const c_void);
fn CFRunLoopRemoveSource(run_loop: *mut c_void, source: *mut c_void, mode: *const c_void);
fn CFRunLoopGetCurrent() -> *mut c_void;
fn CFRunLoopRun();
fn CFRunLoopStop(run_loop: *mut c_void);
fn CFRunLoopTimerCreate(
allocator: *const c_void,
fire_date: f64,
interval: f64,
flags: usize,
order: isize,
callout: unsafe extern "C" fn(timer: *mut c_void, info: *mut c_void),
context: *mut RunLoopTimerContext,
) -> *mut c_void;
fn CFRunLoopAddTimer(run_loop: *mut c_void, timer: *mut c_void, mode: *const c_void);
fn CFRunLoopTimerInvalidate(timer: *mut c_void);
fn CFAbsoluteTimeGetCurrent() -> f64;
fn CFMachPortIsValid(port: *mut c_void) -> u8;
fn CFRelease(value: *const c_void);
static kCFRunLoopCommonModes: *const c_void;
}
#[repr(C)]
struct RunLoopTimerContext {
version: isize,
info: *mut c_void,
retain: *const c_void,
release: *const c_void,
copy_description: *const c_void,
}
#[derive(Clone, Copy, Debug)]
pub enum InputEvent {
Flags(u64),
Key {
code: u16,
down: bool,
flags: u64,
},
/// A key press seen at the HID level. It only signals a chord: the session
/// `Key` events, when they arrive, remain the source of key state.
PhysicalKeyDown {
code: u16,
timing: HidTiming,
},
MouseDown,
TapDisabled,
}
/// How a HID-tap timestamp was read, kept only for diagnostics.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct HidTiming {
pub raw: u64,
pub clock: HidClock,
/// When the tap callback ran.
pub received_at: CaptureInstant,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum HidClock {
MachTicks,
Nanos,
/// Neither reading was recent, so the event took its arrival time.
Arrival,
}
impl HidClock {
fn as_str(self) -> &'static str {
match self {
Self::MachTicks => "mach",
Self::Nanos => "nanos",
Self::Arrival => "arrival",
}
}
}
/// What ended a press as a chord before it became a dictation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DiscardCause {
Key,
HidKey,
Mouse,
ExtraModifier,
}
impl DiscardCause {
pub fn as_str(self) -> &'static str {
match self {
Self::Key => "key",
Self::HidKey => "hid-key",
Self::Mouse => "mouse",
Self::ExtraModifier => "extra-modifier",
}
}
}
impl InputEvent {
pub fn is_escape_down(self) -> bool {
matches!(
self,
Self::Key {
code: ESCAPE_KEY_CODE,
down: true,
..
}
)
}
}
#[derive(Clone, Copy, Debug)]
pub struct ObservedInputEvent {
sequence: u64,
pub event: InputEvent,
pub capture_at: CaptureInstant,
}
#[derive(Clone, Default)]
pub struct PendingInputEvents(Arc<Mutex<VecDeque<(u64, CaptureInstant)>>>);
impl PendingInputEvents {
#[cfg(test)]
pub fn with_pending_for_test(at: CaptureInstant) -> (Self, impl FnOnce()) {
let pending = Self::default();
pending.push(0, at);
let acknowledge = pending.clone();
(pending, move || acknowledge.acknowledge(0))
}
pub fn oldest(&self) -> Option<CaptureInstant> {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.front()
.map(|(_, at)| *at)
}
fn push(&self, sequence: u64, at: CaptureInstant) {
self.0
.lock()
.unwrap_or_else(|error| error.into_inner())
.push_back((sequence, at));
}
fn acknowledge(&self, sequence: u64) {
let mut pending = self.0.lock().unwrap_or_else(|error| error.into_inner());
if pending.front().is_some_and(|(next, _)| *next == sequence) {
pending.pop_front();
}
}
}
pub struct InputMonitor {
pub events: Receiver<ObservedInputEvent>,
pub activity: InputActivity,
pending: PendingInputEvents,
escape_cancels: Arc<AtomicBool>,
run_loop: Arc<AtomicPtr<c_void>>,
worker: Option<JoinHandle<()>>,
}
pub struct PendingInputAcknowledgement<'a> {
pending: &'a PendingInputEvents,
sequence: u64,
}
impl Drop for PendingInputAcknowledgement<'_> {
fn drop(&mut self) {
self.pending.acknowledge(self.sequence);
}
}
#[derive(Clone, Default)]
pub struct InputActivity(Arc<AtomicU64>);
impl InputActivity {
pub fn revision(&self) -> u64 {
self.0.load(Ordering::Acquire)
}
pub fn invalidate(&self) {
self.0.fetch_add(1, Ordering::AcqRel);
}
fn observe(&self, input: InputEvent, suppressed: bool) {
if !suppressed
&& matches!(
input,
InputEvent::Key { down: true, .. } | InputEvent::MouseDown
)
{
self.invalidate();
}
}
}
impl InputMonitor {
pub fn start() -> Result<Self> {
let (sender, events) = mpsc::channel::<ObservedInputEvent>();
let (ready_sender, ready_receiver) = mpsc::sync_channel(1);
let activity = InputActivity::default();
let tap_activity = activity.clone();
let run_loop = Arc::new(AtomicPtr::new(ptr::null_mut()));
let tap_run_loop = run_loop.clone();
let escape_cancels = Arc::new(AtomicBool::new(false));
let tap_escape_cancels = escape_cancels.clone();
let pending = PendingInputEvents::default();
let tap_pending = pending.clone();
let worker = thread::spawn(move || {
run_event_tap(
sender,
tap_activity,
tap_escape_cancels,
tap_pending,
tap_run_loop,
ready_sender,
)
});
ready_receiver
.recv_timeout(Duration::from_secs(2))
.map_err(|_| eyre!("timed out starting the keyboard event tap"))??;
Ok(Self {
events,
activity,
pending,
escape_cancels,
run_loop,
worker: Some(worker),
})
}
pub fn set_escape_cancels(&self, enabled: bool) {
self.escape_cancels.store(enabled, Ordering::Release);
}
pub fn pending_events(&self) -> PendingInputEvents {
self.pending.clone()
}
pub fn acknowledge_after(&self, event: ObservedInputEvent) -> PendingInputAcknowledgement<'_> {
PendingInputAcknowledgement {
pending: &self.pending,
sequence: event.sequence,
}
}
}
impl Drop for InputMonitor {
fn drop(&mut self) {
let run_loop = self.run_loop.load(Ordering::Acquire);
if !run_loop.is_null() {
// SAFETY: Core Foundation run loops may be stopped from any thread.
unsafe { CFRunLoopStop(run_loop) };
}
if let Some(worker) = self.worker.take() {
let _ = worker.join();
}
}
}
struct EventTapContext {
sender: Sender<ObservedInputEvent>,
activity: InputActivity,
escape_cancels: Arc<AtomicBool>,
key_tap: AtomicPtr<c_void>,
observation_tap: AtomicPtr<c_void>,
physical_tap: AtomicPtr<c_void>,
shortcut_suppression: Mutex<ShortcutSuppression>,
pending: PendingInputEvents,
next_sequence: AtomicU64,
}
struct AttachedTap {
tap: *mut c_void,
source: *mut c_void,
run_loop: *mut c_void,
}
impl AttachedTap {
/// # Safety
/// `context` and `run_loop` must outlive the returned `AttachedTap`.
unsafe fn create(
location: u32,
options: u32,
mask: u64,
callback: EventTapCallback,
context: *mut EventTapContext,
run_loop: *mut c_void,
slot: &AtomicPtr<c_void>,
) -> Result<Self, &'static str> {
let tap = unsafe {
CGEventTapCreate(
location,
HEAD_INSERT_EVENT_TAP,
options,
mask,
callback,
context.cast(),
)
};
if tap.is_null() {
return Err("could not create event tap");
}
let source = unsafe { CFMachPortCreateRunLoopSource(ptr::null(), tap, 0) };
if source.is_null() {
unsafe { CFRelease(tap.cast_const()) };
return Err("could not create input run-loop sources");
}
slot.store(tap, Ordering::Release);
unsafe {
CFRunLoopAddSource(run_loop, source, kCFRunLoopCommonModes);
CGEventTapEnable(tap, true);
}
Ok(Self {
tap,
source,
run_loop,
})
}
}
impl Drop for AttachedTap {
fn drop(&mut self) {
unsafe {
CGEventTapEnable(self.tap, false);
CFRunLoopRemoveSource(self.run_loop, self.source, kCFRunLoopCommonModes);
CFRelease(self.source.cast_const());
CFRelease(self.tap.cast_const());
}
}
}
const KEY_MASK: u64 = (1_u64 << EVENT_KEY_DOWN)
| (1_u64 << EVENT_KEY_UP)
| (1_u64 << EVENT_LEFT_MOUSE_DOWN)
| (1_u64 << EVENT_LEFT_MOUSE_UP)
| (1_u64 << EVENT_RIGHT_MOUSE_DOWN)
| (1_u64 << EVENT_RIGHT_MOUSE_UP)
| (1_u64 << EVENT_OTHER_MOUSE_DOWN)
| (1_u64 << EVENT_OTHER_MOUSE_UP)
| (1_u64 << EVENT_LEFT_MOUSE_DRAGGED)
| (1_u64 << EVENT_RIGHT_MOUSE_DRAGGED)
| (1_u64 << EVENT_OTHER_MOUSE_DRAGGED);
const OBSERVATION_MASK: u64 = 1_u64 << EVENT_FLAGS_CHANGED;
/// Translate only configured mouse triggers into the shared shortcut reducer.
/// Ordinary clicks retain their cancellation/activity semantics.
fn mouse_input(button: u16, down: bool, flags: u64, hotkeys: RuntimeHotkeys) -> Option<InputEvent> {
let code = crate::app_settings::HotkeyKey::mouse_code(button)?;
let bound = [
Some(hotkeys.dictation),
hotkeys.raw_dictation,
hotkeys.second_dictation,
hotkeys.paste_last,
hotkeys.paste_meeting,
]
.iter()
.flatten()
.any(|binding| binding.key_code == Some(code));
if bound {
Some(InputEvent::Key { code, down, flags })
} else {
down.then_some(InputEvent::MouseDown)
}
}
fn input_is_down(state: u32, code: u16) -> bool {
// SAFETY: both functions are read-only CoreGraphics state queries; mouse
// codes are decoded before crossing the native keyboard API boundary.
unsafe {
match crate::app_settings::HotkeyKey::mouse_button(code) {
Some(button) => CGEventSourceButtonState(state, u32::from(button)),
None => CGEventSourceKeyState(state, code),
}
}
}
/// What the observation tap adds in builds with captures, while the
/// `capture` experiment is on: the pointer moving and scrolling. Clicks and
/// drags already reach the key tap, for mouse shortcuts. The callback drops
/// them at once unless a capture records (`capture_host::wants_input`); they
/// never reach the listener.
#[cfg(hex_capture)]
const CAPTURE_POINTER_MASK: u64 = (1_u64 << EVENT_MOUSE_MOVED) | (1_u64 << EVENT_SCROLL_WHEEL);
fn observation_mask() -> u64 {
#[cfg(hex_capture)]
return OBSERVATION_MASK | CAPTURE_POINTER_MASK;
#[cfg(not(hex_capture))]
OBSERVATION_MASK
}
fn run_event_tap(
sender: Sender<ObservedInputEvent>,
activity: InputActivity,
escape_cancels: Arc<AtomicBool>,
pending: PendingInputEvents,
run_loop: Arc<AtomicPtr<c_void>>,
ready: SyncSender<Result<()>>,
) {
let mut context = Box::new(EventTapContext {
sender,
activity,
escape_cancels,
key_tap: AtomicPtr::new(ptr::null_mut()),
observation_tap: AtomicPtr::new(ptr::null_mut()),
physical_tap: AtomicPtr::new(ptr::null_mut()),
shortcut_suppression: Mutex::new(ShortcutSuppression::default()),
pending,
next_sequence: AtomicU64::new(0),
});
let context_ptr = &raw mut *context;
// SAFETY: This is the dedicated event-tap thread's current run loop.
let current_run_loop = unsafe { CFRunLoopGetCurrent() };
let mut taps = Box::new(TapSet {
context: context_ptr,
run_loop: current_run_loop,
taps: TapKind::ALL.map(|kind| ManagedTap {
kind,
attached: None,
failing: false,
}),
});
for tap in &mut taps.taps {
// SAFETY: `context` outlives `taps`, which is declared after it.
if let Err(message) = unsafe { tap.attach(context_ptr, current_run_loop) } {
match tap.kind {
TapKind::Key => {
let _ = ready.send(Err(eyre!(
"could not create keyboard event tap; grant Accessibility permission"
)));
return;
}
TapKind::Observation => {
let _ = ready.send(Err(eyre!(message)));
return;
}
TapKind::Physical => {
tap.failing = true;
tracing::warn!(
"could not observe HID key presses; global-shortcut chords cannot cancel"
);
}
}
}
}
// SAFETY: `taps` outlives the timer, which is declared after it and
// invalidated on drop, and both live on this run loop's thread.
let _health = unsafe { HealthTimer::start(&raw mut *taps, current_run_loop) };
let _app_nap = AppNapOptOut::begin();
run_loop.store(current_run_loop, Ordering::Release);
let _ = ready.send(Ok(()));
// SAFETY: This dedicated thread exists solely to dispatch the event tap.
unsafe { CFRunLoopRun() };
run_loop.store(ptr::null_mut(), Ordering::Release);
}
/// How often the tap thread confirms its taps still run. macOS can disable
/// or invalidate a tap without delivering a disable event (after sleep,
/// secure input, or an Accessibility change), which leaves the shortcut dead.
const TAP_HEALTH_INTERVAL_SECONDS: f64 = 5.0;
#[derive(Clone, Copy, Debug)]
enum TapKind {
Key,
Observation,
Physical,
}
impl TapKind {
const ALL: [Self; 3] = [Self::Key, Self::Observation, Self::Physical];
fn as_str(self) -> &'static str {
match self {
Self::Key => "key",
Self::Observation => "modifier",
Self::Physical => "hid",
}
}
fn slot(self, context: &EventTapContext) -> &AtomicPtr<c_void> {
match self {
Self::Key => &context.key_tap,
Self::Observation => &context.observation_tap,
Self::Physical => &context.physical_tap,
}
}
/// The key and modifier taps carry shortcut state; a gap in them makes
/// the input history untrustworthy. The HID tap only adds chord evidence.
fn tracks_shortcuts(self) -> bool {
!matches!(self, Self::Physical)
}
}
struct ManagedTap {
kind: TapKind,
attached: Option<AttachedTap>,
/// Creation failed and was logged; log again only once it recovers.
failing: bool,
}
impl ManagedTap {
/// # Safety
/// `context` and `run_loop` must outlive the attached tap.
unsafe fn attach(
&mut self,
context: *mut EventTapContext,
run_loop: *mut c_void,
) -> Result<(), &'static str> {
// SAFETY: the caller keeps `context` alive; the slot lives in it.
let slot = self.kind.slot(unsafe { &*context });
let (location, options, mask, callback): (u32, u32, u64, EventTapCallback) = match self.kind
{
TapKind::Key => (
ANNOTATED_SESSION_EVENT_TAP,
DEFAULT_EVENT_TAP,
KEY_MASK,
event_callback,
),
// A modifying tap disrupts Finder's Option-driven alternate menu items even
// when it returns flagsChanged events unchanged. Observe modifiers with a
// passive tap; bound mouse clicks use the filtering tap.
TapKind::Observation => (
ANNOTATED_SESSION_EVENT_TAP,
LISTEN_ONLY_EVENT_TAP,
observation_mask(),
event_callback,
),
// Listens for key presses at the HID level, where shortcuts that other apps
// register globally are still visible. Without it those chords are invisible
// to the session taps; dictation still works.
TapKind::Physical => (
HID_EVENT_TAP,
LISTEN_ONLY_EVENT_TAP,
1_u64 << EVENT_KEY_DOWN,
physical_event_callback,
),
};
// SAFETY: forwarded from the caller.
let attached = unsafe {
AttachedTap::create(location, options, mask, callback, context, run_loop, slot)
}?;
self.attached = Some(attached);
Ok(())
}
}
/// The taps on the event-tap thread, checked by its health timer.
struct TapSet {
context: *mut EventTapContext,
run_loop: *mut c_void,
taps: [ManagedTap; 3],
}
impl TapSet {
/// Re-enables a disabled tap and recreates an invalidated or missing one.
fn check(&mut self) {
// SAFETY: `context` outlives this set (see `run_event_tap`).
let context = unsafe { &*self.context };
let mut interrupted = false;
for tap in &mut self.taps {
let kind = tap.kind.as_str();
let recreate = match &tap.attached {
None => true,
// SAFETY: `tap.tap` is a live CFMachPort owned by `AttachedTap`.
Some(attached) if unsafe { CFMachPortIsValid(attached.tap) } == 0 => {
tracing::warn!(tap = kind, "event tap was invalidated; recreating it");
true
}
// SAFETY: as above.
Some(attached) if !unsafe { CGEventTapIsEnabled(attached.tap) } => {
// SAFETY: as above.
unsafe { CGEventTapEnable(attached.tap, true) };
// SAFETY: as above.
let enabled = unsafe { CGEventTapIsEnabled(attached.tap) };
tracing::warn!(
tap = kind,
reenabled = enabled,
"event tap was disabled without notice; re-enabled it"
);
interrupted |= tap.kind.tracks_shortcuts();
!enabled
}
Some(_) => false,
};
if !recreate {
continue;
}
tap.kind
.slot(context)
.store(ptr::null_mut(), Ordering::Release);
let was_attached = tap.attached.take().is_some();
// SAFETY: `context` and the run loop outlive this set.
match unsafe { tap.attach(self.context, self.run_loop) } {
Ok(()) => {
if was_attached || tap.failing {
tracing::warn!(tap = kind, "recreated event tap");
}
tap.failing = false;
interrupted |= was_attached && tap.kind.tracks_shortcuts();
}
Err(message) => {
if !tap.failing {
tracing::error!(
tap = kind,
error = message,
"could not recreate event tap"
);
}
tap.failing = true;
interrupted |= was_attached && tap.kind.tracks_shortcuts();
}
}
}
if interrupted {
send_input(context, InputEvent::TapDisabled, CaptureInstant::ZERO);
}
}
}
/// The repeating run-loop timer that runs `TapSet::check`.
struct HealthTimer(*mut c_void);
impl HealthTimer {
/// # Safety
/// `taps` must outlive the returned timer, and `run_loop` must be the
/// current thread's run loop.
unsafe fn start(taps: *mut TapSet, run_loop: *mut c_void) -> Option<Self> {
let mut context = RunLoopTimerContext {
version: 0,
info: taps.cast(),
retain: ptr::null(),
release: ptr::null(),
copy_description: ptr::null(),
};
// SAFETY: CoreFoundation copies the context; `info` outlives the timer.
let timer = unsafe {
CFRunLoopTimerCreate(
ptr::null(),
CFAbsoluteTimeGetCurrent() + TAP_HEALTH_INTERVAL_SECONDS,
TAP_HEALTH_INTERVAL_SECONDS,
0,
0,
check_tap_health,
&raw mut context,
)
};
if timer.is_null() {
tracing::warn!("could not schedule event tap health checks");
return None;
}
// SAFETY: `timer` is a valid CFRunLoopTimer for this thread's run loop.
unsafe { CFRunLoopAddTimer(run_loop, timer, kCFRunLoopCommonModes) };
Some(Self(timer))
}
}
impl Drop for HealthTimer {
fn drop(&mut self) {
// SAFETY: the timer was created by `HealthTimer::start` and is owned here.
unsafe {
CFRunLoopTimerInvalidate(self.0);
CFRelease(self.0.cast_const());
}
}
}
unsafe extern "C" fn check_tap_health(_timer: *mut c_void, info: *mut c_void) {
// SAFETY: `info` is the `TapSet` that outlives this timer, used only on
// the event-tap thread, so no other reference is live during the call.
unsafe { &mut *info.cast::<TapSet>() }.check();
}
/// Keeps App Nap from throttling the event-tap thread while Hex sits idle in
/// the background: a napped callback can miss its deadline, and its health
/// timer would stretch. Idle system sleep stays allowed.
struct AppNapOptOut(
objc2::rc::Retained<objc2::runtime::ProtocolObject<dyn objc2::runtime::NSObjectProtocol>>,
);
impl AppNapOptOut {
fn begin() -> Self {
use objc2_foundation::{NSActivityOptions, NSProcessInfo, NSString};
let activity = NSProcessInfo::processInfo().beginActivityWithOptions_reason(
NSActivityOptions::UserInitiatedAllowingIdleSystemSleep,
&NSString::from_str("Hex listens for its dictation shortcut"),
);
Self(activity)
}
}
impl Drop for AppNapOptOut {
fn drop(&mut self) {
// SAFETY: the activity came from `beginActivityWithOptions:reason:`.
unsafe { objc2_foundation::NSProcessInfo::processInfo().endActivity(&self.0) };
}
}
/// Re-enables every tap after macOS disables one and records why.
fn reenable_disabled_taps(context: &EventTapContext, event_type: u32, tap: &'static str) {
let reason = if event_type == EVENT_TAP_DISABLED_BY_TIMEOUT {
"timeout"
} else {
"user input"
};
for kind in TapKind::ALL {
let tap = kind.slot(context).load(Ordering::Acquire);
if !tap.is_null() {
// SAFETY: `tap` is a CFMachPort returned by `CGEventTapCreate`.
unsafe { CGEventTapEnable(tap, true) };
}
}
tracing::warn!(tap, reason, "macOS disabled the event tap; re-enabled it");
}
unsafe extern "C" fn physical_event_callback(
_proxy: *mut c_void,
event_type: u32,
event: EventRef,
user_info: *mut c_void,
) -> EventRef {
if user_info.is_null() {
return event;
}
// SAFETY: `user_info` points to the context allocated by `run_event_tap`.
let context = unsafe { &*(user_info.cast::<EventTapContext>()) };
if matches!(
event_type,
EVENT_TAP_DISABLED_BY_TIMEOUT | EVENT_TAP_DISABLED_BY_USER_INPUT
) {
// Missing evidence only lets a chord count as a hold, so just resume.
reenable_disabled_taps(context, event_type, TapKind::Physical.as_str());
return event;
}
if event.is_null()
|| event_type != EVENT_KEY_DOWN
|| crate::app_settings::hotkey_capture_active()
// SAFETY: CoreGraphics supplied a valid event to this callback.
|| unsafe { CGEventGetIntegerValueField(event, EVENT_SOURCE_USER_DATA) }
== crate::keyboard::SYNTHETIC_EVENT_MARKER
{
return event;
}
// SAFETY: CoreGraphics supplied a valid keyboard event.
let code = unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) as u16 };
// SAFETY: CoreGraphics supplied a valid event.
let flags = unsafe { CGEventGetFlags(event) };
if !is_chord_evidence(code, flags, crate::app_settings::runtime_hotkeys()) {
return event;
}
// SAFETY: CoreGraphics supplied a valid event.
let raw = unsafe { CGEventGetTimestamp(event) };
let received_at = CaptureInstant::now();
let (at, clock) = physical_event_instant(raw, received_at);
send_input(
context,
InputEvent::PhysicalKeyDown {
code,
timing: HidTiming {
raw,
clock,
received_at,
},
},
at,
);
event
}
/// Whether a HID key press can reveal a chord Hex would otherwise miss.
/// Escape and Hex's own shortcuts already act through their session events.
fn is_chord_evidence(code: u16, flags: u64, hotkeys: RuntimeHotkeys) -> bool {
code != ESCAPE_KEY_CODE
&& !is_own_globe_key(code, hotkeys.dictation)
&& !hotkeys
.second_dictation
.is_some_and(|second| is_own_globe_key(code, second))
&& !hotkeys
.all()
.iter()
.flatten()
.any(|hotkey| hotkey.matches_key_press(code, flags))
}
/// The Globe key's own key event, which some keyboards and remappers
/// (Karabiner-Elements) send beside the Fn modifier change. For a binding
/// that holds Fn, it is the shortcut itself, never a chord.
fn is_own_globe_key(code: u16, binding: RuntimeHotkey) -> bool {
code == GLOBE_KEY_CODE && binding.modifiers.function && binding.key_code != Some(code)
}
/// HID-tap timestamps arrive as Mach ticks on Apple Silicon and as
/// nanoseconds on some events; keep whichever reading is recent, else `now`.
fn physical_event_instant(raw: u64, now: CaptureInstant) -> (CaptureInstant, HidClock) {
const RECENT: Duration = Duration::from_secs(5);
[
(CaptureInstant::from_mach_ticks(raw), HidClock::MachTicks),
(CaptureInstant::from_nanos(raw), HidClock::Nanos),
]
.into_iter()
.find(|(at, _)| {
now.checked_duration_since(*at)
.is_some_and(|age| age <= RECENT)
})
.unwrap_or((now, HidClock::Arrival))
}
/// Signed milliseconds from `from` to `to`.
fn signed_ms(to: CaptureInstant, from: CaptureInstant) -> f64 {
(i128::from(to.as_nanos()) - i128::from(from.as_nanos())) as f64 / 1e6
}
unsafe extern "C" fn event_callback(
_proxy: *mut c_void,
event_type: u32,
event: EventRef,
user_info: *mut c_void,
) -> EventRef {
if user_info.is_null() {
return event;
}
// SAFETY: `user_info` points to the context allocated by `run_event_tap`.
let context = unsafe { &*(user_info.cast::<EventTapContext>()) };
if matches!(
event_type,
EVENT_TAP_DISABLED_BY_TIMEOUT | EVENT_TAP_DISABLED_BY_USER_INPUT
) {
// The key and modifier taps share this callback.
reenable_disabled_taps(context, event_type, "session");
send_input(context, InputEvent::TapDisabled, CaptureInstant::ZERO);
return event;
}
if event.is_null() {
return event;
}
// SAFETY: CoreGraphics supplied a valid event to this callback.
if unsafe { CGEventGetIntegerValueField(event, EVENT_SOURCE_USER_DATA) }
== crate::keyboard::SYNTHETIC_EVENT_MARKER
{
// The chord breaker has already passed the HID and session taps and
// global monitors that watch for modifier taps; the focused app would
// only beep at it.
let chord_breaker = matches!(event_type, EVENT_KEY_DOWN | EVENT_KEY_UP)
// SAFETY: CoreGraphics supplied a valid keyboard event.
&& unsafe { CGEventGetIntegerValueField(event, KEYBOARD_EVENT_KEYCODE) }
== i64::from(crate::keyboard::CHORD_BREAKER_KEY_CODE);
return if chord_breaker {
ptr::null_mut()
} else {
event
};
}
#[cfg(hex_capture)]
let list_swallows = match list_tap(event_type, event) {
ListSwallow::No => false,
ListSwallow::Only => return ptr::null_mut(),
ListSwallow::AfterListener => true,
};
#[cfg(not(hex_capture))]
let list_swallows = false;
#[cfg(hex_capture)]
let capture_key = if crate::capture_host::wants_input() {
match report_capture_input(event_type, event) {
CaptureTap::Only => return event,
CaptureTap::Shared => None,
CaptureTap::Key(key) => Some(key),
}
} else {
None
};
// A press anywhere while the list or suggestions are open may fold it; the click still
// goes to the app and to the listener as chord evidence.
#[cfg(hex_capture)]
if matches!(
event_type,
EVENT_LEFT_MOUSE_DOWN | EVENT_RIGHT_MOUSE_DOWN | EVENT_OTHER_MOUSE_DOWN
) && (crate::capture_host::list_open() || crate::capture_host::suggesting())
{
crate::capture_host::capsule_key(crate::capture_host::CapsuleKey::Press);
}
if matches!(
event_type,
EVENT_LEFT_MOUSE_DRAGGED | EVENT_RIGHT_MOUSE_DRAGGED | EVENT_OTHER_MOUSE_DRAGGED
) {
// A swallowed press must not leak a drag into the foreground app.