Repository navigation
Fix event tap use-after-free when callback returns a copied CGEvent - #1143
Merged
Merged
Conversation
When a transformer (e.g. SmoothedScrollingTransformer) returns a copy of the event instead of the original, `Unmanaged.passUnretained` caused the copy to be deallocated by ARC before the system could use it. This led to "Invalid event returned by callback" and the event tap being silently disabled, breaking all event processing (e.g. reverse scrolling). Fix: use `passRetained` when the returned event differs from the original, transferring ownership to the system per the CGEventTapCallBack contract. Also add a periodic health check that re-enables the tap if it is found disabled, as a defensive recovery for any remaining edge cases.
lujjjh
force-pushed
the
fix/event-tap-copy-memory-management
branch
from
April 11, 2026 07:12
7683044 to
918b455
Compare
7 of 9 tasks
lujjjh
pushed a commit
that referenced
this pull request
Apr 17, 2026
## Problem Fixes #1138 After a gesture fires (e.g., Mission Control swipe), the trigger button's `mouseUp` event is consumed during cooldown but no release is ever posted. This leaves macOS believing the button is permanently pressed, causing: - **Stuck dragging** in apps like Todoist - **Persistent right-click menus** if right-click is the trigger - **Continuous scrolling** or other unwanted behavior - Quitting LinearMouse immediately resolves the issue Reproduced with Logitech MX Master 3 on macOS 26.x, but affects any mouse using the gesture button feature. ## Root Cause The state machine in `GestureButtonTransformer` has an asymmetry between mouseDown and mouseUp handling: 1. `handleButtonDown` **passes mouseDown through** to the app → app sees "button pressed" 2. `handleDragged` consumes drag events while tracking gesture movement 3. Gesture threshold met → gesture executes → state enters `.cooldown` 4. User releases button → **cooldown guard consumes mouseUp** (`return nil`) 5. `handleButtonUp` is **never reached** 6. App never sees the button release → **button stuck** ## Fix Tag and return the **original** mouseUp event from `transform()` instead of consuming it or creating a new event. ### Key design decisions **Tag original event, don't create a new one:** The initial approach (commit `22fe756`) used `releaseTriggerButton()` to create a new `CGEvent` and post it via `CGEvent.post()`. Review feedback identified two problems: (1) the `isLinearMouseSyntheticEvent` guard needed to prevent re-entrance was too broad, and (2) creating new events risks the `Unmanaged.passUnretained` use-after-free fixed in #1143. This commit tags the original event (which the framework already retains) with `isGestureCleanupRelease` and returns it directly — no re-entrance possible, no ownership issues. **Preserve cooldown on release:** The cooldown state now tracks `released: Bool` instead of resetting to `.idle` on mouseUp. This preserves the full cooldown window so rapid re-presses are still suppressed. **Dedicated cleanup flag:** The returned mouseUp flows through the transformer pipeline into `ButtonActionsTransformer` and `UniversalBackForwardTransformer`. Without protection, a completed gesture on a shared trigger button would also fire the mapped action on release. A dedicated `isGestureCleanupRelease` flag (separate from the generic `isLinearMouseSyntheticEvent`) lets those transformers pass the event through without firing actions. ## Changes - **`GestureButtonTransformer.swift`**: Remove `isLinearMouseSyntheticEvent` guard. Return original mouseUp tagged with `isGestureCleanupRelease` instead of creating a new event. Track `released` in cooldown state. Remove `releaseTriggerButton()` method. - **`CGEvent+LinearMouseSynthetic.swift`**: Add `isGestureCleanupRelease` flag with dedicated sentinel value (`0x4745_5354_5552`). - **`ButtonActionsTransformer.swift`**: Pass through gesture cleanup releases without firing mapped actions. - **`UniversalBackForwardTransformer.swift`**: Pass through gesture cleanup releases without consuming them. ## Evidence ### Before (broken) — drag fails after gesture https://github.com/user-attachments/assets/be2c675c-2a81-49cb-9806-0cd7111b37d1 ### After (fix) — drag works after gesture https://github.com/user-attachments/assets/0c095708-2779-4118-969b-848ca28cc150 ## Pre-existing issues (not regressions) These are pre-existing issues with the "shared trigger" case (same button used for both gesture trigger and button mapping) that predate this PR: - **Modifier-hold cleanup on gesture completion:** When a gesture fires on a button that also has a modifier-hold mapping, `keySimulator.up()` is never called because the mouseUp was consumed during cooldown (even before this PR). This leaves modifier keys stuck. - **Repeat timer cleanup:** Similarly, repeat-enabled mappings sharing the gesture trigger don't get their timer invalidated on gesture completion. - **UniversalBackForward conflict on mouseDown:** If a back/forward button is used as a gesture trigger with `universalBackForward` enabled, the mouseDown still fires a navigation swipe immediately (before gesture tracking begins). - **Dead `.triggered` state:** The `.triggered` state is set and immediately overwritten by `.cooldown` in the same synchronous call, so `handleButtonUp` never observes it. Could be removed as cleanup. ## Test plan - [x] Enable gesture button with middle button as trigger - [x] Perform a gesture (hold trigger + swipe up for Mission Control) - [x] Verify trigger button is released after the gesture completes - [x] Verify drag operations work in apps after performing a gesture - [x] Verify gestures still fire correctly after multiple uses (no use-after-free) - [x] Verify cooldown still prevents accidental re-triggers - [x] Verify normal click behavior when gesture doesn't fire (release before threshold) - [ ] Test with Logitech MX Master 3 using HID++ diverted gesture button - [ ] If using a Kensington Slimblade or generic side-button mouse, verify gesture triggers still work (synthetic button source)
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
EventTap.callbackInvokerwhen a transformer returns a copy of the CGEvent instead of the original.Unmanaged.passUnretainedcaused ARC to deallocate the copy before the system could use it, resulting in "Invalid event returned by callback" and the event tap being silently disabled.passRetainedwhen the returned event is a different object (detected via===), transferring ownership to the caller per theCGEventTapCallBackcontract. KeeppassUnretainedfor the original event to avoid leaks.Context
When horizontal smoothed scrolling is enabled and a scroll event contains both horizontal and vertical deltas (e.g. M720 Triathlon scroll wheel tilted during fast scrolling),
SmoothedScrollingTransformerintercepts the horizontal component and returns aCGEvent.copy()with the horizontal delta zeroed out. This copy was returned viapassUnretained, leading to a dangling pointer that macOS detected as invalid, disabling the event tap and breaking all event processing (reverse scrolling, linear scrolling, etc.) until app restart.Test plan