Files
mxd/mxd.swift
T
yigid 7224d7604e 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>
2026-10-30 23:45:08 +03:00

764 lines
37 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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.
//
// Config: ~/.config/mxd (a plain JSON file, not a folder): {"glideIntensity": 0.5, "ignoredApps": [...]}.
// Written once with defaults if missing (never with --probe); an existing path is never modified.
// Read at startup only: restart to apply. Apps in ignoredApps get native scrolling and native buttons.
// Secrets: none. Writes only the default config above if missing. 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 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_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: ↓ App Exposé fires at once while held;
// ←/→ Spaces and ↑ Mission Control fire on release; tap = its action.
var gestureSwipes = true
var gestureThreshold = 60 // raw sensor counts before a hold counts as a swipe
// 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.
// 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.
// 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) }
// While one of these is involved (scroll target / frontmost app), mxd steps aside: scrolling is native and the
// buttons go back to the firmware. Matched by name, bundle id or .app name, ignoring case and spaces.
var ignoredApps = ["NVIDIA GeForce Now", "GeForce NOW"]
}
let probeOnly = CommandLine.arguments.contains("--probe")
let verbose = CommandLine.arguments.contains("-v")
func log(_ s: String) { FileHandle.standardError.write((s + "\n").data(using: .utf8)!) }
/// Defaults, overridden by the JSON file at `path`. Read once at startup: restart mxd to apply edits.
/// A missing file is created with the defaults (not under --probe). An existing path is never modified.
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 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 }
e.flags = f
e.setIntegerValueField(.eventSourceUserData, value: SYNTH_TAG)
e.post(tap: .cghidEventTap)
}
}
func otherMouseButton(_ n: Int) {
let pos = CGEvent(source: nil)?.location ?? .zero
for type in [CGEventType.otherMouseDown, .otherMouseUp] {
guard let e = CGEvent(mouseEventSource: synthSource, mouseType: type, mouseCursorPosition: pos,
mouseButton: CGMouseButton(rawValue: UInt32(n)) ?? .center) else { continue }
e.setIntegerValueField(.mouseEventButtonNumber, value: Int64(n))
e.setIntegerValueField(.eventSourceUserData, value: SYNTH_TAG)
e.post(tap: .cghidEventTap)
}
}
func perform(_ a: Action) {
if verbose { log("action: \(a)") }
switch a {
case .missionControl:
NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Mission Control.app"))
case .appExpose: key(kVK_Down, .maskControl, arrow: true)
case .prevSpace: key(kVK_Left, .maskControl, arrow: true)
case .nextSpace: key(kVK_Right, .maskControl, arrow: true)
case .back: key(kVK_LeftBracket, .maskCommand)
case .forward: key(kVK_RightBracket, .maskCommand)
case .mouseButton(let n): otherMouseButton(n)
case .shortcut(let k, let f): key(k, f)
case .none: break
}
}
// 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 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
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
let output = filtered
filtered += filter * (frame - filtered)
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
}
func reset() { target = 0; current = 0; lastDelta = 0; filtered = 0 }
}
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 targetPID: pid_t = 0
var flags: CGEventFlags = []
var timer: Timer?
func feed(_ dy: Double, _ dx: Double, event e: CGEvent, pid: pid_t) {
flags = e.flags
let gain = config.scrollSpeed * (flags.contains(.maskAlternate) ? config.scrollDash : 1)
y.add(dy, gain); x.add(dx, gain)
e.setDoubleValueField(.scrollWheelEventIsContinuous, value: 1)
e.setIntegerValueField(.eventSourceUserData, value: SYNTH_TAG)
event = e; targetPID = pid
if timer == nil {
let t = Timer(timeInterval: 1.0 / refreshRate(), repeats: true) { [unowned self] _ in self.tick() }
RunLoop.main.add(t, forMode: .common)
timer = t
}
}
func refreshRate() -> Double {
let mouse = NSEvent.mouseLocation
let fps = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) }?.maximumFramesPerSecond ?? 60
return Double(max(fps, 30))
}
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 max(abs(oy), abs(ox)) > deadZone, let e = event {
e.setDoubleValueField(.scrollWheelEventPointDeltaAxis1, value: oy)
e.setDoubleValueField(.scrollWheelEventPointDeltaAxis2, value: ox)
e.postToPid(targetPID)
}
if y.settled(transition, deadZone) && x.settled(transition, deadZone) {
timer?.invalidate(); timer = nil
y.reset(); x.reset()
event = nil
}
}
}
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: "") }
/// Equality (not substring) against the app's name, bundle id and .app file name.
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 // frontmost app is ignored: buttons go back to the firmware
var lastTargetPID: pid_t = 0, lastTargetIgnored = false // one-entry cache, so a burst of notches looks up once
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
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
guard rawY != 0 || rawX != 0 else { return Unmanaged.passUnretained(event) }
// An ignored target gets the notch untouched: no reversal, no smoothing.
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] {
event.setDoubleValueField(f, value: -event.getDoubleValueField(f))
}
for f in [CGEventField.scrollWheelEventDeltaAxis1, .scrollWheelEventDeltaAxis2] {
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.
guard !event.flags.contains(.maskCommand), pid != 0, let copy = event.copy() else {
return Unmanaged.passUnretained(event)
}
let sign = config.reverseMouseScroll ? -1.0 : 1.0
func notch(_ v: Double) -> Double {
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
}
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 {
log("smooth scroll: tapCreate failed — grant Accessibility, then restart mxd")
return
}
tapPort = port
CFRunLoopAddSource(CFRunLoopGetMain(), CFMachPortCreateRunLoopSource(kCFAllocatorDefault, port, 0), .commonModes)
CGEvent.tapEnable(tap: port, enable: true)
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 F_FEATURESET: UInt16 = 0x0001, F_NAME: UInt16 = 0x0005
let F_REPROG: UInt16 = 0x1B04 // REPROG_CONTROLS_V4
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
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 inbox: [[UInt8]] = []
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
var pressed: Set<UInt16> = []
var gestureDown = false, gestureFired = false, gx = 0, gy = 0
var busy = false
var diverted: [UInt16] = []
var divertsApplied = false // buttons currently match !frontmostIgnored
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)
}
if verbose { log("-> \(hex(r))") }
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
let fnSw = (fn << 4) | SW_ID
d.inbox.removeAll()
guard send(d, [REPORT_LONG, di, fi, fnSw] + params) else { return nil }
let deadline = Date().addingTimeInterval(timeout)
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
}) {
let r = d.inbox.remove(at: i)
if r[2] == 0xFF || r[2] == 0x8F {
if verbose { log(String(format: " error 0x%02x (feat idx %d fn %d dev %d)", r[5], fi, fn, di)) }
return nil
}
return Array(r[4...])
}
CFRunLoopRunInMode(.defaultMode, 0.01, true)
}
if verbose { log(" timeout (feat idx \(fi) fn \(fn) dev \(di))") }
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),
r[0] >= 2, r[2] == 0x5A else { continue }
if featureIndex(d, F_SMARTSHIFT, devIdx: idx) != nil || featureIndex(d, F_SMARTSHIFT_ENH, devIdx: idx) != nil {
d.devIdx = idx
log(String(format: "HID++ %d.%d device at index 0x%02X", r[0], r[1], idx))
return true
}
}
return false
}
func deviceName(_ d: Device) -> String {
guard let fi = d.feat[F_NAME], let n = request(d, feat: fi, fn: 0)?.first else { return "?" }
var s: [UInt8] = []
while s.count < Int(n) {
guard let r = request(d, feat: fi, fn: 1, [UInt8(s.count)]) else { break }
s += r.prefix(Int(n) - s.count)
}
return String(decoding: s, as: UTF8.self)
}
func probe(_ d: Device) {
if let fs = d.feat[F_FEATURESET], let cnt = request(d, feat: fs, fn: 0)?.first {
log("features (index: id version flags):")
for i in 1...cnt {
guard let r = request(d, feat: fs, fn: 1, [i]) else { continue }
let id = UInt16(r[0]) << 8 | UInt16(r[1])
let flags = (r[2] & 0x80 != 0 ? " obsolete" : "") + (r[2] & 0x40 != 0 ? " hidden" : "") + (r[2] & 0x20 != 0 ? " eng" : "")
log(String(format: " [%02d] 0x%04X v%d%@", i, id, r[3], flags))
}
}
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)
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) }
}
func configure(_ d: Device) {
guard !d.busy else { return }
d.busy = true; defer { d.busy = false }
guard findMouse(d) else { log("no HID++ 2.0 mouse answered on this interface"); return }
d.feat = [:]
for f in [F_FEATURESET, F_NAME, F_REPROG, F_SMARTSHIFT, F_SMARTSHIFT_ENH, F_THUMBWHEEL, F_DPI, F_WIRELESS_STATUS] {
if let i = featureIndex(d, f) { d.feat[f] = i }
}
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] {
let ok = request(d, feat: fi, fn: 3, [0, UInt8(dpi >> 8), UInt8(dpi & 0xFF)]) != nil
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.divertsApplied = false
syncDiverts(d) // stays undiverted if an ignored app is frontmost
}
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)
}
}
func undivertAll(_ d: Device) {
for c in d.diverted { setDivert(d, c, on: false, rawXY: c == CID_GESTURE && config.gestureSwipes) }
d.diverted = []; d.pressed = []; d.gestureDown = false
}
/// Call with d.busy held. Loops because the requests spin the run loop and frontmostIgnored can change meanwhile.
/// divertsApplied is set even if a request failed, so this can't loop forever.
func syncDiverts(_ d: Device) {
while d.divertsApplied != !frontmostIgnored {
let want = !frontmostIgnored
if want { divertAll(d) } else { undivertAll(d) }
d.divertsApplied = want
}
}
// MARK: - Button events
func buttonDown(_ d: Device, _ cid: UInt16) {
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 { 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")
DispatchQueue.main.async { configure(d) }
}
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
var now: Set<UInt16> = []
for i in stride(from: 4, to: 12, by: 2) {
let c = UInt16(r[i]) << 8 | UInt16(r[i + 1])
if c != 0 { now.insert(c) }
}
let down = now.subtracting(d.pressed), up = d.pressed.subtracting(now)
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)
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])))
// slide down past the threshold fires App Exposé now, once per hold; release then does nothing
if !d.gestureFired && d.gy >= config.gestureThreshold && d.gy > abs(d.gx) { d.gestureFired = true; perform(.appExpose) }
default: break
}
}
let inputCB: IOHIDReportCallback = { ctx, _, _, _, _, report, len in
guard let ctx else { return }
let d = Unmanaged<Device>.fromOpaque(ctx).takeUnretainedValue()
let r = Array(UnsafeBufferPointer(start: report, count: len))
guard r.count >= 7, r[0] == REPORT_SHORT || r[0] == REPORT_LONG else { return }
if verbose { log("<- \(hex(r))") }
handleReport(d, r)
}
// MARK: - Main
if !probeOnly {
let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
if !AXIsProcessTrustedWithOptions(opts) {
log("warning: no Accessibility permission — key events and smooth scrolling won't work until granted + restart")
}
if config.smoothScroll { startSmoothScroll() }
}
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],
]
IOHIDManagerSetDeviceMatchingMultiple(mgr, matches as CFArray)
IOHIDManagerRegisterDeviceMatchingCallback(mgr, { _, _, _, dev in
let d = Device(dev)
devices[ObjectIdentifier(dev)] = d
let pid = IOHIDDeviceGetProperty(dev, kIOHIDProductIDKey as CFString) as? Int ?? 0
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
}, nil)
IOHIDManagerRegisterDeviceRemovalCallback(mgr, { _, _, _, dev in
devices.removeValue(forKey: ObjectIdentifier(dev))
log("HID interface removed")
}, 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))
}
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)
}
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
watchdogQueue.async { checkTap() }
watchdogQueue.asyncAfter(deadline: .now() + 0.1) { checkTap() }
}
// 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)
src.setEventHandler { devices.values.forEach(undivertAll); exit(0) }
src.resume()
return src
}
if !probeOnly {
frontmostIgnored = isIgnored(NSWorkspace.shared.frontmostApplication)
}
// An ignored frontmost app gets its buttons back from the firmware (real mouse buttons, no frozen pointer on thumb hold).
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 { // a busy device is inside configure, which syncs at its end
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) }
}
CFRunLoopRun()