68 lines
3.0 KiB
Swift
68 lines
3.0 KiB
Swift
import AppKit
|
|
import ApplicationServices
|
|
import Carbon.HIToolbox
|
|
import CockpitKern
|
|
|
|
/// Tasten, die ueberall wirken - auch wenn die Tische vorn sind und der Bot die Maus hat.
|
|
///
|
|
/// ⌃⌥⌘S Not-Aus systemweiter Hotkey, braucht keine Freigabe
|
|
/// ⌃⌥⌘C Leiste ↔ Pille systemweiter Hotkey
|
|
/// ⌃⌥⌘H Cockpit ein/aus systemweiter Hotkey
|
|
/// ESC Not-Aus, solange der Bot laeuft - nur mitgelesen (geht weiter an den Tisch),
|
|
/// braucht die Bedienungshilfen-Freigabe; ESC des Bots selbst zaehlt nicht
|
|
@MainActor
|
|
final class Tasten {
|
|
enum Kuerzel: UInt32 { case notAus = 1, form = 2, sichtbar = 3 }
|
|
|
|
private static var handler: [UInt32: () -> Void] = [:]
|
|
private var refs: [EventHotKeyRef] = []
|
|
private var monitore: [Any] = []
|
|
|
|
var esc: (() -> Void)?
|
|
|
|
func kuerzel(_ k: Kuerzel, _ aktion: @escaping () -> Void) {
|
|
let taste: Int = switch k { case .notAus: kVK_ANSI_S; case .form: kVK_ANSI_C; case .sichtbar: kVK_ANSI_H }
|
|
var ref: EventHotKeyRef?
|
|
let id = EventHotKeyID(signature: OSType(0x5046_434B), id: k.rawValue) // "PFCK"
|
|
let status = RegisterEventHotKey(UInt32(taste), UInt32(controlKey | optionKey | cmdKey), id,
|
|
GetApplicationEventTarget(), 0, &ref)
|
|
guard status == noErr, let ref else { return }
|
|
refs.append(ref)
|
|
Self.handler[k.rawValue] = aktion
|
|
}
|
|
|
|
func starten() {
|
|
var art = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
|
|
InstallEventHandler(GetApplicationEventTarget(), { _, ereignis, _ in
|
|
var id = EventHotKeyID()
|
|
GetEventParameter(ereignis, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID),
|
|
nil, MemoryLayout<EventHotKeyID>.size, nil, &id)
|
|
let n = id.id
|
|
MainActor.assumeIsolated { Tasten.handler[n]?() }
|
|
return noErr
|
|
}, 1, &art, nil, nil)
|
|
escBeobachten()
|
|
}
|
|
|
|
/// Neu scharf machen: ein globaler Waechter, angelegt ohne Bedienungshilfen, bleibt taub -
|
|
/// auch wenn die Freigabe spaeter kommt. Darum nach jeder erteilten Freigabe neu anlegen.
|
|
func escNeuScharf() {
|
|
monitore.forEach(NSEvent.removeMonitor)
|
|
monitore.removeAll()
|
|
escBeobachten()
|
|
Protokoll.schreiben("ESC-Wächter neu angelegt (Bedienungshilfen: \(AXIsProcessTrusted()))")
|
|
}
|
|
|
|
private func escBeobachten() {
|
|
let pruefen: (NSEvent) -> Void = { [weak self] e in
|
|
let mods = e.modifierFlags.intersection([.control, .option, .command])
|
|
guard e.keyCode == UInt16(kVK_Escape), mods.isEmpty, !e.isARepeat else { return }
|
|
MainActor.assumeIsolated { self?.esc?() }
|
|
}
|
|
if let g = NSEvent.addGlobalMonitorForEvents(matching: .keyDown, handler: pruefen) { monitore.append(g) }
|
|
if let l = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: { pruefen($0); return $0 }) {
|
|
monitore.append(l)
|
|
}
|
|
}
|
|
}
|