grammargem/Sources/GrammaGem/System/HotkeyManager.swift
BigMarc 35ae2065b3 Fix 22 audited bugs: stop hangs/crashes/text-corruption; auto-install model
Stability (the "super buggy" feel):
- Move the Accessibility-tree traversal OFF the main thread with a per-message
  timeout, so a busy/wedged target app can't beachball or hang GrammaGem.
- Replace every unchecked `as! AXUIElement` force-cast with a CFTypeID-checked
  safe cast (AXSupport), eliminating crashes from misbehaving AX servers.
- Never scan GrammaGem's own windows (self-PID exclusion).
- Generation tokens + in-flight guard so superseded scans/downloads can't clobber state.

Text safety:
- Live fixes now read the element's CURRENT value before writing (and only apply a
  span edit when the field still matches the snapshot), so edits made since the last
  scan are never overwritten. Cap per-field check length.
- Stable per-field identity (AX id / position) so the Live Check list no longer churns.
- Include focus + identity in change-detection so tabbing updates the focused field.

Other audited fixes:
- Page blocker: conservative skip when a browser's URL can't be read.
- Model download: validate on-disk size (reject HTML/truncated 200s), clean up
  partials on cancel/failure, handle URLError.cancelled.
- Licensing: clear a server-confirmed-invalid license instead of honoring grace;
  show the real device limit instead of "0 Macs".
- Hotkey re-register falls back to the default if a chosen combo is taken.
- Daily free-tier counter tracks the live timezone.
- "Fix focused field" ignores non-text controls.

Feature: auto-install the on-device model in the background on first launch.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 16:08:35 +02:00

85 lines
3.0 KiB
Swift

import Foundation
import Carbon.HIToolbox
/// Registers system-wide global hotkeys via Carbon `RegisterEventHotKey`.
///
/// This is the no-dependency path. The spec lists `KeyboardShortcuts`
/// (Sindre Sorhus) for a nicer recorder UI; you can swap this implementation
/// for that package without touching callers. User-configurable (defaults ⌘; and ⌘').
final class HotkeyManager {
/// Logical actions a hotkey can fire.
enum Action { case fix, ask }
var onAction: ((Action) -> Void)?
private var refs: [EventHotKeyRef?] = []
private var handler: EventHandlerRef?
private var idToAction: [UInt32: Action] = [:]
init() {
installHandler()
}
deinit {
unregisterAll()
if let handler { RemoveEventHandler(handler) }
}
/// Register the two product hotkeys. Call again to re-register after the
/// user changes a shortcut.
func registerDefaults() {
register(id: 1, keyCode: AppConfig.Hotkey.defaultKeyCode,
modifiers: AppConfig.Hotkey.defaultModifiers, action: .fix)
register(id: 2, keyCode: AppConfig.Hotkey.askKeyCode,
modifiers: AppConfig.Hotkey.askModifiers, action: .ask)
}
@discardableResult
func register(id: UInt32, keyCode: UInt32, modifiers: UInt32, action: Action) -> Bool {
idToAction[id] = action
let hotKeyID = EventHotKeyID(signature: OSType(0x47474D31), id: id) // 'GGM1'
var ref: EventHotKeyRef?
let status = RegisterEventHotKey(
keyCode, modifiers, hotKeyID,
GetEventDispatcherTarget(), 0, &ref)
if status == noErr {
refs.append(ref)
return true
}
Log.system.error("RegisterEventHotKey failed: \(status)")
return false
}
func unregisterAll() {
for ref in refs where ref != nil { UnregisterEventHotKey(ref) }
refs.removeAll()
}
// MARK: - Carbon event plumbing
private func installHandler() {
var spec = EventTypeSpec(
eventClass: OSType(kEventClassKeyboard),
eventKind: UInt32(kEventHotKeyPressed))
let selfPtr = Unmanaged.passUnretained(self).toOpaque()
InstallEventHandler(
GetEventDispatcherTarget(),
{ (_, eventRef, userData) -> OSStatus in
guard let eventRef, let userData else { return noErr }
var hkID = EventHotKeyID()
let err = GetEventParameter(
eventRef, EventParamName(kEventParamDirectObject),
EventParamType(typeEventHotKeyID), nil,
MemoryLayout<EventHotKeyID>.size, nil, &hkID)
guard err == noErr else { return err }
let mgr = Unmanaged<HotkeyManager>.fromOpaque(userData).takeUnretainedValue()
if let action = mgr.idToAction[hkID.id] {
DispatchQueue.main.async { mgr.onAction?(action) }
}
return noErr
},
1, &spec, selfPtr, &handler)
}
}