4 Commits

Author SHA1 Message Date
josh f61961b90b Consolidate 2.1.1 into 2.1.0 release notes
Fold the MIDI-CC-vs-tempo-sync note into the single 2.1.0 entry (CHANGELOG + RELEASES);
the CC guard ships as part of 2.1.0 rather than a separate 2.1.1. No code change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 10:14:42 -07:00
josh 7e39842eb2 2.1.1: ignore MIDI CC on tempo-synced parameters
A CC bound to a pedal parameter locked to a note division is now ignored while
synced — the value is tempo-derived and a CC write would be overwritten on the next
tempo change. Index-stable: ccMappableControls is unchanged (persisted bindings resolve
by position), and only the CC *write* is skipped. MIDIController.applyCC checks
Pedal.isNodeTempoSynced(_:) (node-identity match against tempoSyncableParams) and
skips the update; the binding stays intact and resumes control once set back to Free.

Test: MIDIControllerCCTests.ccIsIgnoredWhileParameterIsTempoSynced. 455 tests pass.
Docs: CHANGELOG.md, RELEASES.md, plan MIDI section updated to "implemented".

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 09:00:24 -07:00
josh 2772abdc56 Release 2.1.0: tempo-synced pedal parameters, editable BPM, control mapping badges
Tempo sync
- Lock a delay time or modulation LFO rate to a note division (whole..sixteenth,
  dotted, triplet) of the shared clock. Value is derived from the tempo and follows
  tap tempo, the stepper, the editable BPM field, and MIDI.
- Delay time: Delay, FeedbackDelay, PingPong, ReverseDelay, MultiTap (per tap).
  LFO rate (inverse mapping): Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- Core types NoteDivision / TempoSync / TempoSyncableParam; Pedal.tempoSyncableParams /
  tempoSync / applyTempoSync / setSync; ShoeGaze.setBpm broadcast recomputes all pedals;
  tempoSync persisted in PedalState (lenient decode) and recomputed on load + recall.
- Observable TempoSyncRevision so the sync badge refreshes on any state-change path.

UI
- Division picker with drawn music-notation glyphs (NoteGlyphView + rasterized cache):
  noteheads, stems, flags, augmentation dot, bracketed 3 for triplets. Presented as a
  height-capped popover so it stays on-screen on iOS.
- Editable BPM text field: integer-only, live-filtered, clamped 30-300, commit on
  return / Done / blur.
- Divisions that clamp at the current tempo are disabled in the picker; an active
  clamped sync shows a warning marker.
- In-context control mapping badges (PC / CC / KEY) per pedal control, with a legend.

Delays
- Maximum delay time raised to 5 s across the delay pedals (was 1-2 s).

Docs: CHANGELOG.md, RELEASES.md, docs/plans/2.2-tempo-synced-parameters.md.
All 454 tests pass; passed lyrebird_external_review (RT-safe, main-thread param writes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:47:22 -07:00
josh a33d5488c9 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>
2026-07-08 15:03:12 -07:00
40 changed files with 2660 additions and 61 deletions
+41
View File
@@ -4,6 +4,47 @@ All notable changes to ShoeGaze are recorded here. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[semantic versioning](https://semver.org/spec/v2.0.0.html).
## [2.1.0] — 2026-07-10
Tempo comes to the pedals. Delay times and modulation rates can lock to a note
division of the live tempo — a quarter-note delay, a dotted-eighth, an eighth-triplet
LFO — shown with real music-notation glyphs and following the tempo as it changes.
Delays reach further, the BPM is directly editable, and every mappable control shows
its MIDI / key binding right on the pedal.
### Added
- **Tempo-synced pedal parameters.** Lock a delay time or a modulation rate to a note
division — whole down to sixteenth, including dotted and triplet values — and it is
derived from the shared tempo, following tap tempo, the stepper, the BPM field, and
MIDI. Delay time on Delay, Feedback Delay, Ping-Pong, Reverse Delay, and each of
Multi-Tap's three taps; LFO rate on Tremolo, Vibrato, Chorus, Flanger, Phaser, and
Modulation. A MIDI CC bound to a synced parameter is ignored while it stays synced
(the tempo drives the value) and resumes control once the parameter is set to Free.
- **Note-value glyphs.** The division picker uses drawn music-notation glyphs —
noteheads, stems, flags, an augmentation dot for dotted values, and a bracketed "3"
over triplets — instead of text labels.
- **Editable BPM.** The tempo readout is now a text field: type a tempo directly
(integer only, clamped to 30–300 BPM). The stepper and tap tempo still work, and a
synced pedal follows a typed change immediately.
- **In-context control mapping.** Each pedal draws a small badge on every mappable
control showing its binding source — Program Change footswitch (PC), Control Change
expression (CC), or letter Key (KEY) — with a legend above the board. Completes the
computer-keyboard control mapping.
### Changed
- **Longer delays.** Maximum delay time raised to 5 seconds across the delay pedals
(previously 1–2 s), so tempo-synced values at slow tempos (whole and half notes) fit.
- Note divisions that would exceed a parameter's range at the current tempo are shown
disabled in the picker, and an active sync that has to clamp shows a warning marker.
### Compatibility
Additive: rigs saved before this release load unchanged (every parameter defaults to
"free"), and 2.1 rigs still open in older builds — the tempo-sync state is simply
ignored there.
## [2.0.0] — 2026-07-05
Major release. Performance-focused: a visual metronome, a real rig mute with
+26
View File
@@ -1,4 +1,30 @@
# Releases
## ShoeGaze 2.1.0
Tempo comes to the pedals. Delay times and LFO rates can lock to note divisions of the
live tempo — shown with real music-notation glyphs and following the tempo as it
changes — plus a directly-editable BPM, longer delays, and per-control MIDI/key mapping
badges on every pedal.
### Highlights
- **Tempo-synced parameters** — lock a delay time or a modulation rate to a note value
(whole → sixteenth, dotted, triplet); it follows tap tempo, the stepper, the BPM
field, and MIDI. Delay, Feedback Delay, Ping-Pong, Reverse, and Multi-Tap (per tap);
Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- **Notation glyphs** — the picker draws real note glyphs (augmentation dot for dotted
values, a bracketed "3" over triplets) instead of text.
- **Editable BPM** — type a tempo directly (integer, 30–300); the stepper and tap still
work, and synced pedals follow immediately.
- **Longer delays** — maximum delay time raised to 5 s so slow synced values fit.
- **Control mapping badges** — every pedal shows the PC (footswitch), CC (expression),
or KEY (letter key) binding on each control, with a legend above the board.
- **CC respects tempo sync** — a CC bound to a synced parameter is ignored while synced
(the tempo drives it) and resumes control once the parameter is set back to Free.
### Compatibility
Additive persistence — older rigs load unchanged (every parameter defaults to free),
and 2.1 rigs open in older builds with the tempo-sync state ignored.
## ShoeGaze 2.0.0
Major release. Performance-focused: a visual metronome, a real rig mute with
@@ -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
@@ -248,6 +250,14 @@ public final class MIDIController {
continue
}
guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue }
// A parameter locked to a note division is driven by the tempo; a CC write would be
// overwritten on the next tempo change, so ignore it here. The binding stays intact and
// resumes control the moment the parameter is set back to Free.
if case let .pedalControl(pedalID, _, _, _) = binding.target,
let pedal: Pedal = pedal(id: pedalID),
pedal.isNodeTempoSynced(resolved.node) {
continue
}
let mapped: Double = resolved.range.lowerBound
+ norm * (resolved.range.upperBound - resolved.range.lowerBound)
resolved.node.update(mapped)
@@ -438,6 +448,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() {
+105 -1
View File
@@ -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
+64
View File
@@ -73,6 +73,16 @@ open class Pedal: SynthesizerBase {
/// the engine owns the node tree, not the reverse.
public internal(set) weak var hostEngine: SynthesisEngine?
// MARK: - Tempo sync
/// Sync state per tempo-syncable parameter, keyed by ``TempoSyncableParam/key``. A missing
/// key means ``TempoSync/free``. Persisted in ``PedalState`` and restored on rig load.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Observable signal bumped on every ``tempoSync`` change so a SwiftUI badge re-renders when the
/// sync state changes through any path (the picker, a preset load, or a lightweight recall).
public let tempoSyncRevision: TempoSyncRevision = TempoSyncRevision()
// MARK: - Identity / routing
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
@@ -266,6 +276,60 @@ open class Pedal: SynthesizerBase {
return knobControls + sliderControls
}
// MARK: - Tempo sync
/// Parameters this pedal exposes to tempo sync (delay times, LFO rates). Empty by default —
/// override in subclasses whose time- or rate-based parameters can lock to the tempo.
///
/// Each descriptor's ``TempoSyncableParam/key`` must be unique within the pedal and stable
/// across versions (it is the persistence key). Order is the order the sync controls appear.
open var tempoSyncableParams: [TempoSyncableParam] {
[]
}
/// Recomputes and writes every parameter currently locked to a note division, from the shared
/// clock's tempo. Main-thread only — writing a `@UIParam` is the same path as a knob turn.
///
/// A no-op when no clock is injected. Free parameters are left untouched. A synced value that
/// falls outside the parameter's range (a long division past a delay's maximum time) is clamped.
/// Called by `ShoeGaze` whenever the tempo changes and whenever a parameter's sync state changes.
public func applyTempoSync() {
guard let clock: LyrebirdClock = clock else { return }
let bpm: Double = clock.bpm
guard bpm > 0 else { return }
for param: TempoSyncableParam in tempoSyncableParams {
guard case .division(let division) = tempoSync[param.key] ?? .free else { continue }
param.node.update(param.value(for: division, bpm: bpm).value)
}
}
/// Sets one parameter's sync state and immediately recomputes it. Pass ``TempoSync/free`` to
/// return the parameter to knob control (its value stays at the last synced number until the
/// knob moves it), or `.division(_:)` to lock it to a note value of the live tempo.
///
/// - Parameters:
/// - sync: The new sync state.
/// - key: The ``TempoSyncableParam/key`` of the parameter to update.
public func setSync(_ sync: TempoSync, for key: String) {
tempoSync[key] = sync
tempoSyncRevision.bump()
applyTempoSync()
}
/// Whether `node` backs a tempo-syncable parameter currently locked to a note division.
///
/// Used by MIDI to leave a synced parameter alone: its value is derived from the tempo, so a CC
/// write would be immediately overwritten on the next tempo change. Matches by node identity, so
/// it stays correct regardless of control ordering. Returns `false` for a free or non-syncable node.
public func isNodeTempoSynced(_ node: UIParamNode) -> Bool {
for param: TempoSyncableParam in tempoSyncableParams where param.node === node {
if case .division = tempoSync[param.key] ?? .free {
return true
}
}
return false
}
// MARK: - Subclass hook
/// Returns the processed (wet) mono signal for this pedal.
@@ -61,6 +61,12 @@ public final class ChorusPedal: Pedal {
private let rateRange: ClosedRange<Double> = 0.05 ... 6.0
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.008
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -22,7 +22,7 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - time: Delay time in seconds. Range `[0.01, 1.5]`. Defaults to `0.25`.
/// - time: Delay time in seconds. Range `[0.01, 5.0]`. Defaults to `0.25`.
/// - feedback: Feedback amount expressed as decay time in seconds — the time
/// for echoes to fall to `targetAmp` (−60 dB). Longer values produce more
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
@@ -35,7 +35,7 @@ public final class DelayPedal: Pedal {
// MARK: - Parameters
/// Delay time in seconds. Range [0.01, 1.5].
/// Delay time in seconds. Range [0.01, 5.0].
@UIParam public var time: Double = 0.25
/// Feedback decay time in seconds (time to reach −60 dB amplitude).
@@ -44,7 +44,7 @@ public final class DelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes the delay line buffer at init.
private let maxDelayTime: Double = 1.5
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -55,7 +55,7 @@ public final class DelayPedal: Pedal {
// MARK: - UI knobs
/// Delay-time knob range in seconds.
private let timeRange: ClosedRange<Double> = 0.01 ... 1.5
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
/// Feedback (decay-time) knob range in seconds.
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
@@ -86,6 +86,12 @@ public final class DelayPedal: Pedal {
]
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
// MARK: - Effect
/// Applies a feedback delay line. Returns the pure wet (delayed) signal.
@@ -45,7 +45,7 @@ public final class FeedbackDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes the delay-line buffer at init.
private let maxDelayTime: Double = 1.5
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -58,12 +58,18 @@ public final class FeedbackDelayPedal: Pedal {
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.02 ... 1.5
private let timeRange: ClosedRange<Double> = 0.02 ... 5.0
private let feedbackRange: ClosedRange<Double> = 0.1 ... 8.0
private let toneRange: ClosedRange<Double> = 500.0 ... 8000.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
@@ -57,6 +57,12 @@ public final class FlangerPedal: Pedal {
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -90,6 +90,12 @@ public final class ModulationPedal: Pedal {
)
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -58,18 +58,26 @@ public final class MultiTapDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported per-tap delay time in seconds. Sizes each delay-line buffer at init.
private let maxDelayTime: Double = 1.0
private let maxDelayTime: Double = 5.0
/// Partial wet/dry blend so the dry note and its taps coexist.
private static let defaultMix: Double = 0.4
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.01 ... 1.0
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
private let volRange: ClosedRange<Double> = 0.0 ... 1.0
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time1", label: "Time 1", node: $time1, kind: .time, range: timeRange),
TempoSyncableParam(key: "time2", label: "Time 2", node: $time2, kind: .time, range: timeRange),
TempoSyncableParam(key: "time3", label: "Time 3", node: $time3, kind: .time, range: timeRange),
]
}
/// Two rows of three: the three tap times, then the three tap volumes.
public override var effectKnobs: [PedalKnob] {
[
@@ -68,6 +68,12 @@ public final class PhaserPedal: Pedal {
/// Feedback knob range (all-pass feedback gain).
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.9
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -32,7 +32,7 @@ import LyrebirdUI
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
///
/// - Parameters:
/// - time: Delay time per tap in seconds. Range `[0.05, 1.0]`. Defaults to `0.3`.
/// - time: Delay time per tap in seconds. Range `[0.05, 5.0]`. Defaults to `0.3`.
/// - feedback: Feedback as decay time in seconds (time for echoes to fall to −60 dB).
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
public final class PingPongDelayPedal: Pedal {
@@ -44,7 +44,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - Parameters
/// Delay time per tap in seconds. Range [0.05, 1.0].
/// Delay time per tap in seconds. Range [0.05, 5.0].
@UIParam public var time: Double = 0.3
/// Feedback decay time in seconds (time to reach −60 dB amplitude). Range [0.05, 6.0].
@@ -53,7 +53,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - Constants
/// Maximum supported delay time in seconds. Sizes both delay lines at init.
private let maxDelayTime: Double = 1.0
private let maxDelayTime: Double = 5.0
/// Amplitude target for the `decayTime` calculation (−60 dB).
private let targetAmp: Double = 0.001
@@ -67,7 +67,7 @@ public final class PingPongDelayPedal: Pedal {
// MARK: - UI knobs
/// Delay-time knob range in seconds.
private let timeRange: ClosedRange<Double> = 0.05 ... 1.0
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
/// Feedback (decay-time) knob range in seconds.
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
@@ -96,6 +96,12 @@ public final class PingPongDelayPedal: Pedal {
)
}
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
@@ -15,7 +15,7 @@ import LyrebirdUI
/// so the pedal's `Mix` knob sets the wet/dry blend.
///
/// ## Knobs
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
/// - `time`: Reverse segment length in seconds. Range `[0.05, 5.0]`.
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
public final class ReverseDelayPedal: Pedal {
@@ -26,7 +26,7 @@ public final class ReverseDelayPedal: Pedal {
// MARK: - Parameters
/// Reverse segment length in seconds. Range [0.05, 2.0].
/// Reverse segment length in seconds. Range [0.05, 5.0].
@UIParam public var time: Double = 0.5
/// Reverse-trail feedback. Range [0, 0.95].
@@ -38,15 +38,21 @@ public final class ReverseDelayPedal: Pedal {
private static let defaultMix: Double = 0.5
/// Maximum segment length the buffers are allocated for, in seconds.
private let maxDelayTime: Double = 2.0
private let maxDelayTime: Double = 5.0
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Time", node: $time, range: timeRange),
@@ -63,6 +63,12 @@ public final class TremoloPedal: Pedal {
/// Depth knob range (modulation fraction).
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -50,6 +50,12 @@ public final class VibratoPedal: Pedal {
// MARK: - Knobs
public override var tempoSyncableParams: [TempoSyncableParam] {
[
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
]
}
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Rate", node: $rate, range: rateRange),
@@ -27,7 +27,8 @@ extension Pedal {
switchValues: switchValues,
sliderValues: sliderValues,
selectorValues: selectorValues,
bypass: bypass
bypass: bypass,
tempoSync: tempoSync.isEmpty ? nil : tempoSync
)
}
@@ -61,5 +62,9 @@ extension Pedal {
selector.node.update(value)
}
bypass = state.bypass
// Restore tempo-sync state. The synced values themselves are recomputed from the rig's
// tempo by `ShoeGaze` after the rebuild, so no clock is required here.
tempoSync = state.tempoSync ?? [:]
tempoSyncRevision.bump()
}
}
@@ -45,6 +45,11 @@ public struct PedalState: Codable, Equatable {
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
public let bypass: Double
/// Tempo-sync state per syncable parameter, keyed by ``TempoSyncableParam/key``. `nil` for a
/// pedal with no synced parameters, and for presets saved before tempo sync existed — both
/// decode to "all parameters free".
public let tempoSync: [String: TempoSync]?
/// Creates a pedal state snapshot.
///
/// - Parameters:
@@ -54,6 +59,7 @@ public struct PedalState: Codable, Equatable {
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
/// - tempoSync: Tempo-sync state per syncable parameter, or `nil` for none. Defaults to `nil`.
public init(
id: UUID = UUID(),
type: String,
@@ -61,7 +67,8 @@ public struct PedalState: Codable, Equatable {
switchValues: [Double] = [],
sliderValues: [Double] = [],
selectorValues: [Double] = [],
bypass: Double
bypass: Double,
tempoSync: [String: TempoSync]? = nil
) {
self.id = id
self.type = type
@@ -70,6 +77,7 @@ public struct PedalState: Codable, Equatable {
self.sliderValues = sliderValues
self.selectorValues = selectorValues
self.bypass = bypass
self.tempoSync = tempoSync
}
private enum CodingKeys: String, CodingKey {
@@ -80,10 +88,11 @@ public struct PedalState: Codable, Equatable {
case sliderValues
case selectorValues
case bypass
case tempoSync
}
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
/// `selectorValues` existed by defaulting the missing keys to an empty array.
/// `selectorValues` / `tempoSync` existed by defaulting the missing keys.
public init(from decoder: any Decoder) throws {
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
@@ -93,5 +102,6 @@ public struct PedalState: Codable, Equatable {
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
self.bypass = try container.decode(Double.self, forKey: .bypass)
self.tempoSync = try container.decodeIfPresent([String: TempoSync].self, forKey: .tempoSync)
}
}
@@ -134,6 +134,12 @@ extension ShoeGaze {
if let savedTempoEnabled: Bool = state.tempoEnabled {
setTempoEnabled(savedTempoEnabled)
}
// Bring restored tempo-synced parameters in line with the loaded tempo. `setTempoEnabled`
// already re-syncs when it runs and is enabled, but an older rig with no saved
// `tempoEnabled` skips that path — recompute unconditionally so synced values are correct.
if tempoEnabled {
applyTempoSyncToAllPedals()
}
}
/// Rebuilds every board from a snapshot with all-or-nothing semantics.
@@ -346,6 +352,12 @@ extension ShoeGaze {
for (board, boardState) in zip(boards, state.boards) {
applySegmentParams(boardState.segments, to: board.orderedSegments)
}
// A recall restores each pedal's tempo-sync state but not its derived values (no clock is
// consulted in `Pedal.applyState`), so recompute them against the rig's current tempo —
// mirroring the full `loadRig(from:)` path.
if tempoEnabled {
applyTempoSyncToAllPedals()
}
}
/// Positionally applies segment parameter snapshots to live board segments, including
+26 -1
View File
@@ -139,7 +139,11 @@ public final class ShoeGaze {
/// control by forcing each ``PedalSwitch/tempoDependent`` switch to its first option.
public func setTempoEnabled(_ enabled: Bool) {
tempoEnabled = enabled
guard !enabled else { return }
guard !enabled else {
// Re-enabling: bring every tempo-synced parameter back in line with the current tempo.
applyTempoSyncToAllPedals()
return
}
for pedal: Pedal in allPedals() {
for pedalSwitch: PedalSwitch in pedal.effectSwitches where pedalSwitch.tempoDependent {
if let off: PedalSwitch.Option = pedalSwitch.options.first {
@@ -149,6 +153,27 @@ public final class ShoeGaze {
}
}
/// Sets the shared clock's tempo and recomputes every tempo-synced pedal parameter to match.
/// Route **all** BPM changes (stepper, tap tempo, MIDI) through here so synced delay times and
/// LFO rates follow the tempo. Recompute is skipped while tempo is disabled.
///
/// - Parameter bpm: The new tempo in beats per minute. A non-positive value is ignored (the
/// clock requires a positive tempo); callers that also want an upper bound clamp before calling.
public func setBpm(_ bpm: Double) {
guard bpm > 0 else { return }
clock.bpm = bpm
guard tempoEnabled else { return }
applyTempoSyncToAllPedals()
}
/// Recomputes every tempo-synced parameter on every live pedal from the current tempo.
/// `internal` so the preset-restore path (`ShoeGaze+Preset.swift`) can re-sync after a rig load.
internal func applyTempoSyncToAllPedals() {
for pedal: Pedal in allPedals() {
pedal.applyTempoSync()
}
}
// MARK: - Scope state
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
@@ -0,0 +1,74 @@
// NoteDivision.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A rhythmic note value, expressed as a fraction of a bar and measured in quarter-note beats.
///
/// Used to lock a tempo-syncable pedal parameter (a delay time, an LFO rate) to the shared
/// ``ShoeGaze/clock``. The synced period in seconds is `(60 / bpm) * beats`; a delay time uses
/// that period directly, an LFO rate uses its inverse (one cycle per division).
///
/// Cases are ordered longest-first so a stepped selector reads top-to-bottom from slow to fast.
public enum NoteDivision: String, Codable, CaseIterable, Sendable {
/// Whole note — four quarter-note beats.
case whole
/// Dotted half note — three beats.
case dottedHalf
/// Half note — two beats.
case half
/// Dotted quarter note — one and a half beats.
case dottedQuarter
/// Quarter note — one beat.
case quarter
/// Dotted eighth note — three-quarters of a beat.
case dottedEighth
/// Quarter-note triplet — two-thirds of a beat.
case quarterTriplet
/// Eighth note — half a beat.
case eighth
/// Eighth-note triplet — one-third of a beat.
case eighthTriplet
/// Sixteenth note — a quarter of a beat.
case sixteenth
/// Sixteenth-note triplet — one-sixth of a beat.
case sixteenthTriplet
/// Length of this division in quarter-note beats (a quarter note is `1`).
public var beats: Double {
switch self {
case .whole: return 4.0
case .dottedHalf: return 3.0
case .half: return 2.0
case .dottedQuarter: return 1.5
case .quarter: return 1.0
case .quarterTriplet: return 2.0 / 3.0
case .dottedEighth: return 0.75
case .eighth: return 0.5
case .eighthTriplet: return 1.0 / 3.0
case .sixteenth: return 0.25
case .sixteenthTriplet: return 1.0 / 6.0
}
}
/// Short label for a selector stop (e.g. `"1/4"`, `"1/8."`, `"1/8T"`).
public var label: String {
switch self {
case .whole: return "1/1"
case .dottedHalf: return "1/2."
case .half: return "1/2"
case .dottedQuarter: return "1/4."
case .quarter: return "1/4"
case .quarterTriplet: return "1/4T"
case .dottedEighth: return "1/8."
case .eighth: return "1/8"
case .eighthTriplet: return "1/8T"
case .sixteenth: return "1/16"
case .sixteenthTriplet: return "1/16T"
}
}
}
@@ -50,6 +50,6 @@ extension ShoeGaze {
let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count)
let secondsPerMinute: Double = 60.0
clock.bpm = secondsPerMinute / averageInterval
setBpm(secondsPerMinute / averageInterval)
}
}
@@ -0,0 +1,22 @@
// TempoSync.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Sync state of one tempo-syncable pedal parameter.
///
/// `.free` leaves the parameter at its stored absolute value (seconds or Hz), controlled by the
/// knob as usual. `.division` locks it to a ``NoteDivision`` of the shared ``ShoeGaze/clock`` —
/// the value is derived from the current tempo and rewritten whenever the tempo or the division
/// changes.
public enum TempoSync: Codable, Equatable, Sendable {
/// Absolute value, knob-controlled. The default for every parameter.
case free
/// Locked to a note division of the live tempo.
case division(NoteDivision)
}
@@ -0,0 +1,29 @@
// TempoSyncRevision.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Observation
/// An observable revision counter bumped whenever a pedal's ``Pedal/tempoSync`` state changes.
///
/// ``Pedal/tempoSync`` is a plain dictionary, not observable, so a SwiftUI view showing the sync
/// state (the note-division badge) needs a signal to re-render when the state changes through any
/// path — the knob's own picker, a preset load, or a lightweight recall. Reading ``value`` inside a
/// view body subscribes it; ``Pedal/setSync(_:for:)`` and `Pedal.applyState(_:)` bump it.
@Observable
public final class TempoSyncRevision {
/// Incremented on every ``Pedal/tempoSync`` mutation. Its magnitude is meaningless — only the
/// change matters, as an invalidation signal for observing views.
public internal(set) var value: Int = 0
/// Creates a revision counter starting at zero.
public init() {}
/// Bumps the counter, invalidating any view observing ``value``.
func bump() {
value &+= 1
}
}
@@ -0,0 +1,86 @@
// TempoSyncableParam.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdUI
/// Descriptor for one pedal parameter that can be locked to the tempo.
///
/// A ``Pedal`` publishes an array of these (via ``Pedal/tempoSyncableParams``) so the shared
/// tempo-sync machinery can recompute and rewrite each synced parameter without knowing the
/// concrete pedal type. The stable ``key`` doubles as the persistence key in ``PedalState``.
public struct TempoSyncableParam {
/// How the synced period maps onto the parameter's value.
public enum Kind {
/// A duration in seconds — the value is the synced period `T` directly (delay time).
case time
/// A frequency in Hz — the value is `1 / T` (one LFO cycle per division).
case rate
}
/// Stable identifier for this parameter within its pedal (e.g. `"time"`, `"time1"`, `"rate"`).
/// Used as the ``TempoSync`` dictionary key and the persistence key, so it must never change.
public let key: String
/// Short display label, matching the parameter's knob label.
public let label: String
/// The live parameter node the synced value is written to.
public let node: UIParamNode
/// Whether the value is a duration (`.time`) or a frequency (`.rate`, inverse of the period).
public let kind: Kind
/// Inclusive value range the parameter accepts, in its own units. A synced value outside this
/// range is clamped (a long division can exceed a delay's maximum buffered time).
public let range: ClosedRange<Double>
/// Creates a tempo-syncable parameter descriptor.
///
/// - Parameters:
/// - key: Stable identifier and persistence key. Must be unique within the pedal and stable
/// across versions.
/// - label: Short display label, matching the knob label.
/// - node: The live parameter node (`pedal.$time`, `pedal.$rate`, …).
/// - kind: `.time` for a duration, `.rate` for a frequency (inverse of the period).
/// - range: Inclusive value range in the parameter's units; the synced value is clamped to it.
public init(
key: String,
label: String,
node: UIParamNode,
kind: Kind,
range: ClosedRange<Double>
) {
self.key = key
self.label = label
self.node = node
self.kind = kind
self.range = range
}
private static let secondsPerMinute: Double = 60.0
/// The unclamped parameter value for `division` at `bpm`. For `.time` this is the note's period
/// in seconds; for `.rate` it is `1 / period` in Hz (one LFO cycle per division).
public func rawValue(for division: NoteDivision, bpm: Double) -> Double {
let period: Double = (TempoSyncableParam.secondsPerMinute / bpm) * division.beats
switch kind {
case .time:
return period
case .rate:
return period > 0 ? 1.0 / period : range.upperBound
}
}
/// The value actually written for `division` at `bpm`, plus whether it had to be clamped to the
/// parameter's range. A clamped result means the division can't be represented accurately at this
/// tempo (e.g. a whole note longer than the maximum delay time) — the UI disables/flags it.
public func value(for division: NoteDivision, bpm: Double) -> (value: Double, clamped: Bool) {
let raw: Double = rawValue(for: division, bpm: bpm)
let clampedValue: Double = min(max(raw, range.lowerBound), range.upperBound)
return (clampedValue, clampedValue != raw)
}
}
@@ -0,0 +1,251 @@
// ControlMappingStrip.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
/// The rig's current control map, injected into the board view tree so each ``PedalView`` can draw
/// its own mapping strip without every call site having to thread the map through. `nil` when the
/// rig has no bindings. Set once high in the builder (`builderColumn`) from the observable
/// `ShoeGaze.midiMap`, so learning or clearing a binding updates every strip live.
private struct ControlMappingMapKey: EnvironmentKey {
static let defaultValue: MIDIMap? = nil
}
extension EnvironmentValues {
/// The rig's control map for in-context mapping badges, or `nil` when unset / empty.
var controlMappingMap: MIDIMap? {
get { self[ControlMappingMapKey.self] }
set { self[ControlMappingMapKey.self] = newValue }
}
}
/// The kind of trigger a mapping badge represents, and its colour.
enum MappingBadgeKind {
case programChange
case controlChange
case key
/// The badge fill colour (matches the mapping-sheet chip colours).
var fill: Color {
switch self {
case .programChange: return MappingBadge.pcFill
case .controlChange: return MappingBadge.ccFill
case .key: return MappingBadge.keyFill
}
}
}
/// One coloured pill — e.g. `CC11`, `PC3`, `⇧B` — marking a control's binding.
struct MappingBadge: View {
static let pcFill: Color = Color(red: 0.11, green: 0.37, blue: 0.65)
static let ccFill: Color = Color(red: 0.33, green: 0.29, blue: 0.72)
static let keyFill: Color = Color(red: 0.73, green: 0.46, blue: 0.09)
private static let fontSize: CGFloat = 9
private static let paddingH: CGFloat = 5
private static let paddingV: CGFloat = 1
private static let cornerRadius: CGFloat = 4
private let kind: MappingBadgeKind
private let text: String
/// Creates a mapping badge.
///
/// - Parameters:
/// - kind: The trigger kind (drives the fill colour).
/// - text: The badge label (e.g. `"CC11"`, `"PC3"`, `"⇧B"`).
init(kind: MappingBadgeKind, text: String) {
self.kind = kind
self.text = text
}
var body: some View {
Text(text)
.font(.system(size: MappingBadge.fontSize, weight: .medium))
.foregroundStyle(Color.white)
.padding(.horizontal, MappingBadge.paddingH)
.padding(.vertical, MappingBadge.paddingV)
.background(
RoundedRectangle(cornerRadius: MappingBadge.cornerRadius)
.fill(kind.fill)
)
}
}
/// A one-line legend keying the badge colours (`PC` footswitch, `CC` expression, `KEY` letter key),
/// shown once above the board canvas.
struct ControlMappingLegend: View {
private static let itemSpacing: CGFloat = 10
private static let pairSpacing: CGFloat = 5
private static let fontSize: CGFloat = 11
var body: some View {
HStack(spacing: ControlMappingLegend.itemSpacing) {
legendItem(kind: .programChange, badge: "PC", caption: "footswitch")
legendItem(kind: .controlChange, badge: "CC", caption: "expression")
legendItem(kind: .key, badge: "KEY", caption: "letter key")
}
.foregroundStyle(Color.white.opacity(0.55))
}
private func legendItem(kind: MappingBadgeKind, badge: String, caption: String) -> some View {
HStack(spacing: ControlMappingLegend.pairSpacing) {
MappingBadge(kind: kind, text: badge)
Text(caption)
.font(.system(size: ControlMappingLegend.fontSize))
}
}
}
/// One row of a pedal's mapping strip: a control label and the badges bound to it.
struct PedalMappingRow: Identifiable {
let id: String
let label: String
let badges: [PedalMappingBadge]
}
/// A single badge within a ``PedalMappingRow``.
struct PedalMappingBadge: Identifiable {
let id: String
let kind: MappingBadgeKind
let text: String
}
/// The per-pedal mapping strip: a compact footer listing this pedal's mapped controls and the
/// footswitch / expression / key bindings driving them. Renders nothing when the pedal has no
/// mappings, so unmapped pedals gain no height.
struct PedalMappingStrip: View {
private static let rowSpacing: CGFloat = 3
private static let labelFontSize: CGFloat = 10
private static let badgeSpacing: CGFloat = 4
private static let topPadding: CGFloat = 6
private static let dividerOpacity: Double = 0.18
private let rows: [PedalMappingRow]
/// Creates a mapping strip for a pedal against the current map.
///
/// - Parameters:
/// - pedal: The pedal whose bindings are listed.
/// - map: The rig's control map, or `nil` when there are no bindings.
init(pedal: Pedal, map: MIDIMap?) {
self.rows = PedalMappingStrip.rows(for: pedal, in: map)
}
var body: some View {
if rows.isEmpty {
EmptyView()
} else {
VStack(spacing: PedalMappingStrip.rowSpacing) {
Divider().overlay(Color.white.opacity(PedalMappingStrip.dividerOpacity))
ForEach(rows) { row in
HStack(spacing: PedalMappingStrip.badgeSpacing) {
Text(row.label)
.font(.system(size: PedalMappingStrip.labelFontSize))
.foregroundStyle(Color.white.opacity(0.6))
Spacer(minLength: 0)
ForEach(row.badges) { badge in
MappingBadge(kind: badge.kind, text: badge.text)
}
}
}
}
.padding(.top, PedalMappingStrip.topPadding)
}
}
// MARK: - Row assembly
/// Builds the strip rows for a pedal from the map: one row per mapped CC control, one for a
/// mapped bypass (footswitch + key), and one per mapped looper transport action.
static func rows(for pedal: Pedal, in map: MIDIMap?) -> [PedalMappingRow] {
guard let map: MIDIMap = map else { return [] }
let pedalID: UUID = pedal.id
var rows: [PedalMappingRow] = []
// Continuous controls driven by an expression pedal (CC).
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
let target: MIDIMap.CCTarget = .pedalControl(
pedalID: pedalID, controlIndex: controlPair.offset,
pedalNameHint: nil, controlLabelHint: nil)
guard let cc: MIDIMap.CCBinding = map.ccs.first(where: { $0.target.addresses(target) })
else { continue }
rows.append(PedalMappingRow(
id: "cc-\(controlPair.offset)",
label: controlPair.element.label,
badges: [PedalMappingBadge(id: "cc", kind: .controlChange, text: "CC\(cc.controller)")]))
}
// Bypass — a footswitch and/or a key.
let bypassBadges: [PedalMappingBadge] = badges(for: .pedalBypass(pedalID: pedalID), in: map)
if bypassBadges.isEmpty == false {
rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges))
}
// Looper transport actions.
if pedal is LooperPedal {
for kind: MIDIMap.PedalActionKind in loopedActionOrder {
let action: MIDIMap.Action = .pedalAction(pedalID: pedalID, kind: kind)
let actionBadges: [PedalMappingBadge] = badges(for: action, in: map)
if actionBadges.isEmpty { continue }
rows.append(PedalMappingRow(
id: "la-\(looperActionName(kind))",
label: looperActionName(kind),
badges: actionBadges))
}
}
return rows
}
/// The footswitch (PC) and key badges bound to a toggle action, in that order.
private static func badges(for action: MIDIMap.Action, in map: MIDIMap) -> [PedalMappingBadge] {
var badges: [PedalMappingBadge] = []
if let pc: MIDIMap.SwitchBinding = map.switches.first(where: { $0.action == action }) {
badges.append(PedalMappingBadge(id: "pc", kind: .programChange, text: "PC\(pc.program)"))
}
if let key: MIDIMap.KeyBinding = map.keys.first(where: { $0.action == action }) {
badges.append(PedalMappingBadge(id: "key", kind: .key, text: keyLabel(key)))
}
return badges
}
/// A key binding formatted with modifier glyphs (macOS order: control, option, shift).
private static 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()
}
/// The looper transport actions in the order they appear in the mapping sheet.
private static let loopedActionOrder: [MIDIMap.PedalActionKind] = [
.looperRecordStop, .looperOverdubToggle, .looperLoopToggle, .looperStop,
.looperCueStop, .looperReverse, .looperSyncToggle, .looperReset,
.looperTrack(index: 0), .looperTrack(index: 1),
.looperTrack(index: 2), .looperTrack(index: 3),
]
/// A short user-facing name for a looper transport action.
private static func looperActionName(_ kind: MIDIMap.PedalActionKind) -> String {
switch kind {
case .looperRecordStop: return "Record"
case .looperOverdubToggle: return "Overdub"
case .looperLoopToggle: return "Loop"
case .looperStop: return "Stop"
case .looperCueStop: return "Cue Stop"
case .looperReverse: return "Reverse"
case .looperSyncToggle: return "Sync"
case .looperReset: return "Reset"
case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))"
}
}
}
+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)
@@ -0,0 +1,244 @@
// NoteGlyphView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
// MARK: - Notation spec
/// The notation elements that make up one ``NoteDivision`` glyph. Derived purely from the division;
/// consumed by ``NoteGlyphView`` to draw the note.
private struct NoteGlyphSpec {
/// `true` for a solid notehead (quarter and shorter), `false` for an open ring (whole, half).
let filledHead: Bool
/// `true` when the note has a vertical stem (everything except the whole note).
let hasStem: Bool
/// Number of flags on the stem (`0` = quarter/half, `1` = eighth, `2` = sixteenth).
let flags: Int
/// `true` for a dotted value — adds an augmentation dot right of the head.
let dotted: Bool
/// `true` for a triplet — adds a bracket with a "3" above the note.
let triplet: Bool
init(_ division: NoteDivision) {
switch division {
case .whole:
self.init(filledHead: false, hasStem: false, flags: 0, dotted: false, triplet: false)
case .dottedHalf:
self.init(filledHead: false, hasStem: true, flags: 0, dotted: true, triplet: false)
case .half:
self.init(filledHead: false, hasStem: true, flags: 0, dotted: false, triplet: false)
case .dottedQuarter:
self.init(filledHead: true, hasStem: true, flags: 0, dotted: true, triplet: false)
case .quarter:
self.init(filledHead: true, hasStem: true, flags: 0, dotted: false, triplet: false)
case .dottedEighth:
self.init(filledHead: true, hasStem: true, flags: 1, dotted: true, triplet: false)
case .quarterTriplet:
self.init(filledHead: true, hasStem: true, flags: 0, dotted: false, triplet: true)
case .eighth:
self.init(filledHead: true, hasStem: true, flags: 1, dotted: false, triplet: false)
case .eighthTriplet:
self.init(filledHead: true, hasStem: true, flags: 1, dotted: false, triplet: true)
case .sixteenth:
self.init(filledHead: true, hasStem: true, flags: 2, dotted: false, triplet: false)
case .sixteenthTriplet:
self.init(filledHead: true, hasStem: true, flags: 2, dotted: false, triplet: true)
}
}
private init(filledHead: Bool, hasStem: Bool, flags: Int, dotted: Bool, triplet: Bool) {
self.filledHead = filledHead
self.hasStem = hasStem
self.flags = flags
self.dotted = dotted
self.triplet = triplet
}
}
// MARK: - NoteGlyphView
/// Draws a single music-notation glyph for a ``NoteDivision`` — notehead, stem, flags, an
/// augmentation dot for dotted values, and a bracketed "3" for triplets — with `Canvas`.
///
/// Drawn in solid black so the rasterized image can be used as a **template** in a menu (only the
/// alpha channel matters; the system tints it to the menu's foreground colour). See
/// ``NoteGlyphImageCache``.
struct NoteGlyphView: View {
// Logical drawing box. The note sits in the lower portion; the triplet bracket uses the top,
// which is left clear on every glyph so the note baseline stays consistent across the menu.
private static let boxWidth: CGFloat = 18
private static let boxHeight: CGFloat = 26
// Notehead.
private static let headCenterX: CGFloat = 6.5
private static let headCenterY: CGFloat = 19.0
private static let headRadiusX: CGFloat = 4.3
private static let headRadiusY: CGFloat = 3.0
private static let wholeHeadRadiusX: CGFloat = 5.0
private static let openHeadLineWidth: CGFloat = 1.5
// Stem.
private static let stemLineWidth: CGFloat = 1.3
private static let stemTopY: CGFloat = 8.0
// Flags.
private static let flagLineWidth: CGFloat = 1.5
private static let flagSpread: CGFloat = 5.5
private static let flagDrop: CGFloat = 6.0
private static let flagGap: CGFloat = 3.5
// Augmentation dot — pushed clear of the notehead's right edge.
private static let dotRadius: CGFloat = 1.5
private static let dotGap: CGFloat = 3.8
// Triplet bracket + numeral. The "3" is centred in the bracket gap; `bracketTopY` leaves room
// above it so the numeral is never clipped by the raster bounds.
private static let bracketTopY: CGFloat = 4.0
private static let bracketTickHeight: CGFloat = 2.0
private static let bracketInsetX: CGFloat = 1.5
private static let bracketLineWidth: CGFloat = 1.0
private static let bracketNumberGap: CGFloat = 3.0
private static let bracketNumberSize: CGFloat = 6.0
let division: NoteDivision
var body: some View {
Canvas { context, size in
let scaleX: CGFloat = size.width / NoteGlyphView.boxWidth
let scaleY: CGFloat = size.height / NoteGlyphView.boxHeight
let s: CGFloat = min(scaleX, scaleY)
context.scaleBy(x: s, y: s)
draw(NoteGlyphSpec(division), in: &context)
}
.frame(width: NoteGlyphView.boxWidth, height: NoteGlyphView.boxHeight)
}
private func draw(_ spec: NoteGlyphSpec, in context: inout GraphicsContext) {
let ink: GraphicsContext.Shading = .color(.black)
// Stem — draw before the head so the head overlaps its lower end cleanly.
let stemX: CGFloat = NoteGlyphView.headCenterX + NoteGlyphView.headRadiusX - 0.3
if spec.hasStem {
var stem: Path = Path()
stem.move(to: CGPoint(x: stemX, y: NoteGlyphView.headCenterY))
stem.addLine(to: CGPoint(x: stemX, y: NoteGlyphView.stemTopY))
context.stroke(stem, with: ink, lineWidth: NoteGlyphView.stemLineWidth)
}
// Flags — hooks off the top of the stem, one per flag, stacked downward.
for flagIndex: Int in 0 ..< spec.flags {
let startY: CGFloat = NoteGlyphView.stemTopY + CGFloat(flagIndex) * NoteGlyphView.flagGap
var flag: Path = Path()
flag.move(to: CGPoint(x: stemX, y: startY))
flag.addQuadCurve(
to: CGPoint(x: stemX + NoteGlyphView.flagSpread, y: startY + NoteGlyphView.flagDrop),
control: CGPoint(x: stemX + NoteGlyphView.flagSpread, y: startY)
)
context.stroke(flag, with: ink, lineWidth: NoteGlyphView.flagLineWidth)
}
// Notehead.
let headRadiusX: CGFloat = spec.hasStem ? NoteGlyphView.headRadiusX : NoteGlyphView.wholeHeadRadiusX
let headRect: CGRect = CGRect(
x: NoteGlyphView.headCenterX - headRadiusX,
y: NoteGlyphView.headCenterY - NoteGlyphView.headRadiusY,
width: headRadiusX * 2,
height: NoteGlyphView.headRadiusY * 2
)
let headPath: Path = Path(ellipseIn: headRect)
if spec.filledHead {
context.fill(headPath, with: ink)
} else {
context.stroke(headPath, with: ink, lineWidth: NoteGlyphView.openHeadLineWidth)
}
// Augmentation dot, right of the head.
if spec.dotted {
let dotX: CGFloat = NoteGlyphView.headCenterX + headRadiusX + NoteGlyphView.dotGap
let dotRect: CGRect = CGRect(
x: dotX - NoteGlyphView.dotRadius,
y: NoteGlyphView.headCenterY - NoteGlyphView.dotRadius,
width: NoteGlyphView.dotRadius * 2,
height: NoteGlyphView.dotRadius * 2
)
context.fill(Path(ellipseIn: dotRect), with: ink)
}
// Triplet bracket with a centred "3".
if spec.triplet {
drawTripletBracket(in: &context, ink: ink)
}
}
private func drawTripletBracket(in context: inout GraphicsContext, ink: GraphicsContext.Shading) {
let leftX: CGFloat = NoteGlyphView.bracketInsetX
let rightX: CGFloat = NoteGlyphView.boxWidth - NoteGlyphView.bracketInsetX
let midX: CGFloat = (leftX + rightX) / 2
let topY: CGFloat = NoteGlyphView.bracketTopY
let tickBottomY: CGFloat = topY + NoteGlyphView.bracketTickHeight
let gap: CGFloat = NoteGlyphView.bracketNumberGap
var bracket: Path = Path()
// Left tick down, then horizontal to the number gap.
bracket.move(to: CGPoint(x: leftX, y: tickBottomY))
bracket.addLine(to: CGPoint(x: leftX, y: topY))
bracket.addLine(to: CGPoint(x: midX - gap, y: topY))
// Right side: horizontal from the gap out to the right tick, then down.
bracket.move(to: CGPoint(x: midX + gap, y: topY))
bracket.addLine(to: CGPoint(x: rightX, y: topY))
bracket.addLine(to: CGPoint(x: rightX, y: tickBottomY))
context.stroke(bracket, with: ink, lineWidth: NoteGlyphView.bracketLineWidth)
let numeral: GraphicsContext.ResolvedText = context.resolve(
Text("3")
.font(.system(size: NoteGlyphView.bracketNumberSize, weight: .semibold, design: .rounded))
.foregroundColor(.black)
)
context.draw(numeral, at: CGPoint(x: midX, y: topY), anchor: .center)
}
}
// MARK: - Rasterization cache
/// Renders each ``NoteDivision`` glyph to a template `Image` once and caches it, so the tempo-sync
/// menu can show notation icons without re-rasterizing on every render. Template images tint to the
/// menu's foreground colour automatically.
@MainActor
enum NoteGlyphImageCache {
private static let renderScale: CGFloat = 3.0
private static var cache: [NoteDivision: Image] = [:]
/// The cached notation glyph for `division`, rendered on first request.
static func image(for division: NoteDivision) -> Image {
if let existing: Image = cache[division] {
return existing
}
let rendered: Image = render(division)
cache[division] = rendered
return rendered
}
private static func render(_ division: NoteDivision) -> Image {
let renderer: ImageRenderer = ImageRenderer(content: NoteGlyphView(division: division))
renderer.scale = renderScale
#if os(macOS)
if let nsImage = renderer.nsImage {
nsImage.isTemplate = true
return Image(nsImage: nsImage)
}
#else
if let uiImage = renderer.uiImage {
return Image(uiImage: uiImage.withRenderingMode(.alwaysTemplate))
}
#endif
// Fallback to the division's text label if rasterization ever fails.
return Image(systemName: "music.note")
}
}
+215 -4
View File
@@ -180,6 +180,189 @@ struct FootswitchButton: View {
}
}
// MARK: - Tempo-sync knob
/// A knob that can be locked to a note division of the live tempo.
///
/// When free, it is an ordinary ``ParameterKnob``. A compact menu below the dial lets the user
/// pick `Free` or a ``NoteDivision``; once a division is chosen the knob is driven by the tempo
/// (its dial shows the derived value but is disabled, since the number is computed). The menu is
/// shown only while tempo is enabled — the enclosing view gates on `shoeGazeTempoEnabled`.
struct TempoSyncKnobView: View {
private static let cellSpacing: CGFloat = 4
private static let syncedDialOpacity: Double = 0.55
private static let menuFontSize: CGFloat = 10
private static let labelGlyphSpacing: CGFloat = 3
private static let warningIconSize: CGFloat = 8
/// Height of the glyph in the collapsed menu button, and of the whole menu row, so the row is the
/// same height whether it shows the "Free" text or a note glyph — the pedal card never grows.
private static let labelGlyphHeight: CGFloat = 18
private static let menuRowHeight: CGFloat = 20
private static let freeKey: String = "free"
// Division-picker popover: a height-capped scroll list the system keeps on-screen (it flips
// above the button near the bottom edge) rather than a native menu that can run off-screen.
private static let pickerMaxHeight: CGFloat = 260
private static let pickerGlyphHeight: CGFloat = 22
private static let pickerRowSpacing: CGFloat = 2
private static let pickerPadding: CGFloat = 8
private static let pickerRowMinWidth: CGFloat = 84
private static let checkmarkFontSize: CGFloat = 11
let pedal: Pedal
let knob: PedalKnob
let param: TempoSyncableParam
/// Presentation flag for the division-picker popover.
@State private var showDivisionPicker: Bool = false
var body: some View {
// Observe the pedal's sync-revision so the badge refreshes when `tempoSync` changes through
// any path — this view's picker, a preset load, or a lightweight recall.
let _ = pedal.tempoSyncRevision.value
let currentKey: String = keyForCurrentSync()
let isSynced: Bool = currentKey != TempoSyncKnobView.freeKey
let currentBpm: Double? = pedal.clock?.bpm
// Reading the live parameter value subscribes this view to Observation, so a tempo change
// (which rewrites the node via `applyTempoSync`) re-renders the clamp warning without polling.
let liveValue: Double = param.node.value
let activeDivision: NoteDivision? = NoteDivision(rawValue: currentKey)
let activeClamped: Bool = {
_ = liveValue
guard isSynced, let bpm: Double = currentBpm, let division: NoteDivision = activeDivision else {
return false
}
return param.value(for: division, bpm: bpm).clamped
}()
VStack(spacing: TempoSyncKnobView.cellSpacing) {
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
.disabled(isSynced)
.opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0)
Button {
showDivisionPicker = true
} label: {
HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) {
if isSynced, let division: NoteDivision = activeDivision {
NoteGlyphImageCache.image(for: division)
.resizable()
.scaledToFit()
.frame(height: TempoSyncKnobView.labelGlyphHeight)
.accessibilityLabel(Text(labelForKey(currentKey)))
} else {
Text("Free")
.font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded))
}
if activeClamped {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: TempoSyncKnobView.warningIconSize))
}
Image(systemName: "chevron.down")
.font(.system(size: TempoSyncKnobView.warningIconSize))
.opacity(0.6)
}
.frame(height: TempoSyncKnobView.menuRowHeight)
.foregroundStyle(activeClamped ? Color.orange : Color.white.opacity(isSynced ? 1.0 : 0.65))
}
.buttonStyle(.plain)
.fixedSize()
.help(activeClamped
? "This note can't be represented at the current tempo — \(knob.label) is clamped to its limit."
: "Sync \(knob.label) to the tempo, or set it freely")
.popover(isPresented: $showDivisionPicker) {
divisionPicker
.presentationCompactAdaptation(.popover)
}
}
}
/// Height-capped, scrollable list of `Free` + every note division. Presented as a popover so the
/// system keeps it on-screen (flipping above the button near the bottom edge) and it scrolls when
/// taller than ``pickerMaxHeight`` — unlike a native menu, which ran off the bottom on iOS.
private var divisionPicker: some View {
let currentBpm: Double? = pedal.clock?.bpm
let currentKey: String = keyForCurrentSync()
return ScrollView {
VStack(alignment: .leading, spacing: TempoSyncKnobView.pickerRowSpacing) {
pickerRow(
key: TempoSyncKnobView.freeKey,
glyph: nil,
disabled: false,
selected: currentKey == TempoSyncKnobView.freeKey
)
ForEach(NoteDivision.allCases, id: \.self) { division in
// A division whose value clamps at the current tempo (e.g. a note longer than the
// maximum delay time) can't be represented accurately, so it is shown but disabled.
let unavailable: Bool = currentBpm.map { param.value(for: division, bpm: $0).clamped } ?? false
pickerRow(
key: division.rawValue,
glyph: division,
disabled: unavailable,
selected: currentKey == division.rawValue
)
}
}
.padding(TempoSyncKnobView.pickerPadding)
}
.frame(maxHeight: TempoSyncKnobView.pickerMaxHeight)
}
/// One selectable row in ``divisionPicker`` — a note glyph (or "Free" text), a trailing checkmark
/// when it is the current selection, and a disabled state for divisions that clamp at this tempo.
@ViewBuilder
private func pickerRow(key: String, glyph: NoteDivision?, disabled: Bool, selected: Bool) -> some View {
Button {
select(key)
showDivisionPicker = false
} label: {
HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) {
if let glyph: NoteDivision = glyph {
NoteGlyphImageCache.image(for: glyph)
.resizable()
.scaledToFit()
.frame(height: TempoSyncKnobView.pickerGlyphHeight)
} else {
Text("Free")
.font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded))
}
Spacer(minLength: TempoSyncKnobView.labelGlyphSpacing)
if selected {
Image(systemName: "checkmark")
.font(.system(size: TempoSyncKnobView.checkmarkFontSize, weight: .semibold))
}
}
.frame(minWidth: TempoSyncKnobView.pickerRowMinWidth, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled(disabled)
.accessibilityLabel(Text(glyph?.label ?? "Free"))
}
private func keyForCurrentSync() -> String {
if case .division(let division) = pedal.tempoSync[param.key] ?? .free {
return division.rawValue
}
return TempoSyncKnobView.freeKey
}
private func labelForKey(_ key: String) -> String {
key == TempoSyncKnobView.freeKey ? "Free" : (NoteDivision(rawValue: key)?.label ?? key)
}
private func select(_ key: String) {
// `setSync` bumps `pedal.tempoSyncRevision`, which this view observes — no local flag needed.
if key == TempoSyncKnobView.freeKey {
pedal.setSync(.free, for: param.key)
} else if let division: NoteDivision = NoteDivision(rawValue: key) {
pedal.setSync(.division(division), for: param.key)
}
}
}
// MARK: - PedalView
/// A stompbox-style enclosure view that renders all controls for a single `Pedal`.
@@ -266,6 +449,13 @@ public struct PedalView: View {
/// Presentation flag for the pedal info panel (description + control ranges).
@State private var showInfo: Bool = false
/// The rig's control map, injected by the builder so the pedal can draw a mapping strip. `nil`
/// when the rig has no bindings (or in contexts that don't set it) — the strip renders nothing.
@Environment(\.controlMappingMap) private var controlMappingMap: MIDIMap?
/// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off.
@Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool
// MARK: - Init
/// Creates a stompbox pedal view for the given pedal.
@@ -355,6 +545,7 @@ public struct PedalView: View {
sliderBank(sliders)
Spacer(minLength: 0)
bottomControls
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
}
}
@@ -389,6 +580,7 @@ public struct PedalView: View {
.id(ObjectIdentifier(pedal))
}
Spacer(minLength: 0)
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
}
}
@@ -522,12 +714,12 @@ public struct PedalView: View {
let rowItemSpacing: CGFloat = row.count >= columns
? PedalView.knobSpacing
: PedalView.knobRowItemSpacing
HStack(spacing: rowItemSpacing) {
// Top-align so every dial pins to the row's top edge — a tempo-sync cell grows taller
// below the dial (glyph menu, warning) without dragging its neighbours' dials down.
HStack(alignment: .top, spacing: rowItemSpacing) {
Spacer(minLength: 0)
ForEach(Array(row.enumerated()), id: \.offset) { knobPair in
let knob: PedalKnob = knobPair.element
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
knobCell(knobPair.element)
}
Spacer(minLength: 0)
}
@@ -535,6 +727,25 @@ public struct PedalView: View {
}
}
/// Renders one effect knob — a tempo-sync knob when the parameter is syncable and tempo is
/// enabled, otherwise a plain ``ParameterKnob``. Syncable knobs are matched by node identity
/// against `pedal.tempoSyncableParams`.
@ViewBuilder
private func knobCell(_ knob: PedalKnob) -> some View {
if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) {
TempoSyncKnobView(pedal: pedal, knob: knob, param: param)
} else {
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.foregroundStyle(Color.white)
}
}
/// The tempo-syncable descriptor whose parameter node backs `knob`, or `nil` if the knob is
/// not syncable. Matched by `UIParamNode` identity so it is robust to label changes.
private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? {
pedal.tempoSyncableParams.first { $0.node === knob.node }
}
/// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid.
/// Renders nothing when the pedal publishes no selectors.
@ViewBuilder
@@ -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 {
@@ -495,10 +664,14 @@ public struct ShoeGazeBuilderView: View {
topSection
}
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
ControlMappingLegend()
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
// Feed the rig's control map into the board tree so each pedal can draw its mapping strip.
// Reading `shoeGaze.midiMap` here (observable) refreshes every strip when a binding changes.
.environment(\.controlMappingMap, shoeGaze.midiMap)
}
// MARK: - Compact layout (iPhone / narrow iPad)
+80 -8
View File
@@ -22,6 +22,11 @@ public struct TempoView: View {
private static let minBpm: Double = 30.0
private static let maxBpm: Double = 300.0
private static let bpmStep: Double = 1.0
/// Width of the editable BPM text field — fits three digits at the readout font.
private static let bpmFieldWidth: CGFloat = 44
private static let bpmFontSize: CGFloat = 18
/// Maximum digits accepted in the BPM field (max 300 BPM is three digits).
private static let bpmMaxDigits: Int = 3
private static let rowSpacing: CGFloat = 10
// Metronome track: a dot swings wall-to-wall once per beat, pausing at each wall (the beat)
@@ -56,12 +61,18 @@ public struct TempoView: View {
/// Continuous beat position, polled from the clock; drives the metronome dot.
@State private var beat: Double = 0.0
/// The editable BPM text. Kept in sync with `displayedBpm` while the field isn't focused; on
/// commit it is validated (integer only), clamped to `[minBpm, maxBpm]`, and applied.
@State private var bpmText: String
@FocusState private var bpmFieldFocused: Bool
// MARK: - Init
/// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives.
public init(shoeGaze: ShoeGaze) {
self.shoeGaze = shoeGaze
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
self._bpmText = State(initialValue: String(Int(shoeGaze.clock.bpm.rounded())))
}
// MARK: - Body
@@ -78,18 +89,12 @@ public struct TempoView: View {
if shoeGaze.tempoEnabled {
metronome
Text("\(Int(displayedBpm.rounded())) BPM")
.font(.system(size: 18, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
bpmField
Stepper(
"",
value: Binding(
get: { displayedBpm },
set: { newValue in
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
shoeGaze.clock.bpm = clamped
displayedBpm = clamped
}
set: { newValue in applyBpm(newValue) }
),
in: TempoView.minBpm ... TempoView.maxBpm,
step: TempoView.bpmStep
@@ -106,11 +111,78 @@ public struct TempoView: View {
while shoeGaze.tempoEnabled && !Task.isCancelled {
beat = shoeGaze.clock.currentBeat
displayedBpm = shoeGaze.clock.bpm
// Don't overwrite the field mid-edit — only reflect external tempo changes when the
// field isn't focused (tap tempo, stepper, MIDI, rig load).
if !bpmFieldFocused {
bpmText = String(Int(displayedBpm.rounded()))
}
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
}
}
}
// MARK: - BPM field
/// Editable BPM readout. Accepts integer input, validated and clamped on commit (Return, or the
/// keyboard's Done, or focus loss). Non-numeric or empty input reverts to the current tempo.
private var bpmField: some View {
HStack(spacing: TempoView.rowSpacing / 2) {
TextField("", text: $bpmText)
.textFieldStyle(.plain)
.multilineTextAlignment(.trailing)
.font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
.frame(width: TempoView.bpmFieldWidth)
.fixedSize()
.focused($bpmFieldFocused)
.onSubmit { commitBpm() }
#if os(iOS)
.keyboardType(.numberPad)
.toolbar {
ToolbarItemGroup(placement: .keyboard) {
Spacer()
Button("Done") { bpmFieldFocused = false }
}
}
#endif
Text("BPM")
.font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded))
.foregroundStyle(Color.white)
}
.onChange(of: bpmText) { _, newValue in
// Reject non-numeric input as it is typed, and cap at three digits (max 300 BPM).
let filtered: String = String(newValue.filter { $0.isNumber }.prefix(TempoView.bpmMaxDigits))
if filtered != newValue {
bpmText = filtered
}
}
.onChange(of: bpmFieldFocused) { _, focused in
// Commit when focus leaves the field (tap away / Done), the counterpart to onSubmit.
if !focused {
commitBpm()
}
}
}
/// Validates and applies the typed BPM: integers only, clamped to `[minBpm, maxBpm]`. Non-numeric
/// or empty input reverts the field to the current tempo without changing it.
private func commitBpm() {
let digits: String = bpmText.filter { $0.isNumber }
if let value: Int = Int(digits) {
applyBpm(Double(value))
} else {
bpmText = String(Int(displayedBpm.rounded()))
}
}
/// Clamps `bpm` to the allowed range, applies it to the session, and syncs the field text.
private func applyBpm(_ bpm: Double) {
let clamped: Double = min(max(bpm, TempoView.minBpm), TempoView.maxBpm)
shoeGaze.setBpm(clamped)
displayedBpm = clamped
bpmText = String(Int(clamped.rounded()))
}
// MARK: - Subviews
/// Horizontal pendulum: the dot maps `beat` through a cosine so it eases to a stop at each
@@ -181,6 +181,42 @@ struct MIDIControllerCCTests {
}
}
@Test func ccIsIgnoredWhileParameterIsTempoSynced() throws {
// A CC bound to a parameter that is locked to a note division must be ignored — the value is
// tempo-derived and a CC write would be overwritten on the next tempo change. The binding
// stays intact and resumes control once the parameter is set back to Free.
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = 120.0
let board: PedalBoard = try sg.addBoard()
let delay: DelayPedal = DelayPedal()
try board.add(delay)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
withExtendedLifetime(sg) {
// Bind CC 21 to Time (control 0 on a Delay pedal).
controller.armCCLearn(pedalControl(delay.id, 0))
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 0))
// Lock Time to a quarter note — 0.5 s at 120 BPM.
delay.setSync(.division(.quarter), for: "time")
let syncedValue: Double = delay.$time.value
#expect(abs(syncedValue - 0.5) < 1e-9)
// A CC while synced must not move the value.
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 127))
#expect(abs(delay.$time.value - syncedValue) < 1e-9, "CC must not drive a tempo-synced parameter")
// Back to Free — the same binding drives the control again.
delay.setSync(.free, for: "time")
let timeMax: Double = delay.ccMappableControls[0].range.upperBound
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 127))
#expect(abs(delay.$time.value - timeMax) < 1e-9, "CC resumes control once the parameter is Free")
}
}
@Test func unboundCCIsIgnored() throws {
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
defer { try? FileManager.default.removeItem(at: url) }
@@ -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)
}
}
}
@@ -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)
}
}
@@ -0,0 +1,52 @@
// NoteDivisionTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
@testable import LyrebirdShoeGaze
@Suite("NoteDivision")
struct NoteDivisionTests {
private let tolerance: Double = 1e-9
@Test func beatsMatchMusicalValues() {
#expect(NoteDivision.whole.beats == 4.0)
#expect(NoteDivision.dottedHalf.beats == 3.0)
#expect(NoteDivision.half.beats == 2.0)
#expect(NoteDivision.dottedQuarter.beats == 1.5)
#expect(NoteDivision.quarter.beats == 1.0)
#expect(abs(NoteDivision.quarterTriplet.beats - 2.0 / 3.0) < tolerance)
#expect(NoteDivision.dottedEighth.beats == 0.75)
#expect(NoteDivision.eighth.beats == 0.5)
#expect(abs(NoteDivision.eighthTriplet.beats - 1.0 / 3.0) < tolerance)
#expect(NoteDivision.sixteenth.beats == 0.25)
#expect(abs(NoteDivision.sixteenthTriplet.beats - 1.0 / 6.0) < tolerance)
}
@Test func dottedIsHalfAgainThePlainValue() {
#expect(NoteDivision.dottedQuarter.beats == NoteDivision.quarter.beats * 1.5)
#expect(NoteDivision.dottedEighth.beats == NoteDivision.eighth.beats * 1.5)
}
@Test func casesAreOrderedSlowToFast() {
let beats: [Double] = NoteDivision.allCases.map { $0.beats }
#expect(beats == beats.sorted(by: >), "cases must be ordered longest (slowest) first")
}
@Test func labelsAreUnique() {
let labels: [String] = NoteDivision.allCases.map { $0.label }
#expect(Set(labels).count == labels.count)
}
@Test func codableRoundTrips() throws {
for division: NoteDivision in NoteDivision.allCases {
let data: Data = try JSONEncoder().encode(division)
let decoded: NoteDivision = try JSONDecoder().decode(NoteDivision.self, from: data)
#expect(decoded == division)
}
}
}
@@ -0,0 +1,87 @@
// PedalMappingStripTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@testable import LyrebirdShoeGazeUI
@MainActor
@Suite("Pedal mapping strip")
struct PedalMappingStripTests {
/// Builds an engine + a one-board rig with a single Volume pedal, returning the pedal.
private func makePedal() throws -> (Pedal, 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()
try board.add(VolumePedal())
try sg.finalizeBoard(board)
guard let pedal: Pedal = board.pedals.first else {
throw ShoeGazeTestError.noPedal
}
return (pedal, sg, url)
}
private enum ShoeGazeTestError: Error { case noPedal }
@Test func emptyMapYieldsNoRows() throws {
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
#expect(PedalMappingStrip.rows(for: pedal, in: nil).isEmpty)
#expect(PedalMappingStrip.rows(for: pedal, in: .empty).isEmpty)
}
}
@Test func ccAndBypassRowsBuiltFromMap() throws {
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
#expect(pedal.ccMappableControls.isEmpty == false, "Volume exposes a CC-mappable control")
let controlLabel: String = pedal.ccMappableControls[0].label
let map: MIDIMap = MIDIMap(
switches: [MIDIMap.SwitchBinding(program: 4, action: .pedalBypass(pedalID: pedal.id))],
ccs: [MIDIMap.CCBinding(
controller: 11,
target: .pedalControl(
pedalID: pedal.id, controlIndex: 0,
pedalNameHint: nil, controlLabelHint: nil))],
keys: [MIDIMap.KeyBinding(key: "b", modifiers: [.shift],
action: .pedalBypass(pedalID: pedal.id))]
)
let rows: [PedalMappingRow] = PedalMappingStrip.rows(for: pedal, in: map)
#expect(rows.count == 2, "one CC control row + one bypass row")
let ccRow: PedalMappingRow? = rows.first { $0.label == controlLabel }
#expect(ccRow?.badges.map(\.text) == ["CC11"])
let bypassRow: PedalMappingRow? = rows.first { $0.label == "Bypass" }
#expect(bypassRow?.badges.map(\.text) == ["PC4", "⇧B"], "footswitch then key, shift glyph")
}
}
@Test func unmappedControlsProduceNoRows() throws {
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
defer { try? FileManager.default.removeItem(at: url) }
withExtendedLifetime(sg) {
// A map that only binds a DIFFERENT pedal's control must not surface rows for this pedal.
let otherID: UUID = UUID()
let map: MIDIMap = MIDIMap(
ccs: [MIDIMap.CCBinding(
controller: 5,
target: .pedalControl(
pedalID: otherID, controlIndex: 0,
pedalNameHint: nil, controlLabelHint: nil))]
)
#expect(PedalMappingStrip.rows(for: pedal, in: map).isEmpty)
}
}
}
@@ -0,0 +1,194 @@
// TempoSyncTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Tempo sync")
struct TempoSyncTests {
/// A rig with a single `DelayPedal` on a finalized board, so the pedal has a real clock and
/// engine injected by `board.add(_:)`. Returns the session (kept alive for its clock), the
/// temp render URL, and the pedal.
private func makeRigWithDelay(bpm: Double = 120.0) throws -> (ShoeGaze, URL, DelayPedal) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = bpm
let board: PedalBoard = try sg.addBoard()
let delay: DelayPedal = DelayPedal()
try board.add(delay)
try sg.finalizeBoard(board)
return (sg, url, delay)
}
private let tolerance: Double = 1e-6
@Test func timeDivisionDerivesSecondsFromTempo() throws {
// `sg` owns the clock (the pedal holds it weakly), so it must outlive the assertions.
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
// 120 BPM → 0.5 s per beat. Eighth = 0.5 beat → 0.25 s.
delay.setSync(.division(.eighth), for: "time")
#expect(abs(delay.$time.value - 0.25) < tolerance)
// Quarter = 1 beat → 0.5 s.
delay.setSync(.division(.quarter), for: "time")
#expect(abs(delay.$time.value - 0.5) < tolerance)
}
@Test func freeParameterIsLeftUntouched() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay()
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
let original: Double = delay.$time.value
delay.applyTempoSync() // nothing is synced → value unchanged
#expect(delay.$time.value == original)
}
@Test func longDivisionClampsToParameterRange() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 40.0)
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
// Whole note at 40 BPM = 4 beats × 1.5 s = 6.0 s, past the Delay's 5.0 s maximum.
delay.setSync(.division(.whole), for: "time")
#expect(abs(delay.$time.value - 5.0) < tolerance, "synced value must clamp to the time range")
}
@Test func valueReportsWhenADivisionClamps() throws {
let delay: DelayPedal = DelayPedal()
let param: TempoSyncableParam = try #require(delay.tempoSyncableParams.first)
// Fits within [0.01, 5.0]: quarter @ 120 BPM = 0.5 s, not clamped.
let quarter: (value: Double, clamped: Bool) = param.value(for: .quarter, bpm: 120.0)
#expect(abs(quarter.value - 0.5) < tolerance)
#expect(!quarter.clamped)
// Whole @ 40 BPM = 6.0 s, past the 5.0 s max → clamped and flagged.
let whole: (value: Double, clamped: Bool) = param.value(for: .whole, bpm: 40.0)
#expect(abs(whole.value - 5.0) < tolerance)
#expect(whole.clamped)
}
@Test func setBpmBroadcastsToSyncedParameters() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
delay.setSync(.division(.quarter), for: "time")
#expect(abs(delay.$time.value - 0.5) < tolerance) // quarter @ 120 BPM
// Halving the tempo doubles a beat's length → quarter now 1.0 s.
sg.setBpm(60.0)
#expect(abs(delay.$time.value - 1.0) < tolerance, "setBpm must recompute synced parameters")
}
@Test func rateParameterUsesInverseOfPeriod() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = 120.0
let board: PedalBoard = try sg.addBoard()
let tremolo: TremoloPedal = TremoloPedal()
try board.add(tremolo)
try sg.finalizeBoard(board)
defer { withExtendedLifetime(sg) {} }
// 120 BPM → 0.5 s per beat. A quarter-note LFO = one cycle per 0.5 s → 2 Hz.
tremolo.setSync(.division(.quarter), for: "rate")
#expect(abs(tremolo.$rate.value - 2.0) < tolerance)
// Eighth = 0.25 s period → 4 Hz.
tremolo.setSync(.division(.eighth), for: "rate")
#expect(abs(tremolo.$rate.value - 4.0) < tolerance)
}
@Test func multiTapSyncsEachTapIndependently() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
sg.clock.bpm = 120.0
let board: PedalBoard = try sg.addBoard()
let multiTap: MultiTapDelayPedal = MultiTapDelayPedal()
try board.add(multiTap)
try sg.finalizeBoard(board)
defer { withExtendedLifetime(sg) {} }
let freeTime3: Double = multiTap.$time3.value
multiTap.setSync(.division(.quarter), for: "time1") // 0.5 s
multiTap.setSync(.division(.eighth), for: "time2") // 0.25 s
#expect(abs(multiTap.$time1.value - 0.5) < tolerance)
#expect(abs(multiTap.$time2.value - 0.25) < tolerance)
#expect(multiTap.$time3.value == freeTime3, "an unsynced tap is left free")
}
@Test func lightweightRecallRecomputesSyncedValuesAtCurrentTempo() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
defer { withExtendedLifetime(sg) {} }
delay.setSync(.division(.quarter), for: "time")
#expect(abs(delay.$time.value - 0.5) < tolerance) // quarter @ 120 BPM
// Capture at 120 BPM (time = 0.5 s), then change tempo so a recall must recompute.
let snapshot: ShoeGazeState = sg.captureState()
sg.setBpm(60.0)
#expect(abs(delay.$time.value - 1.0) < tolerance) // quarter @ 60 BPM
// Recall the 120-BPM snapshot onto the (now 60-BPM) rig. The restored division must be
// recomputed against the current tempo — 1.0 s — not left at the captured 0.5 s.
sg.applyState(snapshot)
#expect(delay.tempoSync["time"] == .division(.quarter))
#expect(abs(delay.$time.value - 1.0) < tolerance, "recall must recompute synced values at the current tempo")
}
@Test func syncStatePersistsThroughCaptureAndApply() throws {
let delay: DelayPedal = DelayPedal()
delay.setSync(.division(.dottedEighth), for: "time")
let data: Data = try JSONEncoder().encode(delay.captureState())
let restored: PedalState = try JSONDecoder().decode(PedalState.self, from: data)
let rebuilt: DelayPedal = DelayPedal()
rebuilt.applyState(restored)
#expect(rebuilt.tempoSync["time"] == .division(.dottedEighth))
}
@Test func presetWithoutTempoSyncDecodesToFree() throws {
// A rig saved before tempo sync has no `tempoSync` key — it must decode to "all free".
let legacy: String = """
{"type":"Delay","knobValues":[0.25,1.0,0.35,1.0],"bypass":0.0}
"""
let state: PedalState = try JSONDecoder().decode(PedalState.self, from: Data(legacy.utf8))
#expect(state.tempoSync == nil)
let delay: DelayPedal = DelayPedal()
delay.applyState(state)
#expect(delay.tempoSync.isEmpty, "a legacy preset leaves every parameter free")
}
@Test func disablingTempoStopsRecompute() throws {
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
defer { try? FileManager.default.removeItem(at: url) }
delay.setSync(.division(.quarter), for: "time")
let syncedValue: Double = delay.$time.value // 0.5 s
sg.setTempoEnabled(false)
sg.setBpm(60.0) // tempo disabled → no recompute
#expect(delay.$time.value == syncedValue, "a disabled tempo must not drive synced parameters")
// Re-enabling re-syncs to the current (60 BPM) tempo → quarter = 1.0 s.
sg.setTempoEnabled(true)
#expect(abs(delay.$time.value - 1.0) < tolerance)
}
}
@@ -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`.
+221
View File
@@ -0,0 +1,221 @@
# Tempo-synced pedal parameters
Let a time- or rate-based pedal parameter be locked to a **note division of the live
tempo** (quarter, dotted-eighth, eighth-triplet, …) instead of an absolute value. A delay
time set to "quarter note" tracks the shared clock; change BPM (stepper, tap, MIDI) and the
echo follows. Setting stays "free" (absolute seconds / Hz, as today) unless the user opts a
param into sync.
## Goals
- Any delay **time** param can be marked as a note division; its seconds are derived from
`clock.bpm`.
- Any modulation **rate** param (LFO Hz) can be marked as a note division; its frequency is
the inverse of the synced period (a "quarter-note" LFO = one cycle per quarter note).
- MultiTapDelay's three tap times each sync independently to their own division.
- Sync state travels with the rig (persists in `PedalState`), decoded leniently so older
rigs still load.
- Gated on the existing `tempoEnabled` flag — when tempo is off, sync affordances hide and
synced params fall back to their stored absolute value.
- macOS + iOS.
## Non-goals
- Sample-accurate tempo-ramp tracking (Option B, a clock-backed core Generator). BPM here
changes only at discrete events — stepper, tap, MIDI — so a recompute-on-change ("Push")
model loses nothing. The state format is designed so a Pull generator can back it later
without a migration.
- Syncing envelope- or expression-driven params (AutoWah, Mutant, Wah) — no fixed rate.
- Syncing Rotary `speed` — bimodal slow/fast horn, not a free rate.
- Auto-extending delay buffers to fit long divisions. Buffers are sized at init; a division
whose period exceeds a param's range is **clamped** to the range.
## Which params
**Time family** (synced value = period `T`):
| Pedal | param(s) |
|---|---|
| DelayPedal | `time` |
| FeedbackDelayPedal | `time` |
| PingPongDelayPedal | `time` |
| ReverseDelayPedal | `time` |
| MultiTapDelayPedal | `time1`, `time2`, `time3` |
**Rate family** (synced value = `1/T`, Hz):
| Pedal | param |
|---|---|
| TremoloPedal | `rate` |
| VibratoPedal | `rate` |
| ChorusPedal | `rate` |
| FlangerPedal | `rate` |
| PhaserPedal | `rate` |
| ModulationPedal | `rate` |
## Design
Approach: **Push / recompute-on-change**. When a param is synced, its `@UIParam` value is
recomputed and written whenever BPM or the chosen division changes. Generators are untouched
— they keep reading `$time` / `$rate` exactly as now. Writing a `@UIParam` from the main
thread is identical to a knob turn, so there is no RT concern.
Synced period, given beats-per-division `d` and tempo `bpm`:
```
T = (60 / bpm) * d // seconds
value = kind == .rate ? 1 / T : T
value = min(max(value, range.lowerBound), range.upperBound) // clamp
```
### Core types — new files in `Sources/LyrebirdShoeGaze/Tempo/`
One public type per file (repo rule).
`NoteDivision.swift`:
```swift
public enum NoteDivision: String, Codable, CaseIterable, Sendable {
case whole, dottedHalf, half, dottedQuarter, quarter, quarterTriplet
case dottedEighth, eighth, eighthTriplet, sixteenth, sixteenthTriplet
/// Beats (quarter-note = 1) this division spans.
public var beats: Double { ... } // whole = 4, quarter = 1, eighth = 0.5,
// dottedEighth = 0.75, eighthTriplet = 1/3, ...
public var label: String { ... } // "1/4", "1/8.", "1/8T", ...
}
```
`TempoSync.swift`:
```swift
public enum TempoSync: Codable, Equatable, Sendable {
case free
case division(NoteDivision)
}
```
`TempoSyncableParam.swift` — descriptor a pedal publishes, one per syncable param:
```swift
public struct TempoSyncableParam {
public enum Kind { case time, rate } // rate ⇒ inverse (Hz = 1/T)
public let key: String // stable id, persistence key (e.g. "time", "time1")
public let label: String
public let node: UIParamNode
public let kind: Kind
public let range: ClosedRange<Double>
}
```
### `Pedal` base additions
```swift
/// Params this pedal exposes to tempo sync. Empty for pedals that can't sync.
open var tempoSyncableParams: [TempoSyncableParam] { [] }
/// Per-param sync state, keyed by TempoSyncableParam.key. Default .free.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Recompute + write every synced param from the current clock BPM. Main-thread only.
public func applyTempoSync() { ... } // no-op when no clock, or tempo disabled
/// Set one param's sync state and immediately recompute it.
public func setSync(_ sync: TempoSync, for key: String) { ... }
```
`applyTempoSync()` iterates `tempoSyncableParams`, looks up each key's state, and for a
`.division` writes the clamped `T` (or `1/T`). `.free` leaves the param at its stored value.
Each candidate pedal overrides `tempoSyncableParams` — e.g. DelayPedal:
```swift
public override var tempoSyncableParams: [TempoSyncableParam] {
[TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange)]
}
```
### `ShoeGaze` broadcast — the Push trigger
BPM is currently mutated in three places that set `clock.bpm` directly (TempoView stepper,
`tapTempo()`, MIDI). Funnel them through one entry point:
```swift
public func setBpm(_ bpm: Double) {
clock.bpm = bpm
board.forEachPedal { $0.applyTempoSync() }
}
```
- `TempoView` stepper `set:` → `shoeGaze.setBpm(clamped)` (was `clock.bpm = clamped`).
- `tapTempo()` → compute then `setBpm(...)` (was `clock.bpm = ...`).
- MIDI tempo path → `setBpm`.
- Rig load (BPM restored from `ShoeGazeState`) → call `applyTempoSync()` across the board
after the clock is set, so restored synced params match the loaded tempo.
- `setTempoEnabled(false)` → params keep their last absolute value (no recompute); re-enable
→ `applyTempoSync()`.
(If `board.forEachPedal` doesn't exist, add a thin iterator over the board's pedals.)
### Persistence — `PedalState`
Add one field, decoded leniently (same pattern the tempo/BPM fields already use):
```swift
public let tempoSync: [String: TempoSync]? // param key → sync state; nil for old rigs
```
Custom `init(from:)` decodes with `decodeIfPresent`; absent ⇒ `nil` ⇒ all params `.free`.
`Pedal+Preset` captures `pedal.tempoSync` on save and restores it on load, then calls
`applyTempoSync()` so values line up with the rig's restored BPM.
### UI — `PedalView`
For each param that appears in `tempoSyncableParams`:
- Show a small **Sync** toggle beside/under the knob.
- Sync **off** → render the existing `PedalKnob` rotary, unchanged.
- Sync **on** → replace the rotary with a `PedalSelectorKnob` (already exists: a knob that
snaps to labelled stops) bound to the `NoteDivision` list; changing it calls
`pedal.setSync(.division(sel), for: key)`.
- Gate the whole affordance on the `shoeGazeTempoEnabled` environment flag — when tempo is
off, only the plain knob shows.
### MIDI — implemented (inert while synced)
A synced param's value is derived, so a CC bound to it would be overwritten on the next
tempo/division change. Rather than drop `.division`-synced params from `ccMappableControls` —
which is addressed by a *stable index* (persisted CC bindings resolve by position), so filtering it
live would shift indices and break existing bindings — the exclusion is **index-stable**: the slot
stays, and the CC *write* is skipped while the target parameter is division-synced.
`MIDIController.applyCC` checks `Pedal.isNodeTempoSynced(_:)` (node-identity match against
`tempoSyncableParams`) and ignores the incoming CC for a synced control; the binding stays intact and
resumes control the moment the parameter is set back to Free. Learning/binding a CC to a synced
param is still allowed — the tempo simply wins while synced.
## Testing
One `@Suite` per file (repo rule):
- `NoteDivisionTests` — `beats` values (whole = 4, quarter = 1, dottedEighth = 0.75,
eighthTriplet ≈ 0.3333, …) and `label`s.
- `TempoSyncTests` — `applyTempoSync` for a `.time` param (period), a `.rate` param
(inverse), and range-clamp (whole note @ 60 BPM = 4 s clamps to Delay's 1.5 s max).
- `ShoeGazeTempoBroadcastTests` — `setBpm` recomputes a synced param across the board;
changing division recomputes; `.free` params untouched.
- `PedalStatePersistenceTests` (extend existing) — `tempoSync` round-trips; a rig saved
without the field decodes to all-`.free`.
## Build order
Vertical slice first to validate the whole path end to end, then fan out:
1. Core types (`NoteDivision`, `TempoSync`, `TempoSyncableParam`).
2. `Pedal` hooks (`tempoSyncableParams`, `tempoSync`, `applyTempoSync`, `setSync`).
3. `ShoeGaze.setBpm` broadcast + reroute the three BPM writers + rig-load hook.
4. **DelayPedal** override + its `PedalView` sync UI.
5. Tests for 1–4.
6. Persistence (`PedalState.tempoSync`, `Pedal+Preset`).
7. Fan out to the remaining delays, then the modulation (rate) pedals, then MultiTap's
three taps.
8. `lyrebird_external_review` (ShoeGaze is out-of-tree) before merge.