openlogi-hook 0.8.14

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
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
//! macOS `CGEventTap` implementation of the OS-level mouse hook.
#![expect(
    unsafe_code,
    reason = "the event tap uses Core Graphics / Core Foundation C APIs, and workspace observation uses typed Objective-C notification APIs"
)]

mod foreground;
mod grant;
pub(crate) mod pointer;
mod sender;
mod translate;
mod watchdog;

use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::Duration;

use core_foundation::runloop::{
    CFRunLoop, CFRunLoopRunResult, kCFRunLoopCommonModes, kCFRunLoopDefaultMode,
};
use core_graphics::event::{
    CGEvent, CGEventTap, CGEventTapLocation, CGEventTapOptions, CGEventTapPlacement,
    CGEventTapProxy, CGEventType, CallbackResult,
};
use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};
use objc2_app_kit::NSWorkspace;
use objc2_application_services::{AXIsProcessTrusted, AXIsProcessTrustedWithOptions};
use tracing::{debug, error, warn};

use crate::{
    CursorPosition, Delivery, EventDisposition, EventTapInfo, ForegroundApp, HookBackend,
    HookError, HookEvent, MouseEvent, TapLocation,
};
pub use foreground::ForegroundApplicationObserver;
use foreground::observe_frontmost_application;
pub(crate) use foreground::{frontmost_safari_pid, watch_frontmost_application_activations};
use grant::{ProbeCue, can_filter_events};
use translate::{VERTICAL, translate, translate_key};
use watchdog::{
    CALLBACK_POLL_INTERVAL, CallbackActivity, CallbackWatchdog, LIFECYCLE_POLL_INTERVAL,
    LifecycleDecision, LifecycleExitReason, LifecycleObservation, LifecycleWatchdog, PowerEpoch,
    RearmBudget, TapPhase, WatchdogSignals,
};

/// Everything `Hook` needs to control the background thread.
pub(crate) struct HookInner {
    thread: thread::JoinHandle<()>,
    lifecycle_watchdog: thread::JoinHandle<()>,
    run_loop: CFRunLoop,
    /// Lifecycle signals 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 the stop latch — not the CF stop alone — is the reliable
    /// shutdown signal. The independent lifecycle watchdog keeps observing
    /// that latch until the tap thread proves the tap is gone.
    signals: Arc<WatchdogSignals>,
}

// 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 {}

#[link(name = "CoreGraphics", kind = "framework")]
unsafe extern "C" {
    // `core-graphics` exposes only the enable-true operation, and does not
    // expose the state read used to budget re-arms.
    fn CGEventTapEnable(tap: core_foundation::mach_port::CFMachPortRef, enable: bool);
    fn CGEventTapIsEnabled(tap: core_foundation::mach_port::CFMachPortRef) -> bool;
}

const FREEZE_HAZARD_EXIT_CODE: i32 = 78;

/// Event types the HID tap observes. Pointer *Dragged variants are required
/// because a held button makes the OS emit those instead of `MouseMoved`.
/// The macOS backend: a `CGEventTap` serviced by a private run-loop thread.
pub(crate) struct Backend;

impl HookBackend for Backend {
    type Running = HookInner;

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

        // Seed the press-time snapshot before the tap can receive input. Later
        // NSWorkspace activation notifications refresh it off the tap thread.
        let _ = Self::frontmost_app();

        // 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 signals = Arc::new(WatchdogSignals::default());
        let lifecycle_watchdog = spawn_lifecycle_watchdog(Arc::clone(&signals))?;
        let (rl_tx, rl_rx) = mpsc::channel::<CFRunLoop>();

        let thread = {
            let thread_signals = Arc::clone(&signals);
            match thread::Builder::new()
                .name("openlogi-hook".into())
                .spawn(move || thread_main(cb, rl_tx, thread_signals))
            {
                Ok(thread) => thread,
                Err(error) => {
                    signals.set_phase(TapPhase::ThreadExited);
                    lifecycle_watchdog.thread().unpark();
                    let _ = lifecycle_watchdog.join();
                    return Err(HookError::MacOsTap(error.to_string()));
                }
            }
        };

        // Block until the background thread confirms the run loop is live, or
        // reports failure by dropping its sender.
        let Ok(run_loop) = rl_rx.recv() else {
            let error = HookError::MacOsTap(
                "background thread exited before the run loop started; \
                 CGEventTapCreate likely returned null"
                    .into(),
            );
            if let Err(panic) = thread.join() {
                error!(?panic, "hook thread panicked during startup");
            }
            lifecycle_watchdog.thread().unpark();
            if let Err(panic) = lifecycle_watchdog.join() {
                error!(?panic, "hook lifecycle watchdog panicked during startup");
            }
            return Err(error);
        };

        Ok(HookInner {
            thread,
            lifecycle_watchdog,
            run_loop,
            signals,
        })
    }

    /// Signal the run loop to stop and join the background thread.
    fn stop(inner: HookInner) {
        // Latch stop before waking either thread. The lifecycle watchdog stays
        // armed across the blocking join and accepts only `ThreadExited` as proof
        // that explicit shutdown completed.
        inner.signals.request_stop();
        inner.lifecycle_watchdog.thread().unpark();
        inner.run_loop.stop();
        if let Err(e) = inner.thread.join() {
            error!("hook thread panicked on shutdown: {e:?}");
        }
        inner.lifecycle_watchdog.thread().unpark();
        if let Err(e) = inner.lifecycle_watchdog.join() {
            error!("hook lifecycle watchdog panicked on shutdown: {e:?}");
        }
    }

    /// Check whether this process can still install the hook's event tap.
    ///
    /// `AXIsProcessTrusted()` alone is not that answer: it keeps returning `true`
    /// after the user *deletes* the app's row from System Settings → Privacy &
    /// Security → Accessibility, so a hook that believes it would never learn it
    /// had been revoked, would keep re-arming a tap macOS no longer lets it
    /// service, and would wedge clicks machine-wide until reboot (#674). Only
    /// creating a filtering tap tracks the live grant, so both are consulted: the
    /// trust read short-circuits the probe for a process that was never granted.
    /// While the tap is live, [`ProbeCue`] decides when this runs at all.
    fn has_accessibility() -> bool {
        // SAFETY: takes no arguments and only reads the current trust state — the
        // non-prompting counterpart of `AXIsProcessTrustedWithOptions`.
        let trusted = unsafe { AXIsProcessTrusted() };
        trusted && can_filter_events()
    }

    /// Raise the Accessibility prompt + register the process. See
    /// [`super::Hook::prompt_accessibility`].
    ///
    /// The `kAXTrustedCheckOptionPrompt = true` option is what makes macOS surface
    /// the dialog and list the process in System Settings; without it this is just
    /// [`Self::has_accessibility`].
    fn prompt_accessibility() {
        use objc2_application_services::kAXTrustedCheckOptionPrompt;
        use objc2_core_foundation::{CFDictionary, kCFBooleanTrue};

        // SAFETY: both are framework-provided constants, live for the process
        // lifetime; reading them copies a `&'static` reference.
        let (key, value) = unsafe { (kAXTrustedCheckOptionPrompt, kCFBooleanTrue) };
        let Some(value) = value else { return };
        let options = CFDictionary::from_slices(&[key], &[value]);
        // SAFETY: the dictionary holds exactly the documented key/value types
        // (`kAXTrustedCheckOptionPrompt` → `CFBoolean`). The returned trust state is
        // observed separately via the watcher, so it is deliberately dropped here.
        let _trusted = unsafe { AXIsProcessTrustedWithOptions(Some(options.as_opaque())) };
    }

    /// See [`super::Hook::list_event_taps`].
    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];
        // SAFETY: `taps` holds exactly `count` initialised, correctly aligned slots
        // and stays alive for the call, and that same `count` is the maximum passed
        // in, so the C side cannot write past the allocation; the out-parameter
        // points at a live local it may only overwrite.
        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()
    }

    /// Read the frontmost application via `NSWorkspace`. Use its bundle
    /// identifier for profile matching, or its executable path when no bundle
    /// identifier is available. Use its localized name for the UI. Return `None`
    /// when no app is frontmost or neither identifier is available.
    ///
    /// `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.)
    fn frontmost_app() -> Option<ForegroundApp> {
        use objc2::rc::autoreleasepool;

        autoreleasepool(|pool| {
            let app = NSWorkspace::sharedWorkspace().frontmostApplication();
            observe_frontmost_application(app.as_deref(), pool)
        })
    }

    /// Read the global cursor position from a HID-state event source, which
    /// needs no tap and no permission.
    fn cursor_position() -> Option<CursorPosition> {
        let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState).ok()?;
        let point = CGEvent::new(source).ok()?.location();
        Some(CursorPosition {
            x: point.x,
            y: point.y,
        })
    }
}

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,
    ]
}

/// Whether this event is a mouse-wheel scroll software inversion applies to.
///
/// Trackpad scrolling is excluded by contract — the setting reverses one
/// mouse, not the system direction — and so is any source the hook would not
/// remap buttons for, so a second vendor's mouse is left alone.
fn wheel_scroll_to_invert(event: &HookEvent) -> bool {
    matches!(
        event,
        HookEvent::Mouse(MouseEvent::Scroll {
            delta,
            from_trackpad: false,
            device,
            ..
        }) if delta.y() != 0.0 && crate::source_is_remappable(device.as_ref())
    )
}

/// Negate the vertical scroll fields of `event`, in place.
///
/// Every field the reader might have used is negated, so the
/// value that reaches the desktop is the device's own magnitude with its sign
/// flipped. Re-synthesising the event from the normalised `delta_y` instead
/// would have to choose a unit, and a hi-res wheel reports pixels in one field
/// while a detented one reports lines in another — writing back the same
/// fields sidesteps the choice entirely.
///
/// Order matters: writing the line field makes CoreGraphics recompute the
/// fixed-point and point fields from it, so writing it last clobbered the
/// negated point delta and shrank an inverted scroll by a fifth (a three-line
/// notch's 30 px came out as 24). Every field is read before any is written,
/// the line field goes first, and the finer two follow it — even a zero one,
/// which the line write may have filled in.
fn invert_scroll_event(event: &CGEvent) {
    let lines = event.get_integer_value_field(VERTICAL.line);
    let finer =
        [VERTICAL.fixed, VERTICAL.point].map(|field| (field, event.get_double_value_field(field)));
    if lines != 0 {
        event.set_integer_value_field(VERTICAL.line, -lines);
    }
    for (field, value) in finer {
        if lines != 0 || value != 0.0 {
            event.set_double_value_field(field, -value);
        }
    }
}

/// 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;
        };
        // Decided before the callback consumes the event: a Logitech wheel
        // scroll (never a trackpad) is the only thing software inversion may
        // touch.
        let invert = crate::scroll_inversion() && wheel_scroll_to_invert(&hook_event);
        dispatch(cb, hook_event, invert, event)
    }));
    if let Ok(disposition) = result {
        disposition
    } else {
        error!(
            "OS mouse-hook callback panicked — passing event through to \
             avoid wedging system input"
        );
        CallbackResult::Keep
    }
}

/// Deliver `hook_event` to the callback and carry its verdict out on the
/// native `event`, reversing the event's vertical scroll first when software
/// inversion applies and the event is passed through (#1737).
///
/// Split out of [`run_tap_callback`] because `invert` hinges on the event's
/// source attribution, which only a real Logitech device produces; taking it
/// as an argument lets a synthetic event exercise the inversion path.
fn dispatch(
    cb: &dyn Fn(HookEvent) -> EventDisposition,
    hook_event: HookEvent,
    invert: bool,
    event: &CGEvent,
) -> CallbackResult {
    let delivery = Delivery::run(hook_event, invert, cb);
    if delivery.invert_native {
        invert_scroll_event(event);
    }
    match delivery.disposition {
        EventDisposition::PassThrough => CallbackResult::Keep,
        EventDisposition::Suppress => CallbackResult::Drop,
    }
}

/// 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(
    signals: Arc<WatchdogSignals>,
    callback_activity: Arc<CallbackActivity>,
) -> std::io::Result<()> {
    thread::Builder::new()
        .name("openlogi-hook-watchdog".into())
        .spawn(move || {
            let mut watchdog =
                CallbackWatchdog::watching_since(signals.now_millis(), power_epoch());
            loop {
                let phase = signals.phase();
                if matches!(phase, TapPhase::TapStopped | TapPhase::ThreadExited) {
                    return;
                }
                thread::sleep(CALLBACK_POLL_INTERVAL);
                let entered = callback_activity.entered_at_ms();
                let Some(stuck) =
                    watchdog.evaluate(signals.now_millis(), entered, power_epoch())
                else {
                    continue;
                };
                // Re-sample: a fresh high-frequency event may have rewritten
                // the complete activity state during the budget check.
                if callback_activity.entered_at_ms() != entered {
                    continue;
                }
                if signals.phase() != TapPhase::Armed {
                    continue;
                }
                error!(
                    stalled_ms = duration_millis(stuck.stalled),
                    watched_ms = duration_millis(stuck.watched),
                    "OS mouse-hook callback stuck past budget — exiting agent to \
                     restore system input (HID CGEventTap freeze hazard)"
                );
                // A live callback owns the tap thread, so no in-process
                // teardown can make progress. Process death releases its Mach
                // port and removes the tap from the system event chain.
                #[expect(
                    clippy::exit,
                    reason = "this watchdog thread has no caller to return to and the stuck callback owns the active HID tap, which serialises every pointer event machine-wide; only process death makes macOS tear the tap down"
                )]
                std::process::exit(FREEZE_HAZARD_EXIT_CODE);
            }
        })
        .map(|_| ())
}

/// The kernel's last sleep and wake instants, for [`PowerEpoch`]. A failed
/// read yields the zero epoch, which never differs from itself, so the
/// watchdog then charges every gap in full — the behaviour before #952.
fn power_epoch() -> PowerEpoch {
    PowerEpoch {
        slept_us: kernel_instant_us(c"kern.sleeptime"),
        woke_us: kernel_instant_us(c"kern.waketime"),
    }
}

/// One `timeval` sysctl as microseconds since the epoch; zero when unreadable.
fn kernel_instant_us(name: &std::ffi::CStr) -> i64 {
    let mut value = libc::timeval {
        tv_sec: 0,
        tv_usec: 0,
    };
    let mut len = std::mem::size_of::<libc::timeval>();
    // SAFETY: `name` is NUL-terminated; `value` and `len` describe a live,
    // correctly sized buffer the kernel fills up to `len` before storing the
    // byte count back into `len`. Nothing is written (null new value, 0).
    let rc = unsafe {
        libc::sysctlbyname(
            name.as_ptr(),
            (&raw mut value).cast(),
            &raw mut len,
            std::ptr::null_mut(),
            0,
        )
    };
    if rc != 0 || len != std::mem::size_of::<libc::timeval>() {
        return 0;
    }
    value
        .tv_sec
        .saturating_mul(1_000_000)
        .saturating_add(i64::from(value.tv_usec))
}

/// Independent lifecycle watchdog for paths that never enter the Rust tap
/// callback (for example, TCC revocation wedging `CFRunLoopRunInMode` or the
/// Accessibility query itself).
///
/// This thread is started before the tap thread, uses only atomics and a
/// monotonic clock, and remains armed after a stop request. It deliberately
/// does not call `has_accessibility()`: that query can itself stop returning
/// after TCC revocation. It disarms only after the tap thread reports that the
/// tap was synchronously disabled and destroyed, or (for explicit shutdown)
/// after that thread has exited.
fn spawn_lifecycle_watchdog(
    signals: Arc<WatchdogSignals>,
) -> Result<thread::JoinHandle<()>, HookError> {
    thread::Builder::new()
        .name("openlogi-hook-lifecycle-watchdog".into())
        .spawn(move || {
            let mut watchdog = LifecycleWatchdog::default();
            loop {
                let observation = LifecycleObservation {
                    phase: signals.phase(),
                    stop_requested: signals.stop_requested(),
                    tap_progress_at: signals.tap_progress_at(),
                    power: power_epoch(),
                };
                match watchdog.evaluate(signals.now(), observation) {
                    LifecycleDecision::Continue => {
                        thread::park_timeout(LIFECYCLE_POLL_INTERVAL);
                    }
                    LifecycleDecision::Complete => return,
                    LifecycleDecision::Exit {
                        reason,
                        watched,
                        stalled,
                    } => {
                        // The tap thread may have completed immediately after
                        // the decision. Only a still-hazardous phase may exit.
                        let phase = signals.phase();
                        let still_hazardous = match reason {
                            LifecycleExitReason::TapThreadStalled => {
                                matches!(
                                    phase,
                                    TapPhase::Arming | TapPhase::Armed | TapPhase::Probing
                                )
                            }
                            LifecycleExitReason::StopTimedOut => phase != TapPhase::ThreadExited,
                        };
                        if !still_hazardous {
                            continue;
                        }
                        let reason = match reason {
                            LifecycleExitReason::TapThreadStalled if phase == TapPhase::Arming => {
                                "HID tap creation or activation stopped making progress"
                            }
                            LifecycleExitReason::TapThreadStalled if phase == TapPhase::Probing => {
                                "HID tap capability probe stopped making progress"
                            }
                            LifecycleExitReason::TapThreadStalled => {
                                "HID tap thread stopped making progress while tap remained active"
                            }
                            LifecycleExitReason::StopTimedOut => {
                                "hook stop requested but tap thread did not exit"
                            }
                        };
                        // `stalled` is uptime since the stall began; `watched` is
                        // the part this thread was running to see. A wide gap
                        // between them says the process itself was frozen.
                        error!(
                            reason,
                            stalled_ms = duration_millis(stalled),
                            watched_ms = duration_millis(watched),
                            ?phase,
                            "HID CGEventTap lifecycle did not make progress before deadline — \
                             exiting agent to restore system input"
                        );
                        #[expect(
                            clippy::exit,
                            reason = "the tap thread is wedged (TCC revocation can stall it inside CoreGraphics), so no unwinding path can reach it from this watchdog thread; a live HID tap left behind freezes all input until the process dies"
                        )]
                        std::process::exit(FREEZE_HAZARD_EXIT_CODE);
                    }
                }
            }
        })
        .map_err(|error| HookError::MacOsTap(format!("could not spawn tap watchdog: {error}")))
}

/// Service the tap until it has to be released: an explicit stop, a stopped run
/// loop, a revoked permission, or a tap the OS will not keep enabled.
fn service_tap(
    tap: &CGEventTap<'_>,
    signals: &WatchdogSignals,
    tap_disabled: &AtomicBool,
    probe: &ProbeCue,
) {
    // Service the tap in short slices instead of an unbounded
    // `run_current()`. Between slices, when the grant watch cues it, we
    // re-check that we may still filter events: 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 the stop latch 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 latch,
    // 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.
    let mut rearm = RearmBudget::default();
    loop {
        if signals.stop_requested() {
            break;
        }
        signals.mark_tap_progress();
        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 => {}
        }
        signals.mark_tap_progress();
        // Everything below this point is a WindowServer or TCC round trip, not
        // tap servicing. Publish that so the lifecycle watchdog judges it
        // against `TAP_PROBE_BUDGET`: around a sleep transition these calls
        // have been measured at ~1.6 s, and charging them to the 1.5 s stall
        // budget force-exited a perfectly healthy agent (#952). The capability
        // probe itself runs only when the cue says the grant may have changed.
        signals.set_phase(TapPhase::Probing);
        if probe.take() && !Backend::has_accessibility() {
            warn!(
                "Accessibility revoked while the event tap was live — \
                 disabling the tap to avoid wedging system input"
            );
            break;
        }
        // Observe both disable signals: the callback catches the documented
        // TapDisabledBy* notification, while the port state catches the
        // sleep/wake edge where CoreGraphics disables the tap without one.
        // Either one consumes the same bounded re-arm budget.
        let was_disabled = tap_disabled.swap(false, Ordering::AcqRel) || !tap_is_enabled(tap);
        if was_disabled && !rearm.allow(signals.now()) {
            error!(
                "the OS keeps disabling the HID tap — releasing it instead of \
                 re-arming a tap nothing is servicing"
            );
            break;
        }
        // Enabling is idempotent while the tap is already live. Only reached
        // while the live capability probe above still succeeds.
        tap.enable();
        signals.mark_armed();
    }
}

/// Body of the background hook thread.
#[expect(
    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>,
    signals: Arc<WatchdogSignals>,
) {
    // Declared first so it drops last, after the tap, callback, source, and run
    // loop locals have unwound. The lifecycle watchdog treats this notification
    // as proof that an explicit stop has completed, not merely been requested.
    let _thread_exit = signals.thread_exit_guard();

    // A successful CGEventTapCreate may install the HID tap before returning,
    // so lifecycle monitoring must be armed before entering CoreGraphics.
    signals.mark_tap_progress();
    signals.set_phase(TapPhase::Arming);

    let callback_activity = Arc::new(CallbackActivity::default());
    // Latched by the callback when the OS disables the tap, consumed by the
    // run-loop slice that decides whether to re-arm it.
    let tap_disabled = Arc::new(AtomicBool::new(false));

    let tap_result = {
        let callback_signals = Arc::clone(&signals);
        let callback_activity = Arc::clone(&callback_activity);
        let tap_disabled = Arc::clone(&tap_disabled);
        CGEventTap::new(
            CGEventTapLocation::HID,
            CGEventTapPlacement::HeadInsertEventTap,
            CGEventTapOptions::Default,
            hooked_event_types(),
            move |_proxy: CGEventTapProxy, etype: CGEventType, event: &CGEvent| {
                if matches!(
                    etype,
                    CGEventType::TapDisabledByTimeout | CGEventType::TapDisabledByUserInput
                ) {
                    tap_disabled.store(true, Ordering::Release);
                }
                callback_activity.enter(callback_signals.now_millis());
                let disposition = run_tap_callback(cb.as_ref(), etype, event);
                callback_activity.exit();
                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;
    };
    signals.mark_tap_progress();

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

    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);
    }
    signals.mark_tap_progress();
    if let Err(error) =
        spawn_callback_watchdog(Arc::clone(&signals), Arc::clone(&callback_activity))
    {
        error!(%error, "could not spawn callback watchdog — refusing to arm HID tap");
        return;
    }
    signals.mark_tap_progress();
    tap.enable();
    signals.mark_armed();

    if rl_tx.send(run_loop.clone()).is_err() {
        debug!("hook parent dropped before run loop was ready; stopping");
        disable_tap(&tap);
        // SAFETY: framework-provided static CFStringRef, 'static.
        run_loop.remove_source(&loop_source, unsafe { kCFRunLoopCommonModes });
        drop(loop_source);
        drop(tap);
        signals.set_phase(TapPhase::TapStopped);
        return;
    }

    // Armed on the tap thread and dropped with it, so the grant watch's
    // observers go away when the tap does.
    let probe = ProbeCue::arm();
    service_tap(&tap, &signals, &tap_disabled, &probe);
    // Every exit uses the short teardown budget, including a revoked grant
    // or exhausted re-arm budget that leaves the loop in `Probing`.
    signals.mark_armed();

    // 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);
    // SAFETY: framework-provided static CFStringRef, 'static.
    run_loop.remove_source(&loop_source, unsafe { kCFRunLoopCommonModes });
    drop(loop_source);
    drop(tap);
    signals.set_phase(TapPhase::TapStopped);
}

fn duration_millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

/// Whether CoreGraphics currently considers `tap` enabled. Checked on the tap
/// thread so an unreported OS disable consumes the same budget as a callback.
fn tap_is_enabled(tap: &CGEventTap<'_>) -> bool {
    use core_foundation::base::TCFType as _;

    // SAFETY: the port is owned by `tap` and remains live for this call.
    unsafe { CGEventTapIsEnabled(tap.mach_port().as_concrete_TypeRef()) }
}

/// Disable an active tap synchronously. Dropping `CGEventTap` then invalidates
/// its Mach port on the same thread.
fn disable_tap(tap: &CGEventTap<'_>) {
    use core_foundation::base::TCFType as _;

    // SAFETY: the port is owned by `tap` and remains live for this call;
    // disabling is idempotent.
    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)]
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;
}

/// 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())
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use core_graphics::event::ScrollEventUnit;
    use core_graphics::event_source::{CGEventSource, CGEventSourceStateID};

    use super::*;
    use crate::ScrollDelta;

    #[test]
    fn tap_callback_suppresses_normally_and_passes_through_panics() {
        let source = CGEventSource::new(CGEventSourceStateID::Private)
            .expect("CGEventSourceCreate must succeed");
        let event = CGEvent::new(source).expect("CGEventCreate must succeed");

        assert!(matches!(
            run_tap_callback(
                &|_| EventDisposition::Suppress,
                CGEventType::MouseMoved,
                &event
            ),
            CallbackResult::Drop
        ));
        assert!(matches!(
            run_tap_callback(
                &|_| panic!("test callback panic"),
                CGEventType::MouseMoved,
                &event
            ),
            CallbackResult::Keep
        ));
    }

    /// A detented wheel notch of `lines`, as a synthetic event.
    fn wheel_notch(lines: i32) -> CGEvent {
        let source = CGEventSource::new(CGEventSourceStateID::Private)
            .expect("CGEventSourceCreate must succeed");
        CGEvent::new_scroll_event(source, ScrollEventUnit::LINE, 1, lines, 0, 0)
            .expect("CGEventCreateScrollWheelEvent must succeed")
    }

    /// Every vertical field [`invert_scroll_event`] negates.
    fn vertical_fields(event: &CGEvent) -> (i64, f64, f64) {
        (
            event.get_integer_value_field(VERTICAL.line),
            event.get_double_value_field(VERTICAL.point),
            event.get_double_value_field(VERTICAL.fixed),
        )
    }

    /// Whether every vertical field of a [`wheel_notch`] now points down. The
    /// notch starts positive in all of them, so this holds after exactly one
    /// reversal: none leaves it positive, and a second would restore it.
    fn reversed_once(event: &CGEvent) -> bool {
        let (line, point, fixed) = vertical_fields(event);
        line < 0 && point < 0.0 && fixed < 0.0
    }

    /// Run a wheel notch through [`dispatch`] with a callback that answers
    /// `disposition`, returning the delta the callback saw, the tap's verdict
    /// and the native event as it would leave the tap.
    fn dispatch_notch(
        invert: bool,
        disposition: EventDisposition,
    ) -> (Option<ScrollDelta>, CallbackResult, CGEvent) {
        let event = wheel_notch(3);
        let hook_event = HookEvent::Mouse(
            translate(CGEventType::ScrollWheel, &event).expect("a wheel notch translates"),
        );
        let seen = Cell::new(None);
        let result = dispatch(
            &|hook_event| {
                if let HookEvent::Mouse(MouseEvent::Scroll { delta, .. }) = hook_event {
                    seen.set(Some(delta));
                }
                disposition
            },
            hook_event,
            invert,
            &event,
        );
        (seen.get(), result, event)
    }

    /// The delta [`translate`] reads from an untouched wheel notch.
    fn notch_delta() -> ScrollDelta {
        match translate(CGEventType::ScrollWheel, &wheel_notch(3)) {
            Some(MouseEvent::Scroll { delta, .. }) => delta,
            other => panic!("a wheel notch translates to a scroll, got {other:?}"),
        }
    }

    /// With inversion on, the callback sees the reversed delta whatever it
    /// decides, so an impulse the agent suppresses and replays is reversed
    /// too (#1737), and a forwarded event leaves the tap reversed exactly once.
    #[test]
    fn inverted_wheel_reaches_the_callback_reversed_and_the_desktop_reversed_once() {
        let delta = notch_delta();
        let untouched = vertical_fields(&wheel_notch(3));
        assert!(
            untouched.0 > 0 && untouched.1 > 0.0 && untouched.2 > 0.0,
            "the notch carries every vertical field: {untouched:?}"
        );

        let (seen, result, event) = dispatch_notch(true, EventDisposition::PassThrough);
        assert_eq!(seen, Some(delta.negate_y()));
        assert!(matches!(result, CallbackResult::Keep));
        assert!(
            reversed_once(&event),
            "forwarded {:?}, untouched {untouched:?}",
            vertical_fields(&event)
        );

        let (seen, result, event) = dispatch_notch(true, EventDisposition::Suppress);
        assert_eq!(seen, Some(delta.negate_y()));
        assert!(matches!(result, CallbackResult::Drop));
        assert_eq!(vertical_fields(&event), untouched);
    }

    /// With inversion off, neither the callback nor the desktop sees a change.
    #[test]
    fn wheel_is_left_alone_when_inversion_is_off() {
        let delta = notch_delta();
        let untouched = vertical_fields(&wheel_notch(3));
        for disposition in [EventDisposition::PassThrough, EventDisposition::Suppress] {
            let (seen, _, event) = dispatch_notch(false, disposition);
            assert_eq!(seen, Some(delta));
            assert_eq!(vertical_fields(&event), untouched);
        }
    }

    /// Every vertical field comes out negated with its magnitude intact: a
    /// line notch, and pixel scrolls with and without a whole line in them.
    #[test]
    fn invert_scroll_event_keeps_every_magnitude() {
        for (unit, amount) in [
            (ScrollEventUnit::LINE, 3),
            (ScrollEventUnit::PIXEL, 40),
            (ScrollEventUnit::PIXEL, 5),
        ] {
            let source = CGEventSource::new(CGEventSourceStateID::Private)
                .expect("CGEventSourceCreate must succeed");
            let event = CGEvent::new_scroll_event(source, unit, 1, amount, 0, 0)
                .expect("CGEventCreateScrollWheelEvent must succeed");
            let (line, point, fixed) = vertical_fields(&event);
            invert_scroll_event(&event);
            assert_eq!(
                vertical_fields(&event),
                (-line, -point, -fixed),
                "unit {unit}, amount {amount}"
            );
        }
    }
}