From c9873c03e4ec1152829e3241c3761812fb13bbe2 Mon Sep 17 00:00:00 2001 From: Esteban Uribe Date: Thu, 30 Apr 2026 03:01:54 -0700 Subject: [PATCH] Add configurable menu keyboard focus shortcut --- .../Sources/MenuBand/AppDelegate.swift | 133 ++++++++++++++++-- .../Sources/MenuBand/GlobalHotkey.swift | 26 +++- .../Sources/MenuBand/LocalKeyCapture.swift | 20 ++- .../Sources/MenuBand/MenuBandController.swift | 7 +- .../Sources/MenuBand/MenuBandPopover.swift | 127 ++++++++++++++++- .../Sources/MenuBand/MenuBandShortcut.swift | 120 ++++++++++++++++ 6 files changed, 409 insertions(+), 24 deletions(-) create mode 100644 slab/menuband/Sources/MenuBand/MenuBandShortcut.swift diff --git a/slab/menuband/Sources/MenuBand/AppDelegate.swift b/slab/menuband/Sources/MenuBand/AppDelegate.swift index 3cc6c74852..4255a09195 100644 --- a/slab/menuband/Sources/MenuBand/AppDelegate.swift +++ b/slab/menuband/Sources/MenuBand/AppDelegate.swift @@ -8,8 +8,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private var hoveredElement: KeyboardIconRenderer.HitResult? = nil private var trackingArea: NSTrackingArea? private var typeModeHotkey: GlobalHotkey? + private var focusCaptureHotkey: GlobalHotkey? private let popover = NSPopover() private var popoverVC: MenuBandPopoverViewController? + private var appBeforeFocusCapture: NSRunningApplication? + private var focusCaptureArmedByShortcut = false /// Periodic check that the status item is actually visible in the /// menu bar. macOS silently hides items when there's no room (notch + @@ -156,13 +159,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } updateIcon() - // Global hotkey: Ctrl+Opt+Cmd+P toggles TYPE. - let hotkey = GlobalHotkey { [weak self] in - self?.menuBand.toggleTypeMode() - } - let modMask: UInt32 = UInt32(cmdKey | controlKey | optionKey) - hotkey.register(keyCode: UInt32(kVK_ANSI_P), modifiers: modMask) - typeModeHotkey = hotkey + registerTypeModeHotkey() + _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) // Dev affordance: post the // `computer.aestheticcomputer.menuband.showPopover` @@ -185,7 +183,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // wants to release focus without clicking another app. if isDown && keyCode == 53 /* kVK_Escape */ { NSSound(named: NSSound.Name("Tink"))?.play() - self.localCapture.disarm() + self.localCapture.disarm(reason: .cancelled) return true } let consumed = self.menuBand.handleLocalKey( @@ -201,13 +199,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } return consumed } - localCapture.onCaptureEnd = { [weak self] in + localCapture.onCaptureEnd = { [weak self] reason in // Focus lost (user clicked another app). Drop the ghost and // any held notes so we don't leave anything hanging. - self?.ghostUntil = 0 - self?.ghostRefreshTimer?.invalidate() - self?.ghostRefreshTimer = nil - self?.updateIcon() + self?.finishLocalCapture(reason: reason) } // Pre-instance the popover + force its view to load now so the @@ -217,6 +212,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let vc = MenuBandPopoverViewController() vc.menuBand = menuBand vc.popover = popover + vc.onFocusShortcutChange = { [weak self] shortcut in + self?.applyFocusShortcut(shortcut) ?? false + } + vc.onFocusShortcutRecordingChanged = { [weak self] isRecording in + self?.setShortcutRecording(isRecording) + } popoverVC = vc popover.contentViewController = vc // .applicationDefined: never auto-close. We manage closing manually @@ -241,6 +242,111 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } + // MARK: - Global shortcuts + + private func registerTypeModeHotkey() { + let hotkey = GlobalHotkey( + signature: OSType(0x4E544B59), // 'NTKY' + id: 1 + ) { [weak self] in + self?.menuBand.toggleTypeMode() + } + let shortcut = MenuBandShortcut.typeMode + if hotkey.register(keyCode: shortcut.keyCode, modifiers: shortcut.modifiers) { + typeModeHotkey = hotkey + } + } + + @discardableResult + private func registerFocusCaptureHotkey(_ shortcut: MenuBandShortcut) -> Bool { + let hotkey = GlobalHotkey( + signature: OSType(0x4D42464B), // 'MBFK' + id: 1 + ) { [weak self] in + self?.toggleFocusCaptureFromShortcut() + } + guard hotkey.register(keyCode: shortcut.keyCode, modifiers: shortcut.modifiers) else { + return false + } + focusCaptureHotkey = hotkey + localCapture.cancelShortcut = shortcut + return true + } + + private func applyFocusShortcut(_ shortcut: MenuBandShortcut) -> Bool { + guard shortcut.isValidForRecording, !shortcut.isReservedForTypeMode else { + return false + } + let previous = MenuBandShortcutPreferences.focusShortcut + focusCaptureHotkey?.unregister() + focusCaptureHotkey = nil + guard registerFocusCaptureHotkey(shortcut) else { + _ = registerFocusCaptureHotkey(previous) + return false + } + MenuBandShortcutPreferences.focusShortcut = shortcut + return true + } + + private func setShortcutRecording(_ isRecording: Bool) { + if isRecording { + typeModeHotkey?.unregister() + typeModeHotkey = nil + focusCaptureHotkey?.unregister() + focusCaptureHotkey = nil + } else { + if typeModeHotkey == nil { registerTypeModeHotkey() } + if focusCaptureHotkey == nil { + _ = registerFocusCaptureHotkey(MenuBandShortcutPreferences.focusShortcut) + } + } + } + + private func toggleFocusCaptureFromShortcut() { + if localCapture.isArmed, focusCaptureArmedByShortcut { + localCapture.disarm(reason: .cancelled) + return + } + beginFocusCaptureFromShortcut() + } + + private func beginFocusCaptureFromShortcut() { + let frontmost = NSWorkspace.shared.frontmostApplication + if frontmost?.bundleIdentifier == Bundle.main.bundleIdentifier { + appBeforeFocusCapture = nil + } else { + appBeforeFocusCapture = frontmost + } + closePopover() + if menuBand.typeMode { + menuBand.disableTypeModeForFocusCapture() + } + focusCaptureArmedByShortcut = true + localCapture.arm() + updateIcon() + } + + private func finishLocalCapture(reason: LocalKeyCapture.EndReason) { + let shouldRestoreFocus = focusCaptureArmedByShortcut && reason == .cancelled + focusCaptureArmedByShortcut = false + menuBand.releaseAllHeldNotes() + ghostUntil = 0 + ghostRefreshTimer?.invalidate() + ghostRefreshTimer = nil + updateIcon() + if shouldRestoreFocus { + restorePreviousAppFocus() + } + appBeforeFocusCapture = nil + } + + private func restorePreviousAppFocus() { + guard let app = appBeforeFocusCapture, + !app.isTerminated, + app.bundleIdentifier != Bundle.main.bundleIdentifier else { return } + app.activate(options: [.activateIgnoringOtherApps]) + } + // MARK: - Adaptive menubar layout /// `true` when the status item button is laid out on a real screen. @@ -609,6 +715,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { /// starts at the pivot and ripples outward; fade-out starts at the /// outermost cell and retreats toward the pivot. private func letterAlpha(for midi: UInt8) -> CGFloat { + if focusCaptureArmedByShortcut { return 1.0 } return letterAlphas[midi] ?? 0 } diff --git a/slab/menuband/Sources/MenuBand/GlobalHotkey.swift b/slab/menuband/Sources/MenuBand/GlobalHotkey.swift index e75870bebd..0c7395d01a 100644 --- a/slab/menuband/Sources/MenuBand/GlobalHotkey.swift +++ b/slab/menuband/Sources/MenuBand/GlobalHotkey.swift @@ -6,11 +6,15 @@ import Carbon // shortcut that toggles MenuBand TYPE mode regardless of which app is // frontmost. final class GlobalHotkey { + private let signature: OSType + private let id: UInt32 private var hotKeyRef: EventHotKeyRef? private var eventHandler: EventHandlerRef? private let onTrigger: () -> Void - init(onTrigger: @escaping () -> Void) { + init(signature: OSType = OSType(0x4E544B59), id: UInt32 = 1, onTrigger: @escaping () -> Void) { + self.signature = signature + self.id = id self.onTrigger = onTrigger } @@ -19,8 +23,7 @@ final class GlobalHotkey { @discardableResult func register(keyCode: UInt32, modifiers: UInt32) -> Bool { unregister() - let hotKeyID = EventHotKeyID(signature: OSType(0x4E544B59), // 'NTKY' (MenuBand key) - id: 1) + let hotKeyID = EventHotKeyID(signature: signature, id: id) var ref: EventHotKeyRef? let regOK = RegisterEventHotKey(keyCode, modifiers, hotKeyID, GetApplicationEventTarget(), 0, &ref) @@ -33,9 +36,24 @@ final class GlobalHotkey { var spec = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed)) let opaque = Unmanaged.passUnretained(self).toOpaque() - let handler: EventHandlerUPP = { _, _, userData -> OSStatus in + let handler: EventHandlerUPP = { _, event, userData -> OSStatus in guard let userData = userData else { return noErr } let hk = Unmanaged.fromOpaque(userData).takeUnretainedValue() + guard let event = event else { return OSStatus(eventNotHandledErr) } + var incomingID = EventHotKeyID() + let status = GetEventParameter( + event, + EventParamName(kEventParamDirectObject), + EventParamType(typeEventHotKeyID), + nil, + MemoryLayout.size, + nil, + &incomingID + ) + guard status == noErr else { return status } + guard incomingID.signature == hk.signature, incomingID.id == hk.id else { + return OSStatus(eventNotHandledErr) + } DispatchQueue.main.async { hk.onTrigger() } return noErr } diff --git a/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift b/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift index d8aa8ff2e6..2687642d23 100644 --- a/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift +++ b/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift @@ -11,6 +11,11 @@ import AppKit /// The current global-tap mode (Notepat / Ableton in the popover) survives /// any focus change, but requires Accessibility and isn't App-Store-eligible. final class LocalKeyCapture { + enum EndReason { + case cancelled + case resignedKey + } + /// Called on every keyDown the panel observes. Return `true` to consume /// (so cmd-q etc. can still fall through if false). Receives the same /// (keyCode, isDown, isRepeat, flags) shape as the global tap so the @@ -18,7 +23,8 @@ final class LocalKeyCapture { var onKey: ((UInt16, Bool, Bool, NSEvent.ModifierFlags) -> Bool)? /// Called when the panel resigns key — capture has ended naturally /// because the user clicked another app. - var onCaptureEnd: (() -> Void)? + var onCaptureEnd: ((EndReason) -> Void)? + var cancelShortcut: MenuBandShortcut? private var panel: NSPanel? private var monitor: Any? @@ -50,6 +56,10 @@ final class LocalKeyCapture { monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp]) { [weak self] event in guard let self = self else { return event } let isDown = (event.type == .keyDown) + if isDown, self.cancelShortcut?.matches(event: event) == true { + self.disarm(reason: .cancelled) + return nil + } let consumed = self.onKey?(event.keyCode, isDown, event.isARepeat, event.modifierFlags) ?? false return consumed ? nil : event } @@ -66,7 +76,7 @@ final class LocalKeyCapture { ) { [weak self] _ in guard let self = self else { return } let stillKeyInApp = NSApp.windows.contains { $0.isKeyWindow } - if !stillKeyInApp { self.disarm() } + if !stillKeyInApp { self.disarm(reason: .resignedKey) } } } isArmed = true @@ -74,7 +84,7 @@ final class LocalKeyCapture { /// Tear down the panel + monitor. Called when the user clicks another /// app (panel resigns key) or explicitly when we want to drop capture. - func disarm() { + func disarm(reason: EndReason = .cancelled) { guard isArmed else { return } isArmed = false if let m = monitor { @@ -86,7 +96,7 @@ final class LocalKeyCapture { resignKeyObserver = nil } panel?.orderOut(nil) - onCaptureEnd?() + onCaptureEnd?(reason) } private func buildPanel() { @@ -111,7 +121,7 @@ final class LocalKeyCapture { panel = p } - deinit { disarm() } + deinit { disarm(reason: .cancelled) } } /// `NSPanel` subclass that overrides `canBecomeKey` to return true. Without diff --git a/slab/menuband/Sources/MenuBand/MenuBandController.swift b/slab/menuband/Sources/MenuBand/MenuBandController.swift index 31f1cfbcdf..2ce1e433f9 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandController.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandController.swift @@ -370,6 +370,11 @@ final class MenuBandController { } } + func disableTypeModeForFocusCapture() { + guard typeMode else { return } + disableTypeMode() + } + func shutdown() { disableTypeMode() disableMIDIMode() @@ -906,7 +911,7 @@ final class MenuBandController { } } - private func releaseAllHeldNotes() { + func releaseAllHeldNotes() { heldLock.lock() let noteSnapshot = heldNotes let chanSnapshot = heldKeyChannel diff --git a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift index 707c8ae4df..922c3b5ba0 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandPopover.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandPopover.swift @@ -1,4 +1,5 @@ import AppKit +import Carbon /// NSSegmentedControl subclass that reports the currently-hovered segment /// (or nil when the cursor leaves). Used by the input-mode picker so @@ -61,9 +62,15 @@ final class MenuBandPopoverViewController: NSViewController { /// we don't extend its lifetime; used to animate `contentSize` when the /// instrument palette collapses / expands. weak var popover: NSPopover? + var onFocusShortcutChange: ((MenuBandShortcut) -> Bool)? + var onFocusShortcutRecordingChanged: ((Bool) -> Void)? private var inputSegmented: HoverSegmentedControl! // legacy reference; no longer added to stack private var modeButtons: [NSButton] = [] // vertical stack: Mouse Only / Notepat.com / Ableton MIDI Keys + private var focusShortcutButton: NSButton! + private var focusShortcutStatusLabel: NSTextField! + private var focusShortcutRecorderMonitor: Any? + private var isRecordingFocusShortcut = false private var midiSwitch: NSSwitch! private var midiInlineLabel: NSTextField! private var midiSelfTestLabel: NSTextField! // legacy — created but never added to stack @@ -90,6 +97,12 @@ final class MenuBandPopoverViewController: NSViewController { private var waveformView: WaveformView! private var waveformBezel: NSView! + deinit { + if let monitor = focusShortcutRecorderMonitor { + NSEvent.removeMonitor(monitor) + } + } + override func loadView() { // Plain solid-color background — no NSVisualEffectView. The visual // effect view sampled the surrounding context and shifted appearance @@ -271,6 +284,45 @@ final class MenuBandPopoverViewController: NSViewController { inputLabel.font = NSFont.systemFont(ofSize: 11, weight: .semibold) inputLabel.textColor = .labelColor + let shortcuts = NSStackView() + shortcuts.orientation = .horizontal + shortcuts.alignment = .centerY + shortcuts.distribution = .fill + shortcuts.spacing = 8 + shortcuts.translatesAutoresizingMaskIntoConstraints = false + + let focusLabel = NSTextField(labelWithString: "Focus menu piano") + focusLabel.font = NSFont.systemFont(ofSize: 11) + focusLabel.textColor = .labelColor + shortcuts.addArrangedSubview(focusLabel) + + let focusSpacer = NSView() + focusSpacer.setContentHuggingPriority(.defaultLow, for: .horizontal) + shortcuts.addArrangedSubview(focusSpacer) + + focusShortcutButton = NSButton( + title: MenuBandShortcutPreferences.focusShortcut.displayString, + target: self, + action: #selector(focusShortcutButtonClicked(_:)) + ) + focusShortcutButton.bezelStyle = .recessed + focusShortcutButton.controlSize = .small + focusShortcutButton.translatesAutoresizingMaskIntoConstraints = false + focusShortcutButton.widthAnchor.constraint(equalToConstant: 96).isActive = true + shortcuts.addArrangedSubview(focusShortcutButton) + + shortcuts.widthAnchor.constraint( + equalToConstant: InstrumentListView.preferredWidth + ).isActive = true + + focusShortcutStatusLabel = NSTextField(labelWithString: "") + focusShortcutStatusLabel.font = NSFont.systemFont(ofSize: 10) + focusShortcutStatusLabel.textColor = .secondaryLabelColor + focusShortcutStatusLabel.lineBreakMode = .byTruncatingTail + focusShortcutStatusLabel.widthAnchor.constraint( + equalToConstant: InstrumentListView.preferredWidth + ).isActive = true + // Vertical mode buttons — full labels fit without truncation, each // button is the full content width with an SF Symbol leading the // text so the mode is recognizable at a glance. @@ -329,6 +381,10 @@ final class MenuBandPopoverViewController: NSViewController { // insertion point. let layoutBlock = (label: inputLabel, picker: modeStack, hint: inputHint) + let shortcutLabel = NSTextField(labelWithString: "Key Shortcuts") + shortcutLabel.font = NSFont.systemFont(ofSize: 11, weight: .semibold) + shortcutLabel.textColor = .labelColor + // Live segmented LED meter of the local synth output. Hidden in // MIDI mode (DAW handles audio there; our local mixer is silent // so the bars would just sit dark). @@ -612,11 +668,14 @@ final class MenuBandPopoverViewController: NSViewController { stack.addArrangedSubview(layoutBlock.label) stack.addArrangedSubview(layoutBlock.picker) stack.addArrangedSubview(layoutBlock.hint) + stack.addArrangedSubview(shortcutLabel) + stack.addArrangedSubview(shortcuts) + stack.addArrangedSubview(focusShortcutStatusLabel) // No divider above the about/brand block — the palette + Layout // section above gives plenty of separation. Custom airspace // before the about block. - stack.setCustomSpacing(14, after: layoutBlock.hint) + stack.setCustomSpacing(14, after: focusShortcutStatusLabel) // About + Crash logs in a side-by-side row. About has low hugging // so it expands when the crash column is hidden (no reports) — @@ -780,6 +839,7 @@ final class MenuBandPopoverViewController: NSViewController { override func viewDidDisappear() { super.viewDidDisappear() + stopFocusShortcutRecording(status: nil) waveformView.isLive = false } @@ -878,6 +938,7 @@ final class MenuBandPopoverViewController: NSViewController { for (i, btn) in modeButtons.enumerated() { btn.state = (i == segIdx) ? .on : .off } + updateFocusShortcutControls() instrumentList.selectedProgram = n.melodicProgram applyAppearanceToVisualizer() updateInstrumentReadout() @@ -937,6 +998,62 @@ final class MenuBandPopoverViewController: NSViewController { /// (no leading "078" program number — the cell's own backdrop color /// is the visual identifier; the number was redundant noise). A /// hair space on each side keeps the chip from touching its text. + private func updateFocusShortcutControls(status: String? = nil) { + guard focusShortcutButton != nil else { return } + if isRecordingFocusShortcut { + focusShortcutButton.title = "Press keys" + } else { + focusShortcutButton.title = MenuBandShortcutPreferences.focusShortcut.displayString + } + focusShortcutStatusLabel.stringValue = status ?? "" + } + + private func startFocusShortcutRecording() { + guard focusShortcutRecorderMonitor == nil else { return } + isRecordingFocusShortcut = true + onFocusShortcutRecordingChanged?(true) + updateFocusShortcutControls(status: "Use ⌘, ⌃, or ⌥") + focusShortcutRecorderMonitor = NSEvent.addLocalMonitorForEvents( + matching: [.keyDown] + ) { [weak self] event in + self?.handleFocusShortcutRecording(event) + return nil + } + } + + private func stopFocusShortcutRecording(status: String?) { + guard isRecordingFocusShortcut || focusShortcutRecorderMonitor != nil else { return } + if let monitor = focusShortcutRecorderMonitor { + NSEvent.removeMonitor(monitor) + focusShortcutRecorderMonitor = nil + } + isRecordingFocusShortcut = false + onFocusShortcutRecordingChanged?(false) + updateFocusShortcutControls(status: status) + } + + private func handleFocusShortcutRecording(_ event: NSEvent) { + if event.keyCode == UInt16(kVK_Escape) { + stopFocusShortcutRecording(status: nil) + return + } + let shortcut = MenuBandShortcut( + keyCode: UInt32(event.keyCode), + modifiers: MenuBandShortcut.carbonModifiers(from: event.modifierFlags) + ) + guard shortcut.isValidForRecording else { + updateFocusShortcutControls(status: "Use ⌘, ⌃, or ⌥") + return + } + guard !shortcut.isReservedForTypeMode else { + updateFocusShortcutControls(status: "⌃⌥⌘P is reserved") + return + } + let saved = onFocusShortcutChange?(shortcut) ?? false + stopFocusShortcutRecording( + status: saved ? "Saved \(shortcut.displayString)" : "Shortcut unavailable" + ) + } private func updateInstrumentReadout() { guard let m = menuBand else { return } let safe = max(0, min(127, Int(m.melodicProgram))) @@ -1329,6 +1446,14 @@ final class MenuBandPopoverViewController: NSViewController { } } + @objc private func focusShortcutButtonClicked(_ sender: NSButton) { + if isRecordingFocusShortcut { + stopFocusShortcutRecording(status: nil) + } else { + startFocusShortcutRecording() + } + } + private func handleInstrumentCommit(_ program: Int) { guard let m = menuBand else { return } // If MIDI mode is on, picking an instrument from the GM palette diff --git a/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift b/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift new file mode 100644 index 0000000000..a201dfb684 --- /dev/null +++ b/slab/menuband/Sources/MenuBand/MenuBandShortcut.swift @@ -0,0 +1,120 @@ +import AppKit +import Carbon + +struct MenuBandShortcut: Equatable { + let keyCode: UInt32 + let modifiers: UInt32 + + static let defaultFocus = MenuBandShortcut( + keyCode: UInt32(kVK_ANSI_K), + modifiers: UInt32(cmdKey | controlKey | optionKey) + ) + + static let typeMode = MenuBandShortcut( + keyCode: UInt32(kVK_ANSI_P), + modifiers: UInt32(cmdKey | controlKey | optionKey) + ) + + var isValidForRecording: Bool { + (modifiers & UInt32(cmdKey | controlKey | optionKey)) != 0 + } + + var isReservedForTypeMode: Bool { + self == Self.typeMode + } + + var displayString: String { + var parts = "" + if (modifiers & UInt32(controlKey)) != 0 { parts += "⌃" } + if (modifiers & UInt32(optionKey)) != 0 { parts += "⌥" } + if (modifiers & UInt32(shiftKey)) != 0 { parts += "⇧" } + if (modifiers & UInt32(cmdKey)) != 0 { parts += "⌘" } + return parts + Self.keyLabel(for: keyCode) + } + + func matches(event: NSEvent) -> Bool { + UInt32(event.keyCode) == keyCode && + Self.carbonModifiers(from: event.modifierFlags) == modifiers + } + + static func carbonModifiers(from flags: NSEvent.ModifierFlags) -> UInt32 { + var mask: UInt32 = 0 + if flags.contains(.command) { mask |= UInt32(cmdKey) } + if flags.contains(.control) { mask |= UInt32(controlKey) } + if flags.contains(.option) { mask |= UInt32(optionKey) } + if flags.contains(.shift) { mask |= UInt32(shiftKey) } + return mask + } + + private static func keyLabel(for keyCode: UInt32) -> String { + if let label = ansiKeyLabels[keyCode] { return label } + if let label = specialKeyLabels[keyCode] { return label } + return "Key \(keyCode)" + } + + private static let ansiKeyLabels: [UInt32: String] = [ + 0: "A", 1: "S", 2: "D", 3: "F", 4: "H", 5: "G", 6: "Z", + 7: "X", 8: "C", 9: "V", 11: "B", 12: "Q", 13: "W", + 14: "E", 15: "R", 16: "Y", 17: "T", 18: "1", 19: "2", + 20: "3", 21: "4", 22: "6", 23: "5", 24: "=", 25: "9", + 26: "7", 27: "-", 28: "8", 29: "0", 30: "]", 31: "O", + 32: "U", 33: "[", 34: "I", 35: "P", 37: "L", 38: "J", + 39: "'", 40: "K", 41: ";", 42: "\\", 43: ",", 44: "/", + 45: "N", 46: "M", 47: ".", 50: "`" + ] + + private static let specialKeyLabels: [UInt32: String] = [ + UInt32(kVK_Space): "Space", + UInt32(kVK_Return): "Return", + UInt32(kVK_Tab): "Tab", + UInt32(kVK_Escape): "Esc", + UInt32(kVK_Delete): "Delete", + UInt32(kVK_ForwardDelete): "FwdDel", + UInt32(kVK_Home): "Home", + UInt32(kVK_End): "End", + UInt32(kVK_PageUp): "PgUp", + UInt32(kVK_PageDown): "PgDn", + UInt32(kVK_LeftArrow): "←", + UInt32(kVK_RightArrow): "→", + UInt32(kVK_UpArrow): "↑", + UInt32(kVK_DownArrow): "↓", + UInt32(kVK_F1): "F1", + UInt32(kVK_F2): "F2", + UInt32(kVK_F3): "F3", + UInt32(kVK_F4): "F4", + UInt32(kVK_F5): "F5", + UInt32(kVK_F6): "F6", + UInt32(kVK_F7): "F7", + UInt32(kVK_F8): "F8", + UInt32(kVK_F9): "F9", + UInt32(kVK_F10): "F10", + UInt32(kVK_F11): "F11", + UInt32(kVK_F12): "F12" + ] +} + +enum MenuBandShortcutPreferences { + private static let focusKeyCodeKey = "notepat.focusShortcut.keyCode" + private static let focusModifiersKey = "notepat.focusShortcut.modifiers" + + static var focusShortcut: MenuBandShortcut { + get { + let defaults = UserDefaults.standard + guard defaults.object(forKey: focusKeyCodeKey) != nil, + defaults.object(forKey: focusModifiersKey) != nil else { + return .defaultFocus + } + let shortcut = MenuBandShortcut( + keyCode: UInt32(defaults.integer(forKey: focusKeyCodeKey)), + modifiers: UInt32(defaults.integer(forKey: focusModifiersKey)) + ) + return shortcut.isValidForRecording && !shortcut.isReservedForTypeMode + ? shortcut + : .defaultFocus + } + set { + UserDefaults.standard.set(Int(newValue.keyCode), forKey: focusKeyCodeKey) + UserDefaults.standard.set(Int(newValue.modifiers), forKey: focusModifiersKey) + } + } +} -- knotmirror 0.0.1