diff --git a/mxd.swift b/mxd.swift index d66de9c..6b34155 100644 --- a/mxd.swift +++ b/mxd.swift @@ -12,7 +12,10 @@ // 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. +// 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. @@ -86,12 +89,50 @@ struct Config { // 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 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)!) } + +/// 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 @@ -230,6 +271,22 @@ func wheelDelta(_ e: CGEvent, _ point: CGEventField, _ fixed: CGEventField, _ li 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 // macOS disables a tap that stalls or on secure input; just turn it back on. if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { @@ -248,6 +305,10 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in 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] { @@ -258,7 +319,6 @@ let scrollTapCB: CGEventTapCallBack = { _, type, event, _ in } } // Cmd+wheel stays unsmoothed. So does a notch with no target app, since there's nowhere to send frames. - let pid = pid_t(event.getIntegerValueField(.eventTargetUnixProcessID)) guard !event.flags.contains(.maskCommand), pid != 0, let copy = event.copy() else { return Unmanaged.passUnretained(event) } @@ -309,6 +369,7 @@ final class Device { var gestureDown = 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] = [:] @@ -454,7 +515,11 @@ func configure(_ d: Device) { else if let fi = d.feat[F_SMARTSHIFT] { ok = request(d, feat: fi, fn: 1, [0, t, 0]) != nil } log(" SmartShift threshold \(t): \(ok ? "ok" : "FAILED")") } - d.diverted = []; d.pressed = []; d.gestureDown = false + d.diverted = []; d.pressed = []; d.gestureDown = false; d.divertsApplied = false + syncDiverts(d) // 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) @@ -463,7 +528,17 @@ func configure(_ d: Device) { func undivertAll(_ d: Device) { for c in d.diverted { setDivert(d, c, on: false, rawXY: c == CID_GESTURE && config.gestureSwipes) } - d.diverted = [] + d.diverted = []; d.pressed = []; d.gestureDown = false +} + +/// 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 @@ -603,6 +678,23 @@ let sigSources = [SIGINT, SIGTERM].map { s -> DispatchSourceSignal in 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) } }