Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600import AppKitimport ApplicationServicesimport Carbon
@MainActorprotocol HotKeyBackend: AnyObject { var onCarbonEvent: (@MainActor (UInt32, Bool) -> Void)? { get set } var onTapEvent: (@MainActor (CGEventType, CGEvent) -> Bool)? { get set } var onFailure: (@MainActor (InputError) -> Void)? { get set } func registerCarbon(_ key: HotKey, id: UInt32) throws -> Int32 func unregisterCarbon(id: UInt32) throws func isPressed(_ key: HotKey) -> Bool? func startTap() throws func stopTap()}
@MainActorpublic final class HotKeyCenter { private struct Binding { let id: UInt32 let registration: HotKeyRegistration let switcher: Bool }
private struct SwitcherCapture { let holdModifiers: HotKey.Modifiers let openingKeyCode: UInt16? let onEvent: @MainActor (SwitcherInputEvent) -> Void let onVoiceOverInput: @MainActor () -> Void }
private let backend: any HotKeyBackend private let onPress: @MainActor (HotKeyPress) -> Void private let trace: any ParcelTraceSink private let onFailure: @MainActor (InputError) -> Void private let isEventTapInputAllowed: @MainActor () -> Bool private let isActive: @MainActor () -> Bool private let isVoiceOverEnabled: @MainActor () -> Bool private let onCarbonPress: @MainActor () -> Void private let onRepeatedTapTimeout: @MainActor (Int) -> Void public private(set) var tapTimeoutCount = 0 private var registeredCarbon: Set<UInt32> = [] private var bindings: [HotKey: Binding] = [:] private var carbonState = HotKeyState() private var tapState = HotKeyState() private var switcherCapture: SwitcherCapture? private var openingSwitcherKey: UInt16? private var capturedKeys: Set<UInt16> = [] private var passthroughKeys: Set<UInt16> = [] private var repeats: [HotKey: @MainActor () -> Void] = [:] private var repeatGeneration: UInt64 = 0 private let scheduleRepeat: @MainActor (@escaping @MainActor () -> Void) -> (@MainActor () -> Void) private static var nextID: UInt32 = 1
public convenience init( onPress: @escaping @MainActor (HotKeyPress) -> Void, onFailure: @escaping @MainActor (InputError) -> Void, isEventTapInputAllowed: @escaping @MainActor () -> Bool = { true }, isActive: @escaping @MainActor () -> Bool = { true }, isVoiceOverEnabled: @escaping @MainActor () -> Bool = { VoiceOverStatus.isRunning }, onCarbonPress: @escaping @MainActor () -> Void = {}, onRepeatedTapTimeout: @escaping @MainActor (Int) -> Void = { _ in } ) { self.init( backend: NativeHotKeyBackend(), onPress: onPress, onFailure: onFailure, isEventTapInputAllowed: { isEventTapInputAllowed() && !IsSecureEventInputEnabled() }, isActive: isActive, isVoiceOverEnabled: isVoiceOverEnabled, onCarbonPress: onCarbonPress, onRepeatedTapTimeout: onRepeatedTapTimeout) }
init( backend: any HotKeyBackend, onPress: @escaping @MainActor (HotKeyPress) -> Void, onFailure: @escaping @MainActor (InputError) -> Void, trace: any ParcelTraceSink = SignpostTraceSink.shared, isEventTapInputAllowed: @escaping @MainActor () -> Bool = { true }, isActive: @escaping @MainActor () -> Bool = { true }, isVoiceOverEnabled: @escaping @MainActor () -> Bool = { false }, onCarbonPress: @escaping @MainActor () -> Void = {}, onRepeatedTapTimeout: @escaping @MainActor (Int) -> Void = { _ in }, scheduleRepeat: @escaping @MainActor (@escaping @MainActor () -> Void) -> (@MainActor () -> Void) = HotKeyCenter .systemRepeat ) { self.scheduleRepeat = scheduleRepeat self.backend = backend self.onPress = onPress self.trace = trace self.onFailure = onFailure self.isEventTapInputAllowed = isEventTapInputAllowed self.isActive = isActive self.isVoiceOverEnabled = isVoiceOverEnabled self.onCarbonPress = onCarbonPress self.onRepeatedTapTimeout = onRepeatedTapTimeout backend.onCarbonEvent = { [weak self] id, down in self?.carbonEvent(id: id, down: down) } backend.onTapEvent = { [weak self] type, event in self?.tapEvent(type, event) ?? false } backend.onFailure = { [weak self, onFailure] error in guard let self else { onFailure(error) return } if case .carbon = error { self.onFailure(error) return } self.backend.stopTap() self.bindings = self.bindings.filter { $0.value.registration.route == .carbon } self.tapState = HotKeyState() self.capturedKeys.removeAll() self.passthroughKeys.removeAll() self.finishSwitcherCapture(.cancel) self.onFailure(error) } }
isolated deinit { cancelRepeats() }
private func cancelRepeats() { repeatGeneration &+= 1 for cancel in repeats.values { cancel() } repeats.removeAll() }
static func sampledPressedState(secureInput: Bool, read: () -> Bool) -> Bool? { secureInput ? nil : read() }
private static func systemRepeat(_ tick: @escaping @MainActor () -> Void) -> (@MainActor () -> Void) { let timer = Timer(timeInterval: max(0.01, NSEvent.keyRepeatInterval), repeats: true) { _ in MainActor.assumeIsolated { tick() } } timer.fireDate = Date(timeIntervalSinceNow: NSEvent.keyRepeatDelay) RunLoop.main.add(timer, forMode: .common) return { timer.invalidate() } }
public var registrations: [HotKeyRegistration] { bindings.values.sorted { $0.id < $1.id }.map(\.registration) }
public func isRegistered(_ hotKey: HotKey) -> Bool { bindings[hotKey] != nil }
/// Switcher registrations use the event tap and reserve the same chord with an added Shift. @discardableResult public func register(_ hotKey: HotKey, repeats: Bool = false, switcher: Bool = false) throws -> HotKeyRegistration { guard bindings[hotKey] == nil else { throw InputError.duplicateHotKey(hotKey) } let reverse = switcher ? Self.reverseChord(for: hotKey) : nil for (key, binding) in bindings { if key == reverse || (binding.switcher && Self.reverseChord(for: key) == hotKey) { throw InputError.duplicateHotKey(hotKey) } } let id = Self.nextID precondition(id < UInt32.max, "Hotkey registration IDs exhausted") Self.nextID += 1 var route: HotKeyRoute = switcher ? .eventTap : HotKeyRoute.preferred(for: hotKey) var rejection: Int32? if route == .carbon, permits(hotKey) { let status = try backend.registerCarbon(hotKey, id: id) guard status != eventHotKeyExistsErr else { throw InputError.carbon(operation: "register", status: status) } route = HotKeyRoute.afterCarbonRegistration(status: status) if status != 0 { rejection = status } if status == noErr { registeredCarbon.insert(id) } } if route == .eventTap { do { try backend.startTap() } catch let error as InputError { if let rejection { throw InputError.tapFallbackFailed(carbonStatus: rejection, cause: error) } throw error } tapState.bindings[hotKey] = repeats } else { carbonState.bindings[hotKey] = repeats } let registration = HotKeyRegistration(hotKey: hotKey, route: route, carbonRejection: rejection) bindings[hotKey] = Binding(id: id, registration: registration, switcher: switcher) return registration }
private static func reverseChord(for key: HotKey) -> HotKey? { guard !key.modifiers.contains(.shift) else { return nil } return HotKey(keyCode: key.keyCode, modifiers: key.modifiers.union(.shift)) }
/// Begin synchronously in the opening press callback so modifier releases cannot overtake it. /// Releasing an initiating non-Shift modifier confirms; Shift confirms only when it is the sole modifier. /// The opening key cycles unless it is an arrow, Return, keypad Enter, or Escape, which keep their usual actions. public func beginSwitcherCapture( modifiers: HotKey.Modifiers, openingKeyCode: UInt16? = nil, onVoiceOverInput: @escaping @MainActor () -> Void = {}, onEvent: @escaping @MainActor (SwitcherInputEvent) -> Void ) throws { guard switcherCapture == nil else { throw InputError.switcherCaptureAlreadyActive } guard permitsEventTapInput() else { throw InputError.eventTapInputUnavailable } try backend.startTap() cancelRepeats() let nonShift = modifiers.subtracting(.shift) let holdModifiers = nonShift.isEmpty ? modifiers : nonShift switcherCapture = SwitcherCapture( holdModifiers: holdModifiers, openingKeyCode: openingKeyCode, onEvent: onEvent, onVoiceOverInput: onVoiceOverInput) if let openingSwitcherKey { capturedKeys.insert(openingSwitcherKey) } }
/// Ends capture without emitting an event; consumed key releases remain reserved. public func endSwitcherCapture() { finishSwitcherCapture(nil) }
private func finishSwitcherCapture(_ event: SwitcherInputEvent?) { guard let capture = switcherCapture else { return } switcherCapture = nil if let event { capture.onEvent(event) } stopIdleTap() }
public func updateRepeats(_ hotKey: HotKey, enabled: Bool) { guard let binding = bindings[hotKey] else { return } let current = binding.registration.route == .carbon ? carbonState.bindings[hotKey] : tapState.bindings[hotKey] guard current != enabled else { return } repeats.removeValue(forKey: hotKey)?() if binding.registration.route == .carbon { carbonState.bindings[hotKey] = enabled } else { tapState.bindings[hotKey] = enabled } }
public func unregister(_ hotKey: HotKey) throws { guard let binding = bindings[hotKey] else { return } defer { finishSwitcherCapture(.cancel) stopIdleTap() } if registeredCarbon.contains(binding.id) { try backend.unregisterCarbon(id: binding.id) registeredCarbon.remove(binding.id) } bindings.removeValue(forKey: hotKey) repeats.removeValue(forKey: hotKey)?() if binding.registration.route == .carbon { carbonState.remove(hotKey) _ = carbonState.up(keyCode: hotKey.keyCode) } else { tapState.remove(hotKey) } }
/// Successful removals stay removed if a later Carbon removal fails; retry to finish cleanup. public func stop() throws { finishSwitcherCapture(.cancel) for registration in registrations { try unregister(registration.hotKey) } stopIdleTap() }
private func stopIdleTap() { if switcherCapture == nil && capturedKeys.isEmpty && passthroughKeys.isEmpty && tapState.bindings.isEmpty && !tapState.hasHeldKeys { backend.stopTap() } }
public func resetPressedState() { cancelRepeats() carbonState.reset() resetEventTapPressedState() }
public func resetEventTapPressedState() { tapState.reset(preservingConsumedKeys: true) finishSwitcherCapture(.cancel) stopIdleTap() }
private func permits(_ hotKey: HotKey) -> Bool { isActive() && !(isVoiceOverEnabled() && hotKey.conflictsWithVoiceOver) }
public func refreshActivity() throws { for binding in bindings.values.sorted(by: { $0.id < $1.id }) { let key = binding.registration.hotKey guard binding.registration.route == .carbon else { continue } if !permits(key) { repeats.removeValue(forKey: key)?() _ = carbonState.up(keyCode: key.keyCode) if registeredCarbon.contains(binding.id) { try backend.unregisterCarbon(id: binding.id) registeredCarbon.remove(binding.id) } } else if !registeredCarbon.contains(binding.id) { let status = try backend.registerCarbon(key, id: binding.id) guard status == noErr else { throw InputError.carbon(operation: "resume", status: status) } registeredCarbon.insert(binding.id) } } if switcherCapture == nil || !isActive() || !isEventTapInputAllowed() { resetEventTapPressedState() } }
public func isAvailable(_ hotKey: HotKey) -> Bool { guard permits(hotKey), let binding = bindings[hotKey] else { return false } return binding.registration.route == .carbon ? registeredCarbon.contains(binding.id) : permitsEventTapInput() }
private func permitsEventTapInput() -> Bool { guard isActive(), isEventTapInputAllowed() else { resetEventTapPressedState() return false } return true }
public private(set) var switcherPresentationTrace: TabViewPresentationTrace?
private func dispatch(_ press: HotKeyPress) { let interval = trace.beginIfEnabled( .hotkeyDispatch, value: UInt64(press.hotKey.keyCode), detail: press.isRepeat ? 1 : 0) defer { trace.endIfStarted(.hotkeyDispatch, interval) } onPress(press) }
private func carbonEvent(id: UInt32, down: Bool) { guard let binding = bindings.values.first(where: { $0.id == id }) else { return } let key = binding.registration.hotKey if down { onCarbonPress() guard switcherCapture == nil, !passthroughKeys.contains(key.keyCode), permits(key), registeredCarbon.contains(id), let press = carbonState.down(key, isRepeat: false).press, !press.isRepeat else { return } cancelRepeats() // Carbon does not promise repeat events, so use the user's system timing. if carbonState.bindings[key] == true { let generation = repeatGeneration repeats[key] = scheduleRepeat { [weak self] in guard let self, self.repeatGeneration == generation, self.repeats[key] != nil, self.bindings[key]?.id == id else { return } guard self.permits(key), self.registeredCarbon.contains(id) else { self.repeats.removeValue(forKey: key)?() _ = self.carbonState.up(keyCode: key.keyCode) return } // Protected input hides sampled state, but Carbon still reports releases. if self.backend.isPressed(key) == false { self.repeats.removeValue(forKey: key)?() _ = self.carbonState.up(keyCode: key.keyCode) return } self.dispatch(HotKeyPress(hotKey: key, isRepeat: true)) } } dispatch(press) } else { _ = carbonState.up(keyCode: key.keyCode) repeats.removeValue(forKey: key)?() } }
static let carbonRegistrationOptions = UInt32(kEventHotKeyExclusive)
static func eventHotKey(keyCode: UInt16, flags: CGEventFlags, functionKeyIsHeld: Bool) -> HotKey { HotKey(keyCode: keyCode, modifiers: .init(eventFlags: flags)) .normalizingArrowFunctionContext(functionKeyIsHeld: functionKeyIsHeld) }
private func tapEvent(_ type: CGEventType, _ event: CGEvent) -> Bool { if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { resetEventTapPressedState() if type == .tapDisabledByTimeout { tapTimeoutCount += 1 if tapTimeoutCount == 3 { onRepeatedTapTimeout(tapTimeoutCount) } } return false } let permitsInput = permitsEventTapInput() if type == .flagsChanged { guard permitsInput else { return false } if isVoiceOverEnabled() { switcherCapture?.onVoiceOverInput() } if let capture = switcherCapture, !isVoiceOverEnabled(), !capture.holdModifiers.isEmpty, !HotKey.Modifiers(eventFlags: event.flags).isSuperset(of: capture.holdModifiers) { finishSwitcherCapture(.confirm) } return false } let code = event.getIntegerValueField(.keyboardEventKeycode) guard let keyCode = UInt16(exactly: code) else { return false } if type == .keyUp { if passthroughKeys.remove(keyCode) != nil { if isVoiceOverEnabled() { switcherCapture?.onVoiceOverInput() } stopIdleTap() return false } let captured = capturedKeys.remove(keyCode) != nil let bound = tapState.up(keyCode: keyCode) stopIdleTap() return captured || bound } guard type == .keyDown, permitsInput else { return false } if passthroughKeys.contains(keyCode) { if isVoiceOverEnabled() { switcherCapture?.onVoiceOverInput() } return false } let voiceOverModifiers = HotKey.Modifiers(eventFlags: event.flags).isSuperset(of: [.control, .option]) || event.flags.contains(.maskAlphaShift) let voiceOverNavigation = switcherCapture != nil && Self.switcherAction( keyCode: keyCode, flags: event.flags, openingKeyCode: switcherCapture?.openingKeyCode) == nil let quickNavArrow = switcherCapture != nil && [kVK_LeftArrow, kVK_RightArrow, kVK_UpArrow, kVK_DownArrow].contains(Int(keyCode)) if isVoiceOverEnabled(), voiceOverModifiers || voiceOverNavigation || quickNavArrow { let key = Self.eventHotKey( keyCode: keyCode, flags: event.flags, functionKeyIsHeld: CGEventSource.keyState(.combinedSessionState, key: UInt16(kVK_Function))) let matched = matchedTapKey(key).key if switcherCapture != nil || bindings[matched]?.switcher == true { if capturedKeys.contains(keyCode) || tapState.isHeld(keyCode: keyCode) || carbonState.isHeld(keyCode: keyCode) { return true } switcherCapture?.onVoiceOverInput() passthroughKeys.insert(keyCode) return false } } let isRepeat = event.getIntegerValueField(.keyboardEventAutorepeat) != 0 if let capture = switcherCapture { let wasHeld = capturedKeys.contains(keyCode) // A repeat without a captured down may belong to the previously focused app. if !isRepeat { capturedKeys.insert(keyCode) } if let action = Self.switcherAction( keyCode: keyCode, flags: event.flags, openingKeyCode: capture.openingKeyCode) { if action == .confirm || action == .cancel { if !isRepeat && !wasHeld { finishSwitcherCapture(action) } } else { capture.onEvent(action) } } return true } if capturedKeys.contains(keyCode) { return true } let key = Self.eventHotKey( keyCode: keyCode, flags: event.flags, functionKeyIsHeld: CGEventSource.keyState(.combinedSessionState, key: UInt16(kVK_Function))) let (matched, isReverse) = matchedTapKey(key) guard permits(matched) else { resetEventTapPressedState() return false } let result = tapState.down(matched, isRepeat: isRepeat) if let press = result.press { if !press.isRepeat { cancelRepeats() } let previousOpeningKey = openingSwitcherKey if bindings[matched]?.switcher == true && !press.isRepeat { openingSwitcherKey = keyCode switcherPresentationTrace = TabViewPresentationTrace(eventTimestamp: event.timestamp) } defer { openingSwitcherKey = previousOpeningKey switcherPresentationTrace = nil } dispatch(HotKeyPress(hotKey: press.hotKey, isRepeat: press.isRepeat, isReverse: isReverse)) } return result.consume }
private func matchedTapKey(_ key: HotKey) -> (key: HotKey, isReverse: Bool) { if bindings[key] == nil, key.modifiers.contains(.shift) { let base = HotKey(keyCode: key.keyCode, modifiers: key.modifiers.subtracting(.shift)) if bindings[base]?.switcher == true { return (base, true) } } return (key, false) }
private static func switcherAction( keyCode: UInt16, flags: CGEventFlags, openingKeyCode: UInt16? ) -> SwitcherInputEvent? { switch Int(keyCode) { case kVK_LeftArrow: .left case kVK_RightArrow: .right case kVK_UpArrow: .up case kVK_DownArrow: .down case kVK_Return, kVK_ANSI_KeypadEnter: .confirm case kVK_Escape: .cancel case kVK_Tab: flags.contains(.maskShift) ? .previous : .next default: keyCode == openingKeyCode ? (flags.contains(.maskShift) ? .previous : .next) : nil } }}
@MainActorprivate final class NativeHotKeyBackend: HotKeyBackend { var onCarbonEvent: (@MainActor (UInt32, Bool) -> Void)? var onTapEvent: (@MainActor (CGEventType, CGEvent) -> Bool)? var onFailure: (@MainActor (InputError) -> Void)? private var references: [UInt32: EventHotKeyRef] = [:] private var eventHandler: EventHandlerRef? private var tap: InputEventTap? private static let signature: OSType = 0x5473_496E
isolated deinit { tap?.stop() for reference in references.values { let status = UnregisterEventHotKey(reference) if status != noErr { onFailure?(.carbon(operation: "unregister", status: status)) } } if let eventHandler { let status = RemoveEventHandler(eventHandler) if status != noErr { onFailure?(.carbon(operation: "removeHandler", status: status)) } } }
func registerCarbon(_ key: HotKey, id: UInt32) throws -> Int32 { try installHandler() var reference: EventHotKeyRef? let status = RegisterEventHotKey( UInt32(key.keyCode), key.modifiers.carbonModifiers, EventHotKeyID(signature: Self.signature, id: id), GetApplicationEventTarget(), HotKeyCenter.carbonRegistrationOptions, &reference) if status == noErr { guard let reference else { throw InputError.carbon(operation: "missingRegistration", status: -50) } references[id] = reference } return status }
func unregisterCarbon(id: UInt32) throws { if let reference = references[id] { let status = UnregisterEventHotKey(reference) guard status == noErr else { throw InputError.carbon(operation: "unregister", status: status) } references.removeValue(forKey: id) } if references.isEmpty, let eventHandler { let status = RemoveEventHandler(eventHandler) guard status == noErr else { throw InputError.carbon(operation: "removeHandler", status: status) } self.eventHandler = nil } }
func isPressed(_ key: HotKey) -> Bool? { HotKeyCenter.sampledPressedState(secureInput: IsSecureEventInputEnabled()) { CGEventSource.keyState(.combinedSessionState, key: key.keyCode) && HotKey.Modifiers(eventFlags: CGEventSource.flagsState(.combinedSessionState)) == key.modifiers } }
func startTap() throws { guard tap == nil else { return } tap = try InputEventTap( mask: (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue) | (1 << CGEventType.flagsChanged.rawValue), handler: { [weak self] type, event in self?.onTapEvent?(type, event) ?? false }, onFailure: { [weak self] error in self?.onFailure?(error) }) }
func stopTap() { tap?.stop() tap = nil }
private func installHandler() throws { guard eventHandler == nil else { return } var events = [ EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)), EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyReleased)), ] let status = InstallEventHandler( GetApplicationEventTarget(), { _, event, context in guard let event, let context else { return OSStatus(eventNotHandledErr) } return MainActor.assumeIsolated { let owner = Unmanaged<NativeHotKeyBackend>.fromOpaque(context).takeUnretainedValue() var id = EventHotKeyID() let result = GetEventParameter( event, EventParamName(kEventParamDirectObject), EventParamType(typeEventHotKeyID), nil, MemoryLayout<EventHotKeyID>.size, nil, &id) guard result == noErr else { owner.onFailure?(.carbon(operation: "readEvent", status: result)) return result } guard id.signature == NativeHotKeyBackend.signature, owner.references[id.id] != nil else { return OSStatus(eventNotHandledErr) } owner.onCarbonEvent?(id.id, GetEventKind(event) == UInt32(kEventHotKeyPressed)) return noErr } }, events.count, &events, Unmanaged.passUnretained(self).toOpaque(), &eventHandler) guard status == noErr else { throw InputError.carbon(operation: "installHandler", status: status) } }}