openlogi-hook 0.6.26

OS-level mouse-event hook for OpenLogi. macOS via CGEventTap; Linux via evdev+uinput; Windows via WH_MOUSE_LL.
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
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
//! macOS `CGEventTap` implementation of the OS-level mouse hook.

use std::cell::RefCell;
use std::collections::HashMap;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use core_foundation::base::{CFTypeRef, TCFType as _};
use core_foundation::number::CFNumber;
use core_foundation::runloop::{
    CFRunLoop, CFRunLoopRunResult, kCFRunLoopCommonModes, kCFRunLoopDefaultMode,
};
use core_foundation::string::{CFString, CFStringRef};
use core_graphics::event::{
    CGEvent, CGEventField, CGEventFlags, CGEventTap, CGEventTapLocation, CGEventTapOptions,
    CGEventTapPlacement, CGEventTapProxy, CGEventType, CallbackResult, EventField,
};
use foreign_types_shared::ForeignType as _;
use tracing::{debug, error, warn};

use crate::{
    ButtonId, EventDevice, EventDisposition, EventTapInfo, HookError, HookEvent, KeyEvent,
    KeyModifiers, MouseEvent, TapLocation,
};

/// Everything `Hook` needs to control the background thread.
pub(crate) struct HookInner {
    thread: thread::JoinHandle<()>,
    run_loop: CFRunLoop,
    /// Termination flag, re-checked at the top of every run-loop slice.
    /// `run_loop.stop()` only interrupts the loop while it is *inside* a
    /// `run_in_mode` slice; a stop landing in the gap between slices is
    /// dropped, so this flag — not the CF stop alone — is the reliable
    /// shutdown signal that guarantees the thread can never hang forever.
    stop: Arc<AtomicBool>,
}

// SAFETY: CFRunLoop is a Core Foundation ref-counted object. The CF
// documentation states that CFRunLoop objects can be passed between
// threads; only CFRunLoopRun must be called on the owning thread.
unsafe impl Send for HookInner {}

// Raw FFI for `AXIsProcessTrustedWithOptions` from the Accessibility
// framework. Passing `NULL` queries trust state without prompting; passing
// a dictionary with `kAXTrustedCheckOptionPrompt = true` raises the system
// permission dialog and registers the process in the Accessibility list.
#[link(name = "ApplicationServices", kind = "framework")]
unsafe extern "C" {
    fn AXIsProcessTrustedWithOptions(options: *const std::ffi::c_void) -> bool;
    static kAXTrustedCheckOptionPrompt: core_foundation::string::CFStringRef;
}

/// Opaque `IOHIDEventRef` — the HID event backing a `CGEvent`.
type IOHIDEventRef = *mut std::ffi::c_void;

// Device-of-origin lookup. `CGEventCopyIOHIDEvent` (CoreGraphics) returns the
// HID event behind a CGEvent; `IOHIDEventGetSenderID` (IOKit) yields the
// registry id of the producing service. These are undocumented but long-stable
// symbols (Mac Mouse Fix / Karabiner use them) — the only reliable way to tell a
// hi-res mouse wheel from a trackpad, which carry identical CGEvent phase flags.
#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    fn CGEventCopyIOHIDEvent(event: *const std::ffi::c_void) -> IOHIDEventRef;
}
#[link(name = "IOKit", kind = "framework")]
unsafe extern "C" {
    fn IOHIDEventGetSenderID(event: IOHIDEventRef) -> u64;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
    fn CFRelease(cf: *const std::ffi::c_void);
}

/// The registry id of the device that produced `event`, via its backing
/// IOHIDEvent. `None` for events with no HID backing (e.g. synthetic ones).
fn event_sender_id(event: &CGEvent) -> Option<u64> {
    // SAFETY: `event.as_ptr()` is the live CGEventRef; `CGEventCopyIOHIDEvent`
    // returns a +1-retained IOHIDEvent (or null) which we release below.
    let hid = unsafe { CGEventCopyIOHIDEvent(event.as_ptr().cast()) };
    if hid.is_null() {
        return None;
    }
    // SAFETY: `hid` is a live IOHIDEvent for the duration of the call.
    let sender = unsafe { IOHIDEventGetSenderID(hid) };
    // SAFETY: balance the +1 retain from `CGEventCopyIOHIDEvent`.
    unsafe { CFRelease(hid) };
    Some(sender)
}

/// IOKit registry walk to read a device's HID usage page. `IORegistryEntryIDMatching`
/// builds a matching dict for the service id; `IOServiceGetMatchingService` resolves
/// it (and releases the dict); `IORegistryEntrySearchCFProperty` reads a property,
/// searching parents so the usage page on the owning `IOHIDDevice` is found.
type IoObjectT = u32;
#[link(name = "IOKit", kind = "framework")]
unsafe extern "C" {
    fn IORegistryEntryIDMatching(entry_id: u64) -> *mut std::ffi::c_void;
    fn IOServiceGetMatchingService(main_port: u32, matching: *const std::ffi::c_void) -> IoObjectT;
    fn IORegistryEntrySearchCFProperty(
        entry: IoObjectT,
        plane: *const std::ffi::c_char,
        key: CFStringRef,
        allocator: CFTypeRef,
        options: u32,
    ) -> CFTypeRef;
    fn IOObjectRelease(object: IoObjectT) -> i32;
}

const IO_REGISTRY_ITERATE_RECURSIVELY: u32 = 1;
const IO_REGISTRY_ITERATE_PARENTS: u32 = 2;

/// Resolve `sender_id` to its IO service, or `None`. Caller must
/// `IOObjectRelease` the result.
fn open_service(sender_id: u64) -> Option<IoObjectT> {
    // SAFETY: returns a +1 matching dict; `IOServiceGetMatchingService` consumes it.
    let matching = unsafe { IORegistryEntryIDMatching(sender_id) };
    if matching.is_null() {
        return None;
    }
    // SAFETY: `matching` is a valid +1 dict (consumed here); 0 = default main port.
    let service = unsafe { IOServiceGetMatchingService(0, matching) };
    (service != 0).then_some(service)
}

/// Read property `key` off `service` (searching parents), as a `+1` CFTypeRef the
/// caller owns. `None` if absent.
fn service_property(service: IoObjectT, key: &str) -> Option<CFTypeRef> {
    let cf_key = CFString::new(key);
    let plane = c"IOService";
    // SAFETY: `service` is live; `cf_key` is a valid CFStringRef; null allocator is
    // the documented default; returns a +1 CF value (or null).
    let prop = unsafe {
        IORegistryEntrySearchCFProperty(
            service,
            plane.as_ptr(),
            cf_key.as_concrete_TypeRef(),
            std::ptr::null(),
            IO_REGISTRY_ITERATE_RECURSIVELY | IO_REGISTRY_ITERATE_PARENTS,
        )
    };
    (!prop.is_null()).then_some(prop)
}

/// Cached device facts derived from the IOKit sender id behind a scroll event.
#[derive(Clone, Default)]
struct SenderDeviceInfo {
    event_device: EventDevice,
    is_trackpad: bool,
}

/// Device facts for the registry id `sender_id`. A trackpad presents a *mouse*
/// HID interface for scrolling, so usage can't separate it from a real wheel;
/// product identity stays stable across wheel modes, unlike CGEvent phase.
/// Cached per id because the registry walk is slow and identity never changes.
fn sender_device_info(sender_id: u64) -> SenderDeviceInfo {
    thread_local! {
        static CACHE: RefCell<HashMap<u64, SenderDeviceInfo>> = RefCell::new(HashMap::new());
    }
    CACHE.with_borrow_mut(|cache| {
        cache
            .entry(sender_id)
            .or_insert_with(|| {
                let Some(service) = open_service(sender_id) else {
                    return SenderDeviceInfo::default();
                };
                let string_prop = |k| {
                    // SAFETY: a String property is a +1 CFString; wrap takes ownership.
                    service_property(service, k)
                        .map(|p| unsafe { CFString::wrap_under_create_rule(p.cast()) }.to_string())
                };
                let num_prop = |k| {
                    // SAFETY: a numeric property is a +1 CFNumber; wrap takes ownership.
                    service_property(service, k)
                        .and_then(|p| {
                            unsafe { CFNumber::wrap_under_create_rule(p.cast()) }.to_i64()
                        })
                        .and_then(|n| u32::try_from(n).ok())
                };
                // SAFETY: a String property is a +1 CFString; wrap takes ownership.
                let product_name = string_prop("Product");
                let info = SenderDeviceInfo {
                    is_trackpad: product_name
                        .as_deref()
                        .is_some_and(|p| p.to_lowercase().contains("trackpad")),
                    event_device: EventDevice {
                        vendor_id: num_prop("VendorID").or_else(|| num_prop("idVendor")),
                        product_id: num_prop("ProductID").or_else(|| num_prop("idProduct")),
                        product_name,
                    },
                };
                // SAFETY: `service` is a live io_object_t we own.
                unsafe { IOObjectRelease(service) };
                info
            })
            .clone()
    })
}

/// Check whether this process has been granted Accessibility access.
pub(crate) fn has_accessibility() -> bool {
    // SAFETY: NULL is documented as a valid argument; it queries the current
    // trust state without raising a permission dialog.
    unsafe { AXIsProcessTrustedWithOptions(std::ptr::null()) }
}

/// Raise the Accessibility prompt + register the process. See
/// [`super::Hook::prompt_accessibility`].
pub(crate) fn prompt_accessibility() {
    use core_foundation::base::TCFType as _;
    use core_foundation::boolean::CFBoolean;
    use core_foundation::dictionary::CFDictionary;
    use core_foundation::string::CFString;

    // SAFETY: `kAXTrustedCheckOptionPrompt` is a framework-provided
    // `CFStringRef` constant; wrapping under the get rule borrows it
    // without taking ownership.
    let key = unsafe { CFString::wrap_under_get_rule(kAXTrustedCheckOptionPrompt) };
    let options =
        CFDictionary::from_CFType_pairs(&[(key.as_CFType(), CFBoolean::true_value().as_CFType())]);
    // SAFETY: `options` is a valid `CFDictionaryRef` for the lifetime of
    // the call; the function reads it and (if untrusted) shows the dialog.
    // The returned trust state is observed separately via the watcher.
    let _trusted = unsafe { AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef().cast()) };
}

/// Read the frontmost application's bundle identifier via `NSWorkspace`.
/// Returns `None` when no app is frontmost or the identifier is missing.
///
/// `NSWorkspace` is `AnyThread`, so this is sound on the watcher thread. The
/// reads return owned `Retained` values (no leak by construction), but the
/// framework still autoreleases internal temporaries and `to_str` borrows its
/// UTF-8 view from the pool — so an explicit `autoreleasepool` is required off
/// the main thread, where no run loop drains one. (Without it the old raw path
/// leaked the workspace/app/bundle-id objects: hundreds of MB across a workday.)
pub(crate) fn frontmost_bundle_id() -> Option<String> {
    use objc2::rc::autoreleasepool;
    use objc2_app_kit::NSWorkspace;

    autoreleasepool(|pool| {
        let app = NSWorkspace::sharedWorkspace().frontmostApplication()?;
        let bundle_id = app.bundleIdentifier()?;
        // SAFETY: `to_str` yields a UTF-8 view valid for `pool`'s lifetime; we
        // copy it into an owned `String` before the pool (and `bundle_id`) drop,
        // so the borrow never escapes.
        Some(unsafe { bundle_id.to_str(pool) }.to_owned())
    })
}

/// Translate a raw OS button number to a [`ButtonId`].
///
/// Logi's convention: button 0 = left, 1 = right, 2 = middle, 3 = back,
/// 4 = forward. Numbers ≥5 don't map to a `ButtonId` we track.
fn button_number_to_id(n: i64) -> Option<ButtonId> {
    match n {
        0 => Some(ButtonId::LeftClick),
        1 => Some(ButtonId::RightClick),
        2 => Some(ButtonId::MiddleClick),
        3 => Some(ButtonId::Back),
        4 => Some(ButtonId::Forward),
        _ => None,
    }
}

/// Best-effort device identity for a button event's HID sender.
fn button_source(event: &CGEvent) -> Option<crate::EventDevice> {
    event_sender_id(event).map(|id| sender_device_info(id).event_device)
}

/// Map the macOS modifier flags on a `CGEvent` to our [`KeyModifiers`].
/// `SecondaryFn` is deliberately ignored: it is firmware-internal and
/// unreliable as a trigger (function-key-remapper spec, Appendix A).
fn modifiers_from_flags(flags: CGEventFlags) -> KeyModifiers {
    KeyModifiers {
        shift: flags.contains(CGEventFlags::CGEventFlagShift),
        control: flags.contains(CGEventFlags::CGEventFlagControl),
        option: flags.contains(CGEventFlags::CGEventFlagAlternate),
        command: flags.contains(CGEventFlags::CGEventFlagCommand),
    }
}

/// Translate a keyboard `CGEvent` into a [`KeyEvent`]. Returns `None` for
/// non-key event types (the mouse path handles those) and for `FlagsChanged`
/// (modifier state rides on the next key event via its flags; a standalone
/// flags change carries no key of interest to the remapper).
fn translate_key(etype: CGEventType, event: &CGEvent) -> Option<KeyEvent> {
    let pressed = match etype {
        CGEventType::KeyDown => true,
        CGEventType::KeyUp => false,
        // FlagsChanged: no key to remap here.
        _ => return None,
    };
    let keycode = event.get_integer_value_field(EventField::KEYBOARD_EVENT_KEYCODE);
    let keycode = u16::try_from(keycode).ok()?;
    Some(KeyEvent {
        keycode,
        pressed,
        modifiers: modifiers_from_flags(event.get_flags()),
    })
}

/// Convert a `CGEvent` to our [`MouseEvent`] vocabulary. Returns `None`
/// for event types we don't translate (e.g. move events, unknown buttons).
fn translate(etype: CGEventType, event: &CGEvent) -> Option<MouseEvent> {
    // Skip events OpenLogi itself synthesised, so a remapped click or inverted
    // scroll we posted doesn't re-enter the hook as real input. Gate the field
    // read to events we synthesize — keeping the FFI call off the high-rate
    // pointer-move stream.
    let can_be_synthetic = matches!(
        etype,
        CGEventType::LeftMouseDown
            | CGEventType::LeftMouseUp
            | CGEventType::RightMouseDown
            | CGEventType::RightMouseUp
            | CGEventType::OtherMouseDown
            | CGEventType::OtherMouseUp
            | CGEventType::ScrollWheel
    );
    if can_be_synthetic
        && event.get_integer_value_field(EventField::EVENT_SOURCE_USER_DATA)
            == openlogi_inject::SYNTHETIC_EVENT_USER_DATA
    {
        return None;
    }
    match etype {
        CGEventType::LeftMouseDown => Some(MouseEvent::Button {
            id: ButtonId::LeftClick,
            pressed: true,
            device: button_source(event),
        }),
        CGEventType::LeftMouseUp => Some(MouseEvent::Button {
            id: ButtonId::LeftClick,
            pressed: false,
            device: button_source(event),
        }),
        CGEventType::RightMouseDown => Some(MouseEvent::Button {
            id: ButtonId::RightClick,
            pressed: true,
            device: button_source(event),
        }),
        CGEventType::RightMouseUp => Some(MouseEvent::Button {
            id: ButtonId::RightClick,
            pressed: false,
            device: button_source(event),
        }),
        CGEventType::OtherMouseDown => {
            let n = event.get_integer_value_field(EventField::MOUSE_EVENT_BUTTON_NUMBER);
            button_number_to_id(n).map(|id| MouseEvent::Button {
                id,
                pressed: true,
                device: button_source(event),
            })
        }
        CGEventType::OtherMouseUp => {
            let n = event.get_integer_value_field(EventField::MOUSE_EVENT_BUTTON_NUMBER);
            button_number_to_id(n).map(|id| MouseEvent::Button {
                id,
                pressed: false,
                device: button_source(event),
            })
        }
        CGEventType::ScrollWheel => {
            // axis 1 = vertical scroll; axis 2 = horizontal scroll. Read the
            // pixel-precise delta in preference to the coarse line delta (a hi-res
            // wheel reports its motion in the pixel field with the line field at 0,
            // so reading only the line field would look like "no scroll").
            let dy = usable_scroll_delta(event, VERTICAL);
            let dx = usable_scroll_delta(event, HORIZONTAL);
            // Device identity is the reliable signal: a free-spinning Logitech
            // wheel sets the CGEvent phase, so phase alone misclassifies it as a
            // trackpad. Fall back to the phase heuristic only for a sender-less
            // (synthetic) event, which has no device to identify.
            let phase = event.get_integer_value_field(SCROLL_PHASE) != 0
                || event.get_integer_value_field(MOMENTUM_PHASE) != 0
                || event.get_integer_value_field(SCROLL_COUNT) != 0;
            let sender = event_sender_id(event);
            let device_info = sender.map(sender_device_info);
            let from_trackpad = device_info.as_ref().map_or(phase, |info| info.is_trackpad);
            #[allow(
                clippy::cast_possible_truncation,
                reason = "scroll deltas are small fractional values that fit comfortably in f32"
            )]
            Some(MouseEvent::Scroll {
                delta_x: dx as f32,
                delta_y: dy as f32,
                from_trackpad,
                device: device_info.map(|info| info.event_device),
            })
        }
        // Pointer movement feeds gesture-button swipe detection. While a button
        // is physically held the OS reports *Dragged rather than MouseMoved, so
        // a gesture button's hold-and-swipe arrives here as OtherMouseDragged.
        CGEventType::MouseMoved
        | CGEventType::LeftMouseDragged
        | CGEventType::RightMouseDragged
        | CGEventType::OtherMouseDragged => {
            let dx = event.get_integer_value_field(EventField::MOUSE_EVENT_DELTA_X);
            let dy = event.get_integer_value_field(EventField::MOUSE_EVENT_DELTA_Y);
            #[allow(
                clippy::cast_possible_truncation,
                reason = "per-event pointer deltas are small integers, far within i32"
            )]
            Some(MouseEvent::Moved {
                delta_x: dx as i32,
                delta_y: dy as i32,
            })
        }
        CGEventType::TapDisabledByTimeout | CGEventType::TapDisabledByUserInput => {
            // The run-loop slice re-enables the tap (see `thread_main`); surface
            // the interruption so the runtime cancels any in-progress hold — a
            // button-up dropped during the gap must not later fire a phantom
            // swipe off ordinary cursor motion. Logged at debug, not warn:
            // TapDisabledByUserInput fires during ordinary heavy input bursts and
            // self-heals next slice, so it isn't worth a warning each time.
            debug!("CGEventTap disabled by OS (type={etype:?}); re-enabling, cancelling any hold");
            Some(MouseEvent::CaptureInterrupted)
        }
        _ => None,
    }
}

/// The three delta encodings macOS attaches to one scroll axis: the coarse
/// integer line delta, the fixed-point delta, and the pixel-precise point
/// delta. An app reads whichever it prefers, so any transform must touch all
/// three.
#[derive(Clone, Copy)]
struct ScrollAxisFields {
    line: CGEventField,
    fixed: CGEventField,
    point: CGEventField,
}

const VERTICAL: ScrollAxisFields = ScrollAxisFields {
    line: EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_1,
    fixed: EventField::SCROLL_WHEEL_EVENT_FIXED_POINT_DELTA_AXIS_1,
    point: EventField::SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_1,
};
const HORIZONTAL: ScrollAxisFields = ScrollAxisFields {
    line: EventField::SCROLL_WHEEL_EVENT_DELTA_AXIS_2,
    fixed: EventField::SCROLL_WHEEL_EVENT_FIXED_POINT_DELTA_AXIS_2,
    point: EventField::SCROLL_WHEEL_EVENT_POINT_DELTA_AXIS_2,
};

// Phase fields aren't exposed by core-graphics 0.25; the raw ids come from
// `CGEventTypes.h`. A trackpad sets one of these; a mouse wheel never does.
const SCROLL_PHASE: CGEventField = 99; // kCGScrollWheelEventScrollPhase
const SCROLL_COUNT: CGEventField = 100; // kCGScrollWheelEventScrollCount
const MOMENTUM_PHASE: CGEventField = 123; // kCGScrollWheelEventMomentumPhase

/// The scroll magnitude for `axis`, preferring the pixel-precise field, then the
/// fixed-point, then the integer line — the order the reference tools use, so a
/// hi-res wheel (which reports in the pixel field with the line field at 0) is
/// not mistaken for "no scroll".
#[allow(
    clippy::cast_precision_loss,
    reason = "scroll line deltas are small integers, exact in f64"
)]
fn usable_scroll_delta(event: &CGEvent, axis: ScrollAxisFields) -> f64 {
    let point = event.get_double_value_field(axis.point);
    if point != 0.0 {
        return point;
    }
    let fixed = event.get_double_value_field(axis.fixed);
    if fixed != 0.0 {
        return fixed;
    }
    event.get_integer_value_field(axis.line) as f64
}

/// Create the event tap and run loop on a dedicated thread.
pub(crate) fn start(
    cb: impl Fn(HookEvent) -> EventDisposition + Send + Sync + 'static,
) -> Result<HookInner, HookError> {
    if !has_accessibility() {
        return Err(HookError::AccessibilityDenied);
    }

    // Wrap in Arc so the closure handed to CGEventTap::new captures it by
    // clone rather than by move — avoids a second Box allocation.
    let cb: Arc<dyn Fn(HookEvent) -> EventDisposition + Send + Sync> = Arc::new(cb);

    let stop = Arc::new(AtomicBool::new(false));
    let (rl_tx, rl_rx) = mpsc::channel::<CFRunLoop>();

    let thread = {
        let stop = Arc::clone(&stop);
        thread::Builder::new()
            .name("openlogi-hook".into())
            .spawn(move || thread_main(cb, rl_tx, stop))
            .map_err(|e| HookError::MacOsTap(e.to_string()))?
    };

    // Block until the background thread confirms the run loop is live, or
    // reports failure by dropping its sender.
    let run_loop = rl_rx.recv().map_err(|_| {
        HookError::MacOsTap(
            "background thread exited before the run loop started; \
             CGEventTapCreate likely returned null"
                .into(),
        )
    })?;

    Ok(HookInner {
        thread,
        run_loop,
        stop,
    })
}

/// How long the tap callback may run before the watchdog treats the agent as
/// wedging system input and force-exits. An active HID-level tap serialises
/// every pointer event through this callback; a hang freezes clicks machine-wide.
const CALLBACK_STUCK_BUDGET: Duration = Duration::from_millis(200);

/// Event types the HID tap observes. Pointer *Dragged variants are required
/// because a held button makes the OS emit those instead of `MouseMoved`.
fn hooked_event_types() -> Vec<CGEventType> {
    vec![
        CGEventType::LeftMouseDown,
        CGEventType::LeftMouseUp,
        CGEventType::RightMouseDown,
        CGEventType::RightMouseUp,
        CGEventType::OtherMouseDown,
        CGEventType::OtherMouseUp,
        CGEventType::ScrollWheel,
        CGEventType::MouseMoved,
        CGEventType::LeftMouseDragged,
        CGEventType::RightMouseDragged,
        CGEventType::OtherMouseDragged,
        // Function-key remapper: F1–F12/Esc arrive as KeyDown/KeyUp.
        CGEventType::KeyDown,
        CGEventType::KeyUp,
        CGEventType::FlagsChanged,
    ]
}

/// Invoke the user callback under `catch_unwind`, always failing open.
fn run_tap_callback(
    cb: &dyn Fn(HookEvent) -> EventDisposition,
    etype: CGEventType,
    event: &CGEvent,
) -> CallbackResult {
    let result = catch_unwind(AssertUnwindSafe(|| {
        // Mouse first, then keyboard; a given event type is one or the other.
        let hook_event = if let Some(mouse_event) = translate(etype, event) {
            HookEvent::Mouse(mouse_event)
        } else if let Some(key_event) = translate_key(etype, event) {
            HookEvent::Key(key_event)
        } else {
            return CallbackResult::Keep;
        };
        match cb(hook_event) {
            EventDisposition::PassThrough => CallbackResult::Keep,
            EventDisposition::Suppress => CallbackResult::Drop,
        }
    }));
    if let Ok(disposition) = result {
        disposition
    } else {
        error!(
            "OS mouse-hook callback panicked — passing event through to \
             avoid wedging system input"
        );
        CallbackResult::Keep
    }
}

/// Sibling watchdog: if the callback is still entered past the budget, abort
/// the agent so macOS tears the tap down and system input recovers.
fn spawn_callback_watchdog(
    stop: Arc<AtomicBool>,
    in_callback: Arc<AtomicBool>,
    entered_at_ms: Arc<AtomicU64>,
) {
    let budget_ms = u64::try_from(CALLBACK_STUCK_BUDGET.as_millis()).unwrap_or(200);
    let _ = thread::Builder::new()
        .name("openlogi-hook-watchdog".into())
        .spawn(move || {
            while !stop.load(Ordering::Relaxed) {
                thread::sleep(Duration::from_millis(20));
                if !in_callback.load(Ordering::Acquire) {
                    continue;
                }
                let entered = entered_at_ms.load(Ordering::Acquire);
                if entered == 0 {
                    continue;
                }
                let elapsed = unix_now_ms().saturating_sub(entered);
                if elapsed < budget_ms {
                    continue;
                }
                // Re-sample: a fresh entry may have rewritten the stamp between
                // the first loads and the budget check.
                if !in_callback.load(Ordering::Acquire)
                    || entered_at_ms.load(Ordering::Acquire) != entered
                {
                    continue;
                }
                error!(
                    stuck_ms = elapsed,
                    "OS mouse-hook callback stuck past budget — exiting agent to \
                     restore system input (HID CGEventTap freeze hazard)"
                );
                // Hard exit: disable_tap alone cannot unblock an in-flight
                // callback, and a live active HID tap freezes all pointer I/O.
                std::process::exit(78);
            }
        });
}

/// Body of the background hook thread.
#[allow(
    clippy::needless_pass_by_value,
    reason = "rl_tx must be owned: dropping it signals the parent's recv() to return Err on failure paths"
)]
fn thread_main(
    cb: Arc<dyn Fn(HookEvent) -> EventDisposition + Send + Sync>,
    rl_tx: mpsc::Sender<CFRunLoop>,
    stop: Arc<AtomicBool>,
) {
    // Watchdog state: the run-loop thread can't observe a stuck callback (it
    // *is* the callback), so a sibling thread samples these atomics and kills
    // the process if the budget is exceeded — process death is the only reliable
    // way to release a wedged HID-level tap and restore system input.
    let in_callback = Arc::new(AtomicBool::new(false));
    let entered_at_ms = Arc::new(AtomicU64::new(0));

    let tap_result = {
        let in_callback = Arc::clone(&in_callback);
        let entered_at_ms = Arc::clone(&entered_at_ms);
        CGEventTap::new(
            CGEventTapLocation::HID,
            CGEventTapPlacement::HeadInsertEventTap,
            CGEventTapOptions::Default,
            hooked_event_types(),
            move |_proxy: CGEventTapProxy, etype: CGEventType, event: &CGEvent| {
                // Publish the enter timestamp *before* the in-callback flag so
                // the watchdog never pairs a fresh entry with a stale stamp
                // (which would false-positive process::exit after a quiet gap).
                entered_at_ms.store(unix_now_ms(), Ordering::Relaxed);
                in_callback.store(true, Ordering::Release);
                let disposition = run_tap_callback(cb.as_ref(), etype, event);
                in_callback.store(false, Ordering::Release);
                disposition
            },
        )
    };

    let Ok(tap) = tap_result else {
        error!("CGEventTapCreate returned null — Accessibility may have been revoked");
        // Dropping rl_tx causes rl_rx.recv() on the parent to return Err,
        // which we surface as MacOsTap.
        return;
    };

    let Ok(loop_source) = tap.mach_port().create_runloop_source(0) else {
        error!("CFRunLoopSourceCreate failed for event tap");
        return;
    };

    let run_loop = CFRunLoop::get_current();

    // SAFETY: kCFRunLoopCommonModes is a static CF string constant that
    // lives for the duration of the process.
    unsafe {
        run_loop.add_source(&loop_source, kCFRunLoopCommonModes);
    }
    tap.enable();
    spawn_callback_watchdog(
        Arc::clone(&stop),
        Arc::clone(&in_callback),
        Arc::clone(&entered_at_ms),
    );

    if rl_tx.send(run_loop).is_err() {
        debug!("hook parent dropped before run loop was ready; stopping");
        disable_tap(&tap);
        return;
    }

    // Service the tap in short slices instead of an unbounded
    // `run_current()`. Between slices we re-check Accessibility: an active
    // tap at the HID location that outlives its permission wedges the
    // *entire* system input stream — mouse and keyboard alike — until
    // reboot. If the user revokes access while we're live, tear the tap
    // down right here, on the tap's own thread, so input is restored even
    // when the UI thread is already stuck.
    //
    // `stop()` requests shutdown two ways: it sets `stop` and calls
    // `run_loop.stop()`. The CF stop returns `Stopped` and breaks promptly
    // while a slice is running, but is a no-op if it lands in the gap
    // between slices (CFRunLoopStop only acts on a running loop). The `stop`
    // flag, checked at the top of every slice, is the reliable signal: in
    // that race the thread notices one 500 ms slice later instead of joining
    // forever.
    loop {
        if stop.load(Ordering::Relaxed) {
            break;
        }
        match CFRunLoop::run_in_mode(
            // SAFETY: framework-provided static CFStringRef, 'static.
            unsafe { kCFRunLoopDefaultMode },
            Duration::from_millis(500),
            false,
        ) {
            CFRunLoopRunResult::Stopped | CFRunLoopRunResult::Finished => break,
            CFRunLoopRunResult::TimedOut | CFRunLoopRunResult::HandledSource => {}
        }
        if !has_accessibility() {
            warn!(
                "Accessibility revoked while the event tap was live — \
                 disabling the tap to avoid wedging system input"
            );
            break;
        }
        // Recover from an OS-initiated disable (TapDisabledByTimeout/UserInput):
        // re-enabling is idempotent while the tap is already live, so this brings
        // a disabled tap back within one slice instead of the hook going
        // permanently deaf. Only reached while Accessibility is still granted.
        tap.enable();
    }

    // Detach the tap from the event stream synchronously before unwinding,
    // so input recovers immediately rather than whenever CF happens to
    // release the port.
    disable_tap(&tap);
}

/// Milliseconds since the Unix epoch for the stuck-callback watchdog.
fn unix_now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
}

/// Disable an active event tap now. core-graphics only exposes the enable
/// side of `CGEventTapEnable`, so we bind the disable side ourselves.
fn disable_tap(tap: &CGEventTap) {
    use core_foundation::base::TCFType as _;

    #[link(name = "CoreGraphics", kind = "framework")]
    unsafe extern "C" {
        fn CGEventTapEnable(tap: core_foundation::mach_port::CFMachPortRef, enable: bool);
    }

    // SAFETY: `tap.mach_port()` is a live `CFMachPort` for the duration of
    // the call; `CGEventTapEnable(.., false)` is idempotent and merely
    // detaches the tap from the system event stream.
    unsafe { CGEventTapEnable(tap.mach_port().as_concrete_TypeRef(), false) };
}

/// Mirror of CoreGraphics' `CGEventTapInformation`. `#[repr(C)]` reproduces the
/// header layout (including the padding before `events_of_interest` and
/// `min_usec_latency`) so `CGGetEventTapList` writes into the right offsets.
#[repr(C)]
#[derive(Clone, Copy)]
#[allow(
    dead_code,
    reason = "events_of_interest and the latency floats are unread but must \
              exist so the struct keeps CoreGraphics' exact 48-byte stride; \
              CGGetEventTapList writes whole records into the buffer"
)]
struct CGEventTapInformation {
    event_tap_id: u32,
    tap_point: u32,
    options: u32,
    events_of_interest: u64,
    tapping_process: i32,
    process_being_tapped: i32,
    enabled: bool,
    min_usec_latency: f32,
    avg_usec_latency: f32,
    max_usec_latency: f32,
}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    // `core-graphics` doesn't bind the enumeration side (it ships the tap
    // *create/enable* path only), so we declare it ourselves. Passing a null
    // list with count 0 returns the number of taps via `event_tap_count`.
    fn CGGetEventTapList(
        max_number_of_taps: u32,
        tap_list: *mut CGEventTapInformation,
        event_tap_count: *mut u32,
    ) -> i32;
}

#[link(name = "System", kind = "dylib")]
unsafe extern "C" {
    // libproc; resolves a PID to its executable path. Returns the byte length
    // written, or <= 0 on failure (e.g. the process exited, or it's out of the
    // caller's permission scope).
    fn proc_pidpath(pid: i32, buffer: *mut std::ffi::c_void, buffersize: u32) -> i32;
}

/// See [`super::Hook::list_event_taps`].
pub(crate) fn list_event_taps() -> Vec<EventTapInfo> {
    let mut count: u32 = 0;
    // SAFETY: a null `tap_list` with `max == 0` is the documented count-probe
    // form; it only writes `count`.
    let err = unsafe { CGGetEventTapList(0, std::ptr::null_mut(), &raw mut count) };
    if err != 0 || count == 0 {
        return Vec::new();
    }

    // SAFETY: `CGEventTapInformation` is a plain `repr(C)` POD; an all-zero bit
    // pattern is a valid instance (`enabled = false`, all numeric fields 0).
    // `CGGetEventTapList` overwrites each slot it fills.
    let mut taps: Vec<CGEventTapInformation> = vec![unsafe { std::mem::zeroed() }; count as usize];
    let err = unsafe { CGGetEventTapList(count, taps.as_mut_ptr(), &raw mut count) };
    if err != 0 {
        return Vec::new();
    }
    // The second call may report fewer taps than the probe; never read past it.
    taps.truncate(count as usize);

    taps.into_iter()
        .map(|t| EventTapInfo {
            tap_id: t.event_tap_id,
            location: match t.tap_point {
                0 => TapLocation::Hid,
                1 => TapLocation::Session,
                2 => TapLocation::AnnotatedSession,
                other => TapLocation::Other(other),
            },
            // kCGEventTapOptionDefault == 0 (active); kCGEventTapOptionListenOnly == 1.
            active: t.options == 0,
            enabled: t.enabled,
            owner_pid: t.tapping_process,
            owner_name: process_name(t.tapping_process),
            target_pid: (t.process_being_tapped != 0).then_some(t.process_being_tapped),
        })
        .collect()
}

/// Best-effort PID → executable file name via libproc.
fn process_name(pid: i32) -> Option<String> {
    // PROC_PIDPATHINFO_MAXSIZE is 4 * MAXPATHLEN (4 * 1024).
    const BUF_LEN: u32 = 4096;
    if pid <= 0 {
        return None;
    }
    let mut buf = vec![0u8; BUF_LEN as usize];
    // SAFETY: `buf` is a live, writable buffer of `BUF_LEN` bytes; the C side
    // writes at most that many and returns the length actually written.
    let len = unsafe { proc_pidpath(pid, buf.as_mut_ptr().cast(), BUF_LEN) };
    if len <= 0 {
        return None;
    }
    // `len > 0` here, so `unsigned_abs` is the value itself; widening to usize
    // is lossless and sidesteps the sign-loss cast lint.
    buf.truncate(len.unsigned_abs() as usize);
    let path = String::from_utf8_lossy(&buf);
    Some(path.rsplit('/').next().unwrap_or(&path).to_string())
}

/// Signal the run loop to stop and join the background thread.
pub(crate) fn stop(inner: HookInner) {
    // Set the flag *before* waking the loop: if `run_loop.stop()` lands in
    // the gap between slices and is dropped, the thread still observes the
    // flag at the next slice top. Relaxed suffices — the flag carries no
    // other data, and `thread.join()` below is the final synchronisation.
    inner.stop.store(true, Ordering::Relaxed);
    inner.run_loop.stop();
    if let Err(e) = inner.thread.join() {
        error!("hook thread panicked on shutdown: {e:?}");
    }
}