import Foundation import ParcelConfig import ParcelPlatform struct HotkeyDispatchGate { private var generation: UInt64 = 0 private var transitionPending = false mutating func begin(_ action: BindingAction) -> UInt64? { guard !transitionPending else { return nil } if action.isModeTransition { generation &+= 1 transitionPending = true } return generation } func allows(_ ticket: UInt64) -> Bool { ticket == generation } mutating func finish(_ action: BindingAction) { if action.isModeTransition { transitionPending = false } } mutating func invalidate() { generation &+= 1 } } extension BindingAction { fileprivate var isModeTransition: Bool { switch self { case .command: false case .enterMode, .exitMode: true } } } @MainActor final class AppHotkeys { struct Conflict { let action: BindingAction let chord: KeyChord let cause: any Error } private(set) var bindings: [HotKey: BindingAction] = [:] private var registered: [HotKey: BindingAction] = [:] private var mode: String? private var repeatSuppressed: Set = [] private let register: @MainActor (HotKey, Bool) throws -> Void private let registerSwitcher: @MainActor (HotKey, Bool) throws -> Void private let unregister: @MainActor (HotKey) throws -> Void private let updateRepeats: @MainActor (HotKey, Bool) -> Void private let registrationIsPresent: @MainActor (HotKey) -> Bool private let isReserved: @MainActor (KeyChord) -> Bool init( register: @escaping @MainActor (HotKey, Bool) throws -> Void, registerSwitcher: (@MainActor (HotKey, Bool) throws -> Void)? = nil, unregister: @escaping @MainActor (HotKey) throws -> Void, updateRepeats: @escaping @MainActor (HotKey, Bool) -> Void, registrationIsPresent: @escaping @MainActor (HotKey) -> Bool = { _ in true }, isReserved: @escaping @MainActor (KeyChord) -> Bool = { _ in false } ) { self.register = register self.registerSwitcher = registerSwitcher ?? register self.unregister = unregister self.updateRepeats = updateRepeats self.registrationIsPresent = registrationIsPresent self.isReserved = isReserved } func reload(_ configuration: ParcelConfiguration, mode nextMode: String? = nil) -> ( active: [ConfigCommand: KeyChord], conflicts: [Conflict] ) { let desired: [(BindingAction, KeyChord)] if !configuration.general.shortcutsEnabled { desired = [] } else if let nextMode { desired = (configuration.modes[nextMode] ?? [:]).map { ($0.key, $0.value) } .sorted { $0.1.description < $1.1.description } } else { desired = ConfigCommand.allCases.compactMap { command in configuration.keybindings[command].map { (.command(command), $0) } } + configuration.defaultModeEntries.keys.sorted().compactMap { name in configuration.defaultModeEntries[name].map { (.enterMode(name), $0) } } } registered = registered.filter { registrationIsPresent($0.key) } let modeChanged = mode != nextMode var next: [HotKey: BindingAction] = [:] var active: [ConfigCommand: KeyChord] = [:] var conflicts: [Conflict] = [] var failed: Set = [] for (action, chord) in desired { guard !isReserved(chord) else { continue } if case .command(let command) = action, DefaultKeybindings.isApplicationMenuShortcut(for: command, chord: chord) { active[command] = chord continue } let key = NativeAppRuntime.hotkey(chord) let repeats: Bool if case .command(let command) = action { repeats = NativeAppRuntime.repeats(command) } else { repeats = false } do { let isSwitcher = action == .command(.tabView) if let previous = registered[key], (previous == .command(.tabView)) != isSwitcher { try unregister(key) registered.removeValue(forKey: key) } if registered[key] == nil { if isSwitcher, let old = registered.first(where: { $0.value == .command(.tabView) && $0.key.keyCode == key.keyCode && $0.key.modifiers.symmetricDifference(key.modifiers) == .shift })?.key { try unregister(old) registered.removeValue(forKey: old) do { try registerSwitcher(key, repeats) } catch { do { try registerSwitcher(old, NativeAppRuntime.repeats(.tabView)) registered[old] = .command(.tabView) } catch let restorationError { guard let physical = ANSIKey.allCases.first(where: { $0.keyCode == old.keyCode }) else { preconditionFailure("An app hotkey must have a configured physical key") } let oldChord = KeyChord( modifiers: KeyModifiers(rawValue: UInt8(old.modifiers.rawValue)), key: physical) conflicts.append( Conflict(action: .command(.tabView), chord: oldChord, cause: restorationError)) } throw error } } else { try (isSwitcher ? registerSwitcher : register)(key, repeats) } } else if modeChanged || bindings[key] != action { updateRepeats(key, false) } updateRepeats(key, repeats) registered[key] = action next[key] = action if case .command(let command) = action { active[command] = chord } } catch { failed.insert(action) conflicts.append(Conflict(action: action, chord: chord, cause: error)) } } for (key, action) in registered where next[key] == nil { if !modeChanged, bindings[key] == action, failed.contains(action) { next[key] = action if case .command(let command) = action { guard let physical = ANSIKey.allCases.first(where: { $0.keyCode == key.keyCode }) else { preconditionFailure("An app hotkey must have a configured physical key") } active[command] = KeyChord( modifiers: KeyModifiers(rawValue: UInt8(key.modifiers.rawValue)), key: physical) } continue } updateRepeats(key, false) do { try unregister(key) registered.removeValue(forKey: key) } catch { let modifiers = KeyModifiers(rawValue: UInt8(key.modifiers.rawValue)) if let physical = ANSIKey.allCases.first(where: { $0.keyCode == key.keyCode }) { conflicts.append( Conflict(action: action, chord: KeyChord(modifiers: modifiers, key: physical), cause: error)) } else { preconditionFailure("An app hotkey must have a configured physical key") } } } repeatSuppressed.formIntersection(next.keys) for (key, action) in next where modeChanged || bindings[key] != action { repeatSuppressed.insert(key) } bindings = next mode = nextMode return (active, conflicts) } func action(for press: HotKeyPress) -> BindingAction? { guard let action = bindings[press.hotKey] else { return nil } if press.isRepeat, repeatSuppressed.contains(press.hotKey) { return nil } if !press.isRepeat { repeatSuppressed.remove(press.hotKey) } return action } func clear() { bindings.removeAll() registered.removeAll() repeatSuppressed.removeAll() mode = nil } } struct AppHotkeyFailure: Error, LocalizedError { let chords: [KeyChord] var errorDescription: String? { AppText.detail( "Shortcuts could not be registered: %@. Choose different chords in Settings.", chords.map(\.description).joined(separator: ", ") ).message } }