Files
mxd/mxd.swift
T
yigid 3a1d9d3b8d initial commit
Signed-off-by: Yigit BALABAN <balaban@yigid.dev>
2026-10-30 22:22:35 +03:00

576 lines
27 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.
//
// 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. All HID++ settings here are volatile.
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 ←/→ Spaces, ↓ App Exposé, tap = its action.
var gestureSwipes = true
var gestureThreshold = 60 // raw sensor counts before a hold counts as a swipe
// Sensor / wheel
var dpi: Int? = 1600 // 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).
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 scrollDuration = 4.35 // 0...5, higher = longer glide. See scrollTransition.
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 = true // 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: Mos's generateDurationTransition (0.085 at 4.35).
var scrollTransition: Double { (1000 * (1 - (scrollDuration / 5.2).squareRoot())).rounded() / 1000 }
}
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 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 sent through a short smoothing
// window and posted as a pixel-unit scroll event, which apps treat like trackpad scrolling.
// 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 window = [0.0, 0.0, 0.0, 0.0, 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 (a 2-frame delay with a 5-point curve).
func next(_ transition: Double) -> Double {
let frame = (target - current) * transition
current += frame
let first = window[1], diff = frame - first
window = [first, first + 0.23 * diff, first + 0.5 * diff, first + 0.77 * diff, frame]
return window[0]
}
var remaining: Double { abs(target - current) }
func reset() { target = 0; current = 0; lastDelta = 0; window = [0, 0, 0, 0, 0] }
}
final class Smoother {
let y = Axis(), x = Axis()
var fracY = 0.0, fracX = 0.0 // sub-pixel carry, since posted events are whole pixels
var flags: CGEventFlags = []
var timer: Timer?
func feed(_ dy: Double, _ dx: Double, flags f: CGEventFlags) {
let gain = config.scrollSpeed * (f.contains(.maskAlternate) ? config.scrollDash : 1)
y.add(dy, gain); x.add(dx, gain)
flags = f
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() {
let a = config.scrollTransition
var oy = y.next(a), ox = x.next(a)
if flags.contains(.maskShift) && oy != 0 && ox == 0 { (oy, ox) = (0, oy) } // Shift+wheel: sideways
let output = max(abs(oy), abs(ox))
if output > config.scrollDeadZone {
fracY += oy; fracX += ox
let iy = Int32(fracY.rounded(.towardZero)), ix = Int32(fracX.rounded(.towardZero))
fracY -= Double(iy); fracX -= Double(ix)
if let e = CGEvent(scrollWheelEvent2Source: synthSource, units: .pixel, wheelCount: 2,
wheel1: iy, wheel2: ix, wheel3: 0) {
e.flags = flags
e.setIntegerValueField(.eventSourceUserData, value: SYNTH_TAG)
e.post(tap: .cgSessionEventTap)
}
}
if output <= config.scrollDeadZone && y.remaining <= config.scrollDeadZone && x.remaining <= config.scrollDeadZone {
timer?.invalidate(); timer = nil
y.reset(); x.reset()
fracY = 0; fracX = 0
}
}
}
let smoother = Smoother()
var tapPort: CFMachPort?
/// 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))
}
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 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) }
if event.flags.contains(.maskCommand) { // pass through unsmoothed, but keep the direction consistent
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))
}
}
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), flags: event.flags)
return nil // swallow the original notch
}
func startSmoothScroll() {
// Mask = scroll events only. This tap never sees keystrokes or clicks.
let mask = CGEventMask(1 << CGEventType.scrollWheel.rawValue)
guard let port = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap, 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, gx = 0, gy = 0
var busy = false
var diverted: [UInt16] = []
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
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 = []
}
// MARK: - Button events
func buttonDown(_ d: Device, _ cid: UInt16) {
if cid == CID_GESTURE && config.gestureSwipes { d.gestureDown = true; 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
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])))
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
// Keep macOS from coalescing the scroll timer while mxd sits in the background.
let activity = ProcessInfo.processInfo.beginActivity(options: [.userInitiated, .latencyCritical], reason: "smooth scrolling")
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))
}
// 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 {
DispatchQueue.main.asyncAfter(deadline: .now() + 5) { log("probe: no device found within 5s"); exit(1) }
}
CFRunLoopRun()