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 <balaban@yigid.dev>
This commit is contained in:
yigid committed 2026-10-30 23:06:52 +03:00
1 parent 3a1d9d3b8d
commit cbbb631f3c
1 file changed
+47 -47
+47 -47
View File
@@ -15,7 +15,7 @@
// Secrets: none. No files written, no network. // Secrets: none. No files written, no network.
// Rollback: Ctrl-C / SIGTERM un-diverts buttons and removes the scroll tap (process exit). // 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 // 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 Foundation
import AppKit import AppKit
@@ -58,18 +58,18 @@ struct Config {
var gestureThreshold = 60 // raw sensor counts before a hold counts as a swipe var gestureThreshold = 60 // raw sensor counts before a hold counts as a swipe
// Sensor / wheel // 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. 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). // 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 smoothScroll = true
var scrollStep = 33.6 // a notch counts as at least this many pixels 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 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 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 scrollDeadZone = 1.0 // frames at or below this many pixels aren't posted
var scrollDash = 5.0 // multiplier while Option is held 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. // 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). // 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 // MARK: - Smooth scrolling
// //
// Mechanism, same as Mos: an active CGEventTap swallows each wheel notch and adds its distance to // 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 // a target. Every display frame, a fixed fraction of what's left is smoothed and sent straight to
// window and posted as a pixel-unit scroll event, which apps treat like trackpad scrolling. // 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. // 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. // 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 { final class Axis {
var target = 0.0, current = 0.0 // pixels requested / pixels consumed so far 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 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) { func add(_ delta: Double, _ gain: Double) {
if delta * lastDelta > 0 { target += delta * gain } if delta * lastDelta > 0 { target += delta * gain }
@@ -147,29 +147,38 @@ final class Axis {
lastDelta = delta 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 { func next(_ transition: Double) -> Double {
let frame = (target - current) * transition let frame = (target - current) * transition
current += frame current += frame
let first = window[1], diff = frame - first let output = filtered
window = [first, first + 0.23 * diff, first + 0.5 * diff, first + 0.77 * diff, frame] filtered += 0.23 * (frame - filtered)
return window[0] return output
} }
var remaining: Double { abs(target - current) } /// True once every later frame would be at or below the dead zone, so none would be posted.
func reset() { target = 0; current = 0; lastDelta = 0; window = [0, 0, 0, 0, 0] } 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 { final class Smoother {
let y = Axis(), x = Axis() 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 flags: CGEventFlags = []
var timer: Timer? var timer: Timer?
func feed(_ dy: Double, _ dx: Double, flags f: CGEventFlags) { func feed(_ dy: Double, _ dx: Double, event e: CGEvent, pid: pid_t) {
let gain = config.scrollSpeed * (f.contains(.maskAlternate) ? config.scrollDash : 1) flags = e.flags
let gain = config.scrollSpeed * (flags.contains(.maskAlternate) ? config.scrollDash : 1)
y.add(dy, gain); x.add(dx, gain) 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 { if timer == nil {
let t = Timer(timeInterval: 1.0 / refreshRate(), repeats: true) { [unowned self] _ in self.tick() } let t = Timer(timeInterval: 1.0 / refreshRate(), repeats: true) { [unowned self] _ in self.tick() }
RunLoop.main.add(t, forMode: .common) RunLoop.main.add(t, forMode: .common)
@@ -184,25 +193,17 @@ final class Smoother {
} }
func tick() { func tick() {
let a = config.scrollTransition var oy = y.next(transition), ox = x.next(transition)
var oy = y.next(a), ox = x.next(a)
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) } // Shift+wheel: sideways
let output = max(abs(oy), abs(ox)) if max(abs(oy), abs(ox)) > deadZone, let e = event {
if output > config.scrollDeadZone { e.setDoubleValueField(.scrollWheelEventPointDeltaAxis1, value: oy)
fracY += oy; fracX += ox e.setDoubleValueField(.scrollWheelEventPointDeltaAxis2, value: ox)
let iy = Int32(fracY.rounded(.towardZero)), ix = Int32(fracX.rounded(.towardZero)) e.postToPid(targetPID)
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 { if y.settled(transition, deadZone) && x.settled(transition, deadZone) {
timer?.invalidate(); timer = nil timer?.invalidate(); timer = nil
y.reset(); x.reset() 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 let rawX = wheelDelta(event, .scrollWheelEventPointDeltaAxis2, .scrollWheelEventFixedPtDeltaAxis2, .scrollWheelEventDeltaAxis2) // thumb wheel
guard rawY != 0 || rawX != 0 else { return Unmanaged.passUnretained(event) } 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 {
if config.reverseMouseScroll { for f in [CGEventField.scrollWheelEventPointDeltaAxis1, .scrollWheelEventPointDeltaAxis2,
for f in [CGEventField.scrollWheelEventPointDeltaAxis1, .scrollWheelEventPointDeltaAxis2, .scrollWheelEventFixedPtDeltaAxis1, .scrollWheelEventFixedPtDeltaAxis2] {
.scrollWheelEventFixedPtDeltaAxis1, .scrollWheelEventFixedPtDeltaAxis2] { event.setDoubleValueField(f, value: -event.getDoubleValueField(f))
event.setDoubleValueField(f, value: -event.getDoubleValueField(f))
}
for f in [CGEventField.scrollWheelEventDeltaAxis1, .scrollWheelEventDeltaAxis2] {
event.setIntegerValueField(f, value: -event.getIntegerValueField(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) return Unmanaged.passUnretained(event)
} }
let sign = config.reverseMouseScroll ? -1.0 : 1.0 let sign = config.reverseMouseScroll ? -1.0 : 1.0
func notch(_ v: Double) -> Double { func notch(_ v: Double) -> Double {
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), flags: event.flags) smoother.feed(notch(rawY), notch(rawX), event: copy, pid: pid)
return nil // swallow the original notch return nil // swallow the original notch
} }
func startSmoothScroll() { func startSmoothScroll() {
// Mask = scroll events only. This tap never sees keystrokes or clicks. // 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: .cgSessionEventTap, place: .headInsertEventTap, 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 {
log("smooth scroll: tapCreate failed — grant Accessibility, then restart mxd") log("smooth scroll: tapCreate failed — grant Accessibility, then restart mxd")
return return
@@ -519,9 +522,6 @@ let inputCB: IOHIDReportCallback = { ctx, _, _, _, _, report, len in
// MARK: - Main // 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 { 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) {