public import AppKit public import ParcelConfig import SwiftUI public enum ShortcutRecorderParser { public static func parse(_ text: String) throws -> KeyChord { try KeyChord(parsing: text) } public static func chord( keyCode: UInt16, modifiers flags: NSEvent.ModifierFlags, functionKeyPressed: Bool = false ) throws -> KeyChord { guard let key = ANSIKey.allCases.first(where: { $0.keyCode == keyCode }) else { throw SettingsFailure(SettingsText.string("This key is not supported. Enter an ANSI shortcut instead.")) } var modifiers: KeyModifiers = [] if flags.contains(.control) { modifiers.insert(.ctrl) } if flags.contains(.option) { modifiers.insert(.alt) } if flags.contains(.command) { modifiers.insert(.cmd) } if flags.contains(.shift) { modifiers.insert(.shift) } // AppKit marks navigation and function keys as function even without a held Fn key. if functionKeyPressed || (flags.contains(.function) && !intrinsicFunctionKeys.contains(key)) { modifiers.insert(.fn) } return KeyChord(modifiers: modifiers, key: key) } private static let intrinsicFunctionKeys: Set = [ .left, .right, .up, .down, .home, .end, .pageUp, .pageDown, .forwardDelete, .help, .f1, .f2, .f3, .f4, .f5, .f6, .f7, .f8, .f9, .f10, .f11, .f12, .f13, .f14, .f15, .f16, .f17, .f18, .f19, .f20, ] } struct ShortcutEditor: View { let model: SettingsModel let command: ConfigCommand @Environment(\.dismiss) private var dismiss @State private var text: String @State private var recording = false @State private var saving = false @State private var failure: String? @State private var environment = SettingsShortcutEnvironment() @State private var warning: SettingsShortcutWarning? @State private var limitations: [String] = [] @State private var checking = true init(model: SettingsModel, command: ConfigCommand) { self.model = model self.command = command _text = State(initialValue: model.configuration.keybindings[command]?.description ?? "") } var body: some View { VStack(alignment: .leading, spacing: 16) { Text(command.settingsTitle).font(.headline) Text( SettingsText.string( "Shortcuts use physical ANSI key positions. You can also type a shortcut using modifier and key names." )) HStack { TextField(SettingsText.string("Shortcut"), text: $text) .accessibilityLabel(SettingsText.string("Shortcut")) .disabled(recording || saving) .onSubmit { save() } if let preview = ShortcutDisplayPreview.chord(text) { ShortcutLabel(tokens: preview.tokens, accessibilityLabel: preview.accessibilityLabel) } } if recording { RecordingKeyView { result in switch result { case .success(let chord): text = chord.description case .failure(let error): failure = error.message } recording = false } .frame(height: 32) Text( SettingsText.string( "Press a shortcut, including any modifiers. Tab and Escape can also be recorded.") ) .font(.caption) } else { Button(SettingsText.string("Record shortcut")) { failure = nil recording = true model.onRecordedShortcut = { chord in text = chord.description recording = false } } .disabled(saving) } if checking { ProgressView().accessibilityLabel(SettingsText.string("Checking shortcut conflicts")) } if let warning { ForEach(warning.messages, id: \.self) { Text($0).textSelection(.enabled) } ForEach(warning.suggestions, id: \.self) { suggestion in Button(SettingsText.string("Use \(suggestion.displayString)")) { text = suggestion.description } .accessibilityLabel(SettingsText.string("Use \(suggestion.accessibilityLabel)")) .accessibilityHint(SettingsText.string("This alternative is free in the checked shortcuts.")) } } if !limitations.isEmpty { DisclosureGroup(SettingsText.string("Shortcut check details")) { ForEach(limitations, id: \.self) { Text($0).font(.caption).textSelection(.enabled) } } } if let failure { Text(failure).foregroundStyle(.red).textSelection(.enabled) } HStack { Button(SettingsText.string("Clear shortcut")) { save(clear: true) } .disabled(saving) Spacer() Button(SettingsText.string("Cancel")) { dismiss() } .disabled(saving) Button(SettingsText.string("Save")) { save() } .disabled(saving || recording) } } .padding(24) .frame(width: 460) .task { do { environment = try await model.shortcutEnvironment() limitations = environment.limitations } catch is CancellationError { return } catch { limitations = [ SettingsText.string("Shortcut conflicts could not be checked: \(error.localizedDescription)") ] } checking = false check() } .onChange(of: recording) { if !recording { model.onRecordedShortcut = nil } } .onDisappear { model.onRecordedShortcut = nil } .onChange(of: text) { check() } .onChange(of: model.configuration.keybindings) { check() } .onChange(of: model.configuration.general.shortcutsEnabled) { recording = false } .onChange(of: model.configuration.defaultModeEntries) { check() } .onChange(of: model.checkedShortcutEnvironment) { environment = model.checkedShortcutEnvironment limitations = environment.limitations check() } } private func check() { guard !text.isEmpty else { warning = nil return } do { let chord = try ShortcutRecorderParser.parse(text) warning = SettingsShortcutChecker.warning( for: chord, command: command, bindings: model.configuration.keybindings, environment: environment, additionalBindings: Array(model.configuration.defaultModeEntries.values)) } catch is KeyChordParseError { warning = nil } catch { failure = error.localizedDescription } } private func save(clear: Bool = false) { saving = true Task { do { if clear { try await model.setShortcut(nil, for: command) } else { try await model.setShortcut(text: text, for: command) } dismiss() } catch { failure = SettingsFailure(error: error).message } saving = false } } } private struct RecordingKeyView: NSViewRepresentable { let captured: @MainActor (Result) -> Void func makeNSView(context: Context) -> RecordingButton { let button = RecordingButton() button.title = SettingsText.string("Listening for a shortcut…") button.bezelStyle = .rounded button.captured = captured return button } func updateNSView(_ nsView: RecordingButton, context: Context) { nsView.captured = captured } } final class RecordingButton: NSButton { override init(frame: NSRect) { super.init(frame: frame) setAccessibilityLabel(SettingsText.string("Shortcut recorder")) setAccessibilityHelp( SettingsText.string("Press a shortcut, including any modifiers. Tab and Escape can also be recorded.")) } required init?(coder: NSCoder) { super.init(coder: coder) } var captured: (@MainActor (Result) -> Void)? private var finished = false private var functionKeyPressed = false override var acceptsFirstResponder: Bool { true } override func viewDidMoveToWindow() { super.viewDidMoveToWindow() window?.makeFirstResponder(self) } override func performKeyEquivalent(with event: NSEvent) -> Bool { guard window?.firstResponder === self, !finished else { return false } keyDown(with: event) return true } override func keyDown(with event: NSEvent) { guard !finished, !event.isARepeat else { return } finished = true do { captured?( .success( try ShortcutRecorderParser.chord( keyCode: event.keyCode, modifiers: event.modifierFlags, functionKeyPressed: functionKeyPressed)) ) } catch { captured?(.failure(SettingsFailure(error: error))) } } override func flagsChanged(with event: NSEvent) { if event.keyCode == 63 { functionKeyPressed = event.modifierFlags.contains(.function) } if event.keyCode == ANSIKey.capsLock.keyCode { keyDown(with: event) } } }