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
@@ -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 {