diff --git a/CHANGELOG.md b/CHANGELOG.md index 75ca3bf..8aa6538 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,46 @@ 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. +- **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 diff --git a/RELEASES.md b/RELEASES.md index 65c2f89..a478ac5 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,4 +1,28 @@ # 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. + +### 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 diff --git a/Sources/LyrebirdShoeGaze/Pedal.swift b/Sources/LyrebirdShoeGaze/Pedal.swift index 8ce1b3b..b6fd353 100644 --- a/Sources/LyrebirdShoeGaze/Pedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedal.swift @@ -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,46 @@ 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() + } + // MARK: - Subclass hook /// Returns the processed (wet) mono signal for this pedal. diff --git a/Sources/LyrebirdShoeGaze/Pedals/ChorusPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ChorusPedal.swift index 68b5060..9c699d2 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/ChorusPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/ChorusPedal.swift @@ -61,6 +61,12 @@ public final class ChorusPedal: Pedal { private let rateRange: ClosedRange = 0.05 ... 6.0 private let depthRange: ClosedRange = 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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift index 146ae83..b739507 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/DelayPedal.swift @@ -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 = 0.01 ... 1.5 + private let timeRange: ClosedRange = 0.01 ... 5.0 /// Feedback (decay-time) knob range in seconds. private let feedbackRange: ClosedRange = 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. diff --git a/Sources/LyrebirdShoeGaze/Pedals/FeedbackDelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/FeedbackDelayPedal.swift index 63f9126..567ae34 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/FeedbackDelayPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/FeedbackDelayPedal.swift @@ -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 = 0.02 ... 1.5 + private let timeRange: ClosedRange = 0.02 ... 5.0 private let feedbackRange: ClosedRange = 0.1 ... 8.0 private let toneRange: ClosedRange = 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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift index e028c06..1da46c6 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/FlangerPedal.swift @@ -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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift index 7c67c94..d472864 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/ModulationPedal.swift @@ -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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/MultiTapDelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/MultiTapDelayPedal.swift index 8ab5592..42e3108 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/MultiTapDelayPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/MultiTapDelayPedal.swift @@ -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 = 0.01 ... 1.0 + private let timeRange: ClosedRange = 0.01 ... 5.0 private let volRange: ClosedRange = 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] { [ diff --git a/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift index 716eff7..335702a 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/PhaserPedal.swift @@ -68,6 +68,12 @@ public final class PhaserPedal: Pedal { /// Feedback knob range (all-pass feedback gain). private let feedbackRange: ClosedRange = 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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift index 548b4cc..14ff592 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/PingPongDelayPedal.swift @@ -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 = 0.05 ... 1.0 + private let timeRange: ClosedRange = 0.05 ... 5.0 /// Feedback (decay-time) knob range in seconds. private let feedbackRange: ClosedRange = 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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift index 976f65c..12d0070 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/ReverseDelayPedal.swift @@ -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 = 0.05 ... 2.0 + private let timeRange: ClosedRange = 0.05 ... 5.0 private let feedbackRange: ClosedRange = 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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift index f4800d8..bc3604b 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/TremoloPedal.swift @@ -63,6 +63,12 @@ public final class TremoloPedal: Pedal { /// Depth knob range (modulation fraction). private let depthRange: ClosedRange = 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), diff --git a/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift b/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift index 78b59d3..2cf1d8c 100644 --- a/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift +++ b/Sources/LyrebirdShoeGaze/Pedals/VibratoPedal.swift @@ -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), diff --git a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift index 6487dbc..fe91e53 100644 --- a/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/Pedal+Preset.swift @@ -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() } } diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift index 067a4f1..3b967b1 100644 --- a/Sources/LyrebirdShoeGaze/Presets/PedalState.swift +++ b/Sources/LyrebirdShoeGaze/Presets/PedalState.swift @@ -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 = 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) } } diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index f3f3518..97cc5dc 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -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 diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 30b871e..7ab756a 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -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. diff --git a/Sources/LyrebirdShoeGaze/Tempo/NoteDivision.swift b/Sources/LyrebirdShoeGaze/Tempo/NoteDivision.swift new file mode 100644 index 0000000..7bd8258 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tempo/NoteDivision.swift @@ -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" + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift b/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift index b5cae06..223d27c 100644 --- a/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift +++ b/Sources/LyrebirdShoeGaze/Tempo/ShoeGaze+Tempo.swift @@ -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) } } diff --git a/Sources/LyrebirdShoeGaze/Tempo/TempoSync.swift b/Sources/LyrebirdShoeGaze/Tempo/TempoSync.swift new file mode 100644 index 0000000..961f699 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tempo/TempoSync.swift @@ -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) +} diff --git a/Sources/LyrebirdShoeGaze/Tempo/TempoSyncRevision.swift b/Sources/LyrebirdShoeGaze/Tempo/TempoSyncRevision.swift new file mode 100644 index 0000000..8d1b6ca --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tempo/TempoSyncRevision.swift @@ -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 + } +} diff --git a/Sources/LyrebirdShoeGaze/Tempo/TempoSyncableParam.swift b/Sources/LyrebirdShoeGaze/Tempo/TempoSyncableParam.swift new file mode 100644 index 0000000..56d4f96 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Tempo/TempoSyncableParam.swift @@ -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 + + /// 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 + ) { + 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) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ControlMappingStrip.swift b/Sources/LyrebirdShoeGazeUI/ControlMappingStrip.swift new file mode 100644 index 0000000..e2cb40f --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ControlMappingStrip.swift @@ -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))" + } + } +} diff --git a/Sources/LyrebirdShoeGazeUI/NoteGlyphView.swift b/Sources/LyrebirdShoeGazeUI/NoteGlyphView.swift new file mode 100644 index 0000000..5618271 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/NoteGlyphView.swift @@ -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") + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalView.swift b/Sources/LyrebirdShoeGazeUI/PedalView.swift index 3dda223..a2f8cfe 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalView.swift @@ -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 diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 518dd2f..b50e25c 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -664,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) diff --git a/Sources/LyrebirdShoeGazeUI/TempoView.swift b/Sources/LyrebirdShoeGazeUI/TempoView.swift index 22b5c08..fa2fc46 100644 --- a/Sources/LyrebirdShoeGazeUI/TempoView.swift +++ b/Sources/LyrebirdShoeGazeUI/TempoView.swift @@ -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 diff --git a/Tests/LyrebirdShoeGazeTests/NoteDivisionTests.swift b/Tests/LyrebirdShoeGazeTests/NoteDivisionTests.swift new file mode 100644 index 0000000..0fd88ca --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/NoteDivisionTests.swift @@ -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) + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/PedalMappingStripTests.swift b/Tests/LyrebirdShoeGazeTests/PedalMappingStripTests.swift new file mode 100644 index 0000000..d54c795 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/PedalMappingStripTests.swift @@ -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) + } + } +} diff --git a/Tests/LyrebirdShoeGazeTests/TempoSyncTests.swift b/Tests/LyrebirdShoeGazeTests/TempoSyncTests.swift new file mode 100644 index 0000000..6a93052 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/TempoSyncTests.swift @@ -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) + } +} diff --git a/docs/plans/2.2-tempo-synced-parameters.md b/docs/plans/2.2-tempo-synced-parameters.md new file mode 100644 index 0000000..b7274cd --- /dev/null +++ b/docs/plans/2.2-tempo-synced-parameters.md @@ -0,0 +1,219 @@ +# 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 +} +``` + +### `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 — deferred + +A synced param's value is derived, so a CC bound to it is overwritten on the next tempo/division +change. The obvious fix — dropping `.division`-synced params from `ccMappableControls` — is +**deferred**: that list is addressed by a *stable index* (persisted CC bindings resolve by position), +so filtering it live would shift indices and silently re-point or break existing bindings. A correct +implementation needs an index-stable exclusion (e.g. keep the slot but mark it inert while synced), +which is out of scope for this change. Until then, binding a CC to a synced param is allowed but the +tempo wins — documented here as a known limitation, not an oversight. + +## 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.