Compare commits

...
10 Commits
  • Remove the build copy after installing
    Spotlight indexed build/mxd.app, and opening it from there started a
    second mxd alongside the installed one.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Wait for launchd to release mxd before reinstalling
    launchctl bootout returns while mxd is still restoring its buttons, so
    an immediate bootstrap failed with "5: Input/output error". Poll for up
    to 10 s until the service is gone.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Default SIGN_ID to the mxd certificate
    Keep the signing identity in the Makefile rather than in shell config.
    A Mac without the certificate fails at signing, before the running mxd
    is stopped. Override with SIGN_ID=- for ad-hoc signing.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Package mxd as an app bundle
    A loose binary can't have a name or icon, so permission lists, Login
    Items and Activity Monitor showed it bare. mxd.app fixes that, and the
    source stays one Swift file.
    
    mxd.icns is committed so Macs without Icon Composer can build. It's
    rendered from mxd.icon by ictool, because compiling the .icon into an
    Assets.car needs actool from full Xcode. The icon is therefore static,
    with no dark or tinted variants.
    
    make install replaces the manual steps. SIGN_ID selects the signing
    identity: ad-hoc by default, which ties grants to the build's hash.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Add app icon
    Created in Icon Composer.
    
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Remove all code comments
    The code should explain itself. Decisions live in commit messages.
    
    Build: swiftc -O -swift-version 5 mxd.swift -o mxd
           codesign -s - mxd
    Run under launchd, so macOS charges the permissions to mxd rather than
    to a terminal. Each rebuild needs a re-grant and a restart.
    
    Comment removal only: code tokens are unchanged.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Reverse the Spaces swipe direction
    Pulling left now brings in the desktop on the right, and pulling right
    the one on the left, like dragging the desktop.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Detect a dead scroll tap from a background watchdog
    The revocation guard never fired: scroll events stalled about 10 s and
    mxd kept running without logging. Either AXIsProcessTrusted stayed true
    in the running process or the main thread was stuck.
    
    Check every 500 ms from a background queue, so a stuck main thread
    can't stop the check. Also watch the outcome instead of trusting the
    permission API alone: the HID scroll counter advancing without events
    reaching the tap for 2 s, the tap staying disabled for 2 s, and two
    timeouts within 30 s. Log which signal fired.
    
    A hard _exit deadline is set first, in case removing the tap blocks.
    Revocation exits 0 so launchd stays down. A stall exits 1, so a false
    positive costs only a restart, and a real revocation leaves mxd idle
    because tapCreate fails.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Fire App Exposé on slide down while held
    Press the thumb button and slide down, and App Exposé fires as soon as
    the slide crosses the threshold, once per hold. The release then does
    nothing. Left, right, up and tap still act on release.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
  • Add app ignore list and ~/.config/mxd
    Read glideIntensity and ignoredApps from a JSON file at ~/.config/mxd,
    written with defaults if missing. An existing path is never modified,
    and a bad file falls back to defaults. Read once at startup.
    
    While an ignored app is the scroll target, its notches pass through
    untouched. While one is frontmost, the buttons are undiverted, so it
    gets real mouse buttons and a thumb hold doesn't freeze the pointer.
    
    Default to NVIDIA GeForce Now, under both its long name and the name
    it is believed to report on macOS. That name is unconfirmed, as the
    app isn't installed where this was written.
    
    Assisted-by: Claude Sonnet 5.5
    Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
8 changed files with 377 additions and 152 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
build/
+26
View File
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>mxd</string>
<key>CFBundleDisplayName</key>
<string>mxd</string>
<key>CFBundleIdentifier</key>
<string>dev.yigid.mxd</string>
<key>CFBundleExecutable</key>
<string>mxd</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleIconFile</key>
<string>mxd</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>LSUIElement</key>
<true/>
</dict>
</plist>
+52
View File
@@ -0,0 +1,52 @@
SIGN_ID ?= mxd
ICTOOL ?= /Applications/Icon Composer.app/Contents/Executables/ictool
LABEL = dev.yigid.mxd
BUILD_DIR = build
BUNDLE = $(BUILD_DIR)/mxd.app
ICONSET = $(BUILD_DIR)/mxd.iconset
INSTALLED_BUNDLE = $(HOME)/Applications/mxd.app
LAUNCH_AGENT = $(HOME)/Library/LaunchAgents/$(LABEL).plist
.PHONY: app icon install uninstall clean
app:
mkdir -p $(BUILD_DIR)
swiftc -O -swift-version 5 mxd.swift -o $(BUILD_DIR)/mxd
rm -rf $(BUNDLE)
mkdir -p $(BUNDLE)/Contents/MacOS $(BUNDLE)/Contents/Resources
cp Info.plist $(BUNDLE)/Contents/Info.plist
cp $(BUILD_DIR)/mxd $(BUNDLE)/Contents/MacOS/mxd
cp mxd.icns $(BUNDLE)/Contents/Resources/mxd.icns
codesign --force --sign "$(SIGN_ID)" --identifier $(LABEL) $(BUNDLE)
icon:
rm -rf $(ICONSET)
mkdir -p $(ICONSET)
for base in 16 32 128 256 512; do \
for scale in 1 2; do \
canvas=$$((base * scale)); \
tile=$$(( (canvas * 824 + 512) / 1024 )); \
if [ $$scale -eq 1 ]; then name=icon_$${base}x$${base}.png; else name=icon_$${base}x$${base}@2x.png; fi; \
"$(ICTOOL)" mxd.icon --export-image --output-file $(ICONSET)/$$name --platform macOS --rendition Default --width $$tile --height $$tile --scale 1 > /dev/null || exit 1; \
sips --padToHeightWidth $$canvas $$canvas $(ICONSET)/$$name > /dev/null || exit 1; \
done; \
done
iconutil --convert icns --output mxd.icns $(ICONSET)
install: app
-launchctl bootout gui/$$(id -u)/$(LABEL)
@for attempt in $$(seq 50); do launchctl print gui/$$(id -u)/$(LABEL) >/dev/null 2>&1 || break; sleep 0.2; done
mkdir -p $(HOME)/Applications $(HOME)/Library/LaunchAgents $(HOME)/Library/Logs
rm -rf $(INSTALLED_BUNDLE)
ditto $(BUNDLE) $(INSTALLED_BUNDLE)
rm -rf $(BUNDLE)
sed "s|__HOME__|$(HOME)|g" $(LABEL).plist > $(LAUNCH_AGENT)
launchctl bootstrap gui/$$(id -u) $(LAUNCH_AGENT)
uninstall:
-launchctl bootout gui/$$(id -u)/$(LABEL)
rm -rf $(INSTALLED_BUNDLE)
rm -f $(LAUNCH_AGENT)
clean:
rm -rf $(BUILD_DIR)
+27
View File
@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>dev.yigid.mxd</string>
<key>ProgramArguments</key>
<array>
<string>__HOME__/Applications/mxd.app/Contents/MacOS/mxd</string>
</array>
<key>AssociatedBundleIdentifiers</key>
<array>
<string>dev.yigid.mxd</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<dict>
<key>SuccessfulExit</key>
<false/>
</dict>
<key>ProcessType</key>
<string>Interactive</string>
<key>StandardErrorPath</key>
<string>__HOME__/Library/Logs/mxd.log</string>
</dict>
</plist>
BIN
View File
Binary file not shown.
+31
View File
@@ -0,0 +1,31 @@
<svg width="515" height="720" viewBox="0 0 515 720" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M411.3 548.553V617.178H445.725V582.753H514.35V514.353H479.925V548.553H411.3Z" fill="white"/>
<path d="M445.725 617.174H479.925V685.799H445.725V617.174Z" fill="white"/>
<path d="M445.725 479.927H479.925V514.352H445.725V479.927Z" fill="white"/>
<path d="M411.3 445.726H445.725V479.926H411.3V445.726Z" fill="white"/>
<path d="M377.1 685.8H445.725V720H377.1V685.8Z" fill="white"/>
<path d="M377.1 411.526H411.3V445.726H377.1V411.526Z" fill="white"/>
<path d="M377.1 102.827H411.3V308.477H377.1V102.827Z" fill="white"/>
<path d="M342.9 617.174H377.1V685.799H342.9V617.174Z" fill="white"/>
<path d="M342.9 377.1H377.1V411.525H342.9V377.1Z" fill="white"/>
<path d="M342.9 68.6262H377.1V102.826H342.9V68.6262Z" fill="white"/>
<path d="M308.475 582.748H342.9V617.173H308.475V582.748Z" fill="white"/>
<path d="M308.475 342.9H342.9V377.1H308.475V342.9Z" fill="white"/>
<path d="M308.475 137.252H342.9V274.277H308.475V137.252Z" fill="white"/>
<path d="M308.475 34.2004H342.9V68.6254H308.475V34.2004Z" fill="white"/>
<path d="M274.275 102.827H308.475V137.252H274.275V102.827Z" fill="white"/>
<path d="M274.275 342.899H308.475V308.474H274.275V274.274H240.075V685.799H274.275V651.374H308.475V617.174H274.275V342.899Z" fill="white"/>
<path d="M205.65 274.277V240.077H274.275V171.452H240.075V137.252H171.45V171.452H137.025V240.077H171.45V274.277H205.65Z" fill="white"/>
<path d="M137.025 68.6262H274.275V102.826H137.025V68.6262Z" fill="white"/>
<path d="M102.825 377.1H205.65V411.525H102.825V377.1Z" fill="white"/>
<path d="M137.025 308.474H205.65V342.899H137.025V308.474Z" fill="white"/>
<path d="M102.825 0H308.475V34.2H102.825V0Z" fill="white"/>
<path d="M102.825 274.274H137.025V308.474H102.825V274.274Z" fill="white"/>
<path d="M102.825 102.827H137.025V137.252H102.825V102.827Z" fill="white"/>
<path d="M68.6251 342.9H102.825V377.1H68.6251V342.9Z" fill="white"/>
<path d="M68.6251 137.252H102.825V274.277H68.6251V137.252Z" fill="white"/>
<path d="M68.6251 34.2004H102.825V68.6254H68.6251V34.2004Z" fill="white"/>
<path d="M34.2001 308.474H68.6251V342.899H34.2001V308.474Z" fill="white"/>
<path d="M34.2001 68.6262H68.6251V102.826H34.2001V68.6262Z" fill="white"/>
<path d="M0 102.827H34.2V308.477H0V102.827Z" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 2.3 KiB

+40
View File
@@ -0,0 +1,40 @@
{
"fill" : {
"automatic-gradient" : "display-p3:0.09412,0.24707,0.57666,1.00000"
},
"groups" : [
{
"layers" : [
{
"blend-mode" : "normal",
"fill" : "automatic",
"glass" : true,
"hidden" : false,
"image-name" : "Group-2.svg",
"name" : "icon",
"position" : {
"scale" : 1,
"translation-in-points" : [
0,
0
]
}
}
],
"shadow" : {
"kind" : "neutral",
"opacity" : 0.5
},
"translucency" : {
"enabled" : true,
"value" : 0.3
}
}
],
"supported-platforms" : {
"circles" : [
"watchOS"
],
"squares" : "shared"
}
}
+200 -152
View File
@@ -1,107 +1,100 @@
// mxd.swift — minimal MX Master 3S daemon for macOS: HID++ 2.0 button remapping + smooth scrolling.
// No Logitech software, no dependencies, no network, no updater. One file you can read in 15 minutes.
//
// Build: swiftc -O -swift-version 5 mxd.swift -o mxd
// codesign -s - mxd # ad-hoc sign. The identity is the binary's hash: every rebuild needs a re-grant.
// Run: ./mxd --probe -v # smoke test: prints device name + feature table, changes nothing
// ./mxd -v # run with logging
//
// Permissions (System Settings → Privacy & Security):
// - Input Monitoring: open the HID++ collection on the mouse.
// - Accessibility: post synthetic key/scroll events and install the scroll event tap.
// macOS charges these to whatever launched the process. Started from a terminal, the terminal app
// gets the grant (and with it, keystrokes from every app). Started by launchd, mxd itself gets it.
//
// Secrets: none. No files written, no network.
// Rollback: Ctrl-C / SIGTERM un-diverts buttons and removes the scroll tap (process exit).
// If SIGKILLed, diverted buttons stay dead until the mouse reconnects — flip the
// power switch on the underside. Diverts are volatile; DPI and SmartShift may stay on the mouse.
import Foundation
import AppKit
import IOKit.hid
import CoreGraphics
import ApplicationServices
// MARK: - Actions
let kVK_LeftBracket: CGKeyCode = 0x21, kVK_RightBracket: CGKeyCode = 0x1E
let kVK_Left: CGKeyCode = 0x7B, kVK_Right: CGKeyCode = 0x7C, kVK_Down: CGKeyCode = 0x7D, kVK_Up: CGKeyCode = 0x7E
enum Action {
case missionControl // opens Mission Control.app (public API; doesn't depend on keyboard-shortcut settings)
case appExpose // Ctrl-↓
case prevSpace, nextSpace // Ctrl-← / Ctrl-→
case back, forward // Cmd-[ / Cmd-] (Safari, Finder, Chrome, Arc, Mail…)
case mouseButton(Int) // synthetic "other" mouse button: 3 = button 4 (back), 4 = button 5 (forward)
case missionControl
case appExpose
case prevSpace, nextSpace
case back, forward
case mouseButton(Int)
case shortcut(CGKeyCode, CGEventFlags)
case none
}
// MARK: - Config (edit me)
let CID_BACK: UInt16 = 0x0053, CID_FWD: UInt16 = 0x0056, CID_GESTURE: UInt16 = 0x00C3
// 0x00C4 is the SmartShift (ratchet) button — divertable too, but then the firmware stops toggling ratchet.
struct Config {
// Buttons. Keys are HID++ control IDs; run --probe -v to see what your mouse reports.
var buttons: [UInt16: Action] = [
CID_GESTURE: .missionControl, // thumb rest press
CID_GESTURE: .missionControl,
CID_BACK: .back,
CID_FWD: .forward,
// examples:
// CID_BACK: .shortcut(0x30, [.maskCommand, .maskShift]), // Cmd-Shift-Tab... (0x30 = Tab)
// CID_BACK: .mouseButton(3), // let each app decide what "back" means
]
// Gesture button: false = act on press (instant). true = hold+swipe ←/→ Spaces, ↓ App Exposé, tap = its action.
var gestureSwipes = true
var gestureThreshold = 60 // raw sensor counts before a hold counts as a swipe
var gestureThreshold = 60
// Sensor / wheel
var dpi: Int? = 1000 // factory default. 200...8000, step 50. nil = don't touch.
var smartShiftThreshold: UInt8? = 20// 1...254, 255 = always ratchet. nil = don't touch.
var dpi: Int? = 1000
var smartShiftThreshold: UInt8? = 20
// Smooth scrolling (applies to every wheel mouse; trackpads/Magic Mouse are untouched).
// Values are Mos's defaults (Mos/Utils/Constants.swift, 4.2.1), except reverseMouseScroll (Mos: true).
var smoothScroll = true
var scrollStep = 33.6 // a notch counts as at least this many pixels
var scrollSpeed = 2.70 // multiplier on every notch, so one slow notch travels 33.6 × 2.70
var glideIntensity = 0.5 // 0...1, how strong the glide is: 0 = jump with no glide, 0.5 = Mos's default, 1 = Mos's longest
var scrollDeadZone = 1.0 // frames at or below this many pixels aren't posted
var scrollDash = 5.0 // multiplier while Option is held
var reverseMouseScroll = false // invert the mouse only, keep trackpad "natural"
// Shift+wheel scrolls sideways. Cmd+wheel skips smoothing, so zooming stays immediate.
var scrollStep = 33.6
var scrollSpeed = 2.70
var glideIntensity = 0.5
var scrollDeadZone = 1.0
var scrollDash = 5.0
var reverseMouseScroll = false
// Fraction of the remaining distance consumed per frame, log-interpolated through 1.0 (0), 0.085 (0.5, Mos's
// default) and 0.019 (1, Mos's generateDurationTransition at its slider maximum of 5.0).
var scrollTransition: Double {
let i = min(max(glideIntensity, 0), 1)
return i < 0.5 ? pow(0.085, i * 2) : 0.085 * pow(0.019 / 0.085, i * 2 - 1)
}
// Blend factor of Mos's ScrollFilter: its own 0.23 from the default up, easing to 1.0 (no extra glide) at 0.
var scrollFilter: Double {
let i = min(max(glideIntensity, 0), 1)
return i >= 0.5 ? 0.23 : 1 - (1 - 0.23) * i * 2
}
// A frame is remaining × transition and is only posted above the dead zone, so a smaller transition
// would drop most of the distance (or all of it); shrink the dead zone in step to keep the full travel.
var scrollEffectiveDeadZone: Double { scrollDeadZone * min(1, scrollTransition / 0.085) }
var ignoredApps = ["NVIDIA GeForce Now", "GeForce NOW"]
}
let config = Config()
let probeOnly = CommandLine.arguments.contains("--probe")
let verbose = CommandLine.arguments.contains("-v")
func log(_ s: String) { FileHandle.standardError.write((s + "\n").data(using: .utf8)!) }
func loadConfig(path: String) -> Config {
var c = Config()
let fm = FileManager.default
var isDir: ObjCBool = false
guard fm.fileExists(atPath: path, isDirectory: &isDir) else {
if probeOnly { return c }
do {
try fm.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)
let json: [String: Any] = ["glideIntensity": c.glideIntensity, "ignoredApps": c.ignoredApps]
try JSONSerialization.data(withJSONObject: json, options: [.prettyPrinted, .sortedKeys])
.write(to: URL(fileURLWithPath: path), options: .withoutOverwriting)
log("config: wrote defaults to \(path)")
} catch { log("config: can't write \(path): \(error.localizedDescription), using defaults") }
return c
}
guard !isDir.boolValue else { log("config: \(path) is a directory, using defaults"); return c }
guard let data = fm.contents(atPath: path),
let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {
log("config: \(path) is unreadable or not a JSON object, using defaults"); return c
}
if let v = obj["glideIntensity"] {
if let n = v as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID() { c.glideIntensity = n.doubleValue }
else { log("config: glideIntensity must be a number, keeping \(c.glideIntensity)") }
}
if let v = obj["ignoredApps"] {
if let a = v as? [String] { c.ignoredApps = a }
else { log("config: ignoredApps must be an array of strings, keeping defaults") }
}
return c
}
let config = loadConfig(path: FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".config/mxd").path)
func hex(_ b: [UInt8]) -> String { b.map { String(format: "%02x", $0) }.joined(separator: " ") }
// MARK: - Event synthesis
let SYNTH_TAG: Int64 = 0x6D7864 // "mxd" — marks our own events so the scroll tap ignores them
let SYNTH_TAG: Int64 = 0x6D7864
let synthSource = CGEventSource(stateID: .hidSystemState)
func key(_ code: CGKeyCode, _ flags: CGEventFlags, arrow: Bool = false) {
var f = flags
// Real keyboards tag arrow keys with fn+numpad flags; some system shortcuts only fire if present.
if arrow { f.formUnion([.maskSecondaryFn, .maskNumericPad]) }
for down in [true, false] {
guard let e = CGEvent(keyboardEventSource: synthSource, virtualKey: code, keyDown: down) else { continue }
@@ -138,29 +131,17 @@ func perform(_ a: Action) {
}
}
// MARK: - Smooth scrolling
//
// Mechanism, same as Mos: an active CGEventTap swallows each wheel notch and adds its distance to
// a target. Every display frame, a fixed fraction of what's left is smoothed and sent straight to
// the target app as a continuous scroll event, so mxd's own frames never come back through its tap.
// Trackpad / Magic Mouse events carry scroll phases and pass through.
//
// One difference: Mos ticks from a CVDisplayLink, mxd from a timer at the display's refresh rate.
// The fraction is per frame, so both glide twice as long on a 60 Hz screen as on a 120 Hz one.
final class Axis {
var target = 0.0, current = 0.0 // pixels requested / pixels consumed so far
var lastDelta = 0.0 // previous notch, to detect a direction change
var target = 0.0, current = 0.0
var lastDelta = 0.0
var filtered = 0.0
func add(_ delta: Double, _ gain: Double) {
if delta * lastDelta > 0 { target += delta * gain }
else { target = delta * gain; current = 0 } // direction change cancels the glide
else { target = delta * gain; current = 0 }
lastDelta = delta
}
/// Next frame's output in pixels: Mos's lerp + ScrollFilter. Its 5-point curve only ever uses
/// two of its points, which reduces to this one-frame delay and a blend of `filter` (23% by default).
func next(_ transition: Double, _ filter: Double) -> Double {
let frame = (target - current) * transition
current += frame
@@ -169,7 +150,6 @@ final class Axis {
return output
}
/// True once every later frame would be at or below the dead zone, so none would be posted.
func settled(_ transition: Double, _ deadZone: Double) -> Bool {
abs(filtered) <= deadZone && abs(target - current) * transition <= deadZone
}
@@ -179,7 +159,7 @@ final class Axis {
final class Smoother {
let y = Axis(), x = Axis()
let transition = config.scrollTransition, filter = config.scrollFilter, deadZone = config.scrollEffectiveDeadZone
var event: CGEvent? // copy of the latest notch, re-sent with each frame's distance
var event: CGEvent?
var targetPID: pid_t = 0
var flags: CGEventFlags = []
var timer: Timer?
@@ -206,7 +186,7 @@ final class Smoother {
func tick() {
var oy = y.next(transition, filter), ox = x.next(transition, filter)
if flags.contains(.maskShift) && oy != 0 && ox == 0 { (oy, ox) = (0, oy) } // Shift+wheel: sideways
if flags.contains(.maskShift) && oy != 0 && ox == 0 { (oy, ox) = (0, oy) }
if max(abs(oy), abs(ox)) > deadZone, let e = event {
e.setDoubleValueField(.scrollWheelEventPointDeltaAxis1, value: oy)
e.setDoubleValueField(.scrollWheelEventPointDeltaAxis2, value: ox)
@@ -221,33 +201,62 @@ final class Smoother {
}
let smoother = Smoother()
var tapPort: CFMachPort?
var scrollEventsSeen = 0
var lastTimeoutAt: Double?
let watchdogQueue = DispatchQueue(label: "mxd.watchdog", qos: .userInteractive)
/// A notch's size, using the first non-zero of point delta, fixed-point delta, line delta (Mos's order).
/// The point delta includes macOS's wheel acceleration, which is how fast spins go further.
func wheelDelta(_ e: CGEvent, _ point: CGEventField, _ fixed: CGEventField, _ line: CGEventField) -> Double {
let p = e.getDoubleValueField(point); if p != 0 { return p }
let f = e.getDoubleValueField(fixed); if f != 0 { return f }
return Double(e.getIntegerValueField(line))
}
func norm(_ s: String) -> String { s.lowercased().replacingOccurrences(of: " ", with: "") }
func isIgnored(_ app: NSRunningApplication?) -> Bool {
guard let app else { return false }
let names = [app.localizedName, app.bundleIdentifier, app.bundleURL?.deletingPathExtension().lastPathComponent]
.compactMap { $0 }.map(norm)
return config.ignoredApps.contains { names.contains(norm($0)) }
}
var frontmostIgnored = false
var lastTargetPID: pid_t = 0, lastTargetIgnored = false
func targetIgnored(_ pid: pid_t) -> Bool {
guard pid != 0 else { return false }
if pid != lastTargetPID { lastTargetPID = pid; lastTargetIgnored = isIgnored(NSRunningApplication(processIdentifier: pid)) }
return lastTargetIgnored
}
let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
// macOS disables a tap that stalls or on secure input; just turn it back on.
if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput {
if type == .scrollWheel { scrollEventsSeen += 1 }
if type == .tapDisabledByTimeout {
let now = ProcessInfo.processInfo.systemUptime
log("tap timed out")
if let last = lastTimeoutAt, now - last < 30 {
watchdogQueue.async { stopTap(reason: "repeated tap timeouts", restart: true) }
return Unmanaged.passUnretained(event)
}
lastTimeoutAt = now
if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) }
return Unmanaged.passUnretained(event)
}
if type == .tapDisabledByUserInput {
if let p = tapPort { CGEvent.tapEnable(tap: p, enable: true) }
return Unmanaged.passUnretained(event)
}
guard type == .scrollWheel,
event.getIntegerValueField(.eventSourceUserData) != SYNTH_TAG,
// Mos's trackpad test: real gestures carry a phase or a scroll count, wheel notches don't.
event.getIntegerValueField(.scrollWheelEventScrollPhase) == 0,
event.getIntegerValueField(.scrollWheelEventMomentumPhase) == 0,
event.getIntegerValueField(.scrollWheelEventScrollCount) == 0 else {
return Unmanaged.passUnretained(event)
}
let rawY = wheelDelta(event, .scrollWheelEventPointDeltaAxis1, .scrollWheelEventFixedPtDeltaAxis1, .scrollWheelEventDeltaAxis1)
let rawX = wheelDelta(event, .scrollWheelEventPointDeltaAxis2, .scrollWheelEventFixedPtDeltaAxis2, .scrollWheelEventDeltaAxis2) // thumb wheel
let rawX = wheelDelta(event, .scrollWheelEventPointDeltaAxis2, .scrollWheelEventFixedPtDeltaAxis2, .scrollWheelEventDeltaAxis2)
guard rawY != 0 || rawX != 0 else { return Unmanaged.passUnretained(event) }
let pid = pid_t(event.getIntegerValueField(.eventTargetUnixProcessID))
if targetIgnored(pid) { return Unmanaged.passUnretained(event) }
if config.reverseMouseScroll {
for f in [CGEventField.scrollWheelEventPointDeltaAxis1, .scrollWheelEventPointDeltaAxis2,
.scrollWheelEventFixedPtDeltaAxis1, .scrollWheelEventFixedPtDeltaAxis2] {
@@ -257,8 +266,6 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
event.setIntegerValueField(f, value: -event.getIntegerValueField(f))
}
}
// Cmd+wheel stays unsmoothed. So does a notch with no target app, since there's nowhere to send frames.
let pid = pid_t(event.getIntegerValueField(.eventTargetUnixProcessID))
guard !event.flags.contains(.maskCommand), pid != 0, let copy = event.copy() else {
return Unmanaged.passUnretained(event)
}
@@ -267,12 +274,10 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
v == 0 ? 0 : sign * (v < 0 ? -1 : 1) * max(abs(v), config.scrollStep)
}
smoother.feed(notch(rawY), notch(rawX), event: copy, pid: pid)
return nil // swallow the original notch
return nil
}
func startSmoothScroll() {
// Mask = scroll events only. This tap never sees keystrokes or clicks.
// The annotated location is the first point where an event names its target app.
let mask = CGEventMask(1 << CGEventType.scrollWheel.rawValue)
guard let port = CGEvent.tapCreate(tap: .cgAnnotatedSessionEventTap, place: .tailAppendEventTap, options: .defaultTap,
eventsOfInterest: mask, callback: scrollTapCB, userInfo: nil) else {
@@ -285,42 +290,36 @@ func startSmoothScroll() {
log("smooth scroll: on")
}
// MARK: - HID++ constants
let REPORT_SHORT: UInt8 = 0x10 // 7 bytes (receiver / HID++ 1.0)
let REPORT_LONG: UInt8 = 0x11 // 20 bytes (always used for HID++ 2.0; BLE on macOS only exposes long)
let SW_ID: UInt8 = 0x0A // our software id nibble; device-initiated notifications use 0
let REPORT_SHORT: UInt8 = 0x10
let REPORT_LONG: UInt8 = 0x11
let SW_ID: UInt8 = 0x0A
let F_FEATURESET: UInt16 = 0x0001, F_NAME: UInt16 = 0x0005
let F_REPROG: UInt16 = 0x1B04 // REPROG_CONTROLS_V4
let F_REPROG: UInt16 = 0x1B04
let F_SMARTSHIFT: UInt16 = 0x2110, F_SMARTSHIFT_ENH: UInt16 = 0x2111
let F_THUMBWHEEL: UInt16 = 0x2150, F_DPI: UInt16 = 0x2201
let F_WIRELESS_STATUS: UInt16 = 0x1D4B // announces a wake that lost volatile settings
// MARK: - Device state
let F_WIRELESS_STATUS: UInt16 = 0x1D4B
final class Device {
let hid: IOHIDDevice
var devIdx: UInt8 = 0xFF // 0xFF = direct (BLE/USB); 1...6 = receiver slot
var feat: [UInt16: UInt8] = [:] // featureID → feature index (device-specific!)
var devIdx: UInt8 = 0xFF
var feat: [UInt16: UInt8] = [:]
var inbox: [[UInt8]] = []
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
var pressed: Set<UInt16> = []
var gestureDown = false, gx = 0, gy = 0
var gestureDown = false, gestureFired = false, gx = 0, gy = 0
var busy = false
var diverted: [UInt16] = []
var divertsApplied = false
init(_ h: IOHIDDevice) { hid = h }
}
var devices: [ObjectIdentifier: Device] = [:]
// MARK: - Transport
@discardableResult
func send(_ d: Device, _ bytes: [UInt8]) -> Bool {
var r = bytes
let len = r[0] == REPORT_SHORT ? 7 : 20
while r.count < len { r.append(0) }
// macOS: buffer includes the report ID byte when the device uses numbered reports.
let rc = r.withUnsafeBufferPointer {
IOHIDDeviceSetReport(d.hid, kIOHIDReportTypeOutput, CFIndex(r[0]), $0.baseAddress!, len)
}
@@ -328,8 +327,6 @@ func send(_ d: Device, _ bytes: [UInt8]) -> Bool {
return rc == kIOReturnSuccess
}
/// Synchronous request: sends a long report, spins the run loop until the matching
/// response (or error) arrives. Returns the 16 param bytes, or nil on error/timeout.
func request(_ d: Device, feat fi: UInt8, fn: UInt8, _ params: [UInt8] = [],
devIdx: UInt8? = nil, timeout: Double = 1.0) -> [UInt8]? {
let di = devIdx ?? d.devIdx
@@ -340,8 +337,8 @@ func request(_ d: Device, feat fi: UInt8, fn: UInt8, _ params: [UInt8] = [],
while Date() < deadline {
if let i = d.inbox.firstIndex(where: { r in
r[1] == di && (
(r[2] == fi && r[3] == fnSw) || // success
((r[2] == 0xFF || r[2] == 0x8F) && r[3] == fi && r[4] == fnSw)) // 2.0 / 1.0 error
(r[2] == fi && r[3] == fnSw) ||
((r[2] == 0xFF || r[2] == 0x8F) && r[3] == fi && r[4] == fnSw))
}) {
let r = d.inbox.remove(at: i)
if r[2] == 0xFF || r[2] == 0x8F {
@@ -356,17 +353,12 @@ func request(_ d: Device, feat fi: UInt8, fn: UInt8, _ params: [UInt8] = [],
return nil
}
/// IRoot.getFeature: featureID → index (0 = unsupported).
func featureIndex(_ d: Device, _ id: UInt16, devIdx: UInt8? = nil) -> UInt8? {
guard let r = request(d, feat: 0x00, fn: 0, [UInt8(id >> 8), UInt8(id & 0xFF)], devIdx: devIdx, timeout: 0.4),
r[0] != 0 else { return nil }
return r[0]
}
// MARK: - Discovery
/// Find the HID++ 2.0 index of the mouse: 0xFF if direct, else scan receiver slots 1...6
/// and pick the one that has SmartShift (so a paired keyboard on the same Bolt is skipped).
func findMouse(_ d: Device) -> Bool {
for idx in [UInt8(0xFF)] + Array(1...6) {
guard let r = request(d, feat: 0x00, fn: 1, [0, 0, 0x5A], devIdx: idx, timeout: 0.4),
@@ -403,25 +395,21 @@ func probe(_ d: Device) {
if let fi = d.feat[F_DPI], let r = request(d, feat: fi, fn: 2, [0]) {
log("current DPI: \(Int(r[1]) << 8 | Int(r[2])) default: \(Int(r[3]) << 8 | Int(r[4]))")
}
// List reprogrammable controls and which can be diverted.
if let fi = d.feat[F_REPROG], let cnt = request(d, feat: fi, fn: 0)?.first {
log("controls (CID: flags):")
for i in 0..<cnt {
guard let r = request(d, feat: fi, fn: 1, [i]) else { continue }
let cid = UInt16(r[0]) << 8 | UInt16(r[1])
// getCidInfo: cid(2) taskId(2) flags(1) pos(1) group(1) gmask(1) flags2(1)
let divertable = r[4] & 0x20 != 0, rawXY = r[8] & 0x01 != 0
log(String(format: " CID 0x%04X%@%@", cid, divertable ? " divertable" : "", rawXY ? " rawXY" : ""))
}
}
}
// MARK: - Configuration
func setDivert(_ d: Device, _ cid: UInt16, on: Bool, rawXY: Bool = false) {
guard let fi = d.feat[F_REPROG] else { return }
var flags: UInt8 = 0x02 | (on ? 0x01 : 0) // dvalid | divert
if rawXY { flags |= 0x20 | (on ? 0x10 : 0) } // rvalid | rawXY (stream dx/dy while held)
var flags: UInt8 = 0x02 | (on ? 0x01 : 0)
if rawXY { flags |= 0x20 | (on ? 0x10 : 0) }
let ok = request(d, feat: fi, fn: 3, [UInt8(cid >> 8), UInt8(cid & 0xFF), flags, 0, 0]) != nil
log(String(format: " %@ CID 0x%04X: %@", on ? "divert" : "undivert", cid, ok ? "ok" : "FAILED"))
if ok && on { d.diverted.append(cid) }
@@ -439,8 +427,6 @@ func configure(_ d: Device) {
log("device: \(deviceName(d))")
if probeOnly { probe(d); exit(0) }
// Receiver: enable wireless (dis)connect notifications (HID++ 1.0 register 0x00, flag 0x000100)
// so we hear about sleep/wake and can re-apply volatile settings. Best effort.
if d.devIdx != 0xFF { send(d, [REPORT_SHORT, 0xFF, 0x80, 0x00, 0x00, 0x01, 0x00]) }
if let dpi = config.dpi, let fi = d.feat[F_DPI] {
@@ -448,13 +434,16 @@ func configure(_ d: Device) {
log(" DPI \(dpi): \(ok ? "ok" : "FAILED")")
}
if let t = config.smartShiftThreshold {
// wheelMode 0 = leave as-is (respects the ratchet button), autoDisengage = t, 3rd byte 0 = no change.
var ok = false
if let fi = d.feat[F_SMARTSHIFT_ENH] { ok = request(d, feat: fi, fn: 2, [0, t, 0]) != nil }
else if let fi = d.feat[F_SMARTSHIFT] { ok = request(d, feat: fi, fn: 1, [0, t, 0]) != nil }
log(" SmartShift threshold \(t): \(ok ? "ok" : "FAILED")")
}
d.diverted = []; d.pressed = []; d.gestureDown = false
d.diverted = []; d.pressed = []; d.gestureDown = false; d.divertsApplied = false
syncDiverts(d)
}
func divertAll(_ d: Device) {
for (cid, action) in config.buttons {
if case .none = action { continue }
setDivert(d, cid, on: true, rawXY: cid == CID_GESTURE && config.gestureSwipes)
@@ -463,28 +452,34 @@ func configure(_ d: Device) {
func undivertAll(_ d: Device) {
for c in d.diverted { setDivert(d, c, on: false, rawXY: c == CID_GESTURE && config.gestureSwipes) }
d.diverted = []
d.diverted = []; d.pressed = []; d.gestureDown = false
}
// MARK: - Button events
func syncDiverts(_ d: Device) {
while d.divertsApplied != !frontmostIgnored {
let want = !frontmostIgnored
if want { divertAll(d) } else { undivertAll(d) }
d.divertsApplied = want
}
}
func buttonDown(_ d: Device, _ cid: UInt16) {
if cid == CID_GESTURE && config.gestureSwipes { d.gestureDown = true; d.gx = 0; d.gy = 0; return }
if cid == CID_GESTURE && config.gestureSwipes { d.gestureDown = true; d.gestureFired = false; d.gx = 0; d.gy = 0; return }
if let a = config.buttons[cid] { perform(a) }
}
func buttonUp(_ d: Device, _ cid: UInt16) {
guard cid == CID_GESTURE, config.gestureSwipes, d.gestureDown else { return }
d.gestureDown = false
if d.gestureFired { return }
let t = config.gestureThreshold
if verbose { log("gesture dx=\(d.gx) dy=\(d.gy)") }
if abs(d.gx) < t && abs(d.gy) < t { perform(config.buttons[CID_GESTURE] ?? .missionControl) }
else if abs(d.gx) > abs(d.gy) { perform(d.gx > 0 ? .nextSpace : .prevSpace) }
else if abs(d.gx) > abs(d.gy) { perform(d.gx > 0 ? .prevSpace : .nextSpace) }
else { perform(d.gy < 0 ? .missionControl : .appExpose) }
}
func handleReport(_ d: Device, _ r: [UInt8]) {
// Receiver HID++ 1.0 "device connection" notification (sub-id 0x41). Bit 6 of byte 4 = link NOT established.
if r[0] == REPORT_SHORT && r[2] == 0x41 && r[1] != 0xFF {
if r[1] == d.devIdx && (r[4] & 0x40) == 0 {
log("device \(r[1]) (re)connected → re-applying")
@@ -492,20 +487,17 @@ func handleReport(_ d: Device, _ r: [UInt8]) {
}
return
}
// Responses to our requests (our SW_ID) and errors go to the inbox.
if r[2] == 0xFF || r[2] == 0x8F || (r[3] & 0x0F) == SW_ID { d.inbox.append(r); return }
// Mouse woke without the HID interface going away: the diverts are gone, so apply them again.
if r[1] == d.devIdx, let fi = d.feat[F_WIRELESS_STATUS], r[2] == fi, r[3] >> 4 == 0, r[4] == 1, r[5] == 1 {
log("device woke → re-applying")
DispatchQueue.main.async { configure(d) }
return
}
// Device-initiated notifications from REPROG_CONTROLS_V4.
guard r.count >= 12, r[1] == d.devIdx, let fi = d.feat[F_REPROG], r[2] == fi else { return }
switch r[3] >> 4 {
case 0: // divertedButtonsEvent: up to 4 currently-held CIDs
case 0:
var now: Set<UInt16> = []
for i in stride(from: 4, to: 12, by: 2) {
let c = UInt16(r[i]) << 8 | UInt16(r[i + 1])
@@ -515,10 +507,11 @@ func handleReport(_ d: Device, _ r: [UInt8]) {
d.pressed = now
down.forEach { buttonDown(d, $0) }
up.forEach { buttonUp(d, $0) }
case 1: // divertedRawMouseXYEvent: int16 BE dx, dy (only while a rawXY-diverted button is held)
case 1:
guard d.gestureDown else { return }
d.gx += Int(Int16(bitPattern: UInt16(r[4]) << 8 | UInt16(r[5])))
d.gy += Int(Int16(bitPattern: UInt16(r[6]) << 8 | UInt16(r[7])))
if !d.gestureFired && d.gy >= config.gestureThreshold && d.gy > abs(d.gx) { d.gestureFired = true; perform(.appExpose) }
default: break
}
}
@@ -532,8 +525,6 @@ let inputCB: IOHIDReportCallback = { ctx, _, _, _, _, report, len in
handleReport(d, r)
}
// MARK: - Main
if !probeOnly {
let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
if !AXIsProcessTrustedWithOptions(opts) {
@@ -543,7 +534,6 @@ if !probeOnly {
}
let mgr = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone))
// HID++ long-report collection: 0xFF00/0x0002 over Bolt/Unifying/USB, 0xFF43/0x0202 over BLE-direct.
let matches: [[String: Any]] = [
[kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF00, kIOHIDDeviceUsageKey: 0x0002],
[kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF43, kIOHIDDeviceUsageKey: 0x0202],
@@ -557,7 +547,7 @@ IOHIDManagerRegisterDeviceMatchingCallback(mgr, { _, _, _, dev in
let name = IOHIDDeviceGetProperty(dev, kIOHIDProductKey as CFString) as? String ?? "?"
log(String(format: "matched HID interface: %@ (pid 0x%04X)", name, pid))
IOHIDDeviceRegisterInputReportCallback(dev, d.buf, 64, inputCB, Unmanaged.passUnretained(d).toOpaque())
DispatchQueue.main.async { configure(d) } // don't do blocking I/O inside the matching callback
DispatchQueue.main.async { configure(d) }
}, nil)
IOHIDManagerRegisterDeviceRemovalCallback(mgr, { _, _, _, dev in
@@ -566,35 +556,77 @@ IOHIDManagerRegisterDeviceRemovalCallback(mgr, { _, _, _, dev in
}, nil)
IOHIDManagerScheduleWithRunLoop(mgr, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
// kIOHIDOptionsTypeNone = NOT exclusive. Seizing would kill pointer input on BLE (single IOHIDDevice).
let rc = IOHIDManagerOpen(mgr, IOOptionBits(kIOHIDOptionsTypeNone))
if rc != kIOReturnSuccess {
log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc))
}
// A tap that outlives its Accessibility grant can stall scroll events, and every later click and key
// queues behind them. So when the grant goes: remove the tap first, restore the buttons, exit.
// Run under launchd with KeepAlive/SuccessfulExit=false, so exit(0) doesn't restart mxd.
func checkPermission() {
guard let port = tapPort, !AXIsProcessTrusted() else { return }
struct StallDetector {
var lastSeen = 0, hidAtLastSeen = 0, behindSince: Double? = nil
mutating func update(seen: Int, hid: Int, now: Double, limit: Double) -> Bool {
if seen != lastSeen {
lastSeen = seen; hidAtLastSeen = hid; behindSince = nil
return false
}
if hid > hidAtLastSeen {
if behindSince == nil { behindSince = now }
return now - behindSince! >= limit
}
behindSince = nil
return false
}
}
func hidScrollCount() -> Int { Int(CGEventSource.counterForEventType(.hidSystemState, eventType: .scrollWheel)) }
var tapStopped = false
var tapDisabledSince: Double?
var postAccessAtStart = false, listenAccessAtStart = false
var stall = StallDetector()
func stopTap(reason: String, restart: Bool) {
if tapStopped { return }
tapStopped = true
DispatchQueue.global().asyncAfter(deadline: .now() + 3) { _exit(restart ? 1 : 0) }
log("tap removed: \(reason), exiting")
if let port = tapPort {
CGEvent.tapEnable(tap: port, enable: false)
CFMachPortInvalidate(port)
tapPort = nil
log("Accessibility revoked: tap removed, exiting")
devices.values.forEach(undivertAll)
exit(0)
}
// The notification is immediate but can fire just before the new state is readable; the timer is the backstop.
DispatchQueue.main.async { devices.values.forEach(undivertAll); exit(restart ? 1 : 0) }
}
func checkTap() {
guard let port = tapPort, !tapStopped else { return }
if !AXIsProcessTrusted() { return stopTap(reason: "AXIsProcessTrusted false", restart: false) }
if postAccessAtStart && !CGPreflightPostEventAccess() { return stopTap(reason: "CGPreflightPostEventAccess false", restart: false) }
if listenAccessAtStart && !CGPreflightListenEventAccess() { return stopTap(reason: "CGPreflightListenEventAccess false", restart: false) }
let now = ProcessInfo.processInfo.systemUptime
if CGEvent.tapIsEnabled(tap: port) { tapDisabledSince = nil }
else {
if tapDisabledSince == nil { tapDisabledSince = now }
if now - tapDisabledSince! >= 2 { return stopTap(reason: "tap disabled", restart: true) }
}
if stall.update(seen: scrollEventsSeen, hid: hidScrollCount(), now: now, limit: 2) {
stopTap(reason: "scroll events not reaching tap", restart: true)
}
}
let watchdogTimer = DispatchSource.makeTimerSource(queue: watchdogQueue)
if !probeOnly && tapPort != nil {
postAccessAtStart = CGPreflightPostEventAccess()
listenAccessAtStart = CGPreflightListenEventAccess()
stall = StallDetector(lastSeen: scrollEventsSeen, hidAtLastSeen: hidScrollCount())
watchdogTimer.schedule(deadline: .now() + 0.5, repeating: .milliseconds(500))
watchdogTimer.setEventHandler { checkTap() }
watchdogTimer.resume()
}
let permissionObserver = DistributedNotificationCenter.default().addObserver(
forName: NSNotification.Name("com.apple.accessibility.api"), object: nil, queue: nil) { _ in
checkPermission()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { checkPermission() }
watchdogQueue.async { checkTap() }
watchdogQueue.asyncAfter(deadline: .now() + 0.1) { checkTap() }
}
let permissionTimer = Timer(timeInterval: 1, repeats: true) { _ in checkPermission() }
permissionTimer.tolerance = 0.2
RunLoop.main.add(permissionTimer, forMode: .common)
// Clean shutdown: un-divert so buttons work natively again.
signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN)
let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in
let src = DispatchSource.makeSignalSource(signal: s, queue: .main)
@@ -603,6 +635,22 @@ let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in
return src
}
if !probeOnly {
frontmostIgnored = isIgnored(NSWorkspace.shared.frontmostApplication)
}
let frontmostObserver = probeOnly ? nil : NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { n in
let app = n.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
let ign = isIgnored(app)
guard ign != frontmostIgnored else { return }
frontmostIgnored = ign
log("ignored app frontmost: \(app?.localizedName ?? "?"), buttons \(ign ? "native" : "diverted")")
for d in devices.values where !d.busy {
d.busy = true; defer { d.busy = false }
syncDiverts(d)
}
}
if probeOnly {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { log("probe: no device found within 5s"); exit(1) }
}