Add computer-keyboard control mapping

Bind letter/digit keys (with Shift/Control/Option; Command reserved for
menu shortcuts) to the same rig toggle Actions a MIDI Program-Change
footswitch drives. Keys reuse MIDIController's perform(_:) dispatch via a
new .key learn target and ingestKey(_:modifiers:).

Key capture is platform-specific: macOS installs an AppKit
NSEvent.addLocalMonitorForEvents(.keyDown) monitor (SwiftUI .onKeyPress
only delivers to the focused view); iOS uses .onKeyPress with the root
made focusable/focused, reclaiming focus when a text-field modal closes.
Both gate on the first responder not being a text field so typing is
never hijacked, filter key-repeat, and reserve Command for the menu.

MIDIMap gains keys:[KeyBinding] and a KeyModifiers OptionSet, both with
tolerant Codable decode so old rigs (no keys / no modifiers) still load
with switches/ccs intact. The mapping sheet is unified: each switch row
shows its footswitch (PC) and key bindings with per-source learn/clear,
and the sheet is retitled "MIDI / Control Mapping".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-08 15:03:12 -07:00
parent 2c2ce06797
commit a33d5488c9
8 changed files with 785 additions and 28 deletions
+15 -8
View File
@@ -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.",
@@ -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)
@@ -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 {