diff --git a/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift b/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift index 9088a94..248aa43 100644 --- a/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift +++ b/Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift @@ -38,6 +38,8 @@ public final class MIDIController { case cc(MIDIMap.CCTarget) /// A toggle action awaiting a Program Change. case action(MIDIMap.Action) + /// A toggle action awaiting a computer key press. + case key(MIDIMap.Action) } /// The control currently armed for Learn, or `nil` when not learning. Observable so the UI can @@ -438,6 +440,89 @@ public final class MIDIController { return nil } + // MARK: - Key learn + apply + + /// Arms MIDI Learn for a toggle action awaiting a key: the next ingested key press binds to it. + public func armKeyLearn(_ action: MIDIMap.Action) { + learnTarget = .key(action) + } + + /// The key binding currently assigned to an action, or `nil` if unbound. + public func keyBinding(for action: MIDIMap.Action) -> MIDIMap.KeyBinding? { + shoeGaze?.midiMap?.keys.first { $0.action == action } + } + + /// Removes any key binding assigned to an action. + public func clearKeyBinding(for action: MIDIMap.Action) { + guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return } + let before: Int = map.keys.count + map.keys.removeAll { $0.action == action } + guard map.keys.count != before else { return } + shoeGaze.midiMap = map + onMapChanged?() + } + + /// Normalizes a raw key string to the single lowercased character used for storage and matching, + /// or `nil` when the input is not exactly one letter or digit. Restricting to alphanumerics keeps + /// non-printing keys (Return, Tab, Escape, arrows — all single `Character`s) from being learned + /// and then silently swallowed app-wide. + private func normalizedKey(_ raw: String) -> String? { + let lowered: String = raw.lowercased() + guard lowered.count == 1, let character: Character = lowered.first, character.isASCII, + character.isLetter || character.isNumber else { return nil } + return lowered + } + + /// Routes a computer key press: captures a binding when armed for key Learn, otherwise performs + /// every action bound to that key + modifier combination. Returns `true` when the press was + /// consumed (learned or matched a binding) so the caller can swallow the event; `false` lets it + /// fall through. + /// + /// - Parameters: + /// - rawKey: The pressed key; normalized to a single lowercased character. + /// - modifiers: The modifier keys held with the press. `a` and `⇧a` bind independently. + @discardableResult + public func ingestKey(_ rawKey: String, modifiers: MIDIMap.KeyModifiers = []) -> Bool { + guard let key: String = normalizedKey(rawKey) else { return false } + if case .key(let action) = learnTarget { + captureKey(key: key, modifiers: modifiers, action: action) + return true + } + return applyKey(key, modifiers: modifiers) + } + + /// Captures a learned key binding for the armed action and clears the Learn state. One binding + /// per action — re-learning replaces it — but a single key may drive multiple actions (a scene), + /// so we do not steal by key. + private func captureKey(key: String, modifiers: MIDIMap.KeyModifiers, action: MIDIMap.Action) { + learnTarget = nil + guard let shoeGaze: ShoeGaze = shoeGaze else { return } + let binding: MIDIMap.KeyBinding = MIDIMap.KeyBinding( + key: key, + modifiers: modifiers, + action: action, + displayNameHint: hint(for: action) + ) + var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty + map.keys.removeAll { $0.action == action } + map.keys.append(binding) + shoeGaze.midiMap = map + onMapChanged?() + } + + /// Performs every action bound to a key + modifier combination. Returns `true` when at least one + /// binding matched (key and modifiers both equal). + private func applyKey(_ key: String, modifiers: MIDIMap.KeyModifiers) -> Bool { + guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return false } + var matched: Bool = false + for binding: MIDIMap.KeyBinding in map.keys + where binding.key == key && binding.modifiers == modifiers { + perform(binding.action) + matched = true + } + return matched + } + // MARK: - Device detection private func refreshDevices() { diff --git a/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift b/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift index d6d388a..d1ba37f 100644 --- a/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift +++ b/Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift @@ -24,6 +24,10 @@ public struct MIDIMap: Codable, Equatable, Sendable { /// Control-Change → pedal-knob bindings (expression pedals). public var ccs: [CCBinding] + /// Computer letter/digit key → action bindings. Same toggle ``Action`` set as ``switches`` — + /// a key press is a software footswitch — but keys never drive continuous CC targets. + public var keys: [KeyBinding] + /// An empty map (no bindings). public static let empty: MIDIMap = MIDIMap() @@ -32,12 +36,32 @@ public struct MIDIMap: Codable, Equatable, Sendable { /// - Parameters: /// - switches: Program-Change bindings. Defaults to empty. /// - ccs: Control-Change bindings. Defaults to empty. + /// - keys: Letter-key bindings. Defaults to empty. public init( switches: [SwitchBinding] = [], - ccs: [CCBinding] = [] + ccs: [CCBinding] = [], + keys: [KeyBinding] = [] ) { self.switches = switches self.ccs = ccs + self.keys = keys + } + + private enum CodingKeys: String, CodingKey { + case switches + case ccs + case keys + } + + /// Decodes a map, tolerating an absent `keys` list so a rig saved before keyboard mapping + /// existed still decodes with its `switches` / `ccs` intact (synthesized Codable would fail + /// the whole map on the missing key, silently dropping the MIDI bindings too). `encode(to:)` + /// stays synthesized and always writes `keys` (empty when there are none). + public init(from decoder: Decoder) throws { + let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) + self.switches = try container.decode([SwitchBinding].self, forKey: .switches) + self.ccs = try container.decode([CCBinding].self, forKey: .ccs) + self.keys = try container.decodeIfPresent([KeyBinding].self, forKey: .keys) ?? [] } // MARK: - Action @@ -127,6 +151,86 @@ public struct MIDIMap: Codable, Equatable, Sendable { } } + // MARK: - Key modifiers + + /// The modifier keys that qualify a ``KeyBinding``, so `a` and `⇧a` (and `⌃a`, `⌥a`) are + /// distinct triggers. Shift is a modifier here rather than being folded into the key's case, + /// which keeps the base key a single lowercased character on every platform. Command is + /// deliberately absent — it is reserved for the app's menu keyboard shortcuts. + public struct KeyModifiers: OptionSet, Codable, Equatable, Hashable, Sendable { + + public let rawValue: Int + + public init(rawValue: Int) { + self.rawValue = rawValue + } + + /// The Shift key (`⇧`). + public static let shift: KeyModifiers = KeyModifiers(rawValue: 1 << 0) + /// The Control key (`⌃`). + public static let control: KeyModifiers = KeyModifiers(rawValue: 1 << 1) + /// The Option key (`⌥`). + public static let option: KeyModifiers = KeyModifiers(rawValue: 1 << 2) + } + + // MARK: - Key binding + + /// A computer letter/digit key bound to a toggle ``Action``. Fires on key-down when no text + /// field is focused; the same latch semantics as a footswitch (booleans flip in software, + /// `boardSolo` is exclusive). `key` is a single lowercased character; ``modifiers`` distinguish + /// `a` from `⇧a`, `⌃a`, and `⌥a`. + public struct KeyBinding: Codable, Equatable, Sendable { + + /// The bound key as a single lowercased character (e.g. `"b"`, `"3"`). + public var key: String + + /// The modifier keys held with ``key``. Empty for an unmodified press. + public var modifiers: KeyModifiers + + /// The control to toggle. + public var action: Action + + /// The resolved control's display name at learn time, for stale-binding detection. + public var displayNameHint: String? + + /// Creates a key binding. + /// + /// - Parameters: + /// - key: The bound key, normalized to a single lowercased character. + /// - modifiers: The qualifying modifier keys. Defaults to none. + /// - action: The toggle action to perform. + /// - displayNameHint: Resolved control name at learn time. Defaults to `nil`. + public init( + key: String, + modifiers: KeyModifiers = [], + action: Action, + displayNameHint: String? = nil + ) { + self.key = key + self.modifiers = modifiers + self.action = action + self.displayNameHint = displayNameHint + } + + private enum CodingKeys: String, CodingKey { + case key + case modifiers + case action + case displayNameHint + } + + /// Decodes a key binding, defaulting `modifiers` to none when absent so a binding saved + /// before modifiers existed still decodes (unmodified, as it was learned). `encode(to:)` + /// stays synthesized. + public init(from decoder: Decoder) throws { + let container: KeyedDecodingContainer = try decoder.container(keyedBy: CodingKeys.self) + self.key = try container.decode(String.self, forKey: .key) + self.modifiers = try container.decodeIfPresent(KeyModifiers.self, forKey: .modifiers) ?? [] + self.action = try container.decode(Action.self, forKey: .action) + self.displayNameHint = try container.decodeIfPresent(String.self, forKey: .displayNameHint) + } + } + // MARK: - CC target /// A continuous control an expression pedal can drive — either a specific pedal control (a knob diff --git a/Sources/LyrebirdShoeGazeUI/HelpView.swift b/Sources/LyrebirdShoeGazeUI/HelpView.swift index 19d0342..dc35fcf 100644 --- a/Sources/LyrebirdShoeGazeUI/HelpView.swift +++ b/Sources/LyrebirdShoeGazeUI/HelpView.swift @@ -109,8 +109,9 @@ public struct HelpView: View { "Tracks A–D: tap a dot to select the track Record overdubs into; tap a selected, " + "recorded track again to mute or unmute it.", "MIDI: Record, Stop, Cue Stop, Reverse, Sync, Reset, and each Track A–D map as " - + "footswitch (Program Change) actions in MIDI Mapping; the Crossfade / Playback / " - + "Overdub / Feedback knobs sweep from an expression pedal like any pedal knob.", + + "footswitch (Program Change) or key actions in MIDI / Control Mapping; the " + + "Crossfade / Playback / Overdub / Feedback knobs sweep from an expression pedal " + + "like any pedal knob.", ] ) topicSection( @@ -136,13 +137,19 @@ public struct HelpView: View { ) topicSection( icon: "pianokeys", - title: "MIDI Control", - intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) for hands-free control.", + title: "MIDI / Control", + intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) or your computer keyboard for " + + "hands-free control.", steps: [ - "The keys icon in the top bar lights green when a device is connected. Tap it to open MIDI Mapping.", - "Switches (Program Change): footswitches toggle Rig Bypass, All Boards, and each board's " - + "Solo / Audible / Bypass or a pedal's bypass. Tap Learn, then press the footswitch. " - + "One switch can drive several actions at once — a scene.", + "The keys icon in the top bar lights green when a device is connected. Tap it to open " + + "MIDI / Control Mapping.", + "Switches: footswitches and letter keys toggle Rig Bypass, All Boards, and each board's " + + "Solo / Audible / Bypass or a pedal's bypass. Tap PC then press a footswitch, or Key " + + "then press a key. One switch or key can drive several actions at once — a scene.", + "Keys fire only when you're not typing — while a text field (like a rig name) is focused, " + + "letters go to the field, not to your mappings.", + "Hold Shift, Control, or Option while learning to bind a modified key — a and ⇧a are " + + "separate triggers. Command is reserved for the menu shortcuts.", "Expression (Control Change): an expression pedal sweeps any pedal knob or slider, or a " + "board's Level. Tap Learn, then move the pedal. Invert reverses the sweep — map one " + "CC to two controls and invert one for a crossfade.", diff --git a/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift b/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift index e678219..138f4e8 100644 --- a/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift +++ b/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift @@ -22,6 +22,7 @@ public struct MIDIMappingSheet: View { private static let sheetMinWidth: CGFloat = 460 private static let sheetMinHeight: CGFloat = 520 private static let rowVerticalPadding: CGFloat = 2 + private static let switchRowControlSpacing: CGFloat = 8 // MARK: - Inputs @@ -49,7 +50,7 @@ public struct MIDIMappingSheet: View { switchesSection expressionSection } - .navigationTitle("MIDI Mapping") + .navigationTitle("MIDI / Control Mapping") .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { @@ -174,30 +175,37 @@ public struct MIDIMappingSheet: View { // MARK: - Switches (Program Change) private var switchesSection: some View { - Section("Switches (Program Change)") { + Section("Switches (footswitch / key)") { ForEach(switchRowModels) { row in switchRow(row) } } } + /// A switch row carries two independent trigger sources for one toggle action: a MIDI Program + /// Change (footswitch) and a computer key. Each has its own learn / clear; the detail line + /// summarises whichever are bound, or the "Listening…" prompt for the armed source. private func switchRow(_ row: SwitchRowModel) -> some View { - let isArmed: Bool = controller.learnTarget == .action(row.action) - let binding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action) - return HStack { + let isArmedPC: Bool = controller.learnTarget == .action(row.action) + let isArmedKey: Bool = controller.learnTarget == .key(row.action) + let pcBinding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action) + let keyBinding: MIDIMap.KeyBinding? = controller.keyBinding(for: row.action) + let isArmed: Bool = isArmedPC || isArmedKey + return HStack(spacing: MIDIMappingSheet.switchRowControlSpacing) { VStack(alignment: .leading, spacing: 1) { Text(row.label) - Text(switchBindingLabel(isArmed: isArmed, binding: binding)) + Text(switchBindingLabel(isArmedPC: isArmedPC, isArmedKey: isArmedKey, + pc: pcBinding, key: keyBinding)) .font(.caption) .foregroundStyle(isArmed ? Color.orange : .secondary) } Spacer() - if binding != nil { - Button("Clear") { controller.clearSwitchBinding(for: row.action) } + if pcBinding != nil { + Button("Clear PC") { controller.clearSwitchBinding(for: row.action) } .buttonStyle(.borderless) } - Button(isArmed ? "Cancel" : "Learn") { - if isArmed { + Button(isArmedPC ? "Cancel" : "PC") { + if isArmedPC { controller.cancelLearn() } else { controller.armSwitchLearn(row.action) @@ -205,15 +213,50 @@ public struct MIDIMappingSheet: View { } .buttonStyle(.bordered) .tint(.orange) + if keyBinding != nil { + Button("Clear Key") { controller.clearKeyBinding(for: row.action) } + .buttonStyle(.borderless) + } + Button(isArmedKey ? "Cancel" : "Key") { + if isArmedKey { + controller.cancelLearn() + } else { + controller.armKeyLearn(row.action) + } + } + .buttonStyle(.bordered) + .tint(.orange) } .padding(.vertical, MIDIMappingSheet.rowVerticalPadding) } - private func switchBindingLabel(isArmed: Bool, binding: MIDIMap.SwitchBinding?) -> String { - if isArmed { return "Listening — press a footswitch…" } - guard let binding: MIDIMap.SwitchBinding = binding else { return "Unassigned" } - let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? "" - return "PC \(binding.program)\(channelText)" + private func switchBindingLabel( + isArmedPC: Bool, + isArmedKey: Bool, + pc: MIDIMap.SwitchBinding?, + key: MIDIMap.KeyBinding? + ) -> String { + if isArmedPC { return "Listening — press a footswitch…" } + if isArmedKey { return "Listening — press a key…" } + var parts: [String] = [] + if let pc: MIDIMap.SwitchBinding = pc { + let channelText: String = pc.channel.map { " · ch \($0 + 1)" } ?? "" + parts.append("PC \(pc.program)\(channelText)") + } + if let key: MIDIMap.KeyBinding = key { + parts.append("Key \(keyLabel(key))") + } + return parts.isEmpty ? "Unassigned" : parts.joined(separator: " · ") + } + + /// A key binding formatted with its modifier glyphs, e.g. `A`, `⇧A`, `⌃A` (macOS modifier order: + /// control, option, shift). + private func keyLabel(_ binding: MIDIMap.KeyBinding) -> String { + var prefix: String = "" + if binding.modifiers.contains(.control) { prefix += "⌃" } + if binding.modifiers.contains(.option) { prefix += "⌥" } + if binding.modifiers.contains(.shift) { prefix += "⇧" } + return prefix + binding.key.uppercased() } // MARK: - Expression (CC) diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 1cb2677..518dd2f 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -185,6 +185,16 @@ public struct ShoeGazeBuilderView: View { @State private var showRecordingFolderImporter: Bool = false #endif + #if os(macOS) + /// The AppKit local key-down monitor that routes bare letter/digit keys to `midi.ingestKey`, + /// or `nil` when not installed. Stored so it can be removed on disappear. + @State private var keyMonitor: Any? + #else + /// Whether the builder root holds keyboard focus, so `.onKeyPress` delivers hardware-keyboard + /// presses to the key bindings. Held `true` except while a text field is being edited. + @FocusState private var keyboardFocused: Bool + #endif + // MARK: - Init /// Creates a builder view. @@ -232,7 +242,10 @@ public struct ShoeGazeBuilderView: View { } - public var body: some View { + // The builder body is split across `layoutChrome` → `presentationChrome` → `body` because the + // full modifier chain (layout + lifecycle + every sheet / dialog / alert + key capture) is too + // large for the Swift expression type-checker as a single expression. + private var layoutChrome: some View { rootContent .padding(ShoeGazeBuilderView.outerPadding) // A large min width is a macOS window sizing hint; on iPad it would force content wider than @@ -268,12 +281,26 @@ public struct ShoeGazeBuilderView: View { restoreInputSelection() syncIdleTimer() maybeWarnICloudUnavailable() + #if os(macOS) + installKeyMonitor() + #else + keyboardFocused = true + #endif + } + .onDisappear { + releaseIdleTimer() + #if os(macOS) + removeKeyMonitor() + #endif } - .onDisappear { releaseIdleTimer() } .onChange(of: transportTick) { syncIdleTimer() } .onChange(of: library.isLoaded) { maybeWarnICloudUnavailable() } + } + + private var presentationChrome: some View { + layoutChrome .background(boardsSheetAnchor) .background(rigExportAnchor) .background(rigImportAnchor) @@ -367,6 +394,136 @@ public struct ShoeGazeBuilderView: View { .overlay(alignment: .top) { midiLearnBanner } } + public var body: some View { + presentationChrome + // Letter/digit keys drive bound rig actions. macOS uses an AppKit key monitor (installed in + // onAppear) because SwiftUI's `.onKeyPress` only delivers to the focused view, and the builder + // root is rarely the focused view. iOS routes hardware-keyboard presses through `.onKeyPress`, + // which requires the root to be focusable AND focused — so the root claims focus on appear and + // reclaims it whenever a modal that stole focus (a text-field sheet) closes. A focused + // `TextField` still wins while open, so typing is never hijacked. + #if !os(macOS) + .modifier(KeyboardCaptureModifier( + keyboardFocused: $keyboardFocused, + modalOpen: anyFocusStealingModalOpen, + onKeyPress: handleKeyPress + )) + #endif + } + + #if !os(macOS) + /// Whether any modal that can take keyboard focus from the builder root is currently open. When + /// it closes, the root reclaims focus so hardware-keyboard bindings keep firing. Text-field- + /// bearing sheets (rig rename, board editor) are the ones that matter, but covering the main + /// content sheets keeps focus robust across all of them. + private var anyFocusStealingModalOpen: Bool { + showMIDISheet || showHelpSheet || showRigsSheet || showPaletteSheet + || showSettingsSheet || showBoardsSheet || namePrompt != nil + } + #endif + + #if !os(macOS) + /// Routes a bare key press to the MIDI controller's key bindings, ignoring modified presses so + /// `⌘`-shortcuts still work. Returns `.handled` when a binding consumed the key, else `.ignored`. + /// A focused text field consumes keys first via the responder chain, so this only fires when the + /// user is not typing. + private func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result { + guard let midi: MIDIController = midi else { return .ignored } + // Command chords belong to the menu shortcuts; shift / control / option qualify the binding. + guard keyPress.modifiers.contains(.command) == false else { return .ignored } + var modifiers: MIDIMap.KeyModifiers = [] + if keyPress.modifiers.contains(.shift) { modifiers.insert(.shift) } + if keyPress.modifiers.contains(.control) { modifiers.insert(.control) } + if keyPress.modifiers.contains(.option) { modifiers.insert(.option) } + // `key.character` is the unshifted base key, so shift stays represented in `modifiers` only. + let base: String = String(keyPress.key.character) + return midi.ingestKey(base, modifiers: modifiers) ? .handled : .ignored + } + #endif + + #if !os(macOS) + /// The iOS/iPadOS key-capture modifiers, factored into a `ViewModifier` so the (large) builder + /// body stays under the Swift expression type-checker's complexity limit. Makes the root + /// focusable and focused so `.onKeyPress` receives hardware-keyboard presses, and reclaims focus + /// whenever a focus-stealing modal closes. + private struct KeyboardCaptureModifier: ViewModifier { + + @FocusState.Binding var keyboardFocused: Bool + let modalOpen: Bool + let onKeyPress: (KeyPress) -> KeyPress.Result + + func body(content: Content) -> some View { + content + .focusable() + .focusEffectDisabled() + .focused($keyboardFocused) + .onKeyPress(phases: .down) { keyPress in onKeyPress(keyPress) } + .onChange(of: modalOpen) { _, isOpen in + if isOpen == false { keyboardFocused = true } + } + } + } + #endif + + #if os(macOS) + /// Installs an AppKit local key-down monitor that routes bare letter/digit keys to the MIDI + /// controller's key bindings. Unlike SwiftUI `.onKeyPress`, a local monitor sees every key-down + /// regardless of which view holds SwiftUI focus, so mapped keys fire even when the board — not a + /// text field — is what the user is looking at. Keys are swallowed only when a binding consumes + /// them; text entry and menu shortcuts pass through untouched. + private func installKeyMonitor() { + guard keyMonitor == nil else { return } + keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in + let flags: NSEvent.ModifierFlags = event.modifierFlags + // Command chords belong to the menu keyboard shortcuts; key-repeat would toggle + // repeatedly while a key is held. Filter both before touching any binding. + // + // Derive the base key with *no* modifiers applied, not `charactersIgnoringModifiers` + // (which still bakes in Shift — `⇧2` → `"@"` — and mangles Control into a C0 code). This + // matches the iOS path's `keyPress.key.character`, so the same physical chord stores the + // same base key on both platforms and a rig stays portable across an iCloud sync. + guard flags.contains(.command) == false, + event.isARepeat == false, + let characters: String = event.characters(byApplyingModifiers: []) else { return event } + let modifiers: MIDIMap.KeyModifiers = ShoeGazeBuilderView.keyModifiers(from: flags) + // Local monitors are delivered on the main thread; hop the actor with only Sendable + // values (NSEvent itself is not Sendable and must not cross the boundary). + let consumed: Bool = MainActor.assumeIsolated { routeMonitoredKey(characters, modifiers) } + return consumed ? nil : event + } + } + + /// Maps AppKit modifier flags to the persisted ``MIDIMap/KeyModifiers`` set (shift / control / + /// option; command is reserved for menu shortcuts and never reaches here). + private static func keyModifiers(from flags: NSEvent.ModifierFlags) -> MIDIMap.KeyModifiers { + var modifiers: MIDIMap.KeyModifiers = [] + if flags.contains(.shift) { modifiers.insert(.shift) } + if flags.contains(.control) { modifiers.insert(.control) } + if flags.contains(.option) { modifiers.insert(.option) } + return modifiers + } + + /// Applies a monitored key press to the MIDI controller's key bindings, returning `true` when a + /// binding consumed it. A field editor holding first responder means the user is typing, so the + /// key is let through untouched — a rig-name or board-label edit is never hijacked into a toggle. + @MainActor + private func routeMonitoredKey(_ characters: String, _ modifiers: MIDIMap.KeyModifiers) -> Bool { + guard let midi: MIDIController = midi else { return false } + if let responder: NSResponder = NSApp.keyWindow?.firstResponder, responder is NSText { + return false + } + return midi.ingestKey(characters, modifiers: modifiers) + } + + /// Removes the local key-down monitor installed by ``installKeyMonitor()``. + private func removeKeyMonitor() { + if let monitor: Any = keyMonitor { + NSEvent.removeMonitor(monitor) + keyMonitor = nil + } + } + #endif + /// Hosts the compact rig-library sheet on its own node. private var rigsSheetAnchor: some View { Color.clear @@ -413,8 +570,8 @@ public struct ShoeGazeBuilderView: View { /// A banner shown while a control is armed for MIDI Learn, prompting the user to move it. @ViewBuilder private var midiLearnBanner: some View { - if let midi: MIDIController = midi, midi.learnTarget != nil { - Text("MIDI Learn — press a footswitch or move an expression pedal to assign it") + if let midi: MIDIController = midi, let target: MIDIController.LearnTarget = midi.learnTarget { + Text(midiLearnBannerText(for: target)) .font(.callout.weight(.semibold)) .foregroundStyle(Color.black) .padding(.horizontal, 14) @@ -424,6 +581,18 @@ public struct ShoeGazeBuilderView: View { } } + /// Banner copy tailored to what the armed Learn target is waiting for. + private func midiLearnBannerText(for target: MIDIController.LearnTarget) -> String { + switch target { + case .key: + return "Learn — press a key to assign it" + case .action: + return "Learn — press a footswitch to assign it" + case .cc: + return "Learn — move an expression pedal to assign it" + } + } + /// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/ /// delete/erase and archive import/export. Selecting a rig replaces the current session. private var rigSidebar: some View { diff --git a/Tests/LyrebirdShoeGazeTests/MIDIControllerKeyTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIControllerKeyTests.swift new file mode 100644 index 0000000..754bb73 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/MIDIControllerKeyTests.swift @@ -0,0 +1,201 @@ +// MIDIControllerKeyTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import LyrebirdSynth +import LyrebirdUI +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("MIDIController key bindings") +struct MIDIControllerKeyTests { + + /// Builds an engine + a one-board rig (a single Volume pedal) + a controller. + private func makeRig() throws -> (MIDIController, ShoeGaze, URL) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256) + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + board.label = "Board 1" + try board.add(VolumePedal()) + try sg.finalizeBoard(board) + let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg) + return (controller, sg, url) + } + + @Test func learnCapturesKeyAndFiresCallback() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + var changed: Bool = false + controller.onMapChanged = { changed = true } + controller.armKeyLearn(.rigBypass) + let consumed: Bool = controller.ingestKey("b") + + #expect(consumed, "the learn press is consumed") + #expect(controller.learnTarget == nil) + #expect(changed) + #expect(controller.keyBinding(for: .rigBypass)?.key == "b") + #expect(sg.midiMap?.keys.count == 1) + #expect(sg.rigBypassed == false, "learn must not toggle") + } + } + + @Test func keyLatchesOnEachPress() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b") // learn only + #expect(sg.rigBypassed == false) + + #expect(controller.ingestKey("b")) + #expect(sg.rigBypassed == true, "first press engages") + #expect(controller.ingestKey("b")) + #expect(sg.rigBypassed == false, "second press releases") + } + } + + @Test func caseInsensitiveMatch() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b") + #expect(controller.ingestKey("B"), "an uppercase press matches a lowercase binding") + #expect(sg.rigBypassed == true) + } + } + + @Test func shiftDistinguishesTwoBindingsOnTheSameKey() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b", modifiers: []) + controller.armKeyLearn(.rigMute) + _ = controller.ingestKey("b", modifiers: [.shift]) + + #expect(sg.midiMap?.keys.count == 2, "b and ⇧b are independent bindings") + + #expect(controller.ingestKey("b", modifiers: [])) + #expect(sg.rigBypassed == true, "unmodified b drives bypass") + #expect(sg.rigMuted == false, "unmodified b must not fire the ⇧b binding") + + #expect(controller.ingestKey("b", modifiers: [.shift])) + #expect(sg.rigMuted == true, "⇧b drives mute") + #expect(sg.rigBypassed == true, "⇧b must not re-fire the plain-b binding") + } + } + + @Test func modifierMismatchIsNotConsumed() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b", modifiers: [.shift]) // learn ⇧b + #expect(controller.ingestKey("b", modifiers: []) == false, "plain b does not match ⇧b") + #expect(controller.ingestKey("b", modifiers: [.control]) == false, "⌃b does not match ⇧b") + #expect(sg.rigBypassed == false) + #expect(controller.ingestKey("b", modifiers: [.shift]), "⇧b matches") + #expect(sg.rigBypassed == true) + } + } + + @Test func unboundKeyIsNotConsumed() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b") + #expect(controller.ingestKey("z") == false, "an unbound key falls through") + #expect(sg.rigBypassed == false) + } + } + + @Test func digitKeyBinds() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("3") + #expect(controller.keyBinding(for: .rigBypass)?.key == "3") + #expect(controller.ingestKey("3")) + #expect(sg.rigBypassed == true) + } + } + + @Test func nonAlphanumericKeyRejected() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + // Return, Tab, and Escape are single Characters but not letters/digits — they must not be + // learnable, or binding one would silently swallow it everywhere in the app. + #expect(controller.ingestKey("\r") == false) + #expect(controller.ingestKey("\t") == false) + #expect(controller.ingestKey("\u{1B}") == false) + #expect(controller.ingestKey(" ") == false) + #expect(controller.learnTarget != nil, "a rejected press leaves learn armed") + #expect(sg.midiMap?.keys.isEmpty ?? true) + } + } + + @Test func multiCharacterInputRejected() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + #expect(controller.ingestKey("ab") == false, "a multi-character press is ignored") + #expect(controller.learnTarget != nil, "an ignored press leaves learn armed") + #expect(sg.midiMap?.keys.isEmpty ?? true) + } + } + + @Test func keyBindingSurvivesSaveLoadAndStillFires() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b") + + try sg.saveRig(to: preset) + try sg.loadRig(from: preset) + + #expect(sg.midiMap?.keys.first?.key == "b", "the key binding survives a file round-trip") + #expect(controller.ingestKey("b"), "the restored binding still fires") + #expect(sg.rigBypassed == true) + withExtendedLifetime(sg) { } + } + + @Test func clearRemovesBinding() throws { + let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig() + defer { try? FileManager.default.removeItem(at: url) } + + withExtendedLifetime(sg) { + controller.armKeyLearn(.rigBypass) + _ = controller.ingestKey("b") + #expect(controller.keyBinding(for: .rigBypass) != nil) + + controller.clearKeyBinding(for: .rigBypass) + #expect(controller.keyBinding(for: .rigBypass) == nil) + #expect(controller.ingestKey("b") == false, "a cleared key no longer fires") + #expect(sg.rigBypassed == false) + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift index aae0a65..8943921 100644 --- a/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift +++ b/Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift @@ -44,6 +44,16 @@ struct MIDIMapCodableTests { channel: 0, target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1") ), + ], + keys: [ + MIDIMap.KeyBinding(key: "b", action: .rigBypass, displayNameHint: "Rig"), + MIDIMap.KeyBinding(key: "b", modifiers: [.shift], action: .rigMute), + MIDIMap.KeyBinding( + key: "r", + modifiers: [.control, .option], + action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop), + displayNameHint: "Looper" + ), ] ) } @@ -79,4 +89,43 @@ struct MIDIMapCodableTests { let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) #expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap") } + + @Test func keyBindingsSurviveArchiveDocumentRoundTrip() throws { + // The `.shoegaze` archive / share path wraps a RigEntry → ShoeGazeState → MIDIMap. Verify a + // key binding survives a full document encode/decode, not just a bare MIDIMap round-trip. + let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap()) + let entry: RigEntry = RigEntry(name: "Keys", state: state) + let document: ShoeGazeDocument = ShoeGazeDocument(rig: entry) + let data: Data = try document.data() + let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data) + let restored: MIDIMap? = decoded.rigEntries?.first?.state.midiMap + #expect(restored?.keys == sampleMap().keys) + } + + @Test func keyBindingWithoutModifiersDecodesUnmodified() throws { + // A key binding saved before modifiers existed has a `key` + `action` but no `modifiers`. + // It must decode as an unmodified binding, not fail and drop the map. + let json: String = #""" + {"switches":[],"ccs":[],"keys":[{"key":"b","action":{"rigBypass":{}}}]} + """# + let data: Data = Data(json.utf8) + let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data) + #expect(decoded.keys.count == 1) + #expect(decoded.keys.first?.key == "b") + #expect(decoded.keys.first?.modifiers == []) + } + + @Test func mapWithoutKeysDecodesWithEmptyKeysNotDropped() throws { + // A rig saved before keyboard mapping existed has a midiMap with switches/ccs but no `keys`. + // It must decode with keys == [] AND keep its switch/cc bindings (a missing-key failure that + // fell through to the malformed path would silently drop the whole map). + let json: String = #""" + {"version":1,"boards":[],"midiMap":{"switches":[{"program":3,"action":{"rigBypass":{}}}],"ccs":[]}} + """# + let data: Data = Data(json.utf8) + let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data) + #expect(decoded.midiMap?.keys == [], "absent keys should decode to an empty array") + #expect(decoded.midiMap?.switches.count == 1, "switch bindings must survive the missing keys") + #expect(decoded.midiMap?.switches.first?.program == 3) + } } diff --git a/docs/plans/2.1-keyboard-control-mapping.md b/docs/plans/2.1-keyboard-control-mapping.md new file mode 100644 index 0000000..21dc5be --- /dev/null +++ b/docs/plans/2.1-keyboard-control-mapping.md @@ -0,0 +1,99 @@ +# Keyboard control mapping + unified mapping sheet + +Bind computer letter keys to the same rig actions MIDI footswitches drive, and rework the +MIDI mapping sheet so each rig action shows **all** of its trigger sources (footswitch, +expression pedal, letter key) on one row. + +## Goals + +- A letter key (e.g. `b`) can toggle rig bypass / mute, a board solo/bypass, a pedal bypass, + a looper transport action, the tuner, or tap tempo — exactly the toggle actions a + Program-Change footswitch already drives. +- Keys fire **only** when no text field is focused (rig rename, board label). Typing a rig + name must never trip a bypass. +- One mapping sheet row per action, showing its PC chip, KEY chip, and per-source learn. +- Keys persist with the rig (travel in `ShoeGazeState`), like MIDI bindings. +- macOS + iOS hardware keyboard. + +## Non-goals + +- Keys driving continuous CC targets (knobs / levels). Keys are momentary → toggle actions + only. CC rows in the sheet are unchanged. +- `⌘`-modified bindings. Shift / Control / Option qualify a key binding (`a` vs `⇧a` vs `⌃a`), + but Command is reserved for the existing menu `⌘`-shortcuts and is never bindable. + +## Design + +Reuse the existing controller. `MIDIController` already owns the shared `perform(_:)` action +dispatch, the `learnTarget` state, the weak `shoeGaze`, and `onMapChanged`. Key learn and key +apply reuse all of it — a separate controller would duplicate that. Key **event capture** is +the only platform piece and lives in the UI module (SwiftUI `.onKeyPress`), per the module +layering rule; the controller exposes a pure `ingestKey` entry point that the UI calls. + +### Model — `MIDIMap` + +Add a third binding list beside `switches` / `ccs`: + +```swift +public var keys: [KeyBinding] + +public struct KeyBinding: Codable, Equatable, Sendable { + public var key: String // single lowercased character + public var action: Action + public var displayNameHint: String? +} +``` + +`MIDIMap` gains a custom `init(from:)` that decodes `keys` with `decodeIfPresent ?? []`, so a +rig saved before this feature (a `midiMap` with `switches`/`ccs` but no `keys`) still decodes +— without it, synthesized Codable would fail the whole map and `ShoeGazeState` would silently +drop existing MIDI bindings. `encode(to:)` stays synthesized. + +### Controller — `MIDIController` + +- `LearnTarget` gains `.key(MIDIMap.Action)`. +- `armKeyLearn(_ action:)`, `keyBinding(for:)`, `clearKeyBinding(for:)` — mirror the switch API. +- `ingestKey(_ key: String) -> Bool` — if armed for key learn, capture + clear learn; else run + every action bound to that key via the shared `perform(_:)`. Returns `true` when the key was + consumed (learned or matched a binding) so the UI can swallow the event; `false` lets the key + fall through. Normalizes to a single lowercased letter/digit (non-printing keys rejected). + `ingestKey` is `public` (no DEBUG gate needed — unlike MIDI messages there is no background-queue + hop to bypass, so tests call it directly). + +### UI capture — `ShoeGazeBuilderView` + +Attach a focus-gated `.onKeyPress(phases: .down)` on the builder root. Handler: +- Ignores repeats (hold = one toggle) and anything with command/control/option modifiers. +- Extracts the single character, calls `controller.ingestKey`. +- Returns `.handled` when consumed, else `.ignored`. + +Focus gate: a focused `TextField` consumes keys first via the responder chain, so a root +`.onKeyPress` never sees them while the user types. Sheets (rig rename, board editor) present +their own text fields and take focus. No extra `@FocusState` plumbing needed for v1. + +### UI sheet — `MIDIMappingSheet` + +Switch rows gain a KEY chip (showing the bound letter, or nothing) and a keyboard-learn button +beside the existing footswitch learn. Armed key-learn shows "Listening — press a key…". CC rows +unchanged. Learn buttons: piano icon = MIDI learn, keyboard icon = key learn. + +## Files + +| File | Change | +|---|---| +| `Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift` | `KeyBinding` type, `keys` array, custom `init(from:)`. | +| `Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift` | `.key` learn target, key learn/apply API, `ingestKey`. | +| `Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift` | focus-gated `.onKeyPress` root modifier. | +| `Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift` | KEY chip + keyboard-learn on switch rows. | +| `Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift` | `keys` round-trip + old-rig (no `keys`) decode. | +| `Tests/LyrebirdShoeGazeTests/MIDIControllerKeyTests.swift` | key learn / apply / clear / latch. | + +## Test plan + +- `MIDIMap` with `keys` encodes + decodes equal; a `midiMap` JSON lacking `keys` decodes with + `keys == []` and its `switches`/`ccs` intact. +- `armKeyLearn` + `ingestKey("b")` captures a `KeyBinding`, clears learn, fires `onMapChanged`, + does not perform the action on the learn press. +- A subsequent `ingestKey("b")` latches the action (e.g. rig bypass on/off). +- `ingestKey` returns `false` for an unbound key; `clearKeyBinding` removes it. +- Case/whitespace normalization: `ingestKey("B")` matches a binding learned as `b`.