Skip to content

Fix event-thread crashes and per-app matching after #1148 - #1154

Merged
lujjjh merged 7 commits into
mainfrom
fix/event-thread-appkit-crashes
Apr 19, 2026
Merged

lujjjh merged 7 commits into
mainfrom
fix/event-thread-appkit-crashes

Conversation

@lujjjh

@lujjjh lujjjh commented Apr 18, 2026 •

Copy link
Copy Markdown
Collaborator

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

  • make test (no system side effects)
  • RUN_INTEGRATION_TESTS=1 make test (KeyKit integration tests pass without leaving stuck modifier state)
  • swiftformat --lint .
  • Manual: heavy scroll input does not stall UI (regression check for Keep mouse event handling off the main thread #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.

lujjjh added 3 commits April 18, 2026 21:14
#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
- Preserve full executable name in `pid_t.processName` by deriving it
  from `processPath` instead of `proc_name()`, which truncates at
  `MAXCOMLEN` (16 bytes) and would break matches like
  `if.processName: "Google Chrome Helper"`. The `getProcessName` shim
  in `Process.m/h` is removed.
- Drop `FrontmostApplicationTracker`'s self-subscription and expose
  `update(with:)` + `prime()` instead. Callers in `DeviceManager` and
  `LogitechReprogrammableControlsMonitor` now extract the activated
  application from the notification and update the snapshot before
  acting on it, eliminating the observer-ordering race that could
  leave `updatePointerSpeed()` / Logitech reconfiguration reading the
  previous app's pid.
Without re-priming, PID-based scheme matching can apply the pre-lock
app's rules for the first events after unlock if no activation
notification fires during the stop/start cycle.
@lujjjh
lujjjh force-pushed the fix/event-thread-appkit-crashes branch from 2ad4f70 to 7ff8911 Compare April 18, 2026 14:32
lujjjh added 4 commits April 18, 2026 22:37
NSRunningApplication(processIdentifier:) and its static metadata
properties (bundleIdentifier, executableURL) query LaunchServices
without touching the main run loop, so they're safe to call off-main
even though Apple's docs generically suggest main-thread use. That
avoids the proc_pidpath shim and the hand-rolled bundle-path walk
added earlier in this branch.

NSEvent.characters, NSEvent.keyRepeatDelay/Interval and
NSWindow.windowNumber(at:) are the APIs that actually assert or race
on the event thread; those fixes stay in place.
InputReportHandler unit tests were calling `simulateButtonEvent` directly,
which posted real `otherMouseDown` events for buttons 3/4 to `cghidEventTap`
without ever sending the matching `otherMouseUp`. WindowServer would then
treat those buttons as held, breaking left-click and middle-drag in apps
like Figma until the buttons were explicitly released.

Refactor the side-button handlers to take an injected `MouseButtonEmitter`
(default = `SyntheticMouseButtonEventEmitter.post`) so tests can capture
emissions against a recorder and assert on them without touching the OS.
Add coverage for button-release transitions while we're here.

Also harden `postSymbolicHotKey`: post explicit `flagsChanged` events that
mirror a real keyboard's modifier press/release sequence so the kernel's
global modifier state can't get stuck after the synthetic hotkey. Gate the
remaining KeyKit tests that genuinely post system events behind
`RUN_INTEGRATION_TESTS=1`.
`NSWorkspace.shared.frontmostApplication` is documented thread-safe and
benchmarks at ~150 ns per call (vs ~90 ns for the locked snapshot read),
so the tracker buys ~60 ns per event — well under 0.01% CPU even at
1000 events/sec. Not worth a singleton + two callsites that have to
remember to keep it in sync.

Reverts the indirection and reads `frontmostApplication` directly.
@lujjjh
lujjjh merged commit 2f90965 into main Apr 19, 2026
1 check passed
@lujjjh
lujjjh deleted the fix/event-thread-appkit-crashes branch April 19, 2026 03:50
lujjjh added a commit that referenced this pull request Apr 19, 2026
The UCKeyTranslate-based rewrite added in this branch was originally
motivated by getting off main thread, but `TISCopyCurrentKeyboardLayoutInputSource`
and `TISGetInputSourceProperty` turned out to need main thread too —
which puts the new implementation on the same footing as the old one
thread-safety-wise.

Without that win the new code only buys an ASCII-layout fallback for
IME-only sources (Pinyin, Kotoeri, etc.), which doesn't justify the
extra ~60 lines and the subtle behavior changes (e.g. blanket
`.lowercased()`). Restore the simpler `NSEvent.characters`-based path
and keep the main-thread wrapper from #1154.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant