import AppKit import Carbon.HIToolbox /// The system-wide ⌘N that shows or hides Plak from any app; no Accessibility permission needed. final class GlobalShortcut { private let onPress: @MainActor () -> Void private var hotKey: EventHotKeyRef? private var handler: EventHandlerRef? init(onPress: @escaping @MainActor () -> Void) { self.onPress = onPress var pressed = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)) InstallEventHandler(GetApplicationEventTarget(), { _, _, userData in guard let userData else { return OSStatus(eventNotHandledErr) } let shortcut = Unmanaged.fromOpaque(userData).takeUnretainedValue() // Carbon calls the handler on the main thread, from the app's run loop. MainActor.assumeIsolated { shortcut.onPress() } return noErr }, 1, &pressed, Unmanaged.passUnretained(self).toOpaque(), &handler) let id = EventHotKeyID(signature: OSType(0x506C_616B), id: 1) RegisterEventHotKey(UInt32(kVK_ANSI_N), UInt32(cmdKey), id, GetApplicationEventTarget(), 0, &hotKey) } deinit { if let hotKey { UnregisterEventHotKey(hotKey) } if let handler { RemoveEventHandler(handler) } } }