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>
This commit is contained in:
yigid committed 2026-10-30 23:46:43 +03:00
1 parent 301614990a
commit ec0f2e8d68
1 file changed
+42 -148
+42 -148
View File
@@ -1,98 +1,54 @@
// 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 Foundation
import AppKit import AppKit
import IOKit.hid import IOKit.hid
import CoreGraphics import CoreGraphics
import ApplicationServices import ApplicationServices
// MARK: - Actions
let kVK_LeftBracket: CGKeyCode = 0x21, kVK_RightBracket: CGKeyCode = 0x1E 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 let kVK_Left: CGKeyCode = 0x7B, kVK_Right: CGKeyCode = 0x7C, kVK_Down: CGKeyCode = 0x7D, kVK_Up: CGKeyCode = 0x7E
enum Action { enum Action {
case missionControl // opens Mission Control.app (public API; doesn't depend on keyboard-shortcut settings) case missionControl
case appExpose // Ctrl-↓ case appExpose
case prevSpace, nextSpace // Ctrl-← / Ctrl-→ case prevSpace, nextSpace
case back, forward // Cmd-[ / Cmd-] (Safari, Finder, Chrome, Arc, Mail…) case back, forward
case mouseButton(Int) // synthetic "other" mouse button: 3 = button 4 (back), 4 = button 5 (forward) case mouseButton(Int)
case shortcut(CGKeyCode, CGEventFlags) case shortcut(CGKeyCode, CGEventFlags)
case none case none
} }
// MARK: - Config (edit me)
let CID_BACK: UInt16 = 0x0053, CID_FWD: UInt16 = 0x0056, CID_GESTURE: UInt16 = 0x00C3 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 { struct Config {
// Buttons. Keys are HID++ control IDs; run --probe -v to see what your mouse reports.
var buttons: [UInt16: Action] = [ var buttons: [UInt16: Action] = [
CID_GESTURE: .missionControl, // thumb rest press CID_GESTURE: .missionControl,
CID_BACK: .back, CID_BACK: .back,
CID_FWD: .forward, 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 gestureSwipes = true
var gestureThreshold = 60 // raw sensor counts before a hold counts as a swipe var gestureThreshold = 60
// Sensor / wheel var dpi: Int? = 1000
var dpi: Int? = 1000 // factory default. 200...8000, step 50. nil = don't touch. var smartShiftThreshold: UInt8? = 20
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 smoothScroll = true
var scrollStep = 33.6 // a notch counts as at least this many pixels var scrollStep = 33.6
var scrollSpeed = 2.70 // multiplier on every notch, so one slow notch travels 33.6 × 2.70 var scrollSpeed = 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 glideIntensity = 0.5
var scrollDeadZone = 1.0 // frames at or below this many pixels aren't posted var scrollDeadZone = 1.0
var scrollDash = 5.0 // multiplier while Option is held var scrollDash = 5.0
var reverseMouseScroll = false // invert the mouse only, keep trackpad "natural" var reverseMouseScroll = false
// 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 { var scrollTransition: Double {
let i = min(max(glideIntensity, 0), 1) 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) 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 { var scrollFilter: Double {
let i = min(max(glideIntensity, 0), 1) let i = min(max(glideIntensity, 0), 1)
return i >= 0.5 ? 0.23 : 1 - (1 - 0.23) * i * 2 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 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"] var ignoredApps = ["NVIDIA GeForce Now", "GeForce NOW"]
} }
let probeOnly = CommandLine.arguments.contains("--probe") let probeOnly = CommandLine.arguments.contains("--probe")
@@ -100,8 +56,6 @@ let verbose = CommandLine.arguments.contains("-v")
func log(_ s: String) { FileHandle.standardError.write((s + "\n").data(using: .utf8)!) } 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 { func loadConfig(path: String) -> Config {
var c = Config() var c = Config()
let fm = FileManager.default let fm = FileManager.default
@@ -136,14 +90,11 @@ let config = loadConfig(path: FileManager.default.homeDirectoryForCurrentUser.ap
func hex(_ b: [UInt8]) -> String { b.map { String(format: "%02x", $0) }.joined(separator: " ") } func hex(_ b: [UInt8]) -> String { b.map { String(format: "%02x", $0) }.joined(separator: " ") }
// MARK: - Event synthesis let SYNTH_TAG: Int64 = 0x6D7864
let SYNTH_TAG: Int64 = 0x6D7864 // "mxd" — marks our own events so the scroll tap ignores them
let synthSource = CGEventSource(stateID: .hidSystemState) let synthSource = CGEventSource(stateID: .hidSystemState)
func key(_ code: CGKeyCode, _ flags: CGEventFlags, arrow: Bool = false) { func key(_ code: CGKeyCode, _ flags: CGEventFlags, arrow: Bool = false) {
var f = flags 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]) } if arrow { f.formUnion([.maskSecondaryFn, .maskNumericPad]) }
for down in [true, false] { for down in [true, false] {
guard let e = CGEvent(keyboardEventSource: synthSource, virtualKey: code, keyDown: down) else { continue } guard let e = CGEvent(keyboardEventSource: synthSource, virtualKey: code, keyDown: down) else { continue }
@@ -180,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 { final class Axis {
var target = 0.0, current = 0.0 // pixels requested / pixels consumed so far var target = 0.0, current = 0.0
var lastDelta = 0.0 // previous notch, to detect a direction change var lastDelta = 0.0
var filtered = 0.0 var filtered = 0.0
func add(_ delta: Double, _ gain: Double) { func add(_ delta: Double, _ gain: Double) {
if delta * lastDelta > 0 { target += delta * gain } 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 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 { func next(_ transition: Double, _ filter: Double) -> Double {
let frame = (target - current) * transition let frame = (target - current) * transition
current += frame current += frame
@@ -211,7 +150,6 @@ final class Axis {
return output 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 { func settled(_ transition: Double, _ deadZone: Double) -> Bool {
abs(filtered) <= deadZone && abs(target - current) * transition <= deadZone abs(filtered) <= deadZone && abs(target - current) * transition <= deadZone
} }
@@ -221,7 +159,7 @@ final class Axis {
final class Smoother { final class Smoother {
let y = Axis(), x = Axis() let y = Axis(), x = Axis()
let transition = config.scrollTransition, filter = config.scrollFilter, deadZone = config.scrollEffectiveDeadZone 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 targetPID: pid_t = 0
var flags: CGEventFlags = [] var flags: CGEventFlags = []
var timer: Timer? var timer: Timer?
@@ -248,7 +186,7 @@ final class Smoother {
func tick() { func tick() {
var oy = y.next(transition, filter), ox = x.next(transition, filter) 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 { if max(abs(oy), abs(ox)) > deadZone, let e = event {
e.setDoubleValueField(.scrollWheelEventPointDeltaAxis1, value: oy) e.setDoubleValueField(.scrollWheelEventPointDeltaAxis1, value: oy)
e.setDoubleValueField(.scrollWheelEventPointDeltaAxis2, value: ox) e.setDoubleValueField(.scrollWheelEventPointDeltaAxis2, value: ox)
@@ -267,8 +205,6 @@ var scrollEventsSeen = 0
var lastTimeoutAt: Double? var lastTimeoutAt: Double?
let watchdogQueue = DispatchQueue(label: "mxd.watchdog", qos: .userInteractive) 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 { func wheelDelta(_ e: CGEvent, _ point: CGEventField, _ fixed: CGEventField, _ line: CGEventField) -> Double {
let p = e.getDoubleValueField(point); if p != 0 { return p } let p = e.getDoubleValueField(point); if p != 0 { return p }
let f = e.getDoubleValueField(fixed); if f != 0 { return f } let f = e.getDoubleValueField(fixed); if f != 0 { return f }
@@ -276,15 +212,14 @@ func wheelDelta(_ e: CGEvent, _ point: CGEventField, _ fixed: CGEventField, _ li
} }
func norm(_ s: String) -> String { s.lowercased().replacingOccurrences(of: " ", with: "") } 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 { func isIgnored(_ app: NSRunningApplication?) -> Bool {
guard let app else { return false } guard let app else { return false }
let names = [app.localizedName, app.bundleIdentifier, app.bundleURL?.deletingPathExtension().lastPathComponent] let names = [app.localizedName, app.bundleIdentifier, app.bundleURL?.deletingPathExtension().lastPathComponent]
.compactMap { $0 }.map(norm) .compactMap { $0 }.map(norm)
return config.ignoredApps.contains { names.contains(norm($0)) } return config.ignoredApps.contains { names.contains(norm($0)) }
} }
var frontmostIgnored = false // frontmost app is ignored: buttons go back to the firmware var frontmostIgnored = false
var lastTargetPID: pid_t = 0, lastTargetIgnored = false // one-entry cache, so a burst of notches looks up once var lastTargetPID: pid_t = 0, lastTargetIgnored = false
func targetIgnored(_ pid: pid_t) -> Bool { func targetIgnored(_ pid: pid_t) -> Bool {
guard pid != 0 else { return false } guard pid != 0 else { return false }
if pid != lastTargetPID { lastTargetPID = pid; lastTargetIgnored = isIgnored(NSRunningApplication(processIdentifier: pid)) } if pid != lastTargetPID { lastTargetPID = pid; lastTargetIgnored = isIgnored(NSRunningApplication(processIdentifier: pid)) }
@@ -310,17 +245,15 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
} }
guard type == .scrollWheel, guard type == .scrollWheel,
event.getIntegerValueField(.eventSourceUserData) != SYNTH_TAG, 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(.scrollWheelEventScrollPhase) == 0,
event.getIntegerValueField(.scrollWheelEventMomentumPhase) == 0, event.getIntegerValueField(.scrollWheelEventMomentumPhase) == 0,
event.getIntegerValueField(.scrollWheelEventScrollCount) == 0 else { event.getIntegerValueField(.scrollWheelEventScrollCount) == 0 else {
return Unmanaged.passUnretained(event) return Unmanaged.passUnretained(event)
} }
let rawY = wheelDelta(event, .scrollWheelEventPointDeltaAxis1, .scrollWheelEventFixedPtDeltaAxis1, .scrollWheelEventDeltaAxis1) 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) } 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)) let pid = pid_t(event.getIntegerValueField(.eventTargetUnixProcessID))
if targetIgnored(pid) { return Unmanaged.passUnretained(event) } if targetIgnored(pid) { return Unmanaged.passUnretained(event) }
@@ -333,7 +266,6 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
event.setIntegerValueField(f, value: -event.getIntegerValueField(f)) 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 { guard !event.flags.contains(.maskCommand), pid != 0, let copy = event.copy() else {
return Unmanaged.passUnretained(event) return Unmanaged.passUnretained(event)
} }
@@ -342,12 +274,10 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in
v == 0 ? 0 : sign * (v < 0 ? -1 : 1) * max(abs(v), config.scrollStep) v == 0 ? 0 : sign * (v < 0 ? -1 : 1) * max(abs(v), config.scrollStep)
} }
smoother.feed(notch(rawY), notch(rawX), event: copy, pid: pid) smoother.feed(notch(rawY), notch(rawX), event: copy, pid: pid)
return nil // swallow the original notch return nil
} }
func startSmoothScroll() { 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) let mask = CGEventMask(1 << CGEventType.scrollWheel.rawValue)
guard let port = CGEvent.tapCreate(tap: .cgAnnotatedSessionEventTap, place: .tailAppendEventTap, options: .defaultTap, guard let port = CGEvent.tapCreate(tap: .cgAnnotatedSessionEventTap, place: .tailAppendEventTap, options: .defaultTap,
eventsOfInterest: mask, callback: scrollTapCB, userInfo: nil) else { eventsOfInterest: mask, callback: scrollTapCB, userInfo: nil) else {
@@ -360,43 +290,36 @@ func startSmoothScroll() {
log("smooth scroll: on") log("smooth scroll: on")
} }
// MARK: - HID++ constants let REPORT_SHORT: UInt8 = 0x10
let REPORT_LONG: UInt8 = 0x11
let REPORT_SHORT: UInt8 = 0x10 // 7 bytes (receiver / HID++ 1.0) let SW_ID: UInt8 = 0x0A
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_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_SMARTSHIFT: UInt16 = 0x2110, F_SMARTSHIFT_ENH: UInt16 = 0x2111
let F_THUMBWHEEL: UInt16 = 0x2150, F_DPI: UInt16 = 0x2201 let F_THUMBWHEEL: UInt16 = 0x2150, F_DPI: UInt16 = 0x2201
let F_WIRELESS_STATUS: UInt16 = 0x1D4B // announces a wake that lost volatile settings let F_WIRELESS_STATUS: UInt16 = 0x1D4B
// MARK: - Device state
final class Device { final class Device {
let hid: IOHIDDevice let hid: IOHIDDevice
var devIdx: UInt8 = 0xFF // 0xFF = direct (BLE/USB); 1...6 = receiver slot var devIdx: UInt8 = 0xFF
var feat: [UInt16: UInt8] = [:] // featureID → feature index (device-specific!) var feat: [UInt16: UInt8] = [:]
var inbox: [[UInt8]] = [] var inbox: [[UInt8]] = []
let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: 64) let buf = UnsafeMutablePointer<UInt8>.allocate(capacity: 64)
var pressed: Set<UInt16> = [] var pressed: Set<UInt16> = []
var gestureDown = false, gestureFired = false, gx = 0, gy = 0 var gestureDown = false, gestureFired = false, gx = 0, gy = 0
var busy = false var busy = false
var diverted: [UInt16] = [] var diverted: [UInt16] = []
var divertsApplied = false // buttons currently match !frontmostIgnored var divertsApplied = false
init(_ h: IOHIDDevice) { hid = h } init(_ h: IOHIDDevice) { hid = h }
} }
var devices: [ObjectIdentifier: Device] = [:] var devices: [ObjectIdentifier: Device] = [:]
// MARK: - Transport
@discardableResult @discardableResult
func send(_ d: Device, _ bytes: [UInt8]) -> Bool { func send(_ d: Device, _ bytes: [UInt8]) -> Bool {
var r = bytes var r = bytes
let len = r[0] == REPORT_SHORT ? 7 : 20 let len = r[0] == REPORT_SHORT ? 7 : 20
while r.count < len { r.append(0) } while r.count < len { r.append(0) }
// macOS: buffer includes the report ID byte when the device uses numbered reports.
let rc = r.withUnsafeBufferPointer { let rc = r.withUnsafeBufferPointer {
IOHIDDeviceSetReport(d.hid, kIOHIDReportTypeOutput, CFIndex(r[0]), $0.baseAddress!, len) IOHIDDeviceSetReport(d.hid, kIOHIDReportTypeOutput, CFIndex(r[0]), $0.baseAddress!, len)
} }
@@ -404,8 +327,6 @@ func send(_ d: Device, _ bytes: [UInt8]) -> Bool {
return rc == kIOReturnSuccess 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] = [], func request(_ d: Device, feat fi: UInt8, fn: UInt8, _ params: [UInt8] = [],
devIdx: UInt8? = nil, timeout: Double = 1.0) -> [UInt8]? { devIdx: UInt8? = nil, timeout: Double = 1.0) -> [UInt8]? {
let di = devIdx ?? d.devIdx let di = devIdx ?? d.devIdx
@@ -416,8 +337,8 @@ func request(_ d: Device, feat fi: UInt8, fn: UInt8, _ params: [UInt8] = [],
while Date() < deadline { while Date() < deadline {
if let i = d.inbox.firstIndex(where: { r in if let i = d.inbox.firstIndex(where: { r in
r[1] == di && ( r[1] == di && (
(r[2] == fi && r[3] == fnSw) || // success (r[2] == fi && r[3] == fnSw) ||
((r[2] == 0xFF || r[2] == 0x8F) && r[3] == fi && r[4] == fnSw)) // 2.0 / 1.0 error ((r[2] == 0xFF || r[2] == 0x8F) && r[3] == fi && r[4] == fnSw))
}) { }) {
let r = d.inbox.remove(at: i) let r = d.inbox.remove(at: i)
if r[2] == 0xFF || r[2] == 0x8F { if r[2] == 0xFF || r[2] == 0x8F {
@@ -432,17 +353,12 @@ func request(_ d: Device, feat fi: UInt8, fn: UInt8, _ params: [UInt8] = [],
return nil return nil
} }
/// IRoot.getFeature: featureID → index (0 = unsupported).
func featureIndex(_ d: Device, _ id: UInt16, devIdx: UInt8? = nil) -> UInt8? { 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), 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 } r[0] != 0 else { return nil }
return r[0] 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 { func findMouse(_ d: Device) -> Bool {
for idx in [UInt8(0xFF)] + Array(1...6) { 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), guard let r = request(d, feat: 0x00, fn: 1, [0, 0, 0x5A], devIdx: idx, timeout: 0.4),
@@ -479,25 +395,21 @@ func probe(_ d: Device) {
if let fi = d.feat[F_DPI], let r = request(d, feat: fi, fn: 2, [0]) { 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]))") 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 { if let fi = d.feat[F_REPROG], let cnt = request(d, feat: fi, fn: 0)?.first {
log("controls (CID: flags):") log("controls (CID: flags):")
for i in 0..<cnt { for i in 0..<cnt {
guard let r = request(d, feat: fi, fn: 1, [i]) else { continue } guard let r = request(d, feat: fi, fn: 1, [i]) else { continue }
let cid = UInt16(r[0]) << 8 | UInt16(r[1]) 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 let divertable = r[4] & 0x20 != 0, rawXY = r[8] & 0x01 != 0
log(String(format: " CID 0x%04X%@%@", cid, divertable ? " divertable" : "", rawXY ? " rawXY" : "")) log(String(format: " CID 0x%04X%@%@", cid, divertable ? " divertable" : "", rawXY ? " rawXY" : ""))
} }
} }
} }
// MARK: - Configuration
func setDivert(_ d: Device, _ cid: UInt16, on: Bool, rawXY: Bool = false) { func setDivert(_ d: Device, _ cid: UInt16, on: Bool, rawXY: Bool = false) {
guard let fi = d.feat[F_REPROG] else { return } guard let fi = d.feat[F_REPROG] else { return }
var flags: UInt8 = 0x02 | (on ? 0x01 : 0) // dvalid | divert var flags: UInt8 = 0x02 | (on ? 0x01 : 0)
if rawXY { flags |= 0x20 | (on ? 0x10 : 0) } // rvalid | rawXY (stream dx/dy while held) 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 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")) log(String(format: " %@ CID 0x%04X: %@", on ? "divert" : "undivert", cid, ok ? "ok" : "FAILED"))
if ok && on { d.diverted.append(cid) } if ok && on { d.diverted.append(cid) }
@@ -515,8 +427,6 @@ func configure(_ d: Device) {
log("device: \(deviceName(d))") log("device: \(deviceName(d))")
if probeOnly { probe(d); exit(0) } 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 d.devIdx != 0xFF { send(d, [REPORT_SHORT, 0xFF, 0x80, 0x00, 0x00, 0x01, 0x00]) }
if let dpi = config.dpi, let fi = d.feat[F_DPI] { if let dpi = config.dpi, let fi = d.feat[F_DPI] {
@@ -524,14 +434,13 @@ func configure(_ d: Device) {
log(" DPI \(dpi): \(ok ? "ok" : "FAILED")") log(" DPI \(dpi): \(ok ? "ok" : "FAILED")")
} }
if let t = config.smartShiftThreshold { if let t = config.smartShiftThreshold {
// wheelMode 0 = leave as-is (respects the ratchet button), autoDisengage = t, 3rd byte 0 = no change.
var ok = false var ok = false
if let fi = d.feat[F_SMARTSHIFT_ENH] { ok = request(d, feat: fi, fn: 2, [0, t, 0]) != nil } 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 } 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")") log(" SmartShift threshold \(t): \(ok ? "ok" : "FAILED")")
} }
d.diverted = []; d.pressed = []; d.gestureDown = false; d.divertsApplied = false d.diverted = []; d.pressed = []; d.gestureDown = false; d.divertsApplied = false
syncDiverts(d) // stays undiverted if an ignored app is frontmost syncDiverts(d)
} }
func divertAll(_ d: Device) { func divertAll(_ d: Device) {
@@ -546,8 +455,6 @@ func undivertAll(_ d: Device) {
d.diverted = []; d.pressed = []; d.gestureDown = false 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) { func syncDiverts(_ d: Device) {
while d.divertsApplied != !frontmostIgnored { while d.divertsApplied != !frontmostIgnored {
let want = !frontmostIgnored let want = !frontmostIgnored
@@ -556,8 +463,6 @@ func syncDiverts(_ d: Device) {
} }
} }
// MARK: - Button events
func buttonDown(_ d: Device, _ cid: UInt16) { 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 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) } if let a = config.buttons[cid] { perform(a) }
@@ -575,7 +480,6 @@ func buttonUp(_ d: Device, _ cid: UInt16) {
} }
func handleReport(_ d: Device, _ r: [UInt8]) { 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[0] == REPORT_SHORT && r[2] == 0x41 && r[1] != 0xFF {
if r[1] == d.devIdx && (r[4] & 0x40) == 0 { if r[1] == d.devIdx && (r[4] & 0x40) == 0 {
log("device \(r[1]) (re)connected → re-applying") log("device \(r[1]) (re)connected → re-applying")
@@ -583,20 +487,17 @@ func handleReport(_ d: Device, _ r: [UInt8]) {
} }
return 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 } 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 { 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") log("device woke → re-applying")
DispatchQueue.main.async { configure(d) } DispatchQueue.main.async { configure(d) }
return 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 } guard r.count >= 12, r[1] == d.devIdx, let fi = d.feat[F_REPROG], r[2] == fi else { return }
switch r[3] >> 4 { switch r[3] >> 4 {
case 0: // divertedButtonsEvent: up to 4 currently-held CIDs case 0:
var now: Set<UInt16> = [] var now: Set<UInt16> = []
for i in stride(from: 4, to: 12, by: 2) { for i in stride(from: 4, to: 12, by: 2) {
let c = UInt16(r[i]) << 8 | UInt16(r[i + 1]) let c = UInt16(r[i]) << 8 | UInt16(r[i + 1])
@@ -606,11 +507,10 @@ func handleReport(_ d: Device, _ r: [UInt8]) {
d.pressed = now d.pressed = now
down.forEach { buttonDown(d, $0) } down.forEach { buttonDown(d, $0) }
up.forEach { buttonUp(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 } guard d.gestureDown else { return }
d.gx += Int(Int16(bitPattern: UInt16(r[4]) << 8 | UInt16(r[5]))) d.gx += Int(Int16(bitPattern: UInt16(r[4]) << 8 | UInt16(r[5])))
d.gy += Int(Int16(bitPattern: UInt16(r[6]) << 8 | UInt16(r[7]))) 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) } if !d.gestureFired && d.gy >= config.gestureThreshold && d.gy > abs(d.gx) { d.gestureFired = true; perform(.appExpose) }
default: break default: break
} }
@@ -625,8 +525,6 @@ let inputCB: IOHIDReportCallback = { ctx, _, _, _, _, report, len in
handleReport(d, r) handleReport(d, r)
} }
// MARK: - Main
if !probeOnly { if !probeOnly {
let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary let opts = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
if !AXIsProcessTrustedWithOptions(opts) { if !AXIsProcessTrustedWithOptions(opts) {
@@ -636,7 +534,6 @@ if !probeOnly {
} }
let mgr = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) 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]] = [ let matches: [[String: Any]] = [
[kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF00, kIOHIDDeviceUsageKey: 0x0002], [kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF00, kIOHIDDeviceUsageKey: 0x0002],
[kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF43, kIOHIDDeviceUsageKey: 0x0202], [kIOHIDVendorIDKey: 0x046D, kIOHIDDeviceUsagePageKey: 0xFF43, kIOHIDDeviceUsageKey: 0x0202],
@@ -650,7 +547,7 @@ IOHIDManagerRegisterDeviceMatchingCallback(mgr, { _, _, _, dev in
let name = IOHIDDeviceGetProperty(dev, kIOHIDProductKey as CFString) as? String ?? "?" let name = IOHIDDeviceGetProperty(dev, kIOHIDProductKey as CFString) as? String ?? "?"
log(String(format: "matched HID interface: %@ (pid 0x%04X)", name, pid)) log(String(format: "matched HID interface: %@ (pid 0x%04X)", name, pid))
IOHIDDeviceRegisterInputReportCallback(dev, d.buf, 64, inputCB, Unmanaged.passUnretained(d).toOpaque()) 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) }, nil)
IOHIDManagerRegisterDeviceRemovalCallback(mgr, { _, _, _, dev in IOHIDManagerRegisterDeviceRemovalCallback(mgr, { _, _, _, dev in
@@ -659,7 +556,6 @@ IOHIDManagerRegisterDeviceRemovalCallback(mgr, { _, _, _, dev in
}, nil) }, nil)
IOHIDManagerScheduleWithRunLoop(mgr, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) IOHIDManagerScheduleWithRunLoop(mgr, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue)
// kIOHIDOptionsTypeNone = NOT exclusive. Seizing would kill pointer input on BLE (single IOHIDDevice).
let rc = IOHIDManagerOpen(mgr, IOOptionBits(kIOHIDOptionsTypeNone)) let rc = IOHIDManagerOpen(mgr, IOOptionBits(kIOHIDOptionsTypeNone))
if rc != kIOReturnSuccess { if rc != kIOReturnSuccess {
log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc)) log(String(format: "IOHIDManagerOpen failed: 0x%08x — grant Input Monitoring to this binary/terminal", rc))
@@ -731,7 +627,6 @@ let permissionObserver = DistributedNotificationCenter.default().addObserver(
watchdogQueue.asyncAfter(deadline: .now() + 0.1) { 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) signal(SIGINT, SIG_IGN); signal(SIGTERM, SIG_IGN)
let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in
let src = DispatchSource.makeSignalSource(signal: s, queue: .main) let src = DispatchSource.makeSignalSource(signal: s, queue: .main)
@@ -743,7 +638,6 @@ let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in
if !probeOnly { if !probeOnly {
frontmostIgnored = isIgnored(NSWorkspace.shared.frontmostApplication) 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( let frontmostObserver = probeOnly ? nil : NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { n in forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { n in
let app = n.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication let app = n.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
@@ -751,7 +645,7 @@ let frontmostObserver = probeOnly ? nil : NSWorkspace.shared.notificationCenter.
guard ign != frontmostIgnored else { return } guard ign != frontmostIgnored else { return }
frontmostIgnored = ign frontmostIgnored = ign
log("ignored app frontmost: \(app?.localizedName ?? "?"), buttons \(ign ? "native" : "diverted")") 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 for d in devices.values where !d.busy {
d.busy = true; defer { d.busy = false } d.busy = true; defer { d.busy = false }
syncDiverts(d) syncDiverts(d)
} }