Repository navigation
Fix event-thread crashes and per-app matching after #1148 - #1154
Merged
Merged
Conversation
#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
force-pushed
the
fix/event-thread-appkit-crashes
branch
from
April 18, 2026 14:32
2ad4f70 to
7ff8911
Compare
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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
NSEvent.charactersinKeyCodeResolver.updateMappingDispatchQueue.main.syncat init; anNSLockguards mapping reads/writes from the event thread.NSEvent.keyRepeatDelay/keyRepeatIntervalKeyboardSettingsSnapshot: refreshed on the main thread at launch and on session activation; the event thread reads the snapshot.NSWindow.windowNumber(at:)inMouseEventView/ LogitechCGPoint.topmostWindowOwnerPid(seeWindowInfo.swift). UsesCGWindowListCopyWindowInfo, 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.maininPointerRedirectsToScrollTransformerevent.location(CG global coordinates), no display lookup needed.KeySimulator.flagsNSLock(viawithLock) around the public API. Behavior is otherwise unchanged.pid_t.bundleIdentifier/processPath/processNameandNSWorkspace.shared.frontmostApplicationstay as direct calls —NSRunningApplicationis documented thread-safe,NSWorkspace.frontmostApplicationbenchmarks 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 ondeactivate(), and thestaticsharedKeySimulatoris restored inButtonActionsTransformer/ModifierActionsTransformerso a mapped action doesn't instantiate a newKeyCodeResolverper event (which wouldDispatchQueue.main.syncon the event thread).Test side-effect fixes
InputReportHandlertests posted real mouse-button-down events for buttons 3/4 tocghidEventTap, 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. RefactoredGenericSideButtonHandler/KensingtonSlimbladeHandlerto take an injectedMouseButtonEmitter(default =SyntheticMouseButtonEventEmitter.post); tests now assert against a captured emission list instead of touching the OS.postSymbolicHotKeyposted a key event with the modifier flags field set, but no matchingflagsChangedto release them. The kernel's global modifier state could stick (Control still appearing held until a real keystroke cleared it). Now bookended with explicitflagsChangedevents using each modifier's virtual key, mirroring a real keyboard.KeyKitTeststhat genuinely post real system events (testPressKey,testPostSymbolicHotKey,testPostSystemDefinedKey) are gated behindRUN_INTEGRATION_TESTS=1so day-to-daymake testis side-effect free.Tests
testKeyRepeatTimingCanBeReadOffMainThreadAfterMainThreadRefresh—KeyboardSettingsSnapshotreads safe off-main.testKeySimulatorInitializesOffMainThread— guards against reintroducing the main-thread-assert regression insideKeyCodeResolver.init.InputReportHandlercoverage for button-release transitions; existing tests updated to use the injected emitter.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 .