Branchwell

Voxley / app · voxley.si / Sources / Voxley / Desktop.swift

Raw 18.4 KB on 65820bdbf93f3277c3f8b2c09a8acbcf3783d60a
1import AppKit
2import ApplicationServices
3import Carbon
4
5
6@MainActor
7final class GlobalShortcut {
8 /// Each shortcut gets its own hot key signature so two registrations never consume each other's events.
9 nonisolated let signature: OSType
10 var onEvent: ((Bool, TimeInterval) -> Void)?
11 var onInterrupted: (() -> Void)?
12 private var handler: EventHandlerRef?
13 private var hotkey: EventHotKeyRef?
14 private var registration: Shortcut?
15 private var nextID: UInt32 = 0
16 private var activeID: UInt32?
17 private var down = false
18 private var modifierTap: CFMachPort?
19 private var modifierSource: CFRunLoopSource?
20 private var lastModifiers: UInt32 = 0
21 private var modifierPressTime: TimeInterval?
22 private var modifierDelay: Task<Void, Never>?
23
24 init(signature: OSType = 0x56584C59) {
25 self.signature = signature
26 }
27
28 func register(_ shortcut: Shortcut) -> Bool {
29 guard !shortcut.isStandardEditingShortcut else { return false }
30 if let registration, registration.code == shortcut.code, registration.modifiers == shortcut.modifiers,
31 !shortcut.isModifierOnly || modifierTap.map(CGEvent.tapIsEnabled) == true {
32 return true
33 }
34 if shortcut.isModifierOnly { return registerModifierChord(shortcut) }
35 guard let dispatcher = GetEventDispatcherTarget() else { return false }
36 if handler == nil {
37 var events = [EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: OSType(kEventHotKeyPressed)),
38 EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: OSType(kEventHotKeyReleased))]
39 let result = InstallEventHandler(dispatcher, shortcutCallback, events.count, &events,
40 Unmanaged.passUnretained(self).toOpaque(), &handler)
41 guard result == noErr else { return false }
42 }
43 nextID &+= 1
44 let id = EventHotKeyID(signature: signature, id: nextID)
45 var newHotkey: EventHotKeyRef?
46 let status = RegisterEventHotKey(shortcut.code, shortcut.modifiers, id, dispatcher,
47 UInt32(kEventHotKeyExclusive), &newHotkey)
48 guard status == noErr, let newHotkey else { return false }
49 suspend()
50 hotkey = newHotkey
51 registration = shortcut
52 activeID = id.id
53 return true
54 }
55
56 func suspend() {
57 if let hotkey { UnregisterEventHotKey(hotkey) }
58 hotkey = nil
59 registration = nil
60 activeID = nil
61 down = false
62 modifierDelay?.cancel()
63 modifierDelay = nil
64 modifierPressTime = nil
65 lastModifiers = 0
66 if let modifierSource { CFRunLoopRemoveSource(CFRunLoopGetMain(), modifierSource, .commonModes) }
67 if let modifierTap { CFMachPortInvalidate(modifierTap) }
68 modifierSource = nil
69 modifierTap = nil
70 }
71
72 func receive(_ pressed: Bool, at time: TimeInterval, id: UInt32) {
73 guard id == activeID, pressed != down else { return }
74 down = pressed
75 onEvent?(pressed, time)
76 }
77
78 private func registerModifierChord(_ shortcut: Shortcut) -> Bool {
79 let events: CGEventMask = (1 << CGEventType.flagsChanged.rawValue) | (1 << CGEventType.keyDown.rawValue)
80 guard let tap = CGEvent.tapCreate(
81 tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap,
82 eventsOfInterest: events, callback: modifierShortcutCallback,
83 userInfo: Unmanaged.passUnretained(self).toOpaque()
84 ) else { return false }
85 guard let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0) else {
86 CFMachPortInvalidate(tap)
87 return false
88 }
89 suspend()
90 registration = shortcut
91 modifierTap = tap
92 modifierSource = source
93 lastModifiers = Shortcut.chordModifiers(for: NSEvent.modifierFlags)
94 CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)
95 CGEvent.tapEnable(tap: tap, enable: true)
96 return true
97 }
98
99 func receiveModifierEvent(_ type: CGEventType, modifiers: UInt32, at time: TimeInterval) {
100 guard let modifierTap, let registration, registration.isModifierOnly else { return }
101 switch type {
102 case .tapDisabledByTimeout, .tapDisabledByUserInput:
103 interruptModifierPress()
104 lastModifiers = Shortcut.chordModifiers(for: NSEvent.modifierFlags)
105 CGEvent.tapEnable(tap: modifierTap, enable: true)
106 case .keyDown:
107 // A modifier chord used as the prefix of another shortcut should type normally.
108 interruptModifierPress()
109 case .flagsChanged:
110 let required = registration.modifiers
111 let previouslyHeld = lastModifiers & required == required
112 lastModifiers = modifiers
113 if modifiers == required, !previouslyHeld {
114 modifierPressTime = time
115 modifierDelay = Task { [weak self] in
116 // Wait briefly to distinguish the chord from a longer key combination.
117 do { try await Task.sleep(for: .milliseconds(120)) }
118 catch { return }
119 guard let self, self.modifierPressTime == time else { return }
120 self.down = true
121 self.onEvent?(true, time)
122 }
123 } else if modifiers & required != required, let pressTime = modifierPressTime {
124 modifierPressTime = nil
125 modifierDelay?.cancel()
126 modifierDelay = nil
127 if !down { onEvent?(true, pressTime) }
128 down = false
129 onEvent?(false, time)
130 } else if modifiers != required {
131 interruptModifierPress()
132 }
133 default: break
134 }
135 }
136
137 private func interruptModifierPress() {
138 modifierDelay?.cancel()
139 modifierDelay = nil
140 modifierPressTime = nil
141 if down {
142 down = false
143 onInterrupted?()
144 }
145 }
146}
147
148private func modifierShortcutCallback(_ proxy: CGEventTapProxy, _ type: CGEventType, _ event: CGEvent,
149 _ context: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? {
150 if let context {
151 let shortcut = Unmanaged<GlobalShortcut>.fromOpaque(context).takeUnretainedValue()
152 let flags = NSEvent.ModifierFlags(rawValue: UInt(event.flags.rawValue))
153 let modifiers = Shortcut.chordModifiers(for: flags)
154 let time = ProcessInfo.processInfo.systemUptime
155 DispatchQueue.main.async { shortcut.receiveModifierEvent(type, modifiers: modifiers, at: time) }
156 }
157 return Unmanaged.passUnretained(event)
158}
159
160private func shortcutCallback(_ handler: EventHandlerCallRef?, _ event: EventRef?,
161 _ context: UnsafeMutableRawPointer?) -> OSStatus {
162 guard let event, let context else { return OSStatus(eventNotHandledErr) }
163 var id = EventHotKeyID()
164 guard GetEventParameter(event, OSType(kEventParamDirectObject), OSType(typeEventHotKeyID), nil,
165 MemoryLayout<EventHotKeyID>.size, nil, &id) == noErr,
166 case let shortcut = Unmanaged<GlobalShortcut>.fromOpaque(context).takeUnretainedValue(),
167 id.signature == shortcut.signature else { return OSStatus(eventNotHandledErr) }
168 let pressed = GetEventKind(event) == OSType(kEventHotKeyPressed)
169 let registration = id.id
170 let time = GetEventTime(event)
171 DispatchQueue.main.async { shortcut.receive(pressed, at: time, id: registration) }
172 return noErr
173}
174
175@MainActor
176struct Destination {
177 enum Delivery {
178 case inserted, pasteRequested, copiedBecausePermissionIsOff, copiedBecauseFocusChanged, copied
179
180 var status: String {
181 switch self {
182 case .inserted: "Paste confirmed"
183 case .pasteRequested: "Paste sent; check the field"
184 case .copiedBecausePermissionIsOff: "Automatic paste permission is off"
185 case .copiedBecauseFocusChanged: "Focus moved before paste"
186 case .copied: "Paste didn’t run"
187 }
188 }
189
190 var needsAttention: Bool {
191 switch self {
192 case .inserted, .pasteRequested: false
193 default: true
194 }
195 }
196
197 var message: String? {
198 switch self {
199 case .inserted: nil
200 case .pasteRequested: nil
201 case .copiedBecausePermissionIsOff:
202 "Transcript copied. Enable Automatic Paste in Voxley Settings to insert it at the cursor."
203 case .copiedBecauseFocusChanged:
204 "Transcript copied because the original text field lost focus."
205 case .copied:
206 "Voxley couldn’t insert the transcript. It’s on the clipboard."
207 }
208 }
209 }
210
211 let app: NSRunningApplication?
212 let windowFrame: NSRect?
213 private let focusedElement: AXUIElement?
214 private let focusedWindow: AXUIElement?
215 private let elementID: String?
216 private weak var practiceWindow: NSWindow?
217 private weak var practiceEditor: NSTextView?
218
219 init(practiceWindow: NSWindow? = nil, explicitPractice: Bool = false) {
220 let usePractice = practiceWindow?.isVisible == true &&
221 (explicitPractice || (NSApp.isActive && NSApp.keyWindow === practiceWindow))
222 app = usePractice ? NSRunningApplication.current : NSWorkspace.shared.frontmostApplication
223 let isOwnApp = app?.processIdentifier == ProcessInfo.processInfo.processIdentifier
224 if usePractice, let practiceWindow {
225 self.practiceWindow = practiceWindow
226 practiceEditor = practiceWindow.firstResponder as? NSTextView
227 }
228 focusedElement = isOwnApp ? nil : app.flatMap { Self.focus(in: $0.processIdentifier) }
229 focusedWindow = isOwnApp ? nil : app.flatMap { Self.focusedWindow(in: $0.processIdentifier) }
230 elementID = focusedElement.flatMap(Self.identifier(of:))
231 windowFrame = self.practiceWindow?.frame ?? app.flatMap { Self.frontWindowFrame(for: $0.processIdentifier) }
232 }
233
234 var name: String { app?.localizedName ?? "Dictation" }
235 var identifier: String? { app?.bundleIdentifier }
236 var isPractice: Bool { practiceWindow != nil }
237 var practiceFieldReady: Bool { practiceEditor != nil }
238
239 static func requestAccessibility() {
240 if AXIsProcessTrusted(), !CGPreflightPostEventAccess() {
241 _ = CGRequestPostEventAccess()
242 return
243 }
244 let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary
245 _ = AXIsProcessTrustedWithOptions(options)
246 }
247
248 private static func focus(in pid: pid_t) -> AXUIElement? {
249 guard AXIsProcessTrusted() else { return nil }
250 let app = AXUIElementCreateApplication(pid)
251 if let focus = focusedElement(of: app) { return focus }
252 guard let focus = focusedElement(of: AXUIElementCreateSystemWide()) else { return nil }
253 var owner: pid_t = 0
254 return AXUIElementGetPid(focus, &owner) == .success && owner == pid ? focus : nil
255 }
256
257 private static func focusedElement(of parent: AXUIElement) -> AXUIElement? {
258 elementAttribute(kAXFocusedUIElementAttribute, of: parent)
259 }
260
261 private static func focusedWindow(in pid: pid_t) -> AXUIElement? {
262 guard AXIsProcessTrusted() else { return nil }
263 return elementAttribute(kAXFocusedWindowAttribute, of: AXUIElementCreateApplication(pid))
264 }
265
266 private static func elementAttribute(_ name: String, of element: AXUIElement) -> AXUIElement? {
267 var value: CFTypeRef?
268 guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success,
269 let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil }
270 return (value as! AXUIElement)
271 }
272
273 private static func stringAttribute(_ name: String, of element: AXUIElement) -> String? {
274 var value: CFTypeRef?
275 guard AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success else { return nil }
276 return value as? String
277 }
278
279 private static func identifier(of element: AXUIElement) -> String? {
280 guard let id = stringAttribute(kAXIdentifierAttribute, of: element), !id.isEmpty else { return nil }
281 return id
282 }
283
284 private func stillFocused(in pid: pid_t) -> Bool {
285 if pid == ProcessInfo.processInfo.processIdentifier {
286 guard let practiceWindow, let practiceEditor else { return false }
287 return practiceWindow.isVisible && practiceWindow.firstResponder === practiceEditor
288 }
289 guard NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { return false }
290 if let focusedWindow, Self.focusedWindow(in: pid).map({ CFEqual(focusedWindow, $0) }) != true {
291 return false
292 }
293 if focusedWindow == nil, let windowFrame, Self.frontWindowFrame(for: pid) != windowFrame {
294 return false
295 }
296 let current = Self.focus(in: pid)
297 if let current, Self.stringAttribute(kAXSubroleAttribute, of: current) == kAXSecureTextFieldSubrole {
298 return false
299 }
300 guard let focusedElement else { return true }
301 guard let current else { return false }
302 if CFEqual(focusedElement, current) { return true }
303 // A web editor can rebuild its accessibility element while leaving the same field focused.
304 return focusedWindow != nil && elementID != nil && elementID == Self.identifier(of: current)
305 }
306
307 private static func frontWindowFrame(for pid: pid_t) -> NSRect? {
308 guard let primaryTop = NSScreen.screens.first?.frame.maxY,
309 let windows = CGWindowListCopyWindowInfo(
310 [.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID
311 ) as? [[String: Any]] else { return nil }
312 for window in windows where window[kCGWindowOwnerPID as String] as? pid_t == pid {
313 guard window[kCGWindowLayer as String] as? Int == 0,
314 let bounds = window[kCGWindowBounds as String] as? NSDictionary,
315 let frame = CGRect(dictionaryRepresentation: bounds),
316 frame.width >= 80, frame.height >= 80 else { continue }
317 return NSRect(x: frame.minX, y: primaryTop - frame.maxY, width: frame.width, height: frame.height)
318 }
319 return nil
320 }
321
322 static func copy(_ text: String) {
323 let board = NSPasteboard.general
324 board.clearContents()
325 board.setString(text, forType: .string)
326 }
327
328 func deliver(_ text: String) async -> Delivery {
329 guard AXIsProcessTrusted(), CGPreflightPostEventAccess() else {
330 Self.copy(text)
331 return .copiedBecausePermissionIsOff
332 }
333 guard let pid = app?.processIdentifier, stillFocused(in: pid) else {
334 Self.copy(text)
335 return .copiedBecauseFocusChanged
336 }
337 guard let source = CGEventSource(stateID: .privateState),
338 let commandDown = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode(kVK_Command), keyDown: true),
339 let down = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode(kVK_ANSI_V), keyDown: true),
340 let up = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode(kVK_ANSI_V), keyDown: false),
341 let commandUp = CGEvent(keyboardEventSource: source, virtualKey: CGKeyCode(kVK_Command), keyDown: false) else {
342 Self.copy(text)
343 return .copied
344 }
345
346 let board = NSPasteboard.general
347 let prior = (board.pasteboardItems ?? []).map { item in
348 item.types.compactMap { type in item.data(forType: type).map { (type, $0) } }
349 }
350 board.clearContents()
351 guard board.setString(text, forType: .string) else { return .copied }
352 let expectedCount = board.changeCount
353 // Give the shortcut modifiers and clipboard time to settle before delivering Cmd+V.
354 try? await Task.sleep(for: .milliseconds(85))
355 guard board.changeCount == expectedCount else { return .copied }
356 guard !Task.isCancelled, stillFocused(in: pid) else { return .copiedBecauseFocusChanged }
357 let originalSelection = selectedRange(in: pid)
358
359 if let practiceEditor {
360 // The local practice editor can handle its own standard Paste action.
361 practiceEditor.paste(nil)
362 } else {
363 commandDown.flags = .maskCommand
364 down.flags = .maskCommand
365 up.flags = .maskCommand
366 commandUp.flags = []
367 commandDown.post(tap: .cghidEventTap)
368 try? await Task.sleep(for: .milliseconds(12))
369 guard !Task.isCancelled, board.changeCount == expectedCount, stillFocused(in: pid) else {
370 commandUp.post(tap: .cghidEventTap)
371 return .copiedBecauseFocusChanged
372 }
373 down.post(tap: .cghidEventTap)
374 try? await Task.sleep(for: .milliseconds(12))
375 up.post(tap: .cghidEventTap)
376 commandUp.post(tap: .cghidEventTap)
377 try? await Task.sleep(for: .milliseconds(550))
378 }
379
380 guard stillFocused(in: pid), let originalSelection, let updated = selectedRange(in: pid),
381 updated.length == 0, updated.location == originalSelection.location + text.utf16.count else {
382 return .pasteRequested
383 }
384 if board.changeCount == expectedCount {
385 board.clearContents()
386 let restored: [NSPasteboardItem] = prior.compactMap { values in
387 guard !values.isEmpty else { return nil }
388 let item = NSPasteboardItem()
389 for (type, data) in values { item.setData(data, forType: type) }
390 return item
391 }
392 if !restored.isEmpty { board.writeObjects(restored) }
393 }
394 return .inserted
395 }
396
397 private func selectedRange(in pid: pid_t) -> CFRange? {
398 if let practiceEditor {
399 let range = practiceEditor.selectedRange()
400 return CFRange(location: range.location, length: range.length)
401 }
402 return Self.focus(in: pid).flatMap(Self.selectedRange)
403 }
404
405 private static func selectedRange(_ element: AXUIElement) -> CFRange? {
406 var attribute: CFTypeRef?
407 guard AXUIElementCopyAttributeValue(element, kAXSelectedTextRangeAttribute as CFString, &attribute) == .success,
408 let attribute, CFGetTypeID(attribute) == AXValueGetTypeID() else { return nil }
409 var range = CFRange()
410 return AXValueGetValue(attribute as! AXValue, .cfRange, &range) ? range : nil
411 }
412}