From cbbb631f3c0833fe025ebf091756982fabc62c74 Mon Sep 17 00:00:00 2001 From: Yigit BALABAN Date: Fri, 30 Oct 2026 23:06:52 +0300 Subject: [PATCH] Fix scroll direction and DPI, reduce scroll CPU Stop reversing the wheel and stop raising DPI to 1600, since both changed behaviour the user relied on. Send glide frames straight to the target app from an annotated-session tap, as Mos does, so frames no longer pass back through mxd's own tap. Reuse one event per notch, reduce the scroll filter to two values, and stop the timer once nothing more can be posted. Remove the background activity assertion, which was preventing idle system sleep. Assisted-by: Claude Opus 5.5 Signed-off-by: Yigit BALABAN --- mxd.swift | 94 +++++++++++++++++++++++++++---------------------------- 1 file changed, 47 insertions(+), 47 deletions(-) diff --git a/mxd.swift b/mxd.swift index d5af2cf..2d4e34a 100644 --- a/mxd.swift +++ b/mxd.swift @@ -15,7 +15,7 @@ // 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. +// power switch on the underside. Diverts are volatile; DPI and SmartShift may stay on the mouse. import Foundation import AppKit @@ -58,18 +58,18 @@ struct Config { 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 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). + // 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 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" + 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: Mos's generateDurationTransition (0.085 at 4.35). @@ -129,8 +129,8 @@ 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 sent through a short smoothing -// window and posted as a pixel-unit scroll event, which apps treat like trackpad scrolling. +// 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. @@ -139,7 +139,7 @@ func perform(_ a: Action) { 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] + var filtered = 0.0 func add(_ delta: Double, _ gain: Double) { if delta * lastDelta > 0 { target += delta * gain } @@ -147,29 +147,38 @@ final class Axis { lastDelta = delta } - /// Next frame's output in pixels: Mos's lerp + ScrollFilter (a 2-frame delay with a 5-point curve). + /// 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 23% blend. 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] + let output = filtered + filtered += 0.23 * (frame - filtered) + return output } - var remaining: Double { abs(target - current) } - func reset() { target = 0; current = 0; lastDelta = 0; window = [0, 0, 0, 0, 0] } + /// 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() - var fracY = 0.0, fracX = 0.0 // sub-pixel carry, since posted events are whole pixels + let transition = config.scrollTransition, deadZone = config.scrollDeadZone + 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, flags f: CGEventFlags) { - let gain = config.scrollSpeed * (f.contains(.maskAlternate) ? config.scrollDash : 1) + 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) - flags = f + 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) @@ -184,25 +193,17 @@ final class Smoother { } func tick() { - let a = config.scrollTransition - var oy = y.next(a), ox = x.next(a) + var oy = y.next(transition), ox = x.next(transition) 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 max(abs(oy), abs(ox)) > deadZone, let e = event { + e.setDoubleValueField(.scrollWheelEventPointDeltaAxis1, value: oy) + e.setDoubleValueField(.scrollWheelEventPointDeltaAxis2, value: ox) + e.postToPid(targetPID) } - if output <= config.scrollDeadZone && y.remaining <= config.scrollDeadZone && x.remaining <= config.scrollDeadZone { + if y.settled(transition, deadZone) && x.settled(transition, deadZone) { timer?.invalidate(); timer = nil y.reset(); x.reset() - fracY = 0; fracX = 0 + event = nil } } } @@ -235,31 +236,33 @@ 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) } - 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)) - } + 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. + let pid = pid_t(event.getIntegerValueField(.eventTargetUnixProcessID)) + 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), flags: event.flags) + 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: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, + 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 @@ -519,9 +522,6 @@ let inputCB: IOHIDReportCallback = { ctx, _, _, _, _, report, len in // 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) {