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:
@@ -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() {
|
||||
|
||||
@@ -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<CodingKeys> = 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<CodingKeys> = 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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user