-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMXMaster.swift
More file actions
290 lines (247 loc) · 10.9 KB
/
MXMaster.swift
File metadata and controls
290 lines (247 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
import Cocoa
import CoreGraphics
import SwiftUI
// MARK: - Settings
class Settings: ObservableObject {
static let shared = Settings()
@Published var reverseMouseScroll: Bool {
didSet { UserDefaults.standard.set(reverseMouseScroll, forKey: "reverseMouseScroll") }
}
@Published var thumbWheelZoom: Bool {
didSet { UserDefaults.standard.set(thumbWheelZoom, forKey: "thumbWheelZoom") }
}
@Published var thumbButtonMissionControl: Bool {
didSet { UserDefaults.standard.set(thumbButtonMissionControl, forKey: "thumbButtonMissionControl") }
}
@Published var zoomSensitivity: Double {
didSet { UserDefaults.standard.set(zoomSensitivity, forKey: "zoomSensitivity") }
}
private init() {
// Load defaults
let defaults = UserDefaults.standard
if defaults.object(forKey: "reverseMouseScroll") == nil {
defaults.set(true, forKey: "reverseMouseScroll")
}
if defaults.object(forKey: "thumbWheelZoom") == nil {
defaults.set(true, forKey: "thumbWheelZoom")
}
if defaults.object(forKey: "thumbButtonMissionControl") == nil {
defaults.set(true, forKey: "thumbButtonMissionControl")
}
if defaults.object(forKey: "zoomSensitivity") == nil {
defaults.set(0.1, forKey: "zoomSensitivity")
}
self.reverseMouseScroll = defaults.bool(forKey: "reverseMouseScroll")
self.thumbWheelZoom = defaults.bool(forKey: "thumbWheelZoom")
self.thumbButtonMissionControl = defaults.bool(forKey: "thumbButtonMissionControl")
self.zoomSensitivity = defaults.double(forKey: "zoomSensitivity")
}
}
// MARK: - Settings View
struct SettingsView: View {
@ObservedObject var settings = Settings.shared
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("MX Master Settings")
.font(.headline)
Toggle("Reverse mouse scroll (not trackpad)", isOn: $settings.reverseMouseScroll)
Toggle("Thumb wheel zooms (pinch gesture)", isOn: $settings.thumbWheelZoom)
if settings.thumbWheelZoom {
HStack {
Text("Zoom sensitivity:")
Slider(value: $settings.zoomSensitivity, in: 0.01...0.5)
Text(String(format: "%.2f", settings.zoomSensitivity))
.frame(width: 35)
.font(.caption.monospacedDigit())
}
.padding(.leading, 20)
}
Toggle("Thumb button opens Mission Control", isOn: $settings.thumbButtonMissionControl)
Spacer()
Text("~100KB • No Logitech bloatware needed")
.font(.caption)
.foregroundColor(.secondary)
}
.padding(20)
.frame(width: 380, height: 220)
}
}
// MARK: - Magnification Event Helper
// Based on mac-mouse-fix's TouchSimulator using undocumented CGEvent fields
// Event Type 29 = NSEventTypeGesture
// Field 110 = 8 (kIOHIDEventTypeZoom)
// Field 113 = magnification value
// Field 132 = phase (1=began, 2=changed, 4=ended)
let kCGEventGesture = CGEventType(rawValue: 29)!
let kGestureFieldSubtype = CGEventField(rawValue: 110)!
let kGestureFieldMagnification = CGEventField(rawValue: 113)!
let kGestureFieldPhase = CGEventField(rawValue: 132)!
let kIOHIDEventTypeZoom: Int64 = 8
let kIOHIDEventPhaseBegan: Int64 = 1
let kIOHIDEventPhaseChanged: Int64 = 2
let kIOHIDEventPhaseEnded: Int64 = 4
var zoomGestureActive = false
var zoomEndTimer: DispatchWorkItem?
var interpolationTimer: DispatchSourceTimer?
var remainingMagnification: Double = 0
func postMagnificationEvent(magnification: Double, phase: Int64) {
guard let event = CGEvent(source: nil) else { return }
event.type = kCGEventGesture
event.setIntegerValueField(kGestureFieldSubtype, value: kIOHIDEventTypeZoom)
event.setDoubleValueField(kGestureFieldMagnification, value: magnification)
event.setIntegerValueField(kGestureFieldPhase, value: phase)
event.post(tap: .cgSessionEventTap)
}
func startInterpolatedZoom(totalMagnification: Double) {
// Add to remaining magnification
remainingMagnification += totalMagnification
// Start interpolation timer if not already running
if interpolationTimer == nil {
let timer = DispatchSource.makeTimerSource(queue: .main)
timer.schedule(deadline: .now(), repeating: .milliseconds(8)) // ~120Hz
timer.setEventHandler {
if abs(remainingMagnification) < 0.001 {
return
}
// Ease out - take 20% of remaining each frame
let step = remainingMagnification * 0.2
remainingMagnification -= step
postMagnificationEvent(magnification: step, phase: kIOHIDEventPhaseChanged)
}
timer.resume()
interpolationTimer = timer
}
}
// MARK: - Event Handling
func eventCallback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? {
let settings = Settings.shared
// Handle thumb button (button 6) -> Mission Control
if type == .otherMouseDown && settings.thumbButtonMissionControl {
let buttonNumber = event.getIntegerValueField(.mouseEventButtonNumber)
if buttonNumber == 6 {
let task = Process()
task.launchPath = "/usr/bin/open"
task.arguments = ["-a", "Mission Control"]
try? task.run()
return nil
}
}
// Handle scroll wheel events
if type == .scrollWheel {
// Check if this is from a mouse (discrete) vs trackpad (continuous)
let isContinuous = event.getIntegerValueField(.scrollWheelEventIsContinuous)
let isMouseWheel = isContinuous == 0
let verticalDelta = event.getIntegerValueField(.scrollWheelEventPointDeltaAxis1)
let horizontalDelta = event.getIntegerValueField(.scrollWheelEventPointDeltaAxis2)
// Thumb wheel -> Smooth zoom via magnification gesture events with interpolation
if horizontalDelta != 0 && isMouseWheel && settings.thumbWheelZoom {
// Cancel any pending end timer
zoomEndTimer?.cancel()
// Convert scroll delta to magnification using user's sensitivity setting
let magnification = Double(-horizontalDelta) * settings.zoomSensitivity * 0.02
if !zoomGestureActive {
// Start new gesture
postMagnificationEvent(magnification: 0, phase: kIOHIDEventPhaseBegan)
zoomGestureActive = true
}
// Post immediate response (30% of delta) then interpolate the rest
let immediate = magnification * 0.3
postMagnificationEvent(magnification: immediate, phase: kIOHIDEventPhaseChanged)
startInterpolatedZoom(totalMagnification: magnification * 0.7)
// Schedule end gesture after scrolling stops
let endTimer = DispatchWorkItem {
if zoomGestureActive {
remainingMagnification = 0
postMagnificationEvent(magnification: 0, phase: kIOHIDEventPhaseEnded)
zoomGestureActive = false
}
}
zoomEndTimer = endTimer
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4, execute: endTimer)
return nil // Consume original event
}
// Reverse vertical mouse scroll (not trackpad)
if verticalDelta != 0 && isMouseWheel && settings.reverseMouseScroll {
event.setIntegerValueField(.scrollWheelEventPointDeltaAxis1, value: -verticalDelta)
let fixedDelta = event.getIntegerValueField(.scrollWheelEventDeltaAxis1)
event.setIntegerValueField(.scrollWheelEventDeltaAxis1, value: -fixedDelta)
}
}
return Unmanaged.passRetained(event)
}
// MARK: - App Delegate
class AppDelegate: NSObject, NSApplicationDelegate {
var statusItem: NSStatusItem!
var settingsWindow: NSWindow?
var eventTap: CFMachPort?
func applicationDidFinishLaunching(_ notification: Notification) {
// Check accessibility - only prompt if not already trusted
if AXIsProcessTrusted() {
setupEventTap()
} else {
// Prompt once
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true]
_ = AXIsProcessTrustedWithOptions(options as CFDictionary)
// Check periodically until granted
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] timer in
if AXIsProcessTrusted() {
timer.invalidate()
self?.setupEventTap()
}
}
}
// Create menu bar item
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
if let button = statusItem.button {
button.image = NSImage(systemSymbolName: "computermouse", accessibilityDescription: "MX Master")
}
let menu = NSMenu()
menu.addItem(NSMenuItem(title: "Settings...", action: #selector(openSettings), keyEquivalent: ","))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit", action: #selector(quit), keyEquivalent: "q"))
statusItem.menu = menu
}
func setupEventTap() {
let eventMask = (1 << CGEventType.otherMouseDown.rawValue) | (1 << CGEventType.scrollWheel.rawValue)
guard let tap = CGEvent.tapCreate(
tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .defaultTap,
eventsOfInterest: CGEventMask(eventMask),
callback: eventCallback,
userInfo: nil
) else {
print("Failed to create event tap")
return
}
self.eventTap = tap
let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
CGEvent.tapEnable(tap: tap, enable: true)
}
@objc func openSettings() {
if settingsWindow == nil {
let contentView = SettingsView()
settingsWindow = NSWindow(
contentRect: NSRect(x: 0, y: 0, width: 350, height: 180),
styleMask: [.titled, .closable],
backing: .buffered,
defer: false
)
settingsWindow?.title = "MX Master"
settingsWindow?.contentView = NSHostingView(rootView: contentView)
settingsWindow?.center()
}
settingsWindow?.makeKeyAndOrderFront(nil)
NSApp.activate(ignoringOtherApps: true)
}
@objc func quit() {
NSApp.terminate(nil)
}
}
// MARK: - Main
let app = NSApplication.shared
let delegate = AppDelegate()
app.delegate = delegate
app.setActivationPolicy(.accessory) // Menu bar only, no dock icon
app.run()