forked from jtroo/kanata
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmacos.rs
More file actions
807 lines (737 loc) · 28.2 KB
/
macos.rs
File metadata and controls
807 lines (737 loc) · 28.2 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
//! Contains the input/output code for keyboards on Macos.
// Caused by unmaintained objc crate triggering warnings.
#![allow(unexpected_cfgs)]
#![cfg_attr(
feature = "simulated_output",
allow(dead_code, unused_imports, unused_variables, unused_mut)
)]
use super::*;
use crate::kanata::CalculatedMouseMove;
use crate::oskbd::KeyEvent;
use anyhow::anyhow;
use core_foundation::runloop::{CFRunLoop, kCFRunLoopCommonModes};
use core_graphics::base::CGFloat;
use core_graphics::display::{CGDisplay, CGPoint};
use core_graphics::event::{
CGEvent, CGEventTap, CGEventTapLocation, CGEventTapOptions, CGEventTapPlacement, CGEventType,
CGMouseButton, EventField,
};
use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
use kanata_parser::cfg::MappedKeys;
use kanata_parser::custom_action::*;
use kanata_parser::keys::*;
use karabiner_driverkit::*;
use objc::runtime::Class;
use objc::{msg_send, sel, sel_impl};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fmt;
use std::io;
use std::io::Error;
use std::sync::mpsc::SyncSender as Sender;
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy)]
pub struct InputEvent {
pub value: u64,
pub page: u32,
pub code: u32,
}
impl InputEvent {
pub fn new(event: DKEvent) -> Self {
InputEvent {
value: event.value,
page: event.page,
code: event.code,
}
}
}
impl From<InputEvent> for DKEvent {
fn from(event: InputEvent) -> Self {
Self {
value: event.value,
page: event.page,
code: event.code,
device_hash: 0,
}
}
}
pub struct KbdIn {
grabbed: bool,
}
impl Drop for KbdIn {
fn drop(&mut self) {
if self.grabbed {
release();
}
}
}
impl KbdIn {
pub fn new(
include_names: Option<Vec<String>>,
exclude_names: Option<Vec<String>>,
) -> Result<Self, anyhow::Error> {
if !driver_activated() {
return Err(anyhow!(
"Karabiner-VirtualHIDDevice driver is not activated."
));
}
// Based on the definition of include and exclude names, they should never be used together.
// Kanata config parser should probably enforce this.
let has_device_filter = include_names.is_some() || exclude_names.is_some();
let device_names = if let Some(included_names) = include_names {
validate_and_register_devices(included_names)
} else if let Some(excluded_names) = exclude_names {
// get all devices
let kb_list = fetch_devices();
// filter out excluded devices
let devices_to_include = kb_list
.iter()
.filter(|k| !excluded_names.iter().any(|n| *k == n.as_str()))
.map(|k| {
if k.product_key.trim().is_empty() {
format!("{:x}", k.hash)
} else {
k.product_key.clone()
}
})
.collect::<Vec<String>>();
// register the remeining devices
validate_and_register_devices(devices_to_include)
} else {
vec![]
};
// When an include/exclude list is configured but no devices matched,
// do NOT fall back to registering all devices. Only use the catch-all
// register_device("") when no device filter was specified at all.
if !device_names.is_empty() || (!has_device_filter && register_device("")) {
if grab() {
Ok(Self { grabbed: true })
} else {
Err(anyhow!("grab failed"))
}
} else {
Err(anyhow!(
"Couldn't register any device. Use 'kanata --list' to see available devices. \
Note: devices with empty names are automatically skipped to prevent crashes."
))
}
}
pub fn read(&mut self) -> Result<InputEvent, io::Error> {
let mut event = DKEvent {
value: 0,
page: 0,
code: 0,
device_hash: 0,
};
let got_event = wait_key(&mut event);
if got_event == 0 {
// Pipe returned EOF — input was released via release_input_only()
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
"input pipe closed (devices released)",
));
}
Ok(InputEvent::new(event))
}
/// Release seized input devices without tearing down the output connection.
/// After this call, `read()` will return `UnexpectedEof`.
pub fn release_input(&mut self) {
if self.grabbed {
release_input_only();
self.grabbed = false;
}
}
/// Re-seize input devices after a previous `release_input()`.
/// Returns true if at least one device was seized.
pub fn regrab_input(&mut self) -> bool {
if !self.grabbed {
let ok = karabiner_driverkit::regrab_input();
self.grabbed = ok;
ok
} else {
true
}
}
pub fn is_grabbed(&self) -> bool {
self.grabbed
}
}
fn validate_and_register_devices(include_names: Vec<String>) -> Vec<String> {
include_names
.iter()
.filter_map(|dev| {
// Defensive check: skip empty device names that could cause crashes
if dev.trim().is_empty() {
log::warn!("Skipping empty device name (likely old keyboard without proper identification)");
return None;
}
// Also skip the Karabiner device
// driverkit already prevents registering it, but this avoids unnecessary warnings
if dev.to_lowercase().contains("karabiner") {
return None;
}
match device_matches(dev) {
true => Some(dev.to_string()),
false => {
log::warn!("'{dev}' doesn't match any connected device");
None
}
}
})
.filter_map(|dev| {
if register_device(&dev) {
Some(dev.to_string())
} else {
log::warn!("Couldn't register device '{}' - device may be in use by another application or disconnected", dev);
None
}
})
.collect()
}
impl fmt::Display for InputEvent {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use kanata_keyberon::key_code::KeyCode;
let ke = KeyEvent::try_from(*self).unwrap();
let direction = match ke.value {
KeyValue::Press => "↓",
KeyValue::Release => "↑",
KeyValue::Repeat => "⟳",
KeyValue::Tap => "↕",
KeyValue::WakeUp => "!",
};
let key_name = KeyCode::from(ke.code);
write!(f, "{direction}{key_name:?}")
}
}
impl TryFrom<InputEvent> for KeyEvent {
type Error = ();
fn try_from(item: InputEvent) -> Result<Self, Self::Error> {
if let Ok(oscode) = OsCode::try_from(PageCode {
page: item.page,
code: item.code,
}) {
Ok(KeyEvent {
code: oscode,
value: if item.value == 1 {
KeyValue::Press
} else {
KeyValue::Release
},
})
} else {
Err(())
}
}
}
impl TryFrom<KeyEvent> for InputEvent {
type Error = ();
fn try_from(item: KeyEvent) -> Result<Self, Self::Error> {
if let Ok(pagecode) = PageCode::try_from(item.code) {
let val = match item.value {
KeyValue::Press | KeyValue::Repeat => 1,
_ => 0,
};
Ok(InputEvent {
value: val,
page: pagecode.page,
code: pagecode.code,
})
} else {
Err(())
}
}
}
#[cfg(all(not(feature = "simulated_output"), not(feature = "passthru_ahk")))]
pub struct KbdOut {
output_pressed_since: HashMap<OsCode, Instant>,
}
#[cfg(all(not(feature = "simulated_output"), not(feature = "passthru_ahk")))]
impl KbdOut {
pub fn new() -> Result<Self, io::Error> {
Ok(KbdOut {
output_pressed_since: HashMap::default(),
})
}
pub fn write(&mut self, event: InputEvent) -> Result<(), io::Error> {
let mut devent = event.into();
log::debug!("Attempting to write {event:?} {devent:?}");
let rc = send_key(&mut devent);
if rc == 2 {
return Err(io::Error::new(
io::ErrorKind::NotConnected,
"DriverKit virtual keyboard not ready (sink disconnected)",
));
}
Ok(())
}
pub fn output_ready(&self) -> bool {
is_sink_ready()
}
pub fn wait_until_ready(&self, timeout: Option<Duration>) -> bool {
let start = Instant::now();
let mut attempt = 0u32;
loop {
if self.output_ready() {
return true;
}
if let Some(timeout) = timeout
&& start.elapsed() >= timeout
{
return false;
}
attempt += 1;
if attempt % 10 == 0 {
if let Some(timeout) = timeout {
log::info!(
"Waiting for DriverKit virtual keyboard... ({:.1}s/{:.1}s)",
start.elapsed().as_secs_f64(),
timeout.as_secs_f64()
);
} else {
log::info!(
"Waiting for DriverKit virtual keyboard... ({:.1}s)",
start.elapsed().as_secs_f64()
);
}
}
std::thread::sleep(Duration::from_millis(100));
}
}
pub fn write_key(&mut self, key: OsCode, value: KeyValue) -> Result<(), io::Error> {
if let Ok(event) = InputEvent::try_from(KeyEvent { value, code: key }) {
let result = self.write(event);
if result.is_ok() {
self.record_output_transition_after_write(key, value);
}
result
} else {
log::debug!("couldn't write unrecognized {key:?}");
Err(io::Error::other("OsCode not recognized!"))
}
}
pub fn write_code(&mut self, code: u32, value: KeyValue) -> Result<(), io::Error> {
if let Ok(event) = InputEvent::try_from(KeyEvent {
value,
code: OsCode::from_u16(code as u16).unwrap(),
}) {
self.write(event)
} else {
log::debug!("couldn't write unrecognized OsCode {code}");
Err(io::Error::other("OsCode not recognized!"))
}
}
pub fn press_key(&mut self, key: OsCode) -> Result<(), io::Error> {
self.write_key(key, KeyValue::Press)
}
pub fn release_key(&mut self, key: OsCode) -> Result<(), io::Error> {
self.write_key(key, KeyValue::Release)
}
pub fn release_tracked_output_keys(&mut self, reason: &str) {
let tracked_keys: Vec<OsCode> = self.output_pressed_since.keys().copied().collect();
if tracked_keys.is_empty() {
return;
}
for key in tracked_keys {
if let Err(error) = self.write_key(key, KeyValue::Release) {
log::warn!(
"failed to release tracked output key during {} recovery: key={key:?} error={error}",
reason
);
}
}
self.output_pressed_since.clear();
}
pub fn send_unicode(&mut self, c: char) -> Result<(), io::Error> {
let event = Self::make_event()?;
let mut arr = [0u16; 2];
// Capture the slice containing the encoded UTF-16 code units.
let encoded = c.encode_utf16(&mut arr);
// Pass only the part of the array that was populated.
event.set_string_from_utf16_unchecked(encoded);
event.set_type(CGEventType::KeyDown);
event.post(CGEventTapLocation::AnnotatedSession);
event.set_type(CGEventType::KeyUp);
event.post(CGEventTapLocation::AnnotatedSession);
Ok(())
}
pub fn scroll(&mut self, _direction: MWheelDirection, _distance: u16) -> Result<(), io::Error> {
let event = Self::make_event()?;
event.set_type(CGEventType::ScrollWheel);
match _direction {
MWheelDirection::Down => event.set_integer_value_field(
EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_1,
_distance as i64,
),
MWheelDirection::Up => event.set_integer_value_field(
EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_1,
-(_distance as i64),
),
MWheelDirection::Left => event.set_integer_value_field(
EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_2,
_distance as i64,
),
MWheelDirection::Right => event.set_integer_value_field(
EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_2,
-(_distance as i64),
),
}
// Mouse control only seems to work with CGEventTapLocation::HID.
event.post(CGEventTapLocation::HID);
Ok(())
}
/// Synthesize a mouse button press or release via CGEvent.
///
/// Side buttons (Backward/Forward) use OtherMouseDown/Up with
/// CGMouseButton::Center as a placeholder, then override the
/// MOUSE_EVENT_BUTTON_NUMBER field to the real index (3=Back, 4=Forward).
/// The Rust CGMouseButton enum only has 3 variants but the underlying
/// Apple API supports up to 32 buttons via this field.
///
/// Ref: [init(mouseEventSource:mouseType:mouseCursorPosition:mouseButton:)][1], [setIntegerValueField][2]
///
/// [1]: https://developer.apple.com/documentation/coregraphics/cgevent/init(mouseeventsource:mousetype:mousecursorposition:mousebutton:)
/// [2]: https://developer.apple.com/documentation/coregraphics/cgevent/setintegervaluefield(_:value:)
fn button_action(&mut self, _btn: Btn, is_click: bool) -> Result<(), io::Error> {
// (event_type, placeholder_button, real_button_number_override)
let (event_type, button, button_number) = match _btn {
Btn::Left => (
if is_click {
CGEventType::LeftMouseDown
} else {
CGEventType::LeftMouseUp
},
CGMouseButton::Left,
None,
),
Btn::Right => (
if is_click {
CGEventType::RightMouseDown
} else {
CGEventType::RightMouseUp
},
CGMouseButton::Right,
None,
),
Btn::Mid => (
if is_click {
CGEventType::OtherMouseDown
} else {
CGEventType::OtherMouseUp
},
CGMouseButton::Center,
None,
),
// Side buttons use OtherMouseDown/Up (same event type as middle click)
// with the button number overridden after event creation.
Btn::Backward => (
if is_click {
CGEventType::OtherMouseDown
} else {
CGEventType::OtherMouseUp
},
CGMouseButton::Center,
Some(3), // USB HID button 4 -> CGEvent button 3 (0-indexed)
),
Btn::Forward => (
if is_click {
CGEventType::OtherMouseDown
} else {
CGEventType::OtherMouseUp
},
CGMouseButton::Center,
Some(4), // USB HID button 5 -> CGEvent button 4 (0-indexed)
),
};
let event_source = Self::make_event_source()?;
let event = Self::make_event()?;
let mouse_position = event.location();
let event = CGEvent::new_mouse_event(event_source, event_type, mouse_position, button)
.map_err(|_| std::io::Error::other("Failed to create mouse event"))?;
if let Some(num) = button_number {
event.set_integer_value_field(EventField::MOUSE_EVENT_BUTTON_NUMBER, num);
}
// Mouse control only seems to work with CGEventTapLocation::HID.
event.post(CGEventTapLocation::HID);
Ok(())
}
pub fn click_btn(&mut self, _btn: Btn) -> Result<(), io::Error> {
Self::button_action(self, _btn, true)
}
pub fn release_btn(&mut self, _btn: Btn) -> Result<(), io::Error> {
Self::button_action(self, _btn, false)
}
pub fn move_mouse(&mut self, _mv: CalculatedMouseMove) -> Result<(), io::Error> {
let pressed = Self::pressed_buttons();
let event_type = if pressed & 1 > 0 {
CGEventType::LeftMouseDragged
} else if pressed & 2 > 0 {
CGEventType::RightMouseDragged
} else {
CGEventType::MouseMoved
};
let event = Self::make_event()?;
let mut mouse_position = event.location();
Self::apply_calculated_move(&_mv, &mut mouse_position);
if let Ok(event) = CGEvent::new_mouse_event(
Self::make_event_source()?,
event_type,
mouse_position,
CGMouseButton::Left,
) {
event.post(CGEventTapLocation::HID);
}
Ok(())
}
fn pressed_buttons() -> usize {
if let Some(ns_event) = Class::get("NSEvent") {
unsafe { msg_send![ns_event, pressedMouseButtons] }
} else {
0
}
}
pub fn move_mouse_many(&mut self, _moves: &[CalculatedMouseMove]) -> Result<(), io::Error> {
let event = Self::make_event()?;
let mut mouse_position = event.location();
let display = CGDisplay::main();
for current_move in _moves.iter() {
Self::apply_calculated_move(current_move, &mut mouse_position);
}
display
.move_cursor_to_point(mouse_position)
.map_err(|_| io::Error::other("failed to move mouse"))?;
Ok(())
}
pub fn set_mouse(&mut self, _x: u16, _y: u16) -> Result<(), io::Error> {
let display = CGDisplay::main();
let point = CGPoint::new(_x as CGFloat, _y as CGFloat);
display
.move_cursor_to_point(point)
.map_err(|_| io::Error::other("failed to move cursor to point"))?;
Ok(())
}
fn make_event_source() -> Result<CGEventSource, Error> {
CGEventSource::new(CGEventSourceStateID::CombinedSessionState)
.map_err(|_| Error::other("failed to create core graphics event source"))
}
/// Creates a core graphics event.
/// The CGEventSourceStateID is a guess at this point - all functionality works using this but
/// I have not verified that this is the correct parameter.
/// Note that the CFRelease function mentioned in the docs is automatically called when the
/// event is dropped, therefore we don't need to care about this ourselves.
fn make_event() -> Result<CGEvent, Error> {
let event_source = Self::make_event_source()?;
let event = CGEvent::new(event_source)
.map_err(|_| Error::other("failed to create core graphics event"))?;
Ok(event)
}
fn record_output_transition_after_write(&mut self, key: OsCode, value: KeyValue) {
match value {
KeyValue::Press | KeyValue::Repeat => {
self.output_pressed_since
.entry(key)
.or_insert_with(Instant::now);
}
KeyValue::Release => {
self.output_pressed_since.remove(&key);
}
KeyValue::Tap | KeyValue::WakeUp => {}
}
}
/// Applies a calculated mouse move to a CGPoint.
///
/// This does _not_ move the mouse, it just mutates the point.
fn apply_calculated_move(_mv: &CalculatedMouseMove, mouse_position: &mut CGPoint) {
match _mv.direction {
MoveDirection::Up => mouse_position.y -= _mv.distance as CGFloat,
MoveDirection::Down => mouse_position.y += _mv.distance as CGFloat,
MoveDirection::Left => mouse_position.x -= _mv.distance as CGFloat,
MoveDirection::Right => mouse_position.x += _mv.distance as CGFloat,
}
}
}
/// Convert a `(CGEventType, button_number)` pair from a CGEventTap into a
/// kanata `KeyEvent`. The button number field is only meaningful for
/// `OtherMouseDown`/`OtherMouseUp` (2=Middle, 3=Back, 4=Forward); Left/Right
/// are determined entirely by the event type.
impl TryFrom<(CGEventType, i64)> for KeyEvent {
type Error = ();
fn try_from((event_type, button_number): (CGEventType, i64)) -> Result<Self, ()> {
use OsCode::*;
let (code, value) = match event_type {
CGEventType::LeftMouseDown => (BTN_LEFT, KeyValue::Press),
CGEventType::LeftMouseUp => (BTN_LEFT, KeyValue::Release),
CGEventType::RightMouseDown => (BTN_RIGHT, KeyValue::Press),
CGEventType::RightMouseUp => (BTN_RIGHT, KeyValue::Release),
CGEventType::OtherMouseDown | CGEventType::OtherMouseUp => {
let code = match button_number {
2 => BTN_MIDDLE,
3 => BTN_SIDE,
4 => BTN_EXTRA,
_ => return Err(()),
};
let value = if matches!(event_type, CGEventType::OtherMouseDown) {
KeyValue::Press
} else {
KeyValue::Release
};
(code, value)
}
_ => return Err(()),
};
Ok(KeyEvent { code, value })
}
}
/// Decode a `ScrollWheel` `CGEvent` into a kanata `KeyEvent`. A scroll event
/// may carry both axes simultaneously (diagonal scroll on a trackpad); we
/// pick the dominant axis with vertical winning ties, matching how Linux
/// processes one `REL_WHEEL`/`REL_HWHEEL` at a time. The axis/sign convention
/// mirrors `OsKbdOut::scroll`.
fn scroll_event_to_key_event(event: &CGEvent) -> Option<KeyEvent> {
use OsCode::*;
let dy = event.get_integer_value_field(EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_1);
let dx = event.get_integer_value_field(EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_2);
let code = if dy.abs() >= dx.abs() {
match dy.signum() {
1 => MouseWheelDown,
-1 => MouseWheelUp,
_ => return None,
}
} else {
match dx.signum() {
1 => MouseWheelLeft,
-1 => MouseWheelRight,
_ => return None,
}
};
Some(KeyEvent {
code,
value: KeyValue::Tap,
})
}
/// Start a CGEventTap on a background thread to intercept mouse button events.
/// macOS equivalent of the Windows mouse hook in `windows/llhook.rs`.
///
/// Mapped buttons are suppressed and forwarded to the processing channel;
/// unmapped buttons pass through. Only installed if the config has mouse
/// buttons in defsrc.
///
/// Requires Accessibility or Input Monitoring permission.
pub fn start_mouse_listener(
tx: Sender<KeyEvent>,
mapped_keys: &MappedKeys,
) -> Option<std::thread::JoinHandle<()>> {
use OsCode::*;
let mouse_oscodes = [
BTN_LEFT,
BTN_RIGHT,
BTN_MIDDLE,
BTN_SIDE,
BTN_EXTRA,
MouseWheelUp,
MouseWheelDown,
MouseWheelLeft,
MouseWheelRight,
];
// Copy only the mouse-relevant mapped keys for the callback closure.
let mapped: MappedKeys = mapped_keys
.iter()
.copied()
.filter(|k| mouse_oscodes.contains(k))
.collect();
if mapped.is_empty() {
log::info!("No mouse buttons or wheel in defsrc. Not installing mouse event tap.");
return None;
}
let handle = std::thread::Builder::new()
.name("mouse-event-tap".into())
.spawn(move || {
let events_of_interest = vec![
CGEventType::LeftMouseDown,
CGEventType::LeftMouseUp,
CGEventType::RightMouseDown,
CGEventType::RightMouseUp,
CGEventType::OtherMouseDown,
CGEventType::OtherMouseUp,
CGEventType::ScrollWheel,
];
let tap = match CGEventTap::new(
CGEventTapLocation::HID,
CGEventTapPlacement::HeadInsertEventTap,
CGEventTapOptions::Default,
events_of_interest,
// Callback receives &CGEvent; return Some(clone) to pass through,
// None to suppress the event.
move |_proxy, event_type, event| {
if matches!(event_type, CGEventType::ScrollWheel) {
let Some(key_event) = scroll_event_to_key_event(event) else {
return Some(event.clone());
};
if !mapped.contains(&key_event.code) {
return Some(event.clone());
}
log::debug!("mouse tap (wheel): {key_event:?}");
if let Err(e) = tx.try_send(key_event) {
log::warn!("mouse tap: failed to send wheel event: {e}");
return Some(event.clone());
}
return None;
}
let button_number =
event.get_integer_value_field(EventField::MOUSE_EVENT_BUTTON_NUMBER);
let mut key_event = match KeyEvent::try_from((event_type, button_number)) {
Ok(ev) => ev,
Err(()) => return Some(event.clone()),
};
if !mapped.contains(&key_event.code) {
return Some(event.clone());
}
// Track pressed state to convert duplicate presses into repeats,
// matching the keyboard event loop behavior.
match key_event.value {
KeyValue::Release => {
crate::kanata::PRESSED_KEYS.lock().remove(&key_event.code);
}
KeyValue::Press => {
let mut pressed_keys = crate::kanata::PRESSED_KEYS.lock();
if pressed_keys.contains(&key_event.code) {
key_event.value = KeyValue::Repeat;
} else {
pressed_keys.insert(key_event.code);
}
}
_ => {}
}
log::debug!("mouse tap: {key_event:?}");
if let Err(e) = tx.try_send(key_event) {
log::warn!("mouse tap: failed to send event: {e}");
return Some(event.clone());
}
// Suppress the original event so it doesn't reach the system.
None
},
) {
Ok(tap) => tap,
Err(()) => {
log::error!(
"Failed to create mouse event tap. \
Ensure kanata has Accessibility or Input Monitoring permission \
in System Settings > Privacy & Security."
);
return;
}
};
let loop_source = tap
.mach_port
.create_runloop_source(0)
.expect("failed to create CFRunLoop source for mouse event tap");
// Safety: kCFRunLoopCommonModes is an extern static from CoreFoundation.
// Accessing it requires unsafe but is always valid in a running process.
let mode = unsafe { kCFRunLoopCommonModes };
CFRunLoop::get_current().add_source(&loop_source, mode);
tap.enable();
log::info!("Mouse event tap installed and active.");
CFRunLoop::run_current();
})
.expect("failed to spawn mouse event tap thread");
Some(handle)
}