Skip to content

Fix gesture button not releasing trigger, causing stuck drag - #1142

Merged
lujjjh merged 3 commits into
linearmouse:mainfrom
diosmiodio:main
Apr 17, 2026
Merged

lujjjh merged 3 commits into
linearmouse:mainfrom
diosmiodio:main

Conversation

@diosmiodio

@diosmiodio diosmiodio commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

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

linearmouse_drag_broken_post_gesture.mov

After (fix) — drag works after gesture

linearmouse_drag_fix_post_gesture.mov

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

  • Enable gesture button with middle button as trigger
  • Perform a gesture (hold trigger + swipe up for Mission Control)
  • Verify trigger button is released after the gesture completes
  • Verify drag operations work in apps after performing a gesture
  • Verify gestures still fire correctly after multiple uses (no use-after-free)
  • Verify cooldown still prevents accidental re-triggers
  • 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)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a macOS stuck-button condition in GestureButtonTransformer where a trigger button mouseUp could be consumed during the gesture cooldown, leaving the OS/app believing the button remained pressed (e.g., stuck drag / persistent context menus).

Changes:

  • Skip re-processing LinearMouse-generated synthetic events in transform(_:) to avoid re-entrance loops.
  • During cooldown, detect trigger-button mouseUp and post a synthetic release event instead of silently consuming it.
  • Add a helper to synthesize and post a trigger-button mouseUp via .cgSessionEventTap.
Comments suppressed due to low confidence (1)

LinearMouse/EventTransformer/GestureButtonTransformer.swift:209

  • releaseTriggerButton(from:) is invoked in the .triggered branch of handleButtonUp, but handleDragged sets state = .triggered and then immediately overwrites it with .cooldown(...), so .triggered is never observed here. Consider removing the .triggered state/branch or adjusting the state transitions so this branch is reachable (otherwise this call is misleading dead code).
        // If we triggered, stay in cooldown and consume the event
        if case .triggered = state {
            releaseTriggerButton(from: event)
            let cooldownNanos = UInt64(cooldownMs) * 1_000_000
            state = .cooldown(until: DispatchTime.now().uptimeNanoseconds + cooldownNanos)
            return nil
        }

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 55 to 67
// Check if we're in cooldown
if case let .cooldown(until) = state {
if DispatchTime.now().uptimeNanoseconds < until {
// Still in cooldown - consume our button events
if matchesTriggerButton(event) {
// os_log("Event consumed during cooldown", log: Self.log, type: .debug)
if event.type == mouseUpEventType {
os_log("Releasing trigger button during cooldown", log: Self.log, type: .debug)
releaseTriggerButton(from: event)
state = .idle
} else {
os_log("Event consumed during cooldown", log: Self.log, type: .debug)
}
return nil

Copilot AI Apr 11, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the cooldown path, state is set back to .idle when a trigger-button mouseUp arrives. This ends the configured cooldown early, so subsequent trigger presses can re-enter tracking immediately (and the rest of the cooldown window will no longer suppress re-triggers). If the intent is to keep cooldown semantics after a gesture, keep state in .cooldown(until: ...) and only synthesize the release; optionally track that the release has already been posted to avoid duplicate releases.

Copilot uses AI. Check for mistakes.

@lujjjh lujjjh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the contribution!


extension GestureButtonTransformer: EventTransformer {
func transform(_ event: CGEvent) -> CGEvent? {
if event.isLinearMouseSyntheticEvent {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This guard looks too broad. isLinearMouseSyntheticEvent is not only used for the synthetic mouse up posted by this transformer, but also for other LinearMouse-generated events such as device-layer synthetic button events. Gesture triggers may legitimately rely on those events, so this early return could bypass valid trigger input.

A safer fix would be either to replace this shared boolean with a more specific synthetic event kind, or to avoid reposting entirely and return the release event directly here instead of post(...) + nil.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Of course makes sense, when I get some time I’ll put up another update and let you know :)

@chaotianshao

Copy link
Copy Markdown

@diosmiodio Thank you for fixing the bug!

When you have a moment, could you please merge the fix? It would really help me out.

Much appreciated!

diosmiodio added a commit to diosmiodio/linearmouse that referenced this pull request Apr 16, 2026
…t guard and preserve cooldown

- Remove isLinearMouseSyntheticEvent guard that would block legitimate
  synthetic button events from InputReportHandler (e.g. Kensington, generic
  side button devices). Instead, return the release event directly from
  transform() via makeTriggerButtonRelease(), eliminating re-entrance
  without filtering unrelated synthetic events.

- Preserve cooldown semantics by keeping state as .cooldown(until:, released:)
  on mouseUp instead of resetting to .idle, so the full cooldown window
  still suppresses re-triggers. Track whether release has been posted to
  avoid duplicate releases.
@diosmiodio
diosmiodio marked this pull request as draft April 16, 2026 21:14
…ouse#1138)

The GestureButtonTransformer passed mouseDown through to apps but consumed
mouseUp during cooldown after a gesture fired. This left macOS believing
the button was still pressed, breaking drag operations in apps like Todoist.

Fix: post a synthetic mouseUp (via cgSessionEventTap) when consuming the
real mouseUp during cooldown or in the triggered state. An explicit
isLinearMouseSyntheticEvent guard prevents re-entrance. The Logitech HID++
path also now clears state on button release during cooldown.
…ng synthetic release

Address PR review feedback:

1. Remove overly broad `isLinearMouseSyntheticEvent` guard that would block
   legitimate synthetic button events from InputReportHandler (Kensington,
   generic side buttons).

2. Preserve full cooldown window on mouseUp instead of resetting to `.idle`
   early — track `released: Bool` in cooldown state so rapid re-presses are
   still suppressed.

3. Return the original mouseUp event (tagged with `isGestureCleanupRelease`)
   instead of creating a new CGEvent via `makeTriggerButtonRelease()`.
   Creating a new event and returning it through the event tap callback
   caused a use-after-free: `Unmanaged.passUnretained` in EventTap.swift
   does not retain the returned event, so ARC releases the new CGEvent
   after the callback returns, leaving macOS with a dangling pointer that
   disables the event tap entirely.

4. Add `isGestureCleanupRelease` flag (dedicated sentinel on
   eventSourceUserData) so downstream transformers (ButtonActionsTransformer,
   UniversalBackForwardTransformer) pass the cleanup release through without
   firing mapped actions or consuming the event.
@diosmiodio

diosmiodio commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor Author

Updated the PR addressing both review comments (broad isLinearMouseSyntheticEvent guard + early cooldown termination). Rebased onto latest main and conflicts resolved cleanly.

However, after rebasing I'm hitting a crash that reproduces on latest main without my changes. The culprit appears to be #1148.

Crash

https://www.icloud.com/iclouddrive/0d1G683o5yKNYdqiP3r3khnhw#LinearMouse-2026-04-16-163919

Investigation

ButtonActionsTransformer has a lazily-initialized static:

// ButtonActionsTransformer.swift:25
static let keySimulator = KeySimulator()

KeySimulator.init() creates a KeyCodeResolver, whose init() calls updateMapping() which iterates key codes and accesses NSEvent.characters:

// KeyCodeResolver.swift:52
guard let characters = nsEvent.characters, characters.count == 1 else {
    continue
}

NSEvent.characters internally asserts it's called on the main queue. Before #1148, the event tap ran on the main thread, so this was fine. After #1148, the tap runs on com.linearmouse-event-thread (background). The first key event to reach ButtonActionsTransformer.transform() triggers the lazy static init → NSEvent.characters on the wrong thread → _dispatch_assert_queue_fail.

The same pattern exists in ModifierActionsTransformer.swift:82 which creates a KeySimulator() inline during zoom handling.

Repro

  1. Use latest main (commit f638ffd)
  2. Configure any button mapping
  3. Press a key (probably a couple) → crash

@diosmiodio

Copy link
Copy Markdown
Contributor Author

@diosmiodio Thank you for fixing the bug!

When you have a moment, could you please merge the fix? It would really help me out.

Much appreciated!

@diosmiodio diosmiodio closed this Apr 17, 2026
@diosmiodio diosmiodio reopened this Apr 17, 2026
@diosmiodio

diosmiodio commented Apr 17, 2026 •

Copy link
Copy Markdown
Contributor Author

@chaotianshao, I zipped up my .app that I'm running locally in case you want to work with that until this gets merged and other bugs/crashes that are on main get fixed.

https://www.icloud.com/iclouddrive/040WiyGeKZMAwpJc0IOyXfi6Q#LinearMouse-Dev

You'll need to right click -> open since I didn't sign this application

@diosmiodio
diosmiodio marked this pull request as ready for review April 17, 2026 00:03
@lujjjh
lujjjh merged commit b3cac7f into linearmouse:main Apr 17, 2026
1 check passed
@lujjjh

lujjjh commented Apr 17, 2026

Copy link
Copy Markdown
Collaborator

Thanks! I’ll fix the crashes later.

@chaotianshao

Copy link
Copy Markdown

Thank you @diosmiodio and @lujjjh for fixing the bug and closing the issue. Really appreciate it!

@lujjjh lujjjh added the bug Something isn't working label Apr 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Gesture button click is not released

4 participants