Repository navigation
Keep mouse event handling off the main thread - #1148
Conversation
The event tap callback and all transformer state access previously ran on the main thread, blocking the UI during event processing. This change introduces a dedicated background thread with its own RunLoop for the event tap, keeping the main thread free for UI work. Thread safety is achieved by funneling all transformer state mutations onto the single event-processing thread: - Timer callbacks (smoothed scrolling, auto scroll, key repeat) now fire on the background RunLoop instead of the main queue. - Logitech HID++ control handlers dispatch state mutations to the event thread via CFRunLoopPerformBlock. - EventTransformerManager uses an NSLock to protect its LRU cache, which is accessed from both the event thread and the Logitech HID thread. - ScreenManager exposes an atomicCurrentScreenName property for thread-safe reads from the event thread. - UI operations (auto-scroll indicator window) are dispatched to the main thread.
1. EventTap: dispatch healthCheckTimer.invalidate() to its RunLoop thread via CFRunLoopPerformBlock instead of calling from the cancellation thread. 2. GlobalEventTap.stop(): queue CFRunLoopStop after pending cleanup blocks (FIFO ordering) so timer invalidation completes first. 3. GlobalEventTap.start(): clean up background thread on observe failure instead of leaking it. 4. performOnEventThread: return Bool so callers know if the block was enqueued. AutoScrollTransformer and GestureButtonTransformer Logitech handlers return false on failure, falling back to synthetic button. ButtonActionsTransformer returns true when a mapping matched (matching is synchronous, execution is best-effort). 5. EventTransformerManager.autoScrollTransformer(for:): dispatch deactivation to event thread via deactivateAutoScrollOnEventThread() so Timer.invalidate() runs on the correct thread. 6. SmoothedScrollingTransformer/AutoScrollTransformer: add deinit to invalidate timers on the event thread when released by cache clear, preventing orphaned timers on the RunLoop.
1. GlobalEventTap.stop() now calls EventTransformerManager.resetForRestart() to clear the transformer cache before stopping the RunLoop. This prevents stale transformer instances (with timers bound to the old RunLoop) from being reused after a stop/start cycle triggered by settings changes. 2. ButtonActionsTransformer.handleLogitechControlEvent now returns false when the event thread is unavailable, matching the behavior of AutoScrollTransformer and GestureButtonTransformer. This prevents modifier key state asymmetry (stuck keys) when a key-down is processed normally but the key-up arrives during a stop/start window. 3. Extracted findLogitechMapping(for:) as a pure matching method so unit tests can verify mapping logic independently of the event thread.
Consolidate scattered event-thread management into two reusable types:
EventThread: Owns the background Thread + RunLoop lifecycle. Exposes
perform(_:) for cross-thread dispatch and scheduleTimer() for creating
timers on the event thread. Uses an onWillStop callback to decouple
shutdown cleanup from specific consumers (GlobalEventTap no longer
directly calls EventTransformerManager.resetForRestart).
EventThreadTimer: Wraps Timer with thread-safe invalidation. Detects
whether the caller is already on the event thread (synchronous path)
or dispatches to it (cross-thread path). Automatically invalidates
on deinit, eliminating manual cleanup in transformer deinit blocks.
Additional cleanup:
- Merge queueActions/queueLogitechActions in ButtonActionsTransformer
into a single scheduleRepeatActions method using a TimerSlot enum.
- Extract clearCacheUnderLock() in EventTransformerManager to
deduplicate the Combine handler and resetForRestart() logic.
- Replace all manual lock()/unlock() pairs with NSLock.withLock {}.
- Remove GlobalEventTap.processingRunLoop and performOnEventThread
stubs — all callers now use EventThread.shared directly.
stop() now waits for the old event thread to finish (via semaphore) before returning. This eliminates the race where stop(); start() causes the old thread's onWillStop callback to fire after the new thread is already live, wiping freshly created transformers. The wait is safe: onWillStop only uses DispatchQueue.main.async (non-blocking) and NSLock (no deadlock risk with the main thread).
Move the nil-out of thread and runLoop into the CFRunLoopPerformBlock, after onWillStop completes. This ensures isCurrent returns true and EventThreadTimer.invalidate() takes the synchronous path during teardown, instead of silently becoming a no-op.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 12 out of 12 changed files in this pull request and generated 5 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| guard let processingRunLoop = eventThread.runLoop else { | ||
| return | ||
| } | ||
|
|
||
| do { | ||
| observationToken = try EventTap.observe(eventTypes) { [weak self] in self?.callback($1) } | ||
| observationToken = try EventTap.observe( | ||
| eventTypes, | ||
| at: processingRunLoop | ||
| ) { [weak self] in self?.callback($1) } | ||
| } catch { |
There was a problem hiding this comment.
EventTap.observe(... at: processingRunLoop ...) is invoked from GlobalEventTap.start() (main thread), but EventTap.observe installs a CFMachPort source and a Timer onto the passed RunLoop. Installing run-loop sources/timers should be done on that RunLoop’s owning thread; doing it from the main thread can lead to timers not firing or to invalidation/thread-affinity issues. Consider creating the tap from inside EventThread (e.g., performAndWait on the event thread) and using .current there, or change EventTap.observe to enqueue its setup onto the target CFRunLoop via CFRunLoopPerformBlock.
| runLoop.add(healthCheckTimer, forMode: .common) | ||
|
|
||
| return ObservationToken { | ||
| // The lifetime of contextHolder needs to be extended until the observation token is cancelled. | ||
| withExtendedLifetime(contextHolder) { | ||
| healthCheckTimer.invalidate() | ||
| // Timer.invalidate() must be called from the thread where the timer was installed. | ||
| // Dispatch it to the target RunLoop; the remaining teardown calls are thread-safe. | ||
| CFRunLoopPerformBlock(cfRunLoop, CFRunLoopMode.commonModes.rawValue) { | ||
| healthCheckTimer.invalidate() | ||
| } | ||
| CFRunLoopWakeUp(cfRunLoop) |
There was a problem hiding this comment.
observe(... at:) adds healthCheckTimer directly to the provided runLoop, but the cancellation path assumes timer invalidation must occur on the RunLoop’s thread and dispatches invalidate() via CFRunLoopPerformBlock. If observe is called from a different thread than the target RunLoop (as in GlobalEventTap.start), timer creation/scheduling and invalidation will be on different threads, which can violate Timer thread-affinity. It would be safer to schedule both installation (add source/add timer) and teardown on the target CFRunLoop using CFRunLoopPerformBlock, or enforce that observe must be called on the target RunLoop thread (e.g., precondition/assert).
| let mouseLocation = NSEvent.mouseLocation | ||
| DispatchQueue.main.async { [self] in | ||
| handleLogitechControlEventOnMain(context, mouseLocation: mouseLocation) | ||
| } | ||
| return true | ||
| } | ||
|
|
||
| private func handleLogitechControlEventOnMain( | ||
| _ context: LogitechEventContext, | ||
| mouseLocation: NSPoint | ||
| ) { | ||
| if context.isPressed { | ||
| // If already active in toggle mode, deactivate on re-press | ||
| if case let .active(_, _, session) = state, session == .toggle { | ||
| guard hasToggleMode else { | ||
| return | ||
| return true | ||
| } | ||
| deactivate() | ||
| return | ||
| return true | ||
| } | ||
|
|
||
| guard trigger.matches(modifierFlags: context.modifierFlags) else { | ||
| return | ||
| return true | ||
| } | ||
|
|
||
| activate(at: CGPoint(x: mouseLocation.x, y: mouseLocation.y), session: activationSession) | ||
| return | ||
| return true |
There was a problem hiding this comment.
handleLogitechControlEvent now runs on the background event thread, but it still reads NSEvent.mouseLocation. AppKit APIs (including NSEvent) are generally main-thread-only, so this can become undefined behavior/crash once Logitech control events are routed off-main. Prefer a CoreGraphics-based location (e.g., CGEvent(source: nil)?.location) or fetch the mouse location on the main thread and pass it in.
| func scheduleTimer( | ||
| interval: TimeInterval, | ||
| repeats: Bool, | ||
| handler: @escaping () -> Void | ||
| ) -> EventThreadTimer? { | ||
| guard let runLoop else { | ||
| return nil | ||
| } | ||
|
|
||
| let timer = Timer(timeInterval: interval, repeats: repeats) { _ in | ||
| handler() | ||
| } | ||
| runLoop.add(timer, forMode: .common) | ||
| return EventThreadTimer(timer: timer, eventThread: self) | ||
| } |
There was a problem hiding this comment.
scheduleTimer calls runLoop.add(timer, ...) directly. If scheduleTimer is ever called off the event thread, this mutates the event thread’s RunLoop from another thread, which is not guaranteed to be safe. Consider enforcing isCurrent (assert/precondition) or internally routing the timer installation through performAndWait so the timer is always created/added on the event thread.
| func stop() { | ||
| guard let cfRunLoop = runLoop?.getCFRunLoop() else { | ||
| return | ||
| } | ||
|
|
||
| // Queue the willStop callback and CFRunLoopStop via FIFO ordering. | ||
| // All previously queued blocks (e.g. timer invalidations) complete first. | ||
| // thread/runLoop are kept alive until onWillStop finishes so that isCurrent | ||
| // and perform() still work correctly during teardown. | ||
| let done = DispatchSemaphore(value: 0) | ||
| CFRunLoopPerformBlock(cfRunLoop, CFRunLoopMode.commonModes.rawValue) { [weak self] in | ||
| self?.onWillStop?() | ||
| // Clear state after onWillStop so isCurrent was valid during teardown. | ||
| self?.thread?.cancel() | ||
| self?.thread = nil | ||
| self?.runLoop = nil | ||
| } | ||
| CFRunLoopPerformBlock(cfRunLoop, CFRunLoopMode.commonModes.rawValue) { | ||
| CFRunLoopStop(cfRunLoop) | ||
| done.signal() | ||
| } | ||
| CFRunLoopWakeUp(cfRunLoop) | ||
|
|
||
| // Wait for the event thread to finish. The teardown callback only posts | ||
| // non-blocking work back to the main queue. | ||
| done.wait() | ||
| } |
There was a problem hiding this comment.
EventThread.stop() blocks on done.wait(). If stop() is ever invoked from the event thread itself, this will deadlock because the queued CFRunLoopPerformBlock blocks cannot run while the thread is waiting. Add a guard/precondition against calling stop() when isCurrent == true, or provide an async stop path for that case.
#1148 moved event processing to a background thread, but several hot paths still touched AppKit APIs that assert on the main thread. Those crash under normal use. Affected APIs and replacements: - `NSEvent.characters` (KeyCodeResolver.updateMapping): now runs on the main thread via DispatchQueue.main.sync at init, with an NSLock guarding mapping reads/writes from the event thread. - `NSEvent.keyRepeatDelay/Interval`: read once on the main thread into KeyboardSettingsSnapshot; the event thread reads the snapshot. - `NSWorkspace.shared.frontmostApplication`: replaced with FrontmostApplicationTracker, which self-subscribes to didActivateApplicationNotification on the main thread. - `NSWindow.windowNumber(at:)`: replaced with CGPoint.topmostWindowOwnerPid in WindowInfo.swift, filtered to `kCGWindowLayer == 0` so overlays (menu bar, Dock, status-bar panels, the auto-scroll indicator, and other apps' HUDs) don't take precedence over the normal application window under the cursor. - `NSRunningApplication(processIdentifier:)` in pid_t extensions: replaced with `proc_pidpath` / `proc_name` syscalls plus a local bundle walk to resolve `bundleIdentifier` from the executable path. - `NSEvent.mouseLocation` / `NSScreen.main` in PointerRedirectsToScrollTransformer: replaced with `event.location`, which is already in CG global coordinates. KeySimulator now wraps its public API with an NSLock so flags cannot be mutated and read concurrently by the event thread. Tests: - Off-main-thread process-metadata access - Off-main-thread snapshot reads for the tracker and keyboard timings - KeySimulator init from a background thread
- Restore AppKit bottom-left coordinates in LogitechEventContext. #1148 replaced `NSEvent.mouseLocation` with `CGEvent.location` (top-left), but `AutoScrollTransformer.activate(at:)` and its indicator still expect unflipped screen coordinates. Convert with `CGDisplayBounds(CGMainDisplayID())` so a Logitech-triggered auto scroll starts at the correct anchor. - Add a single-entry window-bounds cache to CGPoint.topmostWindowOwnerPid. The pre-refactor code kept a CGWindowID->pid LRU; scanning the entire window list on every tapped event regresses input latency on desktops with many windows. Reusing the last (bounds, pid) turns the common case (cursor inside the same window) into a single contains check.
## Summary #1148 moved event processing to a dedicated background thread, but several hot paths still call AppKit APIs that assert on the main thread. They crash under normal use, and per-app scheme matching can resolve to the wrong application. This PR routes each of those call sites to a thread-safe equivalent. While here, also fixes two unrelated test-side bugs that surfaced during this work: KeyKit and InputReportHandler tests were posting real key/mouse events into the OS without matching releases, leaving WindowServer with stuck mouse buttons that broke left-click and middle-drag in apps like Figma after every `make test`. ## Thread-safety fixes | Main-thread-only API | Replacement | |---|---| | `NSEvent.characters` in `KeyCodeResolver.updateMapping` | `DispatchQueue.main.sync` at init; an `NSLock` guards mapping reads/writes from the event thread. | | `NSEvent.keyRepeatDelay` / `keyRepeatInterval` | `KeyboardSettingsSnapshot`: refreshed on the main thread at launch and on session activation; the event thread reads the snapshot. | | `NSWindow.windowNumber(at:)` in `MouseEventView` / Logitech | `CGPoint.topmostWindowOwnerPid` (see `WindowInfo.swift`). Uses `CGWindowListCopyWindowInfo`, skips overlays (menu bar, Dock, status-bar panels, click-through HUDs, LinearMouse's own auto-scroll indicator) so they don't hijack per-app matching. | | `NSEvent.mouseLocation` / `NSScreen.main` in `PointerRedirectsToScrollTransformer` | `event.location` (CG global coordinates), no display lookup needed. | | Concurrent access to `KeySimulator.flags` | `NSLock` (via `withLock`) around the public API. Behavior is otherwise unchanged. | `pid_t.bundleIdentifier` / `processPath` / `processName` and `NSWorkspace.shared.frontmostApplication` stay as direct calls — `NSRunningApplication` is documented thread-safe, `NSWorkspace.frontmostApplication` benchmarks at ~150 ns per call (LaunchServices IPC, no AppKit run-loop dependency), and major macOS open-source tools (AltTab, Rectangle, Karabiner-Elements) call them off-main without issue. Also rolls back a couple of regressions from the initial Copilot rewrite of `KeySimulator`: no more reference-counted modifier state, no synthetic key-up on `deactivate()`, and the `static` shared `KeySimulator` is restored in `ButtonActionsTransformer` / `ModifierActionsTransformer` so a mapped action doesn't instantiate a new `KeyCodeResolver` per event (which would `DispatchQueue.main.sync` on the event thread). ## Test side-effect fixes - **`InputReportHandler` tests posted real mouse-button-down events for buttons 3/4 to `cghidEventTap`, never the matching up.** WindowServer would treat those buttons as held — Figma's left-click and middle-drag (and similar in other apps) stayed broken until something else released them. Refactored `GenericSideButtonHandler` / `KensingtonSlimbladeHandler` to take an injected `MouseButtonEmitter` (default = `SyntheticMouseButtonEventEmitter.post`); tests now assert against a captured emission list instead of touching the OS. - **`postSymbolicHotKey` posted a key event with the modifier flags field set, but no matching `flagsChanged` to release them.** The kernel's global modifier state could stick (Control still appearing held until a real keystroke cleared it). Now bookended with explicit `flagsChanged` events using each modifier's virtual key, mirroring a real keyboard. - **`KeyKitTests` that genuinely post real system events** (`testPressKey`, `testPostSymbolicHotKey`, `testPostSystemDefinedKey`) are gated behind `RUN_INTEGRATION_TESTS=1` so day-to-day `make test` is side-effect free. ## Tests - `testKeyRepeatTimingCanBeReadOffMainThreadAfterMainThreadRefresh` — `KeyboardSettingsSnapshot` reads safe off-main. - `testKeySimulatorInitializesOffMainThread` — guards against reintroducing the main-thread-assert regression inside `KeyCodeResolver.init`. - New `InputReportHandler` coverage for button-release transitions; existing tests updated to use the injected emitter. - 144+ existing unit tests continue to pass. ## Test plan - [x] `make test` (no system side effects) - [x] `RUN_INTEGRATION_TESTS=1 make test` (KeyKit integration tests pass without leaving stuck modifier state) - [x] `swiftformat --lint .` - [ ] Manual: heavy scroll input does not stall UI (regression check for #1148). - [ ] Manual: per-app rules apply while hovering over the target app (Figma: *Auto Scroll off* stays off; per-app button mappings fire). - [ ] Manual: button mappings repeat using the configured repeat delay/interval. - [ ] Manual: Logitech HID++ control buttons still route to the expected actions after app switch. - [ ] Manual: session lock/unlock cycle keeps event tap, trackers, and pointer-speed updates working.
Summary
This PR moves mouse event processing off the main thread so the UI stays responsive under heavy input.
It does that by running the
CGEventtap, Logitech control-button handling, and event-driven timers on the same dedicated background thread with its own RunLoop.What changed
CGEventtap to a dedicated background event thread.Why this structure
The main goal is to avoid blocking the UI without paying a large thread-safety tax.
Instead of spreading locks and cross-thread state management across individual transformers, this change centralizes mutable event-processing state on one background thread. That keeps the concurrency model easier to reason about and keeps the code closer to the original complexity level.
Expected outcome
Test plan
xcodebuild buildsucceeds