13 Commits

Author SHA1 Message Date
josh 3ef09a771a docs(help): explain the pre-board and post-board lanes
The Boards & Rigs help section covered boards but not the pre/post-board
chains. Add bullets: pre-board processes the input once before the split and
feeds every board (shared tuner/comp/gate); post-board runs after the boards
are mixed (global reverb/limiter/EQ); both hide when empty; and the whole
pre/board/post path scrolls together while each board scrolls sideways.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-26 15:06:26 -08:00
josh 3f05cfa416 feat(ui): pre-board, board and post-board in one vertical scroller
The board canvas used to fill the remaining height and centre itself, pinning
the pre-board strip above and the post-board strip below — so a tall pre/post
chain clipped instead of scrolling, and the three sections never read as one
signal path. Wrap pre-board → board → post-board in a single vertical
ScrollView so the whole path scrolls top-to-bottom as one page, on macOS and
iOS alike. The transport / palette / routing header stays fixed above it.

BoardFlowView gains a `sizesToContent` mode: it sizes to its chain height and
scrolls only horizontally, so it nests inside the outer vertical scroller with
no competing vertical scroll (a tall parallel split simply grows the page).
The default fill-and-centre behaviour is unchanged for any other caller.

Verified on the iPad simulator: sections stack in signal-flow order and the
board still scrolls horizontally through a long chain.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-26 14:15:41 -08:00
josh 4cae1e6fd0 fix(tunedverb): silence the wash until a moment is captured
An uncaptured TunedVerb has no filter template, so it must output silence —
but the live cross-map was pouring the dry pass-through straight into the
reverb, so every TunedVerb hummed on startup (and looked like a stale
capture surviving a restart). Gate the reverb input by the Capture latch:
`masked * $captured` feeds the reverb zero until the footswitch fires.

Because `captured` is 0 by default, reset to 0 on every graph rebuild
(resetForRebuild) and on engine stop (engineDidStop -> releaseHold), the
same gate also guarantees a fresh app launch or engine restart comes up
silent with no carried-over capture. The analysis side-chain keeps tracking
while gated, so pressing Capture still freezes the current-moment spectrum.

FreezVerb is unaffected: its Freeze holds a working reverb's tail, so it
should produce sound before freezing.

Tests: new wetIsSilentUntilCaptureThenAudible; panShiftsTheLeftLeg and
captureLocksTheFilter... updated to the new contract (capture before
measuring the wash). 856 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-26 14:02:47 -08:00
josh 24ac361c48 fix(ui): import LyrebirdShoeGaze in VerticalParameterSlider
Clears a missing-import warning.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-26 13:43:42 -08:00
josh 52c676605f feat(postboard): shared post-board chain after the board mix
Add a dedicated linear stereo post-board chain that processes the summed
board mix once, after the board split, before the hardware output — for
global reverb, a bus limiter, a final EQ, and the like.

Routing: when a post-chain exists, every BoardOutputMaster writes a shared
stereo mix bus (parameterized output bus indices) instead of hardware; the
post-chain (PostChain + PostChainOutput) reads that mix, runs its pedals in
order, and copies the tail to the hardware outputs. Always stereo-headed
(dual-mono for a mono rig) so mono pedals auto-stereoize per channel.

The chain's head node is inserted at .tail(of: mainGroup), so it evaluates
after every board master regardless of board add order — no re-order on
board add, and no board dropped from the mix. buildPostChain tracks the
chain before wiring it so a mid-build throw stays reclaimable by teardown.

State: additive ShoeGazeState.postChain (nil-when-empty, decodeIfPresent,
byte-identical old-rig round-trip). Edit API (append/insert/remove/move)
mirrors the pre-board chain: capture-from-live, stop/teardown/rebuild. Undo
treats a post-topology change as a full rebuild via id-sequence compare.
UI: a hide-when-empty post-board strip below the boards, symmetric to the
pre-board strip, with palette routing and per-pedal remove through undo.

Bumps the iOS demo's Lyrebird pin to 2.3.0 (onEditingEnded).

Tests: PostBoardChainTests (render, closed-volume silences output,
post-chain-after-every-master ordering, board-add ordering, insert/move/
remove, save/load round-trip with knob, old-rig decode) + post-pedal undo.
855 tests pass. Reviewed (RT-safety + line sweep); the ordering bug both
reviewers caught is fixed at the root and covered by a deterministic test.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-26 00:22:39 -08:00
josh 10a6e122bf feat(midi): MIDI-mappable primary transport footswitch (Capture / Freeze)
Expose a pedal's primary transport footswitch — TunedVerb's Capture, FreezVerb's
Freeze — as a MIDI-mappable action, so a footswitch (Program Change) can trigger
it. Previously only per-pedal Bypass and the looper's transport were mappable.

- New `MIDITransportPedal` protocol (@MainActor): `midiTransportName` + a
  `toggleMIDITransport()` that presses the pedal's primary footswitch. TunedVerb
  (Capture) and FreezVerb (Freeze) conform.
- `MIDIMap.PedalActionKind.pedalPrimaryTransport`, dispatched by MIDIController to
  `toggleMIDITransport()`. Learn / persist / resolve-by-id ride the existing
  pedalAction path (same as the looper actions).
- The mapping sheet lists the action for any `MIDITransportPedal`
  ("Board 2 · TunedVerb · Capture"); the per-pedal control-mapping strip shows a
  badge for it. A future press-to-trigger pedal just conforms and appears.

Tests: conformance + a Program-Change round-trip toggling Capture on/off. Full
suite 846 green; both demos build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 20:11:07 -08:00
josh 9dfadb129d feat(preboard): shared pre-board chain feeding every board
Add a pre-board stage: one linear pedal chain that processes the input once,
before the board split, and feeds every board — for front-of-chain gates /
drive / EQ, and multi-board "voice spray" rigs (one source → N panned boards →
Blend).

Routing: a stable mono feed bus every board taps. `FeedPassThrough` copies the
input source — or, when a pre-chain exists, that chain's mono output — onto the
feed bus (`ensureFeed`/`buildFeed`/`tearDownFeed`). The pre-chain is modeled as
an unfinalized `PedalBoard` fed from the source; a stereo tail folds to mono
(board heads are mono). Empty pre-chain = passthrough, byte-for-byte
behavior-preserving. addBoard taps the feed bus; teardown releases it
remove-before-release.

State: additive `ShoeGazeState.preChain` (`decodeIfPresent` → nil for old rigs,
no format bump; `hasSameRigContent` includes it). `captureState` reads the LIVE
pre-pedals so knob tweaks are saved; `rebuildAllBoards` sets the pre-chain
before building boards.

Edit API: appendPrePedal / insertPrePedal / removePrePedal / movePrePedal —
each folds in live knob values, then a full ordering-safe rig rebuild
(`setPreBoardChain`, mirrors setInputSource; rolls back on failure). Undo: a
pre-chain topology change (compared by id sequence, so knob-only edits stay on
the surgical path) rebuilds from the snapshot, stopping/starting the engine.
`allPedals()` now includes the pre-chain so pre-pedal knob undo resolves.

UI: an inline pre-board strip above the boards — hidden to a "+ Pre" button when
empty; otherwise the pre-pedals (keyed by stable id) with a per-pedal remove and
a "feeds all boards" divider. Palette adds route to the pre-board via a flag
(reset on any dismissal). Add / remove go through the undo wrapper.

Known scope: a pre-board edit resets transient/looper state (full rebuild, like
input-switch — setup-time); chain-router branches read the input directly and
are not fed by the pre-board. Both documented.

Tests: PreBoardChainTests (feeds boards, closed pre-Volume silences every board,
remove restores direct feed, save/load incl. a knob tweak, prior pre-pedal's
knob survives adding another, old-rig decode) + a pre-board undo test. Full
suite 844 green; both demos build. External review + caveman sweep: one blocking
(live knob sync) fixed + regression-tested, all non-blocking addressed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 19:18:04 -08:00
josh 1f5b70edc7 feat(undo): parameter undo for knobs, sliders, switches, selectors
Tier 2 of the rig-undo feature, on the same undo stack as the structural
(tier 1) edits. Records one undo checkpoint when the user finishes changing a
pedal control, so ⌘Z / the ↶ button step back through knob turns and switch
flips as well as add/remove/move.

- UndoEntry.parameter + PedalControlGroup (knob/advancedKnob/slider/switch/
  selector); UndoCoordinator.recordParameterEdit + .parameter handling in
  undo()/redo(). applyParameter re-resolves the LIVE node by (pedalID, group,
  controlLabel) via ShoeGaze.pedal(id:), so an undo lands on the right control
  even after an intervening structural rebuild replaced the pedal's node
  (pedal ids persist through rebuild). old == new records nothing.
- Knobs record via Lyrebird 2.3.0's ParameterKnob.onEditingEnded (one edit per
  drag): PedalView.recordingKnob (main / advanced / mix / level / looper) and
  TempoSyncKnobView.
- Self-contained views (VerticalParameterSlider, PedalSwitchView,
  PedalSelectorKnobView) record via a new \.pedalParameterEditRecorder
  environment closure PedalView installs, capturing pedal.id + the coordinator.
  Slider/selector snapshot node.value at drag start; switch records old→new on
  the committing tap.
- rebuildsOnChange switches/selectors are deliberately NOT recorded (they alter
  graph topology and would fight the structural restore's live-value merge) —
  documented as a known gap, along with tempo-sync division changes.
- Bump the Lyrebird pin to 2.3.0 (the released tag with onEditingEnded), drop
  the dev-time local path override.

Tests: 18 UndoCoordinator tests (knob/slider/switch/selector round-trips,
post-rebuild re-resolution, + a catalogue test asserting unique control labels
per group so the by-label resolution can't mis-target). Full suite 837 green;
both demo schemes build against 2.3.0. External review + caveman sweep: no
blocking findings.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 14:23:00 -08:00
josh a8bd0242a3 feat(undo): multi-level structural undo/redo for rig edits
Add UndoCoordinator: 50-deep undo/redo of structural edits (add/insert/
remove/move pedals in any lane, stereo-split/parallel/merge/unzip routing,
add/remove/move boards, Clear Board). Each edit records a named checkpoint
via a perform(label:) wrapper threaded through the builder, board-flow,
board-bar, and boards-sheet views (injected through the SwiftUI environment,
re-injected onto the boards sheet).

Restore is surgical, not a whole-rig reload: it reconciles board-by-board
(remove added / re-add removed / rebuild changed / reorder) using the same
per-board rebuild path as an ordinary edit, so undo never tears the rig down
— recording, looper buffers, other boards' reverb/delay tails, and
bypass/solo state all survive. It also merges live parameter values by pedal
id, so undoing a topology edit never reverts a knob turned afterwards; a
pedal the edit removed returns with its snapshot values. No-op edits record
nothing (compared via hasSameRigContent). History clears on rig load / new /
switch.

UI: macOS Edit menu (Undo ⌘Z / Redo ⇧⌘Z with dynamic "Undo <action>" titles,
deferring to a text field's own editor while typing); iOS visible ↶/↷ buttons
+ ⌘Z/⇧⌘Z. Rig mute moves from ⌘Z to ⌘M. Help text updated.

Fix: every pedal edit rebuilt the board via BoardState(label:segments:)
without id:, regenerating the board UUID and breaking MIDI board bindings
after any edit. Thread id: board.id through all 10 rebuild sites; add
editingPreservesBoardIdentity regression test.

Tests: 12 UndoCoordinator tests (restore correctness, param preservation,
untouched-board identity, multi-board re-add, depth cap, no-op, throwing
action). Full suite 830 green; both demo schemes build (macOS + iPad).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-25 10:22:51 -08:00
josh 4c09825c2e rename(reverb): Freeze → FreezVerb, and FreezVerb → TunedVerb
Shuffle the two new reverbs' display names:
- the spectral snapshot/hold pedal (was "Freeze") becomes "FreezVerb"
  (FreezePedal → FreezVerbPedal); its Freeze footswitch keeps its label.
- the filter-from-the-current-moment pedal (was "FreezVerb") becomes
  "TunedVerb" (FreezVerbPedal → TunedVerbPedal).

Renames the types, registry keys, category entries, classes, files and tests,
and updates the cross-reference between them. Behaviour unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 20:55:45 -08:00
josh b1e59d2c03 rename(reverb): Freeze Reverb → Freeze
Shorten the pedal's display name to just "Freeze". Renames the type, registry
key, category entry, class (FreezeReverbPedal → FreezePedal) and its files/tests,
and updates the FreezVerb doc cross-reference. Behaviour unchanged.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 20:07:11 -08:00
josh 0873bbd82e feat(reverb): add FreezVerb — filter-from-the-current-moment into a stereo room
A spectral reverb ported from the composer's FilterFromCurrentMoment process.
Press Capture and the spectrum playing at that instant is locked in as a fixed
filter; everything you play afterwards is masked through that frozen spectral
shape and poured into a large reverb. The name plays on the FreeVerb tank at
its core.

- A side-chain SpectralChain (analyze-only) of the dry drives a SpectralCrossMap
  (maxMagnitude, mode 1.0) as a `.dual` stage on a main chain over the dry. While
  live the mask tracks the input; the Capture footswitch sets crossMap.freeze, so
  the captured moment becomes a fixed formant filter on the ongoing signal.
- The masked result feeds a GVerb room (fixed 120 m, as in the original), with a
  Time knob (T60, tempo-syncable) and a Damp knob shaping the tail.
- Mono in, stereo out (channelKind .widener): the reverb is summed to mono and
  placed across the field by a Pan knob (Pan2), replacing the original's
  ambisonic encoding. The time-stretched random-pointer source is dropped — the
  filter is captured straight off the live input by the footswitch.
- `captured` is transport state (a Capture button indicator) and is not
  serialized into presets.

Wired at all four points (+ README catalog). 818 tests pass;
lyrebird_external_review clean (no blocking findings).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 20:02:13 -08:00
josh 843ae5b5f6 feat(reverb): add Freeze Reverb — a true spectral snapshot / infinite hold
A new reverb pedal that captures the sound at the instant you press Freeze and
holds it as an endless, smoothly-sustaining pad while you keep playing over it.

- Phase-vocoder SpectralFreeze (inside a SpectralChain) locks the magnitude
  spectrum of the moment and keeps each partial rotating at its own frequency,
  so the held chord is natural and glassy rather than a looped ring or a
  metallic feedback tank.
- The frozen spectrum is wrapped in a FreeVerb tank (summed to mono) for a
  diffuse, blooming space — the "reverb" half — then gated by a Lag ramp so the
  freeze blooms in and releases out over the Rise knob.
- The dry signal always passes through undelayed; the wash is layered on top
  (Mix hidden, base mix fully wet). The SpectralChain's FFT latency sits only on
  the gated wet path, and a frozen spectrum is uncorrelated with the moved-on
  dry, so there is no comb filtering.
- Latching Freeze footswitch (LED). On release the gate fades the held pad out
  and the return-to-live analysis is deferred until the fade completes (guarded
  by a generation token), so the fade is of the snapshot, not a live delayed
  copy that would comb against the dry.
- `frozen` is transport state (an @UIParam button indicator, like the Looper's
  isPlaying) and is not serialized into presets.

Wired at all four points (+ README catalog). 808 tests pass;
lyrebird_external_review clean (no blocking findings).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-24 18:10:09 -08:00
48 changed files with 3919 additions and 152 deletions
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7", "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
"version" : "2.2.0" "version" : "2.3.0"
} }
}, },
{ {
+78 -4
View File
@@ -55,6 +55,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
private let shoeGaze: ShoeGaze private let shoeGaze: ShoeGaze
private let window: LyrebirdWindow private let window: LyrebirdWindow
/// Multi-level undo / redo for structural rig edits. The same instance backs both the Edit-menu
/// items here and `ShoeGazeBuilderView`'s own edits, so ⌘Z works from the menu and the canvas.
private let undo: UndoCoordinator
/// Foot-controller MIDI input. The macOS engine is never rebuilt, so this is created once and /// Foot-controller MIDI input. The macOS engine is never rebuilt, so this is created once and
/// started at launch. /// started at launch.
private let midi: MIDIController private let midi: MIDIController
@@ -73,6 +77,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
/// match the current bypass state (which may also change from the UI or MIDI). /// match the current bypass state (which may also change from the UI or MIDI).
private var bypassMenuItem: NSMenuItem? private var bypassMenuItem: NSMenuItem?
/// Undo / Redo items, retained so `validateMenuItem(_:)` can enable them and refresh their
/// titles to the next action (e.g. "Undo Add Reverb").
private var undoMenuItem: NSMenuItem?
private var redoMenuItem: NSMenuItem?
/// The Rigs ▸ Set List submenu, retained so its item titles can be refreshed to the current /// The Rigs ▸ Set List submenu, retained so its item titles can be refreshed to the current
/// library order each time it opens (via `menuNeedsUpdate(_:)`). /// library order each time it opens (via `menuNeedsUpdate(_:)`).
private var setListMenu: NSMenu? private var setListMenu: NSMenu?
@@ -109,6 +118,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
self.coreDriver = coreDriver self.coreDriver = coreDriver
self.engine = engine self.engine = engine
self.shoeGaze = shoeGaze self.shoeGaze = shoeGaze
self.undo = UndoCoordinator(shoeGaze: shoeGaze)
self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze) self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze)
self.window = LyrebirdWindow( self.window = LyrebirdWindow(
title: "ShoeGaze Builder — Lyrebird Pedalboard", title: "ShoeGaze Builder — Lyrebird Pedalboard",
@@ -158,12 +168,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
let driver: CoreAudioDriver = coreDriver let driver: CoreAudioDriver = coreDriver
let rigLibrary: RigLibraryStore = library let rigLibrary: RigLibraryStore = library
let midiController: MIDIController = midi let midiController: MIDIController = midi
let undoCoordinator: UndoCoordinator = undo
window.open { window.open {
ShoeGazeBuilderView( ShoeGazeBuilderView(
shoeGaze: session, shoeGaze: session,
library: rigLibrary, library: rigLibrary,
hardwareSampleRate: { driver.deviceSampleRate }, hardwareSampleRate: { driver.deviceSampleRate },
midi: midiController midi: midiController,
undo: undoCoordinator
) )
} }
anchorWindowLeft() anchorWindowLeft()
@@ -302,6 +314,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e") addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e")
addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i") addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i")
// Edit menu — multi-level undo / redo of structural rig edits (add / remove / move pedals,
// boards, routing). ⌘Z / ⇧⌘Z; titles + enabled state refresh in `validateMenuItem(_:)`.
let editMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(editMenuItem)
let editMenu: NSMenu = NSMenu(title: "Edit")
editMenuItem.submenu = editMenu
self.undoMenuItem = addItem(
to: editMenu,
title: "Undo",
action: #selector(undoAction(_:)),
key: "z"
)
self.redoMenuItem = addItem(
to: editMenu,
title: "Redo",
action: #selector(redoAction(_:)),
key: "z"
)
self.redoMenuItem?.keyEquivalentModifierMask = [.command, .shift]
// Board menu — add board + transport. // Board menu — add board + transport.
let boardMenuItem: NSMenuItem = NSMenuItem() let boardMenuItem: NSMenuItem = NSMenuItem()
mainMenu.addItem(boardMenuItem) mainMenu.addItem(boardMenuItem)
@@ -311,13 +343,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
// config and the mismatch alert), so the Board menu only adds boards. // config and the mismatch alert), so the Board menu only adds boards.
addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b") addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b")
boardMenu.addItem(NSMenuItem.separator()) boardMenu.addItem(NSMenuItem.separator())
// ⌘Z toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry // ⌘M toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry
// passthrough). Owns the ⌘Z key equivalent on macOS; the in-window view binds it on iOS. // passthrough). ⌘Z / ⇧⌘Z are Undo / Redo (Edit menu); the in-window view binds ⌘M on iOS.
self.muteMenuItem = addItem( self.muteMenuItem = addItem(
to: boardMenu, to: boardMenu,
title: "Mute Rig", title: "Mute Rig",
action: #selector(toggleMuteAction(_:)), action: #selector(toggleMuteAction(_:)),
key: "z" key: "m"
) )
// Bypass Rig routes every board to its dry input (pedals skipped) — distinct from Mute's // Bypass Rig routes every board to its dry input (pedals skipped) — distinct from Mute's
// hard silence. No key equivalent: ⌘B is Add Board, and Bypass has a prominent on-screen button. // hard silence. No key equivalent: ⌘B is Add Board, and Bypass has a prominent on-screen button.
@@ -401,6 +433,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
// MARK: - Menu actions // MARK: - Menu actions
/// Reverts the most recent structural rig edit — unless a text field is being edited, in which
/// case its own field editor handles ⌘Z (so typing a rig name keeps normal text undo).
@objc private func undoAction(_ sender: Any?) {
if let editor: NSText = NSApp.keyWindow?.firstResponder as? NSText,
let manager: UndoManager = editor.undoManager {
manager.undo()
return
}
undo.undo()
}
/// Re-applies the most recently undone structural rig edit, deferring to a text field's own redo
/// while one is being edited (mirrors ``undoAction(_:)``).
@objc private func redoAction(_ sender: Any?) {
if let editor: NSText = NSApp.keyWindow?.firstResponder as? NSText,
let manager: UndoManager = editor.undoManager {
manager.redo()
return
}
undo.redo()
}
/// Opens (or re-opens) the Help window hosting the shared ``HelpView``. /// Opens (or re-opens) the Help window hosting the shared ``HelpView``.
@objc private func showHelpAction(_ sender: Any?) { @objc private func showHelpAction(_ sender: Any?) {
let helpWidth: CGFloat = 560 let helpWidth: CGFloat = 560
@@ -476,9 +530,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
@objc private func addBoardAction(_ sender: Any?) { @objc private func addBoardAction(_ sender: Any?) {
var created: PedalBoard? var created: PedalBoard?
do { do {
// Record as an undo checkpoint, matching the in-window Add Board.
try undo.perform("Add Board") {
let board: PedalBoard = try shoeGaze.addBoard() let board: PedalBoard = try shoeGaze.addBoard()
created = board created = board
try shoeGaze.finalizeBoard(board) try shoeGaze.finalizeBoard(board)
}
} catch { } catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) } if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilder] addBoard failed: \(error)") print("[ShoeGazeBuilder] addBoard failed: \(error)")
@@ -547,6 +604,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
menuItem.state = shoeGaze.rigBypassed ? .on : .off menuItem.state = shoeGaze.rigBypassed ? .on : .off
return true return true
} }
if menuItem == undoMenuItem {
// Name the next action so the menu reads "Undo Add Reverb"; disable when there's none.
if let label: String = undo.undoActionLabel {
menuItem.title = "Undo \(label)"
} else {
menuItem.title = "Undo"
}
return undo.canUndo
}
if menuItem == redoMenuItem {
if let label: String = undo.redoActionLabel {
menuItem.title = "Redo \(label)"
} else {
menuItem.title = "Redo"
}
return undo.canRedo
}
if setListMenuItems.contains(menuItem) { if setListMenuItems.contains(menuItem) {
// A slot is live only when the library actually holds a rig at that position. // A slot is live only when the library actually holds a rig at that position.
return menuItem.tag < library.entries.count return menuItem.tag < library.entries.count
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54", "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
"version" : "2.0.0" "version" : "2.3.0"
} }
}, },
{ {
@@ -31,7 +31,8 @@ struct ShoeGazeBuilderiOSApp: App {
library: model.library, library: model.library,
hardwareSampleRate: { model.hardwareSampleRate }, hardwareSampleRate: { model.hardwareSampleRate },
onEnableLiveInput: { model.enableLiveInput() }, onEnableLiveInput: { model.enableLiveInput() },
midi: model.midi midi: model.midi,
undo: model.undo
) )
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.task { await model.startLibrary() } .task { await model.startLibrary() }
@@ -40,6 +40,10 @@ final class ShoeGazeBuilderiOSAppModel {
/// is rebuilt with an input channel); the `@Observable` change re-binds the hosting view. /// is rebuilt with an input channel); the `@Observable` change re-binds the hosting view.
private(set) var shoeGaze: ShoeGaze private(set) var shoeGaze: ShoeGaze
/// Multi-level undo / redo for structural rig edits, bound to the current `shoeGaze`. Recreated
/// when `shoeGaze` is swapped by the live-input rebuild (history resets across that rebuild).
private(set) var undo: UndoCoordinator
private var engine: SynthesisEngine private var engine: SynthesisEngine
private var iosDriver: iOSAudioDriver private var iosDriver: iOSAudioDriver
@@ -70,6 +74,7 @@ final class ShoeGazeBuilderiOSAppModel {
self.engine = built.engine self.engine = built.engine
self.iosDriver = built.driver self.iosDriver = built.driver
self.shoeGaze = shoeGaze self.shoeGaze = shoeGaze
self.undo = UndoCoordinator(shoeGaze: shoeGaze)
// Restore the autosaved working rig if there is one; otherwise seed a default board. Operate // Restore the autosaved working rig if there is one; otherwise seed a default board. Operate
// on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored // on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored
@@ -197,6 +202,8 @@ final class ShoeGazeBuilderiOSAppModel {
self.engine = rebuilt.engine self.engine = rebuilt.engine
self.iosDriver = rebuilt.driver self.iosDriver = rebuilt.driver
self.shoeGaze = rebuilt.shoeGaze self.shoeGaze = rebuilt.shoeGaze
// Bind undo to the new session; history resets across the engine rebuild.
self.undo = UndoCoordinator(shoeGaze: rebuilt.shoeGaze)
do { do {
// Teardown already happened, so a restore failure can only recover by seeding. // Teardown already happened, so a restore failure can only recover by seeding.
+3 -3
View File
@@ -1,5 +1,5 @@
{ {
"originHash" : "c8855e41a403b5b1fccd9ccb4b3ef4d75c4307590ae6a0b8e985e71c41011e09", "originHash" : "6094cf70541e0593db7264ad9c75576ce239a5a5885ca4b783b5444793b6fee5",
"pins" : [ "pins" : [
{ {
"identity" : "linenoise-swift", "identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7", "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
"version" : "2.2.0" "version" : "2.3.0"
} }
}, },
{ {
+1 -1
View File
@@ -24,7 +24,7 @@ let package = Package(
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]), .library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
], ],
dependencies: [ dependencies: [
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "2.0.0"), .package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "2.3.0"),
], ],
targets: [ targets: [
// Both targets depend on the core `Lyrebird` product AND `LyrebirdUI`. // Both targets depend on the core `Lyrebird` product AND `LyrebirdUI`.
+1 -1
View File
@@ -49,7 +49,7 @@ signal (no hardware needed) or on live guitar through an audio input.
| Modulation | Tremolo, Phaser, Script Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator | | Modulation | Tremolo, Phaser, Script Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator |
| Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave | | Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave |
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay, DL4 | | Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay, DL4 |
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb | | Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb, FreezVerb, TunedVerb |
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Karplus Resonator, Looper, Tape Looper | | Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Karplus Resonator, Looper, Tape Looper |
| Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim | | Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim |
| Cabinet | Cabinet (speaker-voice + microphone modeling) | | Cabinet | Cabinet (speaker-voice + microphone modeling) |
@@ -1,5 +1,5 @@
{ {
"originHash" : "13b4323e9d41dfdff1c6aeac595cff272eb4eee9cc1a3146483bdaf8543bc103", "originHash" : "9e278ce69e19f7dabaaaed1b75fb6112a02ece1e30e2aad82c12942c5ddeb192",
"pins" : [ "pins" : [
{ {
"identity" : "linenoise-swift", "identity" : "linenoise-swift",
@@ -15,8 +15,8 @@
"kind" : "remoteSourceControl", "kind" : "remoteSourceControl",
"location" : "https://realizedsound.mooo.com/josh/Lyrebird", "location" : "https://realizedsound.mooo.com/josh/Lyrebird",
"state" : { "state" : {
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54", "revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
"version" : "2.0.0" "version" : "2.3.0"
} }
}, },
{ {
@@ -80,6 +80,12 @@ final class BoardOutputMaster: SynthesizerBase {
/// bypass source so a bypassed board passes its untouched input straight through. /// bypass source so a bypassed board passes its untouched input straight through.
private let dryInputBusIndex: Int private let dryInputBusIndex: Int
/// Destination buses for the master's stereo output — hardware 0 / 1 by default. When a
/// post-board chain exists, the masters are pointed at a shared **mix bus** instead, and the
/// post-chain reads that mix and writes hardware. All boards share the same destination.
private let outputLeftBusIndex: Int
private let outputRightBusIndex: Int
// MARK: - Constants // MARK: - Constants
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed /// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
@@ -99,10 +105,18 @@ final class BoardOutputMaster: SynthesizerBase {
/// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board, /// - boardOutputBusRightIndex: Right board output bus index for a stereo (width-2) board,
/// or `nil` for a mono board (the signal is panned to centre instead). /// or `nil` for a mono board (the signal is panned to centre instead).
/// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source. /// - dryInputBusIndex: The board's head-bus index, read as the dry bypass source.
init(boardOutputBusIndex: Int, boardOutputBusRightIndex: Int? = nil, dryInputBusIndex: Int) { init(
boardOutputBusIndex: Int,
boardOutputBusRightIndex: Int? = nil,
dryInputBusIndex: Int,
outputLeftBusIndex: Int = 0,
outputRightBusIndex: Int = 1
) {
self.boardOutputBusIndex = boardOutputBusIndex self.boardOutputBusIndex = boardOutputBusIndex
self.boardOutputBusRightIndex = boardOutputBusRightIndex self.boardOutputBusRightIndex = boardOutputBusRightIndex
self.dryInputBusIndex = dryInputBusIndex self.dryInputBusIndex = dryInputBusIndex
self.outputLeftBusIndex = outputLeftBusIndex
self.outputRightBusIndex = outputRightBusIndex
super.init() super.init()
} }
@@ -131,15 +145,15 @@ final class BoardOutputMaster: SynthesizerBase {
let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry) let switchedRight: any ValidGeneratorInput = applyBypass(wet: boardOutRight, dry: dry)
let gainedRight: any ValidGeneratorInput = let gainedRight: any ValidGeneratorInput =
((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain ((switchedRight * smoothedSelect) * $masterGain) * rigOutputGain
output(bus: 0, source: gainedLeft) output(bus: outputLeftBusIndex, source: gainedLeft)
output(bus: 1, source: gainedRight) output(bus: outputRightBusIndex, source: gainedRight)
} else { } else {
// Mono board: write the mono signal to both hardware buses at unity (0 dB). Using an // Mono board: write the mono signal to both hardware buses at unity (0 dB). Using an
// equal-power `Pan2` to centre would drop each channel by 3 dB (×0.707) — power-correct // equal-power `Pan2` to centre would drop each channel by 3 dB (×0.707) — power-correct
// for a true pan, but a mono guitar rig should come out at the same level it went in, so // for a true pan, but a mono guitar rig should come out at the same level it went in, so
// the signal is copied to left and right directly instead. // the signal is copied to left and right directly instead.
output(bus: 0, source: gainedLeft) output(bus: outputLeftBusIndex, source: gainedLeft)
output(bus: 1, source: gainedLeft) output(bus: outputRightBusIndex, source: gainedLeft)
} }
} }
@@ -0,0 +1,44 @@
// FeedPassThrough.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Internal synthesizer that copies one mono bus straight to another — the writer of the shared
/// **feed bus** that every board taps.
///
/// The feed bus sits between the input source and the boards: a `FeedPassThrough` copies either the
/// raw input source (when there is no pre-board chain) or the pre-board chain's mono output onto a
/// single stable feed bus, and every board's input tap reads that feed bus. Keeping the feed bus
/// stable means a pre-board edit only rebuilds the pre-chain + this one node, never the boards.
///
/// Unlike ``TestLoopTap`` / ``HardwareInputPassThrough`` it carries no input-mute gain: the input
/// mute lives on the per-board taps (downstream of the feed), so a tail-producing pedal in the
/// pre-board chain is unaffected by it.
///
/// - Note: Must be removed from the engine before the feed bus it writes is released.
final class FeedPassThrough: SynthesizerBase {
/// Index of the bus to read from — the input source bus, or the pre-board chain's mono output.
private let inputBusIndex: Int
/// Index of the shared feed bus to write to.
private let outputBusIndex: Int
/// Creates a pass-through that copies `inputBusIndex` to `outputBusIndex`.
///
/// - Parameters:
/// - inputBusIndex: Bus to read from (input source, or pre-board chain output).
/// - outputBusIndex: The shared feed bus to write to.
init(inputBusIndex: Int, outputBusIndex: Int) {
self.inputBusIndex = inputBusIndex
self.outputBusIndex = outputBusIndex
super.init()
}
override func build() {
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
}
}
@@ -417,6 +417,8 @@ public final class MIDIController {
(pedal as? LooperPedal)?.cycleSyncMode() (pedal as? LooperPedal)?.cycleSyncMode()
case .looperTrack(let index): case .looperTrack(let index):
(pedal as? LooperPedal)?.tapTrack(index) (pedal as? LooperPedal)?.tapTrack(index)
case .pedalPrimaryTransport:
(pedal as? MIDITransportPedal)?.toggleMIDITransport()
} }
} }
@@ -114,6 +114,10 @@ public struct MIDIMap: Codable, Equatable, Sendable {
/// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and /// Looper: taps track `index` (0 = A) — selects it, or mutes it if already selected and
/// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots. /// recorded (`LooperPedal.tapTrack(_:)`), matching the A/B/C/D dots.
case looperTrack(index: Int) case looperTrack(index: Int)
/// Toggles a pedal's primary transport footswitch — any ``MIDITransportPedal`` (e.g.
/// TunedVerb's Capture, FreezVerb's Freeze). Dispatched to `toggleMIDITransport()`.
case pedalPrimaryTransport
} }
// MARK: - Switch binding // MARK: - Switch binding
@@ -0,0 +1,25 @@
// MIDITransportPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A pedal with a primary **transport footswitch** — a momentary, latching action beyond generic
/// bypass (e.g. TunedVerb's *Capture*, FreezVerb's *Freeze*) — that can be driven by a MIDI
/// footswitch.
///
/// Conforming makes the action appear in the MIDI mapping sheet automatically and lets a mapped
/// Program Change fire it: the sheet lists `midiTransportName`, and `MIDIController` calls
/// ``toggleMIDITransport()`` for a `PedalActionKind/pedalPrimaryTransport` binding. A pedal with a
/// richer transport surface (the looper) is handled by its own dedicated action kinds instead.
@MainActor
public protocol MIDITransportPedal: AnyObject {
/// Short display name of the primary transport footswitch (e.g. `"Capture"`, `"Freeze"`), shown
/// in the MIDI mapping sheet after the pedal name.
var midiTransportName: String { get }
/// Toggles the primary transport footswitch — called when a mapped MIDI footswitch fires. Same
/// effect as pressing the pedal's on-screen footswitch.
func toggleMIDITransport()
}
+2
View File
@@ -123,6 +123,8 @@ public extension PedalType {
static let springReverb = PedalType("Spring Reverb") static let springReverb = PedalType("Spring Reverb")
static let reverseReverb = PedalType("Reverse Reverb") static let reverseReverb = PedalType("Reverse Reverb")
static let granularReverb = PedalType("Granular Reverb") static let granularReverb = PedalType("Granular Reverb")
static let freezVerb = PedalType("FreezVerb")
static let tunedVerb = PedalType("TunedVerb")
// Pitch & octave // Pitch & octave
static let octaveSplitter = PedalType("Octave Splitter") static let octaveSplitter = PedalType("Octave Splitter")
@@ -0,0 +1,254 @@
// FreezVerbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import LyrebirdSynth
import LyrebirdUI
/// A true freeze-and-hold — press **Freeze** and the sound playing at that instant is
/// captured and held as an infinite, smoothly-sustaining pad while you keep playing over it.
///
/// Unlike a feedback-tank "infinite reverb" (which just pushes a reverb's decay toward forever and
/// smears everything you play into the wash), this takes a genuine **spectral snapshot**: a
/// phase-vocoder (`SpectralFreeze`) locks the magnitude spectrum of the moment you engage it and
/// keeps each partial rotating at its own frequency, so the held chord sounds natural and glassy
/// rather than a static loop or a metallic ring. That frozen spectrum is then wrapped in a `FreeVerb`
/// tank for a diffuse, blooming space — the "reverb" half of the name.
///
/// The dry signal always passes straight through, so you solo or comp over the held pad; the frozen
/// wash is layered on top (the wet/dry Mix knob is hidden and the base `mix` stays fully wet). Press
/// Freeze again to release it — the pad fades out over **Rise** and live analysis resumes, ready for
/// the next snapshot.
///
/// ## Knobs
/// - `verb`: Size of the reverb space wrapped around the frozen pad. Range `[0, 1]`: bigger = washier.
/// - `tone`: Brightness of the pad. Range `[0, 1]`: `0` = dark, `1` = bright.
/// - `rise`: Fade time in seconds as the freeze blooms in and releases out. Range `[0.02, 4.0]`.
///
/// ## Transport
/// - `Freeze`: latching footswitch — press to snapshot and hold, press again to release.
public final class FreezVerbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Snapshot the moment and hold it forever — a spectral freeze wrapped in a blooming wash."
}
/// The pad is layered over the untouched dry signal, so a wet/dry Mix knob is meaningless — hide
/// it and keep the base `mix` fully wet.
public override var showsMixControl: Bool { false }
// MARK: - Parameters
/// Size of the reverb space wrapped around the frozen pad. Range `[0, 1]`: bigger = washier.
@UIParam public var verb: Double = 0.7
/// Brightness of the pad. Range `[0, 1]`: `0` = dark, `1` = bright.
@UIParam public var tone: Double = 0.5
/// Fade time in seconds as the freeze blooms in and releases out. Range `[0.02, 4.0]`.
@UIParam public var rise: Double = 0.4
// MARK: - Internal live state (read by the audio graph)
/// `1` while a snapshot is held, else `0`. Drives the pad's fade gate and the Freeze footswitch
/// LED. Transport state, not a preset control — captured neither by `captureState` nor restored.
@UIParam public var frozen: Double = 0.0
// MARK: - Constants
/// FFT frame size for the phase-vocoder freeze. Larger = finer frequency resolution (smoother
/// held chords) at the cost of more latency on the wet path; the dry path is never delayed.
private static let fftSize: Int = 2048
/// Samples between FFT hops (75% overlap at `fftSize` 2048) — fine enough for a clean, artifact-
/// free resynthesis of the held spectrum.
private static let hopSize: Int = 512
/// FreeVerb is run fully wet on the pad; the pedal's own dry/wet balance is the `frozen` gate plus
/// the base `mix`, so the tank should contribute none of its own dry path.
private let verbMix: Double = 1.0
/// Gain folding FreeVerb's two decorrelated channels to mono — a conservative trim (the channels
/// are not identical) that leaves output headroom.
private let stereoSumGain: Double = 0.5
/// Floor on the release-fade delay, in seconds. On release the gate ramps down over `rise`, but we
/// keep the snapshot playing until the fade has essentially finished; this ensures even the
/// shortest `rise` still defers the return-to-live by a sensible minimum.
private static let minReleaseDefer: Double = 0.05
// MARK: - Ranges
private let unitRange: ClosedRange<Double> = 0.0 ... 1.0
private let riseRange: ClosedRange<Double> = 0.02 ... 4.0
// MARK: - Live generator references (rebuilt each `effect(_:)`)
/// The live spectral-freeze processor the Freeze footswitch drives. Recreated on every graph
/// rebuild, so the button always acts on the current instance.
private var freezeProcessor: SpectralFreeze?
/// Mirror of the held state, so a toggle knows which way to go and the LED survives a rebuild.
private var isFrozen: Bool = false
/// Bumped on every freeze, release, rebuild, and teardown. A pending deferred return-to-live
/// (``completeRelease(generation:)``) only acts when its captured generation still matches, so a
/// re-freeze (or any state change) during the release fade cancels it.
private var releaseGeneration: Int = 0
// MARK: - Knobs
public override var effectKnobs: [PedalKnob] {
[
PedalKnob(label: "Verb", node: $verb, range: unitRange),
PedalKnob(label: "Tone", node: $tone, range: unitRange),
PedalKnob(label: "Rise", node: $rise, range: riseRange),
]
}
// MARK: - Transport
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(
label: "Freeze",
indicator: $frozen,
dynamicLabel: { [weak self] in (self?.isFrozen ?? false) ? "Release" : "Freeze" }
) { [weak self] in self?.toggleFreeze() }
]
}
/// `true` while a snapshot is held. Exposed for UI / tests.
public var holding: Bool { isFrozen }
/// Snapshot-and-hold, or release a held snapshot. Latched by the Freeze footswitch.
public func toggleFreeze() {
if isFrozen {
// Release: drop the gate (the pad fades over `rise`) but keep the snapshot *playing*, and
// only return the processor to live analysis once the fade has finished. If we unfroze now,
// the still-open fade would carry a live, FFT-delayed copy of the dry signal — combing
// against the undelayed dry. Deferring the unfreeze fades the actual held spectrum instead.
isFrozen = false
frozen = 0.0
releaseGeneration += 1
let generation: Int = releaseGeneration
let fadeSeconds: Double = max(rise, FreezVerbPedal.minReleaseDefer)
DispatchQueue.main.asyncAfter(deadline: .now() + fadeSeconds) { [weak self] in
self?.completeRelease(generation: generation)
}
} else {
releaseGeneration += 1 // cancel any pending deferred release
freezeProcessor?.freeze()
isFrozen = true
frozen = 1.0 // bloom the pad in over `rise`
}
}
/// Returns the processor to live analysis after a release fade, unless a newer freeze/release (or a
/// rebuild/teardown) has superseded this one.
private func completeRelease(generation: Int) {
guard generation == releaseGeneration, !isFrozen else { return }
freezeProcessor?.unfreeze()
}
// MARK: - Init
/// Creates a freeze-and-hold pedal.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "FreezVerb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: 1.0
)
}
// MARK: - Effect
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
// `effect()` re-runs on every add/rebuild. Start from a clean, released state so the button
// never holds a reference to a discarded freeze processor.
resetForRebuild()
// Phase-vocoder spectral freeze: live analysis until `freeze()` captures the current spectrum,
// then an infinite, naturally-rotating held pad regardless of further input.
let freeze: SpectralFreeze = SpectralFreeze(fftSize: FreezVerbPedal.fftSize)
freezeProcessor = freeze
let pad: SpectralChain.Audio = SpectralChain.Audio(
input: dry,
fftSize: FreezVerbPedal.fftSize,
hopSize: FreezVerbPedal.hopSize,
stages: [.mono(freeze)]
)
// Wrap the held spectrum in a diffuse reverb space. Tone brightens by *reducing* FreeVerb's
// damping (`damping = 1 − tone`): tone 1 = bright (little damping), tone 0 = dark.
let damping: any ValidGeneratorInput = 1.0 - $tone
let stereoVerb: FreeVerb.Audio = FreeVerb.Audio(
source: pad,
roomSize: $verb,
damping: damping,
mix: verbMix,
sampleRate: sampleRate
)
let monoVerb: SumChannels.Audio = SumChannels.Audio(input: stereoVerb, mul: stereoSumGain)
// The pad is audible only while a snapshot is held; the gate ramps over `rise` so engaging or
// releasing the freeze blooms rather than clicks. Live analysis (gate 0) stays silent.
let gate: Lag.Control = Lag.Control(input: $frozen, time: $rise)
// Dry always passes through; the frozen wash is layered on top.
return dry + (monoVerb * gate)
}
// MARK: - Lifecycle
/// Releases any held snapshot when the engine stops — a halted engine can't keep a pad rotating.
public override func engineDidStop() {
releaseHold()
}
/// Releases before this instance is discarded on a rig teardown.
public override func rigWillTeardown() {
releaseHold()
}
// MARK: - Helpers
/// Drops any held snapshot and returns the pad to silence.
private func releaseHold() {
releaseGeneration += 1 // cancel any pending deferred release
freezeProcessor?.unfreeze()
isFrozen = false
frozen = 0.0
}
/// Clears the live generator reference and the held state so a graph rebuild starts fresh.
/// Called at the top of ``effect(_:)``.
private func resetForRebuild() {
releaseGeneration += 1 // cancel any pending deferred release against the old processor
freezeProcessor = nil
isFrozen = false
frozen = 0.0
}
}
// MARK: - MIDI transport
extension FreezVerbPedal: MIDITransportPedal {
/// The Freeze footswitch is the mappable transport action.
public var midiTransportName: String { "Freeze" }
public func toggleMIDITransport() { toggleFreeze() }
}
@@ -0,0 +1,262 @@
// TunedVerbPedal.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
import LyrebirdUI
/// A spectral *filter-from-the-current-moment* reverb — press **Capture** and the spectrum playing
/// at that instant is locked in as a fixed filter, and everything you play afterwards is poured
/// through that frozen spectral shape into a big reverb.
///
/// Where ``FreezVerbPedal`` holds a snapshot as a *sounding* pad, this holds a snapshot as a
/// *filter*. A `SpectralCrossMap` masks the live spectrum bin-by-bin against a template taken from a
/// side-chain analysis of the input: while live, the template tracks what you play; press Capture and
/// the template freezes, so the captured moment becomes a fixed formant mask on your ongoing signal.
/// The masked result feeds a large `GVerb` room (fixed 120 m) for a cavernous tail, and a **Pan**
/// knob places the stereo wash anywhere across the field.
///
/// Ported from the composer's `FilterFromCurrentMoment` process: the original drew its filter from a
/// random pointer into a time-stretched buffer and spatialised with ambisonics; here the filter is
/// captured straight off the live input by the footswitch, and the output is plain stereo via the
/// Pan knob.
///
/// ## Knobs
/// - `time`: Reverb tail length (GVerb T60) in seconds. Range `[0.5, 12.0]`.
/// - `damp`: High-frequency damping of the tail. Range `[0, 1]`: `0` = bright, `1` = dark.
/// - `pan`: Stereo position of the wash. Range `[-1, +1]`: `-1` = hard left, `+1` = hard right.
///
/// ## Transport
/// - `Capture`: latching footswitch — press to lock the current-moment spectrum as the filter, press
/// again to return to live tracking.
public final class TunedVerbPedal: Pedal {
/// One-line description shown in the picker and info panel.
public override var summary: String {
"Capture a moment's spectrum as a filter and pour your playing through it into a vast room."
}
/// Mono in, stereo out: the reverb wash is panned across the field by the ``pan`` knob.
public override var channelKind: PedalChannelKind { .widener }
// MARK: - Parameters
/// Reverb tail length (GVerb T60) in seconds. Range `[0.5, 12.0]`.
@UIParam public var time: Double = 6.0
/// High-frequency damping of the tail. Range `[0, 1]`: `0` = bright, `1` = dark.
@UIParam public var damp: Double = 0.5
/// Stereo position of the wash. Range `[-1, +1]`: `-1` = hard left, `+1` = hard right.
@UIParam public var pan: Double = 0.0
// MARK: - Internal live state (read by the audio graph)
/// `1` while the filter is locked to a captured moment, else `0`. Drives the Capture footswitch
/// LED. Transport state — not a preset control, so neither captured nor restored.
@UIParam public var captured: Double = 0.0
// MARK: - Constants
/// FFT frame size for the spectral cross-map. Matches the composer's original process — large
/// enough for a finely-resolved formant filter at the cost of latency on the wet path (the dry
/// path is never delayed).
private static let fftSize: Int = 4096
/// Samples between FFT hops (75% overlap at `fftSize` 4096).
private static let hopSize: Int = 1024
/// GVerb room size in metres — fixed, as in the original process. Large, for a cavernous tail.
private let roomSize: Double = 120.0
/// Cross-map blend: `1.0` = full spectral bandpass mask (loud template bins pass, quiet bins are
/// attenuated). Matches the original process.
private let crossMapMode: Double = 1.0
/// GVerb dry level — kept at `0` so the wet path is pure reverb; the base `mix` provides the
/// dry/wet blend.
private let verbDryLevel: Double = 0.0
/// Gain folding GVerb's two decorrelated channels to mono before the pan — a conservative trim
/// (the channels are not identical) that leaves output headroom.
private let stereoSumGain: Double = 0.5
// MARK: - Ranges
private let timeRange: ClosedRange<Double> = 0.5 ... 12.0
private let dampRange: ClosedRange<Double> = 0.0 ... 1.0
private let panRange: ClosedRange<Double> = -1.0 ... 1.0
// MARK: - Live generator references (rebuilt each `wideEffect(_:)`)
/// The spectral cross-map the Capture footswitch locks. Recreated on every rebuild so the button
/// always acts on the current instance.
private var crossMap: SpectralCrossMap?
/// Mirror of the locked state, so a toggle knows which way to go and the LED survives a rebuild.
private var isCaptured: Bool = false
// 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),
PedalKnob(label: "Damp", node: $damp, range: dampRange),
PedalKnob(label: "Pan", node: $pan, range: panRange),
]
}
// MARK: - Transport
public override var effectTransportButtons: [PedalButton] {
[
PedalButton(
label: "Capture",
indicator: $captured,
dynamicLabel: { [weak self] in (self?.isCaptured ?? false) ? "Live" : "Capture" }
) { [weak self] in self?.toggleCapture() }
]
}
/// `true` while a moment's spectrum is locked as the filter. Exposed for UI / tests.
public var holding: Bool { isCaptured }
/// Lock the current-moment spectrum as the filter, or return to live tracking. Latched by the
/// Capture footswitch. Before the graph is built `crossMap` is nil and only the latch/LED state
/// moves; `resetForRebuild()` then clears it on the next build so the two never drift apart.
public func toggleCapture() {
if isCaptured {
crossMap?.freeze = false
isCaptured = false
captured = 0.0
} else {
crossMap?.freeze = true
isCaptured = true
captured = 1.0
}
}
// MARK: - Init
/// Creates a filter-from-the-current-moment TunedVerb.
///
/// - Parameters:
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
public init(
inputBus: Int = 0,
outputBus: Int = 0
) {
super.init(
name: "TunedVerb",
inputBus: inputBus,
outputBus: outputBus,
initialMix: 0.4
)
}
// MARK: - Effect
public override func wideEffect(
_ dry: any ValidGeneratorInput
) -> (left: any ValidGeneratorInput, right: any ValidGeneratorInput) {
// `wideEffect()` re-runs on every add/rebuild. Start from a clean, live-tracking state so the
// button never holds a reference to a discarded cross-map.
resetForRebuild()
// Side-chain: a continuous analysis of the live input. While the cross-map is live it captures
// its filter template from this each hop; once the footswitch sets `freeze`, the last template
// is held and this side-chain is ignored — the captured moment becomes the fixed filter.
let sideChain: SpectralChain.Audio = SpectralChain.Audio(
input: dry,
fftSize: TunedVerbPedal.fftSize,
hopSize: TunedVerbPedal.hopSize,
analyzeOnly: true
)
let map: SpectralCrossMap = SpectralCrossMap(
fftSize: TunedVerbPedal.fftSize,
normalization: .maxMagnitude
)
map.mode = crossMapMode
crossMap = map
// Main chain: the live input masked by the (tracking or captured) template.
let masked: SpectralChain.Audio = SpectralChain.Audio(
input: dry,
fftSize: TunedVerbPedal.fftSize,
hopSize: TunedVerbPedal.hopSize,
stages: [.dual(map, sideChain: sideChain)]
)
// Gate the wash by the Capture latch. Until a moment is captured there is no filter template,
// so the reverb must be fed silence rather than the live pass-through — otherwise an
// uncaptured TunedVerb pours the dry signal straight into the tail. `captured` is `0` until the
// footswitch fires and is reset to `0` on every rebuild and on engine stop (`resetForRebuild`
// / `releaseHold`), so a fresh app launch or an engine restart comes up silent with no stale
// capture. The analysis side-chain inside `masked` keeps tracking while gated, so pressing
// Capture still freezes the current-moment spectrum.
let gatedIntoVerb: any ValidGeneratorInput = masked * $captured
// A large room for a cavernous tail; `time` sets the T60, `damp` the brightness.
let reverb: GVerb.Audio = GVerb.Audio(
source: gatedIntoVerb,
roomSize: roomSize,
reverbTime: $time,
damping: $damp,
dryLevel: verbDryLevel,
sampleRate: sampleRate
)
// GVerb is natively stereo (two decorrelated channels); fold to mono, then pan the wash across
// the field with the Pan knob.
let monoWet: SumChannels.Audio = SumChannels.Audio(input: reverb, mul: stereoSumGain)
let panned: Pan2 = Pan2(input: monoWet, pan: $pan)
return (panned.left, panned.right)
}
// MARK: - Lifecycle
/// Returns to live tracking when the engine stops.
public override func engineDidStop() {
releaseHold()
}
/// Returns to live tracking before this instance is discarded on a rig teardown.
public override func rigWillTeardown() {
releaseHold()
}
// MARK: - Helpers
/// Unlocks any captured filter and returns to live tracking.
private func releaseHold() {
crossMap?.freeze = false
isCaptured = false
captured = 0.0
}
/// Clears the live generator reference and the locked state so a graph rebuild starts fresh.
/// Called at the top of ``wideEffect(_:)``.
private func resetForRebuild() {
crossMap = nil
isCaptured = false
captured = 0.0
}
}
// MARK: - MIDI transport
extension TunedVerbPedal: MIDITransportPedal {
/// The Capture footswitch is the mappable transport action.
public var midiTransportName: String { "Capture" }
public func toggleMIDITransport() { toggleCapture() }
}
+143
View File
@@ -0,0 +1,143 @@
// PostChain.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// The shared **post-board chain**: a linear chain of pedals that processes the summed board mix
/// once, after the board split, before the hardware output — for global reverb, a bus limiter, a
/// final EQ, and the like.
///
/// Signal flow: every board master writes a shared stereo **mix bus**; this chain reads that mix,
/// runs its pedals in order, and copies the processed tail to the hardware outputs (via
/// ``PostChainOutput``). The chain is **always stereo-headed** — the mix carries two channels even
/// for a mono rig (dual-mono) — so a mono pedal auto-stereoizes per channel while a stereo-native
/// pedal cross-couples, exactly as in a ``PedalBoard``'s stereo region. It is a *linear* stage:
/// no split / parallel / stereo regions, which a post-master bus doesn't need.
///
/// `PostChain` is deliberately a dedicated type (not a `PedalBoard`): it owns only its inter-node
/// buses — the mix buses and the hardware outputs are owned elsewhere — and has post-specific
/// routing (mix in, hardware out). Its pedal buses are wired like `PedalBoard.add`'s width-2 arms.
///
/// - Note: Rig-wide volume / mute live on the board masters, *upstream* of this chain, so a panic
/// mute can let a post-chain reverb tail ring out briefly. Acceptable for a setup-time stage.
@MainActor
final class PostChain {
private let engine: SynthesisEngine
private let clock: LyrebirdClock?
/// The shared mix bus this chain reads (externally owned — never released here).
private let mixLeftBus: Int
private let mixRightBus: Int
/// Hardware output buses the processed tail is copied to.
private let outputLeftBus: Int
private let outputRightBus: Int
/// Inter-node buses this chain allocates and owns (released on ``teardown()``).
private var allocatedBuses: [AudioBus] = []
/// The chain's pedals, in signal-flow order.
private(set) var pedals: [Pedal] = []
/// The current stereo tail — starts at the mix, advances with each pedal.
private var tailLeft: Int
private var tailRight: Int
/// The last node inserted (for `.after` ordering of the next node).
private var lastNode: (any Synthesizer)?
/// The final node copying the tail to the hardware outputs.
private var outputNode: PostChainOutput?
/// Creates a post-board chain reading `mixLeftBus` / `mixRightBus` and writing the hardware
/// outputs. The mix and hardware buses are owned by the caller.
init(
engine: SynthesisEngine,
clock: LyrebirdClock?,
mixLeftBus: Int,
mixRightBus: Int,
outputLeftBus: Int = 0,
outputRightBus: Int = 1
) {
self.engine = engine
self.clock = clock
self.mixLeftBus = mixLeftBus
self.mixRightBus = mixRightBus
self.outputLeftBus = outputLeftBus
self.outputRightBus = outputRightBus
self.tailLeft = mixLeftBus
self.tailRight = mixRightBus
}
/// Appends a pedal to the chain. The first pedal is inserted at the **tail of the main group** so
/// it evaluates after every board master regardless of board add order; later calls chain after
/// the previous node automatically.
///
/// The pedal is wired at stereo width: both input channels read the current tail, both output
/// channels write fresh buses. The pedal's `channelKind` decides how its `build()` uses them (a
/// mono pedal runs `effect(_:)` per channel; a stereo-native pedal cross-couples).
func add(_ pedal: Pedal) throws {
pedal.sampleRate = engine.sampleRate
pedal.hostEngine = engine
pedal.clock = clock
let outLeft: AudioBus = try allocateInterNodeBus()
let outRight: AudioBus = try allocateInterNodeBus()
pedal.inputBus = tailLeft
pedal.inputBusRight = tailRight
pedal.outputBus = outLeft.index
pedal.outputBusRight = outRight.index
try insertNode(pedal)
tailLeft = outLeft.index
tailRight = outRight.index
pedals.append(pedal)
}
/// Adds the output node that copies the chain tail to the hardware outputs. Call once, after all
/// pedals have been added.
func finalize() throws {
let output: PostChainOutput = PostChainOutput(
leftInputBus: tailLeft,
rightInputBus: tailRight,
leftOutputBus: outputLeftBus,
rightOutputBus: outputRightBus
)
try insertNode(output)
outputNode = output
}
/// Removes every node this chain added and releases its inter-node buses. Call before the mix /
/// hardware buses it references are released.
func teardown() {
if let output: PostChainOutput = outputNode { engine.remove(output) }
outputNode = nil
for pedal: Pedal in pedals { engine.remove(pedal) }
pedals.removeAll()
for bus: AudioBus in allocatedBuses { engine.busAllocator.releaseAudioBus(bus) }
allocatedBuses.removeAll()
}
// MARK: - Private
private func allocateInterNodeBus() throws -> AudioBus {
let bus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
allocatedBuses.append(bus)
return bus
}
private func insertNode(_ node: any Synthesizer) throws {
if let previous: any Synthesizer = lastNode {
try engine.add(node, position: .after(previous))
} else {
// Head node: tail of the main group → after every board master already there, and
// order-independent, so a board added later (spliced near the group head) still
// evaluates before this chain. No re-order needed on board add.
try engine.add(node, position: .tail(of: engine.mainGroup))
}
lastNode = node
}
}
@@ -0,0 +1,43 @@
// PostChainOutput.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// Internal synthesizer that copies the post-board chain's stereo tail onto the hardware output
/// buses — the final node of the ``PostChain``.
///
/// The board masters write the shared mix bus, the post-chain's pedals process it, and this node
/// copies the processed tail (left / right) to the hardware outputs. It carries no gain: the
/// rig-wide volume / mute live on the board masters, upstream of the post-chain.
///
/// - Note: Must be removed from the engine before the tail / hardware buses it reads are released.
final class PostChainOutput: SynthesizerBase {
private let leftInputBus: Int
private let rightInputBus: Int
private let leftOutputBus: Int
private let rightOutputBus: Int
/// Creates a stereo copy from the chain tail to the hardware outputs.
///
/// - Parameters:
/// - leftInputBus: Chain-tail left bus to read.
/// - rightInputBus: Chain-tail right bus to read.
/// - leftOutputBus: Hardware output for the left channel (default `0`).
/// - rightOutputBus: Hardware output for the right channel (default `1`).
init(leftInputBus: Int, rightInputBus: Int, leftOutputBus: Int = 0, rightOutputBus: Int = 1) {
self.leftInputBus = leftInputBus
self.rightInputBus = rightInputBus
self.leftOutputBus = leftOutputBus
self.rightOutputBus = rightOutputBus
super.init()
}
override func build() {
output(bus: leftOutputBus, source: input(bus: leftInputBus))
output(bus: rightOutputBus, source: input(bus: rightInputBus))
}
}
@@ -91,6 +91,8 @@ public enum PedalRegistry {
"Spring Reverb": { SpringReverbPedal() }, "Spring Reverb": { SpringReverbPedal() },
"Reverse Reverb": { ReverseReverbPedal() }, "Reverse Reverb": { ReverseReverbPedal() },
"Granular Reverb": { GranularReverbPedal() }, "Granular Reverb": { GranularReverbPedal() },
"FreezVerb": { FreezVerbPedal() },
"TunedVerb": { TunedVerbPedal() },
"Limiter": { LimiterPedal() }, "Limiter": { LimiterPedal() },
"Cabinet": { CabinetPedal() }, "Cabinet": { CabinetPedal() },
"Noise Gate": { NoiseGatePedal() }, "Noise Gate": { NoiseGatePedal() },
@@ -56,7 +56,7 @@ extension ShoeGaze {
branch.append(newState) branch.append(newState)
} }
} }
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Inserts a pedal of the given type at `index` within a lane, shifting later pedals along. /// Inserts a pedal of the given type at `index` within a lane, shifting later pedals along.
@@ -117,7 +117,7 @@ extension ShoeGaze {
branch.insert(newState, at: index) branch.insert(newState, at: index)
} }
} }
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Removes the pedal at `index` within a lane. /// Removes the pedal at `index` within a lane.
@@ -149,7 +149,7 @@ extension ShoeGaze {
branch.remove(at: index) branch.remove(at: index)
} }
} }
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Moves the pedal at `sourceIndex` to `destinationIndex` within a lane. /// Moves the pedal at `sourceIndex` to `destinationIndex` within a lane.
@@ -175,7 +175,7 @@ extension ShoeGaze {
try Self.moveWithinArray(&branch, from: sourceIndex, to: destinationIndex) try Self.moveWithinArray(&branch, from: sourceIndex, to: destinationIndex)
} }
} }
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Moves a pedal from one lane to another (e.g. the main chain into a stereo-unzip lane, or /// Moves a pedal from one lane to another (e.g. the main chain into a stereo-unzip lane, or
@@ -252,7 +252,7 @@ extension ShoeGaze {
} }
} }
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
// MARK: - Branch regions // MARK: - Branch regions
@@ -270,7 +270,7 @@ extension ShoeGaze {
guard board.width == 1 else { throw ShoeGazeError.cannotSplitStereoChain } guard board.width == 1 else { throw ShoeGazeError.cannotSplitStereoChain }
var segments: [BoardSegmentState] = board.captureState().segments var segments: [BoardSegmentState] = board.captureState().segments
segments.append(.stereoSplit(StereoSplitState(left: [], right: [], route: .stereo))) segments.append(.stereoSplit(StereoSplitState(left: [], right: [], route: .stereo)))
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Inserts an empty stereo-unzip region immediately after the segment at `topLevelIndex`, /// Inserts an empty stereo-unzip region immediately after the segment at `topLevelIndex`,
@@ -297,7 +297,7 @@ extension ShoeGaze {
.stereoUnzip(StereoUnzipState(left: [], right: [], route: .stereo)), .stereoUnzip(StereoUnzipState(left: [], right: [], route: .stereo)),
at: topLevelIndex + 1 at: topLevelIndex + 1
) )
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Returns `true` when the segment immediately after `topLevelIndex` is a stereo-unzip region — /// Returns `true` when the segment immediately after `topLevelIndex` is a stereo-unzip region —
@@ -318,7 +318,7 @@ extension ShoeGaze {
public func appendParallelSplit(to board: PedalBoard) throws -> PedalBoard { public func appendParallelSplit(to board: PedalBoard) throws -> PedalBoard {
var segments: [BoardSegmentState] = board.captureState().segments var segments: [BoardSegmentState] = board.captureState().segments
segments.append(.parallel(ParallelSectionState(branchA: [], branchB: [], mode: .both))) segments.append(.parallel(ParallelSectionState(branchA: [], branchB: [], mode: .both)))
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Appends a merge-to-mono node, collapsing a stereo tail back to mono. /// Appends a merge-to-mono node, collapsing a stereo tail back to mono.
@@ -330,7 +330,7 @@ extension ShoeGaze {
guard board.width == 2 else { throw ShoeGazeError.cannotMergeMonoChain } guard board.width == 2 else { throw ShoeGazeError.cannotMergeMonoChain }
var segments: [BoardSegmentState] = board.captureState().segments var segments: [BoardSegmentState] = board.captureState().segments
segments.append(.mergeToMono) segments.append(.mergeToMono)
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
/// Removes the top-level segment (a linear pedal, a split region, or a merge node) at /// Removes the top-level segment (a linear pedal, a split region, or a merge node) at
@@ -345,7 +345,7 @@ extension ShoeGaze {
throw ShoeGazeError.pedalIndexOutOfRange(index: topLevelIndex, count: segments.count) throw ShoeGazeError.pedalIndexOutOfRange(index: topLevelIndex, count: segments.count)
} }
segments.remove(at: topLevelIndex) segments.remove(at: topLevelIndex)
return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) return try rebuildBoard(board, from: BoardState(id: board.id, label: board.label, segments: segments))
} }
// MARK: - Input source switching // MARK: - Input source switching
@@ -481,4 +481,148 @@ extension ShoeGaze {
let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex
array.insert(element, at: insertionIndex) array.insert(element, at: insertionIndex)
} }
// MARK: - Pre-board chain editing
/// Appends a pedal to the end of the pre-board chain — the shared stage that processes the input
/// once, before the board split, and feeds every board.
///
/// - Important: A pre-board edit reshapes the shared feed every board taps, so the whole rig is
/// torn down and rebuilt (ordering-safe). Like ``setInputSource(_:)``, this resets transient
/// live state (solo / bypass) and stateful pedals (looper buffers) — it is a setup-time edit.
/// - Note: The pre-board chain feeds the **main boards** only. Chain-router branches read the
/// input source directly and are not fed by the pre-board chain.
public func appendPrePedal(_ kind: PedalType) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePreBoardStates() // fold in live knob tweaks first
updated.append(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0))
try setPreBoardChain(updated)
}
/// Inserts a pedal at `index` in the pre-board chain (insert-before; `index == count` appends).
public func insertPrePedal(_ kind: PedalType, at index: Int) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePreBoardStates()
guard index >= 0 && index <= updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.insert(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0), at: index)
try setPreBoardChain(updated)
}
/// Removes the pre-board pedal at `index`.
public func removePrePedal(at index: Int) throws {
var updated: [PedalState] = capturePreBoardStates()
guard index >= 0 && index < updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.remove(at: index)
try setPreBoardChain(updated)
}
/// Moves the pre-board pedal at `sourceIndex` to `destinationIndex` (SwiftUI `onMove` semantics).
public func movePrePedal(from sourceIndex: Int, to destinationIndex: Int) throws {
var updated: [PedalState] = capturePreBoardStates()
try Self.moveWithinArray(&updated, from: sourceIndex, to: destinationIndex)
try setPreBoardChain(updated)
}
/// Replaces the pre-board chain with `newStates` and rebuilds the rig. The pre-chain reshapes the
/// shared feed that every board taps, so the whole rig is torn down and rebuilt (ordering-safe);
/// mirrors ``setInputSource(_:)``, resetting transient / looper state like it does. On failure the
/// previous pre-board states are restored so a later capture never persists a half-applied edit.
private func setPreBoardChain(_ newStates: [PedalState]) throws {
let previous: [PedalState] = preBoardStates
preBoardStates = newStates
let wasRunning: Bool = engine.isRunning
if wasRunning { engine.stop() }
let snapshot: ShoeGazeState = captureState().withPreChain(newStates.isEmpty ? nil : newStates)
teardown()
do {
try rebuildAllBoards(from: snapshot)
} catch {
preBoardStates = previous
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after failed pre-board edit failed: \(error)") }
}
throw error
}
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after pre-board edit failed: \(error)") }
}
}
// MARK: - Post-board chain editing
/// Appends a pedal to the end of the post-board chain — the shared stage that processes the
/// summed board mix, after the split, before the hardware output (global reverb, bus limiter).
///
/// - Important: Reshapes the shared mix path, so the whole rig is torn down and rebuilt
/// (ordering-safe); resets transient / looper state like ``setInputSource(_:)``.
public func appendPostPedal(_ kind: PedalType) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePostBoardStates()
updated.append(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0))
try setPostBoardChain(updated)
}
/// Inserts a pedal at `index` in the post-board chain (insert-before; `index == count` appends).
public func insertPostPedal(_ kind: PedalType, at index: Int) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePostBoardStates()
guard index >= 0 && index <= updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.insert(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0), at: index)
try setPostBoardChain(updated)
}
/// Removes the post-board pedal at `index`.
public func removePostPedal(at index: Int) throws {
var updated: [PedalState] = capturePostBoardStates()
guard index >= 0 && index < updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.remove(at: index)
try setPostBoardChain(updated)
}
/// Moves the post-board pedal at `sourceIndex` to `destinationIndex` (SwiftUI `onMove` semantics).
public func movePostPedal(from sourceIndex: Int, to destinationIndex: Int) throws {
var updated: [PedalState] = capturePostBoardStates()
try Self.moveWithinArray(&updated, from: sourceIndex, to: destinationIndex)
try setPostBoardChain(updated)
}
/// Replaces the post-board chain with `newStates` and rebuilds the rig (ordering-safe). The
/// masters' output target (mix bus vs hardware) depends on whether a post-chain exists, so the
/// whole rig is rebuilt; mirrors ``setInputSource(_:)``.
///
/// - Note: On a rebuild failure the `postBoardStates` are restored and the engine is restarted,
/// but the graph was already torn down and is left empty — the rig runs silent until the next
/// successful edit. A setup-time edit, so this is acceptable (same contract as the pre-board edit).
private func setPostBoardChain(_ newStates: [PedalState]) throws {
let previous: [PedalState] = postBoardStates
postBoardStates = newStates
let wasRunning: Bool = engine.isRunning
if wasRunning { engine.stop() }
let snapshot: ShoeGazeState = captureState().withPostChain(newStates.isEmpty ? nil : newStates)
teardown()
do {
try rebuildAllBoards(from: snapshot)
} catch {
postBoardStates = previous
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after failed post-board edit failed: \(error)") }
}
throw error
}
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after post-board edit failed: \(error)") }
}
}
} }
@@ -38,7 +38,12 @@ extension ShoeGaze {
numOutputChannels: engine.numOutputChannels, numOutputChannels: engine.numOutputChannels,
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is // `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is
// unchanged and byte-identical to one saved before router persistence existed. // unchanged and byte-identical to one saved before router persistence existed.
routers: routerStates.isEmpty ? nil : routerStates routers: routerStates.isEmpty ? nil : routerStates,
// Captured from the LIVE pre-pedals (so knob tweaks are saved); `nil` rather than `[]`
// when empty, so a rig without a pre-board chain stays byte-identical to the old format.
preChain: { let s: [PedalState] = capturePreBoardStates(); return s.isEmpty ? nil : s }(),
// Likewise for the post-board chain, captured from the live post-pedals.
postChain: { let s: [PedalState] = capturePostBoardStates(); return s.isEmpty ? nil : s }()
) )
} }
@@ -178,6 +183,11 @@ extension ShoeGaze {
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction. /// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction.
func rebuildAllBoards(from snapshot: ShoeGazeState) throws { func rebuildAllBoards(from snapshot: ShoeGazeState) throws {
do { do {
// Set the pre- and post-board chains before building any board: a board's input tap wires
// through the feed bus (`ensureFeed()` from `preBoardStates`), and its master targets the
// mix bus (`ensurePostMix()` from `postBoardStates`), both decided per board.
preBoardStates = snapshot.preChain ?? []
postBoardStates = snapshot.postChain ?? []
for boardState: BoardState in snapshot.boards { for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard() let board: PedalBoard = try addBoard()
board.id = boardState.id board.id = boardState.id
@@ -188,6 +198,14 @@ extension ShoeGaze {
for routerState: ChainRouterState in snapshot.routers ?? [] { for routerState: ChainRouterState in snapshot.routers ?? [] {
try rebuildRouter(routerState) try rebuildRouter(routerState)
} }
// With no boards to pull the feed into being, build the pre-chain anyway so it isn't an
// invisible accumulation of states (`preBoardPedals` reflects it; a later board taps it).
if boards.isEmpty && !preBoardStates.isEmpty {
_ = try ensureFeed()
}
// Build the post-board chain after every board master exists (it reads the mix those
// masters write and must evaluate after them).
try buildPostChain()
} catch { } catch {
// Leave no partial rig behind: tear down whatever was built, then rethrow. // Leave no partial rig behind: tear down whatever was built, then rethrow.
teardown() teardown()
@@ -62,6 +62,16 @@ public struct ShoeGazeState: Codable, Equatable {
/// routers — decode cleanly to `nil` without a format-version bump. /// routers — decode cleanly to `nil` without a format-version bump.
public let routers: [ChainRouterState]? public let routers: [ChainRouterState]?
/// The rig's pre-board chain — pedals that process the input once, before the board split, and
/// feed every board — or `nil` for a rig saved before the pre-board stage existed. Additive:
/// decoded with `decodeIfPresent`, so older rigs decode cleanly to `nil` without a format bump.
public let preChain: [PedalState]?
/// The rig's post-board chain — pedals that process the summed board mix, after the split, before
/// the hardware output (global reverb, bus limiter, …) — or `nil` for a rig saved before the
/// post-board stage existed. Additive: decoded with `decodeIfPresent`.
public let postChain: [PedalState]?
/// Creates a rig state snapshot. /// Creates a rig state snapshot.
/// ///
/// - Parameters: /// - Parameters:
@@ -83,7 +93,9 @@ public struct ShoeGazeState: Codable, Equatable {
inputSource: InputSource? = nil, inputSource: InputSource? = nil,
numInputChannels: Int? = nil, numInputChannels: Int? = nil,
numOutputChannels: Int? = nil, numOutputChannels: Int? = nil,
routers: [ChainRouterState]? = nil routers: [ChainRouterState]? = nil,
preChain: [PedalState]? = nil,
postChain: [PedalState]? = nil
) { ) {
self.version = version self.version = version
self.boards = boards self.boards = boards
@@ -94,6 +106,8 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = numInputChannels self.numInputChannels = numInputChannels
self.numOutputChannels = numOutputChannels self.numOutputChannels = numOutputChannels
self.routers = routers self.routers = routers
self.preChain = preChain
self.postChain = postChain
} }
private enum CodingKeys: String, CodingKey { private enum CodingKeys: String, CodingKey {
@@ -106,6 +120,8 @@ public struct ShoeGazeState: Codable, Equatable {
case numInputChannels case numInputChannels
case numOutputChannels case numOutputChannels
case routers case routers
case preChain
case postChain
} }
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`. /// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
@@ -139,6 +155,8 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels) self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels) self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers) self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers)
self.preChain = try container.decodeIfPresent([PedalState].self, forKey: .preChain)
self.postChain = try container.decodeIfPresent([PedalState].self, forKey: .postChain)
} }
/// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo — /// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo —
@@ -155,5 +173,26 @@ public struct ShoeGazeState: Codable, Equatable {
&& midiMap == other.midiMap && midiMap == other.midiMap
&& bpm == other.bpm && bpm == other.bpm
&& tempoEnabled == other.tempoEnabled && tempoEnabled == other.tempoEnabled
&& preChain == other.preChain
&& postChain == other.postChain
}
/// Returns a copy of this snapshot with its `preChain` replaced. Used by the pre-board edit path
/// to force the just-mutated intended chain (rather than a re-read of the still-live pre-pedals).
public func withPreChain(_ preChain: [PedalState]?) -> ShoeGazeState {
ShoeGazeState(
version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled,
inputSource: inputSource, numInputChannels: numInputChannels,
numOutputChannels: numOutputChannels, routers: routers, preChain: preChain, postChain: postChain
)
}
/// Returns a copy with its `postChain` replaced. Post-board edit counterpart of ``withPreChain(_:)``.
public func withPostChain(_ postChain: [PedalState]?) -> ShoeGazeState {
ShoeGazeState(
version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled,
inputSource: inputSource, numInputChannels: numInputChannels,
numOutputChannels: numOutputChannels, routers: routers, preChain: preChain, postChain: postChain
)
} }
} }
+247 -23
View File
@@ -192,11 +192,117 @@ public final class ShoeGaze {
private var globalTestSource: TestLoopSource? private var globalTestSource: TestLoopSource?
private var globalTestBus: AudioBus? private var globalTestBus: AudioBus?
/// Per-board taps copying the global test bus into each board's head bus. /// Per-board taps copying the shared feed bus into each board's head bus.
private var testLoopTaps: [TestLoopTap] = [] private var testLoopTaps: [TestLoopTap] = []
private var inputPassThroughs: [HardwareInputPassThrough] = [] private var inputPassThroughs: [HardwareInputPassThrough] = []
private var outputMasters: [BoardOutputMaster] = [] private var outputMasters: [BoardOutputMaster] = []
// MARK: - Pre-board chain
/// The shared **feed bus** every board taps. It carries the input source directly, or — when a
/// pre-board chain exists — that chain's mono output. Allocated lazily by ``ensureFeed()`` when
/// the first board is wired, and rebuilt with the rig on a pre-board edit (which reshapes it).
private var feedBus: AudioBus?
/// The node that writes ``feedBus``: copies the input source, or the pre-board chain's mono
/// output, onto the feed bus. Board taps read the feed bus and so must evaluate after this node.
private var feedWriter: FeedPassThrough?
/// The live pre-board processing chain (a ``PedalBoard`` whose mono output feeds every board),
/// or `nil` when there is no pre-board processing. Rebuilt from ``preBoardStates``.
private var preChainBoard: PedalBoard?
/// The tap that feeds the pre-board chain's head bus from the input source. `nil` when there is
/// no pre-board chain.
private var preChainFeedTap: FeedPassThrough?
/// Persisted pre-board pedal states — the serialization source of truth. The live
/// ``preChainBoard`` is rebuilt from these. Empty when there is no pre-board processing.
/// Set via the pre-board edit API and on rig load; read by ``ensureFeed()`` when wiring the feed.
public internal(set) var preBoardStates: [PedalState] = []
/// The live pedals currently in the pre-board chain, in signal-flow order; empty when there is no
/// pre-board processing. For UI rendering + inspection (the persisted truth is ``preBoardStates``).
public var preBoardPedals: [Pedal] { preChainBoard?.pedals ?? [] }
/// The pre-board states captured from the **live** pre-pedals (so knob / switch tweaks are
/// included), or the stored ``preBoardStates`` when there is no live chain. Use this — never the
/// raw ``preBoardStates`` — wherever the pre-chain is saved or rebuilt, so live edits aren't lost.
func capturePreBoardStates() -> [PedalState] {
guard let pre: PedalBoard = preChainBoard else { return preBoardStates }
return pre.pedals.map { $0.captureState() }
}
// MARK: - Post-board chain
/// Shared stereo mix bus the board masters write **into** when a post-board chain exists; `nil`
/// otherwise (the masters write the hardware outputs directly). Owned here, released with the
/// post-chain. The post-chain reads this mix and writes the hardware outputs.
private var postMixLeft: AudioBus?
private var postMixRight: AudioBus?
/// The live post-board chain (reads the mix, writes hardware), or `nil` when there is none.
private var postChain: PostChain?
/// Persisted post-board pedal states — the serialization source of truth; the live ``postChain``
/// is rebuilt from these. Empty when there is no post-board processing.
public internal(set) var postBoardStates: [PedalState] = []
/// The live pedals in the post-board chain, in signal-flow order; empty when there is none.
public var postBoardPedals: [Pedal] { postChain?.pedals ?? [] }
/// Post-board states captured from the **live** post-pedals (so knob tweaks are included), or the
/// stored ``postBoardStates`` when there is no live chain. Use this wherever the post-chain is
/// saved or rebuilt, so live edits aren't lost.
func capturePostBoardStates() -> [PedalState] {
guard let post: PostChain = postChain else { return postBoardStates }
return post.pedals.map { $0.captureState() }
}
/// Ensures the stereo mix bus exists when a post-board chain is present, returning its bus
/// indices — or `nil` when there is none (the masters then write hardware directly).
private func ensurePostMix() throws -> (left: Int, right: Int)? {
guard !postBoardStates.isEmpty else { return nil }
if let left: AudioBus = postMixLeft, let right: AudioBus = postMixRight {
return (left.index, right.index)
}
let left: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let right: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
postMixLeft = left
postMixRight = right
return (left.index, right.index)
}
/// Builds the post-board chain from ``postBoardStates`` — reading the mix, writing hardware,
/// inserted at the tail of the main group so it evaluates after **every** board master (order-
/// independent). No-op when empty. Call after all boards are finalized.
func buildPostChain() throws {
guard !postBoardStates.isEmpty, let mix: (left: Int, right: Int) = try ensurePostMix() else { return }
let post: PostChain = PostChain(
engine: engine, clock: clock, mixLeftBus: mix.left, mixRightBus: mix.right
)
// Track the chain before wiring it, so a mid-build throw leaves its partial nodes/buses
// reachable for teardown (`tearDownPost` / the rebuild catch) instead of orphaned.
postChain = post
for state: PedalState in postBoardStates {
guard let pedal: Pedal = PedalRegistry.makePedal(type: state.type) else { continue }
pedal.applyState(state)
try post.add(pedal)
}
try post.finalize()
}
/// Removes the post-board chain nodes and releases the mix bus. Call from ``teardown()`` after the
/// masters that write the mix are removed.
private func tearDownPost() {
postChain?.teardown()
postChain = nil
if let left: AudioBus = postMixLeft { engine.busAllocator.releaseAudioBus(left) }
postMixLeft = nil
if let right: AudioBus = postMixRight { engine.busAllocator.releaseAudioBus(right) }
postMixRight = nil
}
/// All chain routers created via ``makeChainRouter()``. /// All chain routers created via ``makeChainRouter()``.
/// Routers are torn down (in reverse-creation order) by ``teardown()``. /// Routers are torn down (in reverse-creation order) by ``teardown()``.
/// ///
@@ -238,9 +344,18 @@ public final class ShoeGaze {
engine.stop() engine.stop()
} }
/// The live pedal with the given `id`, searching every board (main chain + parallel / stereo
/// branches) and router branches, or `nil` if none matches. Used by undo to re-resolve a
/// control's live node after an edit has rebuilt the board it lives on.
func pedal(id: UUID) -> Pedal? {
allPedals().first { $0.id == id }
}
/// Every live `Pedal` across all main boards and chain-router branches. /// Every live `Pedal` across all main boards and chain-router branches.
private func allPedals() -> [Pedal] { private func allPedals() -> [Pedal] {
var result: [Pedal] = [] var result: [Pedal] = []
result.append(contentsOf: preBoardPedals)
result.append(contentsOf: postBoardPedals)
for board: PedalBoard in boards { for board: PedalBoard in boards {
result.append(contentsOf: pedals(in: board)) result.append(contentsOf: pedals(in: board))
} }
@@ -303,38 +418,36 @@ public final class ShoeGaze {
let board: PedalBoard = try PedalBoard(engine: engine, clock: clock) let board: PedalBoard = try PedalBoard(engine: engine, clock: clock)
board.label = "Board \(boards.count + 1)" board.label = "Board \(boards.count + 1)"
// Route the input source to the board head bus. // Every board taps the shared feed bus — the input source, or (when present) the pre-board
// chain's mono output. The tap evaluates after the feed writer so it reads a written bus.
let (feedBusIndex, feedNode): (Int, any Synthesizer) = try ensureFeed()
switch inputSource { switch inputSource {
case .testLoop: case .testLoop:
// All boards share one global test source so they stay phase-locked. Each board // All boards share one feed (and one global test source upstream of it) so they stay
// gets a tap copying the shared test bus into its head bus, added `.after(_:)` the // phase-locked. Each board gets a tap copying the feed bus into its head bus.
// source so it sees the source's output for the current block.
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
let tap: TestLoopTap = TestLoopTap( let tap: TestLoopTap = TestLoopTap(
inputBusIndex: testBus.index, inputBusIndex: feedBusIndex,
outputBusIndex: board.headBus.index outputBusIndex: board.headBus.index
) )
// Prime the mute gain before splicing the node in, so its very first render block // Prime the mute gain before splicing the node in, so its very first render block
// reflects the current mute state with no ramp (see `primeInputMute`). // reflects the current mute state with no ramp (see `primeInputMute`).
primeInputMute(tap.inputMuteNode, muted: inputMuted) primeInputMute(tap.inputMuteNode, muted: inputMuted)
try engine.add(tap, position: NodePosition.after(source)) try engine.add(tap, position: NodePosition.after(feedNode))
testLoopTaps.append(tap) testLoopTaps.append(tap)
// Record the tap as the head input node so PedalBoard.add(_:) can chain the first // Record the tap as the head input node so PedalBoard.add(_:) can chain the first
// pedal after it automatically (without needing an explicit `after:`). // pedal after it automatically (without needing an explicit `after:`).
board.headInputNode = tap board.headInputNode = tap
case .liveInput(let channel): case .liveInput:
// Hardware input channel `channel` lives at bus numOutputChannels + channel. // Live input flows through the same feed bus (which carries the hardware input, or the
// A HardwareInputPassThrough copies it to the board's head bus so all pedals // pre-board chain fed from it). The per-board input mute stays on this tap.
// read from a board-owned bus (not the raw hardware input bus).
let hardwareInputBusIndex: Int = try liveInputBusIndex(channel: channel, engine: engine)
let passThrough: HardwareInputPassThrough = HardwareInputPassThrough( let passThrough: HardwareInputPassThrough = HardwareInputPassThrough(
inputBusIndex: hardwareInputBusIndex, inputBusIndex: feedBusIndex,
outputBusIndex: board.headBus.index outputBusIndex: board.headBus.index
) )
// Prime the mute gain before splicing the node in (see `primeInputMute`). // Prime the mute gain before splicing the node in (see `primeInputMute`).
primeInputMute(passThrough.inputMuteNode, muted: inputMuted) primeInputMute(passThrough.inputMuteNode, muted: inputMuted)
try engine.add(passThrough) try engine.add(passThrough, position: NodePosition.after(feedNode))
inputPassThroughs.append(passThrough) inputPassThroughs.append(passThrough)
board.headInputNode = passThrough board.headInputNode = passThrough
} }
@@ -376,6 +489,100 @@ public final class ShoeGaze {
return (source, testBus) return (source, testBus)
} }
// MARK: - Pre-board feed wiring
/// Ensures the input source for the current ``inputSource`` exists and returns the bus it writes
/// plus the node that writes it (`nil` for live input — the hardware input bus is already
/// populated at block start, so nothing need evaluate before a reader).
private func ensureInputSourceBus() throws -> (bus: Int, node: (any Synthesizer)?) {
switch inputSource {
case .testLoop:
let (source, testBus): (TestLoopSource, AudioBus) = try ensureGlobalTestSource()
return (testBus.index, source)
case .liveInput(let channel):
let index: Int = try liveInputBusIndex(channel: channel, engine: engine)
return (index, nil)
}
}
/// Ensures the shared feed bus and its writer exist for the current input source and pre-board
/// state, returning the feed bus index and the node a board must order its input tap after.
@discardableResult
func ensureFeed() throws -> (bus: Int, node: any Synthesizer) {
if let feedBus: AudioBus = feedBus, let feedWriter: FeedPassThrough = feedWriter {
return (feedBus.index, feedWriter)
}
return try buildFeed()
}
/// Allocates the feed bus (if needed), builds the pre-board chain when ``preBoardStates`` is
/// non-empty (source → pedals → mono output), and creates the feed writer that copies the source
/// or the pre-chain output onto the feed bus. Returns the feed bus index + the feed writer node.
@discardableResult
private func buildFeed() throws -> (bus: Int, node: any Synthesizer) {
let (sourceBus, sourceNode): (Int, (any Synthesizer)?) = try ensureInputSourceBus()
let feed: AudioBus = try feedBus ?? engine.busAllocator.allocateAudioBus(channelCount: 1)
feedBus = feed
// What the feed writer reads: the source directly, or the pre-board chain's mono output.
var writerInputBus: Int = sourceBus
var writerAfter: (any Synthesizer)? = sourceNode
if !preBoardStates.isEmpty {
let pre: PedalBoard = try PedalBoard(engine: engine, clock: clock)
// Feed the pre-chain head from the input source.
let feedTap: FeedPassThrough = FeedPassThrough(
inputBusIndex: sourceBus,
outputBusIndex: pre.headBus.index
)
if let sourceNode: any Synthesizer = sourceNode {
try engine.add(feedTap, position: NodePosition.after(sourceNode))
} else {
try engine.add(feedTap)
}
pre.headInputNode = feedTap
preChainFeedTap = feedTap
for state: PedalState in preBoardStates {
guard let pedal: Pedal = PedalRegistry.makePedal(type: state.type) else { continue }
pedal.applyState(state)
try pre.add(pedal)
}
// The feed is mono (board heads are mono); fold any multi-channel pre-chain tail to mono.
if pre.width > 1 {
try pre.mergeToMono()
}
preChainBoard = pre
writerInputBus = pre.outputBus.index
writerAfter = pre.tailNode ?? feedTap
}
let writer: FeedPassThrough = FeedPassThrough(inputBusIndex: writerInputBus, outputBusIndex: feed.index)
if let after: any Synthesizer = writerAfter {
try engine.add(writer, position: NodePosition.after(after))
} else {
try engine.add(writer)
}
feedWriter = writer
return (feed.index, writer)
}
/// Removes the feed writer + pre-board chain nodes and releases the feed bus. Called from
/// ``teardown()`` (the whole feed is rebuilt from scratch on the next ``ensureFeed()``).
private func tearDownFeed() {
if let writer: FeedPassThrough = feedWriter { engine.remove(writer) }
feedWriter = nil
if let feedTap: FeedPassThrough = preChainFeedTap { engine.remove(feedTap) }
preChainFeedTap = nil
preChainBoard?.teardown()
preChainBoard = nil
if let feed: AudioBus = feedBus {
engine.busAllocator.releaseAudioBus(feed)
feedBus = nil
}
}
/// Connects the output master for a previously prepared board and adds it to the engine. /// Connects the output master for a previously prepared board and adds it to the engine.
/// ///
/// Call this after all pedals have been added to the board via `board.add(_:)`. /// Call this after all pedals have been added to the board via `board.add(_:)`.
@@ -389,10 +596,15 @@ public final class ShoeGaze {
/// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added. /// - Parameter board: A `PedalBoard` returned by `addBoard()` with pedals added.
/// - Throws: `EngineAddError` if the engine rejects the master node. /// - Throws: `EngineAddError` if the engine rejects the master node.
public func finalizeBoard(_ board: PedalBoard) throws { public func finalizeBoard(_ board: PedalBoard) throws {
// When a post-board chain exists, every master writes the shared mix bus (the post-chain
// then reads the mix and writes hardware); otherwise the master writes hardware directly.
let mix: (left: Int, right: Int)? = try ensurePostMix()
let master: BoardOutputMaster = BoardOutputMaster( let master: BoardOutputMaster = BoardOutputMaster(
boardOutputBusIndex: board.outputBus.index, boardOutputBusIndex: board.outputBus.index,
boardOutputBusRightIndex: board.outputBusRight?.index, boardOutputBusRightIndex: board.outputBusRight?.index,
dryInputBusIndex: board.headBus.index dryInputBusIndex: board.headBus.index,
outputLeftBusIndex: mix?.left ?? 0,
outputRightBusIndex: mix?.right ?? 1
) )
// The master evaluates after the entire chain (pedals, splitters, mergers). // The master evaluates after the entire chain (pedals, splitters, mergers).
// `board.tailNode` returns the last inserted node (any Synthesizer), which covers // `board.tailNode` returns the last inserted node (any Synthesizer), which covers
@@ -432,6 +644,11 @@ public final class ShoeGaze {
// Bring a newly-finalized board up at the current rig volume / mute. // Bring a newly-finalized board up at the current rig volume / mute.
master.rigVolumeNode.update(rigVolume) master.rigVolumeNode.update(rigVolume)
master.rigMuteNode.update(rigMuted ? 1.0 : 0.0) master.rigMuteNode.update(rigMuted ? 1.0 : 0.0)
// A board finalized while a post-board chain already exists needs no post-chain rebuild: the
// post-chain sits at the tail of the main group, so the new master (spliced nearer the group
// head) evaluates before it automatically, and the new master already writes the shared mix
// (via the `ensurePostMix()` redirect above). The post-chain keeps its live pedal state.
} }
// MARK: - Board selection / crossfade // MARK: - Board selection / crossfade
@@ -830,9 +1047,17 @@ public final class ShoeGaze {
engine.remove(tap) engine.remove(tap)
} }
testLoopTaps.removeAll() testLoopTaps.removeAll()
for passThrough: HardwareInputPassThrough in inputPassThroughs {
engine.remove(passThrough)
}
inputPassThroughs.removeAll()
// Remove the shared global test source and release its bus (after its taps are removed, // Remove the feed writer + pre-board chain (the taps that read the feed bus are now gone)
// preserving remove-before-release ordering). // and release the feed bus, before the source it reads is removed.
tearDownFeed()
// Remove the shared global test source and release its bus (after the taps + feed that read
// it are removed, preserving remove-before-release ordering).
if let source: TestLoopSource = globalTestSource { if let source: TestLoopSource = globalTestSource {
engine.remove(source) engine.remove(source)
} }
@@ -842,16 +1067,15 @@ public final class ShoeGaze {
} }
globalTestBus = nil globalTestBus = nil
for passThrough: HardwareInputPassThrough in inputPassThroughs {
engine.remove(passThrough)
}
inputPassThroughs.removeAll()
for master: BoardOutputMaster in outputMasters { for master: BoardOutputMaster in outputMasters {
engine.remove(master) engine.remove(master)
} }
outputMasters.removeAll() outputMasters.removeAll()
// Remove the post-board chain (reader of the mix, writer of hardware) and release the mix
// bus, now that the masters that write it are gone.
tearDownPost()
// Step 2: Remove pedals from the engine and release all board-owned buses. // Step 2: Remove pedals from the engine and release all board-owned buses.
// board.teardown() removes pedals from the engine and then releases buses, // board.teardown() removes pedals from the engine and then releases buses,
// so bus release only happens after all writers have been dequeued. // so bus release only happens after all writers have been dequeued.
@@ -0,0 +1,26 @@
// PedalControlGroup.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Identifies which of a pedal's control collections holds a given parameter, so a parameter-undo
/// entry can re-resolve the live ``UIParamNode`` by `(pedal id, group, control label)` after an
/// edit has rebuilt the pedal.
public enum PedalControlGroup: Sendable {
/// A face knob — ``Pedal/knobs`` (includes the trailing `Mix` / `Level`).
case knob
/// A knob in the pedal's advanced popover — ``Pedal/advancedKnobs``.
case advancedKnob
/// A continuous slider — ``Pedal/effectSliders``.
case slider
/// A segmented switch — ``Pedal/effectSwitches``.
case `switch`
/// A stepped selector knob — ``Pedal/effectSelectors``.
case selector
}
@@ -0,0 +1,402 @@
// UndoCoordinator.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
import Observation
import LyrebirdSynth
/// Multi-level undo / redo for rig edits — both structural topology changes and parameter changes,
/// interleaved on one stack.
///
/// **Structural edits** (add / remove / move a pedal, board, split-merge region) are wrapped in
/// ``perform(_:_:)``, which snapshots the whole rig as a ``ShoeGazeState`` before the edit and
/// records that pre-edit snapshot if the rig actually changed. ``undo()`` restores it *surgically*
/// (see ``restore(_:on:)`` — board-by-board reconciliation, not a whole-rig reload) and moves the
/// pre-undo state onto the redo stack; ``redo()`` is the mirror.
///
/// **Parameter edits** (one knob / slider / switch / selector the user finished changing) are
/// recorded by ``recordParameterEdit(label:pedalID:group:controlLabel:oldValue:newValue:)`` as the
/// control's identity plus its before/after values — undo sets it back, redo re-applies, re-resolving
/// the live node by id each time so it survives an intervening rebuild. Topology-changing
/// (`rebuildsOnChange`) controls are deliberately NOT recorded this way (they belong to the
/// structural path).
///
/// Any new edit of either kind clears the redo stack.
///
/// The coordinator holds the ``ShoeGaze`` instance weakly: it is a companion object the UI owns
/// alongside the rig, and the rig never refers back to it. All access is `@MainActor`, matching the
/// rig's isolation. It is `@Observable` so SwiftUI menus and toolbar buttons track ``canUndo`` /
/// ``canRedo`` and the action labels without manual refresh.
@MainActor
@Observable
public final class UndoCoordinator {
/// Default maximum number of actions retained on the undo stack. Entries are small
/// (a `ShoeGazeState` snapshot is a few KB of value types), so the cap is a UX choice — old
/// history past this many actions is dropped oldest-first — rather than a memory limit.
public static let defaultDepth: Int = 50
/// The rig this coordinator records edits for. Weak to avoid any retain cycle; `nil` after the
/// rig is torn down, which makes every operation a safe no-op.
private weak var shoeGaze: ShoeGaze?
/// Maximum retained undo (and redo) depth. Always at least `1`.
private let depth: Int
/// Recorded pre-edit snapshots, oldest first. The last element is the next action ``undo()``
/// reverts.
private var undoStack: [UndoEntry] = []
/// Snapshots moved aside by ``undo()``, oldest first. The last element is the next action
/// ``redo()`` re-applies. Cleared by any new ``perform(_:_:)``.
private var redoStack: [UndoEntry] = []
/// `true` when there is at least one action to undo. Drives the Undo menu item / button enabled
/// state.
public private(set) var canUndo: Bool = false
/// `true` when there is at least one action to redo. Drives the Redo menu item / button enabled
/// state.
public private(set) var canRedo: Bool = false
/// The label of the next action ``undo()`` would revert (e.g. `"Add Reverb"`), or `nil` when the
/// undo stack is empty. Suitable for a `"Undo \(label)"` menu title.
public private(set) var undoActionLabel: String?
/// The label of the next action ``redo()`` would re-apply, or `nil` when the redo stack is empty.
public private(set) var redoActionLabel: String?
/// Creates a coordinator for a rig.
///
/// - Parameters:
/// - shoeGaze: The rig to record structural edits for. Held weakly.
/// - depth: Maximum retained undo/redo depth. Clamped to at least `1`. Defaults to
/// ``defaultDepth``.
public init(shoeGaze: ShoeGaze, depth: Int = UndoCoordinator.defaultDepth) {
self.shoeGaze = shoeGaze
self.depth = max(1, depth)
}
// MARK: - Recording
/// Runs a structural edit, recording an undo checkpoint when it changes the rig.
///
/// Captures the rig state, runs `action`, then captures it again. The checkpoint is recorded only
/// when the two snapshots differ, so a no-op edit (e.g. a move that lands a pedal back in place)
/// adds nothing to the history. A throwing `action` propagates its error and records nothing. On
/// a recorded edit the redo stack is cleared, matching standard undo semantics.
///
/// - Parameters:
/// - label: A short, human-readable description of the action (e.g. `"Add Reverb"`).
/// - action: The edit to run. Its return value is passed straight back to the caller.
/// - Returns: Whatever `action` returns.
/// - Throws: Rethrows any error `action` throws.
@discardableResult
public func perform<T>(_ label: String, _ action: () throws -> T) rethrows -> T {
let before: ShoeGazeState? = shoeGaze?.captureState()
let result: T = try action()
guard let beforeState: ShoeGazeState = before,
let afterState: ShoeGazeState = shoeGaze?.captureState(),
!beforeState.hasSameRigContent(as: afterState) else {
// `hasSameRigContent` compares rig topology / parameters / MIDI / tempo while ignoring the
// session's input + channel-count fields, so a no-op edit records no checkpoint even if
// the engine's input shifted mid-edit.
return result
}
appendUndo(.structural(label: label, state: beforeState))
redoStack.removeAll()
refreshState()
return result
}
/// Records a single parameter edit (a knob / slider the user finished turning). Does nothing when
/// the value is unchanged. Clears the redo stack, matching standard undo semantics.
///
/// - Parameters:
/// - label: Short description (typically the control's label, e.g. `"Drive"`).
/// - pedalID: The id of the pedal the control belongs to.
/// - group: Which of the pedal's control collections holds it.
/// - controlLabel: The control's label, used to find it within the group.
/// - oldValue: The value when the edit began.
/// - newValue: The value when the edit ended.
public func recordParameterEdit(
label: String,
pedalID: UUID,
group: PedalControlGroup,
controlLabel: String,
oldValue: Double,
newValue: Double
) {
guard oldValue != newValue else { return }
appendUndo(.parameter(
label: label,
pedalID: pedalID,
group: group,
controlLabel: controlLabel,
oldValue: oldValue,
newValue: newValue
))
redoStack.removeAll()
refreshState()
}
/// Reverts the most recent recorded edit, restoring the rig to its state before that edit, and
/// moves the edit onto the redo stack. No-op when there is nothing to undo.
public func undo() {
guard let shoeGaze: ShoeGaze = shoeGaze, let entry: UndoEntry = undoStack.popLast() else {
return
}
switch entry {
case .structural(let label, let beforeState):
let afterState: ShoeGazeState = shoeGaze.captureState()
appendRedo(.structural(label: label, state: afterState))
restore(beforeState, on: shoeGaze)
case .parameter(_, let pedalID, let group, let controlLabel, let oldValue, _):
applyParameter(pedalID: pedalID, group: group, controlLabel: controlLabel,
value: oldValue, on: shoeGaze)
appendRedo(entry)
}
refreshState()
}
/// Re-applies the most recently undone edit and moves it back onto the undo stack. No-op when
/// there is nothing to redo.
public func redo() {
guard let shoeGaze: ShoeGaze = shoeGaze, let entry: UndoEntry = redoStack.popLast() else {
return
}
switch entry {
case .structural(let label, let afterState):
let beforeState: ShoeGazeState = shoeGaze.captureState()
appendUndo(.structural(label: label, state: beforeState))
restore(afterState, on: shoeGaze)
case .parameter(_, let pedalID, let group, let controlLabel, _, let newValue):
applyParameter(pedalID: pedalID, group: group, controlLabel: controlLabel,
value: newValue, on: shoeGaze)
appendUndo(entry)
}
refreshState()
}
/// Discards all undo and redo history. Call when the rig is replaced wholesale (new rig, rig
/// switch, library load), where carrying history across would let an undo restore a different
/// rig entirely.
public func clear() {
undoStack.removeAll()
redoStack.removeAll()
refreshState()
}
// MARK: - Private
/// Restores a rig snapshot **surgically**, so undo is safe to use live.
///
/// Rather than `loadRig` (which tears the whole rig down — stopping any recording, discarding
/// looper buffers, losing every board's reverb/delay tail, and resetting solo/bypass), this
/// reconciles board-by-board: it removes boards the undone edit added, re-adds boards it removed,
/// rebuilds only the boards whose topology changed, and reorders to match. Each step uses the
/// same per-board rebuild path as an ordinary edit (at most one block of glitch on a running
/// engine), touching nothing else.
///
/// Crucially it **preserves live parameter values**: a pedal that still exists keeps its current
/// knob/switch values (matched by id), so undoing a topology edit never reverts a knob the player
/// turned afterwards. A pedal the edit removed comes back with its snapshot values. Rig-wide MIDI
/// bindings are restored from the snapshot (so undoing a Clear brings them back); tempo and
/// bypass/solo state are left as they are, being orthogonal to a topology edit.
private func restore(_ state: ShoeGazeState, on shoeGaze: ShoeGaze) {
// Pre-board TOPOLOGY changed (a pre-pedal added / removed / reordered — compared by id
// sequence, so a knob-only change doesn't count) → the shared feed every board taps is
// different, which a surgical per-board reconcile can't express; rebuild the whole rig from
// the snapshot (ordering-safe), matching the forward edit. (Pre-pedal knob changes are
// `.parameter` undo entries, resolved by applyParameter, and never reach here.)
let targetPreIDs: [UUID] = (state.preChain ?? []).map { $0.id }
let livePreIDs: [UUID] = shoeGaze.capturePreBoardStates().map { $0.id }
let targetPostIDs: [UUID] = (state.postChain ?? []).map { $0.id }
let livePostIDs: [UUID] = shoeGaze.capturePostBoardStates().map { $0.id }
if targetPreIDs != livePreIDs || targetPostIDs != livePostIDs {
// A pre- or post-board topology change reshapes the shared feed / mix every board touches,
// which a surgical per-board reconcile can't express → rebuild the whole rig (as the
// forward edit does). Knob-only pre/post changes are `.parameter` entries, not here.
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
shoeGaze.teardown()
do { try shoeGaze.rebuildAllBoards(from: state) }
catch { print("[ShoeGaze] undo/redo pre/post-board rebuild failed: \(error)") }
shoeGaze.midiMap = state.midiMap
if wasRunning {
do { try shoeGaze.engine.start() } catch { print("[ShoeGaze] undo/redo engine restart failed: \(error)") }
}
return
}
// Current per-pedal values, keyed by pedal id, to merge onto the restored topology.
let liveValues: [UUID: PedalState] = currentPedalStatesByID(shoeGaze)
let targetIDs: Set<UUID> = Set(state.boards.map { $0.id })
// 1. Remove boards present now but absent from the target (undo of an Add Board).
for board: PedalBoard in Array(shoeGaze.boards) where !targetIDs.contains(board.id) {
shoeGaze.removeBoard(board)
}
// 2. Ensure each target board exists with the target topology + current parameter values.
for targetBoard: BoardState in state.boards {
let merged: BoardState = mergingLiveValues(into: targetBoard, liveValues: liveValues)
if let existing: PedalBoard = shoeGaze.boards.first(where: { $0.id == merged.id }) {
// Rebuild only when something actually differs, to avoid a needless audio glitch.
if existing.captureState() != merged {
do { _ = try shoeGaze.rebuildBoard(existing, from: merged) }
catch { print("[ShoeGaze] undo/redo rebuild failed: \(error)") }
}
} else {
// The undone edit had removed this board — bring it back (repositioned in step 3).
// `rebuildBoard` is the proven rebuild path; it transiently holds the fresh board's
// buses plus the rebuilt board's, which is immaterial at the default bus budget.
do {
let fresh: PedalBoard = try shoeGaze.addBoard()
_ = try shoeGaze.rebuildBoard(fresh, from: merged)
} catch {
print("[ShoeGaze] undo/redo board re-add failed: \(error)")
}
}
}
// 3. Reorder the boards to match the target order.
for (index, targetBoard): (Int, BoardState) in state.boards.enumerated() {
if let board: PedalBoard = shoeGaze.boards.first(where: { $0.id == targetBoard.id }) {
shoeGaze.moveBoard(board, to: index)
}
}
// 4. Restore the rig's MIDI bindings from the snapshot (they address pedals/boards by id,
// which the rebuild preserved). This re-arms the bindings a Clear had wiped. (It also
// reverts a binding edit made after the checkpoint — a rare edge, accepted for simplicity.)
shoeGaze.midiMap = state.midiMap
// Chain routers are intentionally NOT reconciled: no undoable (`perform`-wrapped) edit
// creates, deletes, or modifies a router, so a router is never part of an undo delta. Any
// routers currently present are left exactly as they are.
}
/// Sets a parameter back to `value` by re-resolving the control's live node from the current rig
/// (by pedal id, group, and label), so a parameter undo/redo lands on the right control even when
/// an earlier structural edit has since rebuilt the pedal. A missing pedal or control is a no-op.
private func applyParameter(
pedalID: UUID,
group: PedalControlGroup,
controlLabel: String,
value: Double,
on shoeGaze: ShoeGaze
) {
guard let pedal: Pedal = shoeGaze.pedal(id: pedalID) else { return }
let node: UIParamNode?
switch group {
case .knob:
node = pedal.knobs.first { $0.label == controlLabel }?.node
case .advancedKnob:
node = pedal.advancedKnobs.first { $0.label == controlLabel }?.node
case .slider:
node = pedal.effectSliders.first { $0.label == controlLabel }?.node
case .switch:
node = pedal.effectSwitches.first { $0.label == controlLabel }?.node
case .selector:
node = pedal.effectSelectors.first { $0.label == controlLabel }?.node
}
node?.update(value)
}
/// Flattens every pedal in the current rig into an `id → PedalState` map, descending into
/// parallel / stereo-split / stereo-unzip branches.
private func currentPedalStatesByID(_ shoeGaze: ShoeGaze) -> [UUID: PedalState] {
var map: [UUID: PedalState] = [:]
for board: BoardState in shoeGaze.captureState().boards {
for segment: BoardSegmentState in board.segments {
collectPedalStates(segment, into: &map)
}
}
return map
}
/// Adds every `PedalState` reachable from a segment (including branch lanes) to `map`, keyed by id.
private func collectPedalStates(_ segment: BoardSegmentState, into map: inout [UUID: PedalState]) {
switch segment {
case .pedal(let state):
map[state.id] = state
case .parallel(let state):
for pedal: PedalState in state.branchA + state.branchB { map[pedal.id] = pedal }
case .stereoSplit(let state):
for pedal: PedalState in state.left + state.right { map[pedal.id] = pedal }
case .stereoUnzip(let state):
for pedal: PedalState in state.left + state.right { map[pedal.id] = pedal }
case .mergeToMono:
break
}
}
/// Returns `board` with every pedal that still exists live (matched by id) swapped for its
/// current `PedalState`, so restoring a topology never reverts a parameter changed since. Pedals
/// absent from `liveValues` (ones the undone edit had removed) keep their snapshot values.
private func mergingLiveValues(into board: BoardState, liveValues: [UUID: PedalState]) -> BoardState {
let segments: [BoardSegmentState] = board.segments.map {
mergingLiveValues(into: $0, liveValues: liveValues)
}
return BoardState(id: board.id, label: board.label, segments: segments)
}
/// Per-segment counterpart of ``mergingLiveValues(into:liveValues:)`` for a single segment.
private func mergingLiveValues(
into segment: BoardSegmentState,
liveValues: [UUID: PedalState]
) -> BoardSegmentState {
switch segment {
case .pedal(let state):
return .pedal(liveValues[state.id] ?? state)
case .parallel(let state):
return .parallel(ParallelSectionState(
branchA: state.branchA.map { liveValues[$0.id] ?? $0 },
branchB: state.branchB.map { liveValues[$0.id] ?? $0 },
mode: state.mode
))
case .stereoSplit(let state):
return .stereoSplit(StereoSplitState(
left: state.left.map { liveValues[$0.id] ?? $0 },
right: state.right.map { liveValues[$0.id] ?? $0 },
route: state.route
))
case .stereoUnzip(let state):
return .stereoUnzip(StereoUnzipState(
left: state.left.map { liveValues[$0.id] ?? $0 },
right: state.right.map { liveValues[$0.id] ?? $0 },
route: state.route
))
case .mergeToMono:
return .mergeToMono
}
}
/// Appends to the undo stack, trimming the oldest entries past ``depth``.
private func appendUndo(_ entry: UndoEntry) {
undoStack.append(entry)
if undoStack.count > depth {
undoStack.removeFirst(undoStack.count - depth)
}
}
/// Appends to the redo stack, trimming the oldest entries past ``depth``.
private func appendRedo(_ entry: UndoEntry) {
redoStack.append(entry)
if redoStack.count > depth {
redoStack.removeFirst(redoStack.count - depth)
}
}
/// Recomputes the published availability flags and action labels from the current stacks.
private func refreshState() {
canUndo = !undoStack.isEmpty
canRedo = !redoStack.isEmpty
undoActionLabel = undoStack.last?.label
redoActionLabel = redoStack.last?.label
}
}
@@ -0,0 +1,50 @@
// UndoEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// One entry on an ``UndoCoordinator`` undo or redo stack.
///
/// Two kinds of edit are recorded:
/// - **Structural** topology changes (adding, removing, moving, or re-routing pedals and boards) are
/// captured as a whole-rig ``ShoeGazeState`` snapshot, restored surgically on undo.
/// - **Parameter** changes (a single knob / slider turn) are captured as the control's identity plus
/// its before/after values, so undo sets it back without disturbing anything else.
///
/// Both undo and redo are a symmetric swap: a structural entry restores its snapshot; a parameter
/// entry sets its control to the old value on undo and the new value on redo. Either way the applied
/// entry moves to the opposite stack.
enum UndoEntry {
/// A whole-rig topology change — adding, removing, or moving a pedal, board, split/merge region,
/// or router. The associated ``ShoeGazeState`` is the snapshot to restore when this entry is
/// applied: the rig state *before* the change for an undo entry, or *after* it for the matching
/// redo entry.
case structural(label: String, state: ShoeGazeState)
/// A single parameter change on one pedal control. The control is addressed by its pedal's id,
/// its group, and its label (re-resolved live so it survives an intervening rebuild); `oldValue`
/// is restored on undo and `newValue` on redo.
case parameter(
label: String,
pedalID: UUID,
group: PedalControlGroup,
controlLabel: String,
oldValue: Double,
newValue: Double
)
/// A human-readable description of the action (e.g. `"Add Reverb"`, `"Drive"`), shown next to the
/// Undo / Redo menu items and toolbar buttons.
var label: String {
switch self {
case .structural(let label, _):
return label
case .parameter(let label, _, _, _, _, _):
return label
}
}
}
@@ -79,6 +79,9 @@ public struct BoardBarView: View {
private let onAddBoard: () -> Void private let onAddBoard: () -> Void
private let onClearBoards: (() -> Void)? private let onClearBoards: (() -> Void)?
/// Undo coordinator injected by the host; `nil` outside the builder (edits run directly).
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
@State private var mode: PlayMode = .solo @State private var mode: PlayMode = .solo
// MARK: - Init // MARK: - Init
@@ -248,7 +251,11 @@ public struct BoardBarView: View {
} }
Divider() Divider()
Button("Delete Board", role: .destructive) { Button("Delete Board", role: .destructive) {
if let undo: UndoCoordinator = undo {
undo.perform("Remove Board") { shoeGaze.removeBoard(board) }
} else {
shoeGaze.removeBoard(board) shoeGaze.removeBoard(board)
}
clampEditingIndex() clampEditingIndex()
} }
} }
+46 -11
View File
@@ -63,6 +63,16 @@ public struct BoardFlowView: View {
private let shoeGaze: ShoeGaze private let shoeGaze: ShoeGaze
private let boardIndex: Int private let boardIndex: Int
/// When `true`, the view sizes to its content height and scrolls only horizontally, so it can sit
/// inside an outer vertical scroller (the pre-board → board → post-board page) without a nested
/// vertical scroll. When `false` (the default), it fills the available height and centres the
/// chain, adding a vertical scroll only for tall parallel splits.
private let sizesToContent: Bool
/// Undo coordinator injected by ``ShoeGazeBuilderView``; `nil` in lightweight hosts (previews),
/// where edits run directly without recording history.
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
/// Identifier of the lane/card currently hovered as a drop target, for highlight. /// Identifier of the lane/card currently hovered as a drop target, for highlight.
@State private var dropTarget: String? @State private var dropTarget: String?
@@ -70,9 +80,10 @@ public struct BoardFlowView: View {
/// lanes exceed the viewport height (tall parallel splits). Otherwise scrolling stays horizontal. /// lanes exceed the viewport height (tall parallel splits). Otherwise scrolling stays horizontal.
@State private var contentHeight: CGFloat = 0 @State private var contentHeight: CGFloat = 0
public init(shoeGaze: ShoeGaze, boardIndex: Int) { public init(shoeGaze: ShoeGaze, boardIndex: Int, sizesToContent: Bool = false) {
self.shoeGaze = shoeGaze self.shoeGaze = shoeGaze
self.boardIndex = boardIndex self.boardIndex = boardIndex
self.sizesToContent = sizesToContent
} }
// MARK: - Body // MARK: - Body
@@ -87,9 +98,22 @@ public struct BoardFlowView: View {
} }
} }
@ViewBuilder
private func flow(board: PedalBoard) -> some View { private func flow(board: PedalBoard) -> some View {
let stages: [StageModel] = stageModels(board: board) let stages: [StageModel] = stageModels(board: board)
return GeometryReader { proxy in if sizesToContent {
// One-scroller mode: the board is only as tall as its chain and scrolls horizontally,
// so the outer vertical scroller flows pre-board → board → post-board as one page with
// no nested vertical scroll. A tall parallel split simply makes the page taller.
ScrollView(.horizontal, showsIndicators: true) {
chainRow(board: board, stages: stages)
}
.frame(height: contentHeight > 0 ? contentHeight : nil)
.onPreferenceChange(BoardFlowContentHeightKey.self) { height in
contentHeight = height
}
} else {
GeometryReader { proxy in
let viewportHeight: CGFloat = proxy.size.height let viewportHeight: CGFloat = proxy.size.height
// Lock to horizontal, adding the vertical axis only when the chain is taller than the // Lock to horizontal, adding the vertical axis only when the chain is taller than the
// viewport (deep parallel splits) so it can be reached instead of clipped. // viewport (deep parallel splits) so it can be reached instead of clipped.
@@ -114,6 +138,7 @@ public struct BoardFlowView: View {
} }
} }
} }
}
/// The left→right chain of endpoints, connectors and stage cards. Reports its own intrinsic /// The left→right chain of endpoints, connectors and stage cards. Reports its own intrinsic
/// height through `BoardFlowContentHeightKey` so `flow` can decide whether vertical scrolling is /// height through `BoardFlowContentHeightKey` so `flow` can decide whether vertical scrolling is
@@ -293,12 +318,12 @@ public struct BoardFlowView: View {
do { do {
if split { if split {
guard !shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return } guard !shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return }
_ = try shoeGaze.insertStereoUnzip(afterSegment: segmentIndex, in: board) try editing("Split L/R") { _ = try shoeGaze.insertStereoUnzip(afterSegment: segmentIndex, in: board) }
} else { } else {
// Only remove the next segment if it is in fact this pedal's unzip region — // Only remove the next segment if it is in fact this pedal's unzip region —
// it may have been removed via the region's own trash button. // it may have been removed via the region's own trash button.
guard shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return } guard shoeGaze.isStereoUnzip(afterSegment: segmentIndex, in: board) else { return }
_ = try shoeGaze.removeSegment(at: segmentIndex + 1, from: board) try editing("Merge L/R") { _ = try shoeGaze.removeSegment(at: segmentIndex + 1, from: board) }
} }
} catch { } catch {
print("[BoardFlowView] split toggle failed: \(error)") print("[BoardFlowView] split toggle failed: \(error)")
@@ -507,7 +532,7 @@ public struct BoardFlowView: View {
sourceIndex = index sourceIndex = index
} }
do { do {
_ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board) try editing("Move Pedal") { _ = try shoeGaze.movePedal(from: sourceLane, at: sourceIndex, to: destination, in: board) }
return true return true
} catch { } catch {
print("[BoardFlowView] cross-lane move failed: \(error)") print("[BoardFlowView] cross-lane move failed: \(error)")
@@ -522,15 +547,25 @@ public struct BoardFlowView: View {
return shoeGaze.boards[boardIndex] return shoeGaze.boards[boardIndex]
} }
/// Runs a structural edit through the undo coordinator (recording a checkpoint when it changes
/// the rig), or directly when no coordinator is present.
@discardableResult
private func editing<T>(_ label: String, _ action: () throws -> T) rethrows -> T {
if let undo: UndoCoordinator = undo {
return try undo.perform(label, action)
}
return try action()
}
private func append(type: String, lane: PedalLane) { private func append(type: String, lane: PedalLane) {
guard let board: PedalBoard = board else { return } guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.appendPedal(PedalType(type), to: board, lane: lane) } do { try editing("Add \(type)") { _ = try shoeGaze.appendPedal(PedalType(type), to: board, lane: lane) } }
catch { print("[BoardFlowView] appendPedal failed: \(error)") } catch { print("[BoardFlowView] appendPedal failed: \(error)") }
} }
private func insert(type: String, at index: Int, lane: PedalLane) { private func insert(type: String, at index: Int, lane: PedalLane) {
guard let board: PedalBoard = board else { return } guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) } do { try editing("Add \(type)") { _ = try shoeGaze.insertPedal(PedalType(type), at: index, to: board, lane: lane) } }
catch { print("[BoardFlowView] insertPedal failed: \(error)") } catch { print("[BoardFlowView] insertPedal failed: \(error)") }
} }
@@ -539,20 +574,20 @@ public struct BoardFlowView: View {
// Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`: // Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`:
// a forward move lands after the target (target + 1); a backward move lands before it. // a forward move lands after the target (target + 1); a backward move lands before it.
let destination: Int = source < target ? target + 1 : target let destination: Int = source < target ? target + 1 : target
do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) } do { try editing("Move Pedal") { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) } }
catch { print("[BoardFlowView] movePedal(main) failed: \(error)") } catch { print("[BoardFlowView] movePedal(main) failed: \(error)") }
} }
private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) { private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) {
guard source != target, let board: PedalBoard = board else { return } guard source != target, let board: PedalBoard = board else { return }
let destination: Int = source < target ? target + 1 : target let destination: Int = source < target ? target + 1 : target
do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) } do { try editing("Move Pedal") { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) } }
catch { print("[BoardFlowView] movePedal(branch) failed: \(error)") } catch { print("[BoardFlowView] movePedal(branch) failed: \(error)") }
} }
private func removePedal(at index: Int, lane: PedalLane) { private func removePedal(at index: Int, lane: PedalLane) {
guard let board: PedalBoard = board else { return } guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) } do { try editing("Remove Pedal") { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) } }
catch { print("[BoardFlowView] removePedal failed: \(error)") } catch { print("[BoardFlowView] removePedal failed: \(error)") }
} }
@@ -563,7 +598,7 @@ public struct BoardFlowView: View {
private func removeSegment(at segmentIndex: Int) { private func removeSegment(at segmentIndex: Int) {
guard let board: PedalBoard = board else { return } guard let board: PedalBoard = board else { return }
do { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) } do { try editing("Remove Section") { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) } }
catch { print("[BoardFlowView] removeSegment failed: \(error)") } catch { print("[BoardFlowView] removeSegment failed: \(error)") }
} }
} }
@@ -48,6 +48,9 @@ public struct BoardsSheetView: View {
private let onAddBoard: () -> Void private let onAddBoard: () -> Void
@Environment(\.dismiss) private var dismiss @Environment(\.dismiss) private var dismiss
/// Undo coordinator; re-injected onto this sheet by the builder so board moves/removals here
/// record history. `nil` outside the builder (edits run directly).
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
@State private var mode: PlayMode = .solo @State private var mode: PlayMode = .solo
// MARK: - Init // MARK: - Init
@@ -219,14 +222,25 @@ public struct BoardsSheetView: View {
// SwiftUI's destination is the insertion point in the pre-move list; moveBoard // SwiftUI's destination is the insertion point in the pre-move list; moveBoard
// removes first, so shift down by one when moving forward. // removes first, so shift down by one when moving forward.
let target: Int = destination > sourceIndex ? destination - 1 : destination let target: Int = destination > sourceIndex ? destination - 1 : destination
if let undo: UndoCoordinator = undo {
undo.perform("Move Board") { shoeGaze.moveBoard(board, to: target) }
} else {
shoeGaze.moveBoard(board, to: target) shoeGaze.moveBoard(board, to: target)
}
clampEditingIndex() clampEditingIndex()
} }
private func deleteBoards(_ offsets: IndexSet) { private func deleteBoards(_ offsets: IndexSet) {
let remove: () -> Void = {
for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count { for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count {
shoeGaze.removeBoard(shoeGaze.boards[index]) shoeGaze.removeBoard(shoeGaze.boards[index])
} }
}
if let undo: UndoCoordinator = undo {
undo.perform("Remove Board", remove)
} else {
remove()
}
clampEditingIndex() clampEditingIndex()
} }
@@ -191,6 +191,15 @@ struct PedalMappingStrip: View {
rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges)) rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges))
} }
// Primary transport footswitch (TunedVerb Capture, FreezVerb Freeze).
if let transport: MIDITransportPedal = pedal as? MIDITransportPedal {
let action: MIDIMap.Action = .pedalAction(pedalID: pedalID, kind: .pedalPrimaryTransport)
let transportBadges: [PedalMappingBadge] = badges(for: action, in: map)
if transportBadges.isEmpty == false {
rows.append(PedalMappingRow(id: "transport", label: transport.midiTransportName, badges: transportBadges))
}
}
// Looper transport actions. // Looper transport actions.
if pedal is LooperPedal { if pedal is LooperPedal {
for kind: MIDIMap.PedalActionKind in loopedActionOrder { for kind: MIDIMap.PedalActionKind in loopedActionOrder {
@@ -248,6 +257,8 @@ struct PedalMappingStrip: View {
case .looperSyncToggle: return "Sync" case .looperSyncToggle: return "Sync"
case .looperReset: return "Reset" case .looperReset: return "Reset"
case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))" case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))"
// Not a looper action; only looper kinds reach this helper, so a plain fallback suffices.
case .pedalPrimaryTransport: return "Transport"
} }
} }
} }
+16 -6
View File
@@ -54,13 +54,15 @@ public struct HelpView: View {
"⌘1–⌘9 switch to (and solo) boards 1–9 — the fastest way to change board live.", "⌘1–⌘9 switch to (and solo) boards 1–9 — the fastest way to change board live.",
"⌘⇧1–⌘⇧9 and ⌘⇧0 load set-list rigs 1–10 in the order shown in the Rigs list — " "⌘⇧1–⌘⇧9 and ⌘⇧0 load set-list rigs 1–10 in the order shown in the Rigs list — "
+ "build a set list by reordering rigs, then step through them hands-free.", + "build a set list by reordering rigs, then step through them hands-free.",
"⌘Z mutes and unmutes the whole rig — a hard silence of all output (distinct " "⌘Z undoes the last board edit and ⇧⌘Z redoes it — add / remove / move a pedal, "
+ "from Bypass Rig, which passes your dry signal through).", + "board, or routing split. ⌘M mutes and unmutes the whole rig (a hard "
+ "silence of all output, distinct from Bypass Rig, which passes your dry "
+ "signal through).",
"On macOS the menu bar adds: ⌘N New Rig, ⌘S Save Rig, ⌘E Export Archive, " "On macOS the menu bar adds: ⌘N New Rig, ⌘S Save Rig, ⌘E Export Archive, "
+ "⌘I Import Archive, ⌘B Add Board, ⇧⌘R Start / Stop Recording, ⌘? Help, and " + "⌘I Import Archive, Edit ▸ Undo / Redo (⌘Z / ⇧⌘Z), ⌘B Add Board, "
+ "Rigs ▸ Set List (the ⌘⇧ rig slots).", + "⇧⌘R Start / Stop Recording, ⌘? Help, and Rigs ▸ Set List (the ⌘⇧ rig slots).",
"The board and set-list shortcuts and ⌘Z also work on iOS / iPadOS with a " "The board and set-list shortcuts, plus ⌘Z / ⇧⌘Z (undo / redo) and ⌘M (mute), "
+ "hardware keyboard attached.", + "also work on iOS / iPadOS with a hardware keyboard attached.",
] ]
) )
topicSection( topicSection(
@@ -88,6 +90,14 @@ public struct HelpView: View {
+ "insert before it; tap a palette pedal to append.", + "insert before it; tap a palette pedal to append.",
"Add boards with +. Solo / Blend / All choose which boards you hear; XFade sets the " "Add boards with +. Solo / Blend / All choose which boards you hear; XFade sets the "
+ "crossfade time; each board has S (solo) and B (bypass).", + "crossfade time; each board has S (solo) and B (bypass).",
"Pre-board is one chain that processes your input once, before the board split, and "
+ "feeds every board — good for a shared tuner, compressor, or noise gate. Tap "
+ "+ Pre-board to start it; it hides when empty.",
"Post-board is one chain after all boards are mixed down — good for a global reverb, "
+ "a limiter, or a final EQ across the whole rig. Tap + Post-board to start it; it "
+ "hides when empty.",
"Pre-board, the boards, and post-board scroll together top-to-bottom as one signal "
+ "path; each board's chain scrolls sideways.",
"The Rigs sidebar lists saved rigs, with New, Save, Save As, Duplicate, Rename, " "The Rigs sidebar lists saved rigs, with New, Save, Save As, Duplicate, Rename, "
+ "Delete, and Erase All.", + "Delete, and Erase All.",
"Reorder rigs into a set list by dragging a row, or via each rig's Move Up / " "Reorder rigs into a set list by dragging a row, or via each rig's Move Up / "
@@ -120,6 +120,14 @@ public struct MIDIMappingSheet: View {
id: "sw-pb-\(pedal.id)", id: "sw-pb-\(pedal.id)",
action: .pedalBypass(pedalID: pedal.id), action: .pedalBypass(pedalID: pedal.id),
label: "\(board.label) · \(pedal.displayName) · Bypass")) label: "\(board.label) · \(pedal.displayName) · Bypass"))
// A pedal with a primary transport footswitch (TunedVerb Capture, FreezVerb Freeze)
// exposes it as a mappable action.
if let transport: MIDITransportPedal = pedal as? MIDITransportPedal {
rows.append(SwitchRowModel(
id: "sw-pt-\(pedal.id)",
action: .pedalAction(pedalID: pedal.id, kind: .pedalPrimaryTransport),
label: "\(board.label) · \(pedal.displayName) · \(transport.midiTransportName)"))
}
// Loopers expose their transport footswitches as mappable switch actions. // Loopers expose their transport footswitches as mappable switch actions.
if pedal is LooperPedal { if pedal is LooperPedal {
var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [ var looperActions: [(String, String, MIDIMap.PedalActionKind)] = [
@@ -60,7 +60,7 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
"Reverse Delay": .delay, "DL4": .delay, "Reverse Delay": .delay, "DL4": .delay,
"Reverb": .reverb, "Shimmer Reverb": .reverb, "Reverb": .reverb, "Shimmer Reverb": .reverb,
"Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb, "Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb,
"Reverse Reverb": .reverb, "Granular Reverb": .reverb, "Reverse Reverb": .reverb, "Granular Reverb": .reverb, "FreezVerb": .reverb, "TunedVerb": .reverb,
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture, "Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
"Karplus Resonator": .texture, "Tape Looper": .texture, "Karplus Resonator": .texture, "Tape Looper": .texture,
] ]
@@ -23,3 +23,20 @@ extension EnvironmentValues {
set { self[PedalRebuildActionKey.self] = newValue } set { self[PedalRebuildActionKey.self] = newValue }
} }
} }
/// Environment action a leaf pedal control calls when the user finishes changing it, so the host
/// can record one undo checkpoint per edit. Arguments: the control's group, its label, and the
/// values before and after the edit. ``PedalView`` installs it capturing the pedal's id and the
/// undo coordinator; it defaults to a no-op, so a control outside the builder records nothing.
private struct PedalParameterEditRecorderKey: EnvironmentKey {
static let defaultValue: @MainActor @Sendable (PedalControlGroup, String, Double, Double) -> Void = { _, _, _, _ in }
}
extension EnvironmentValues {
/// Records a finished parameter edit (group, control label, old value, new value). No-op unless
/// the host installs it.
var pedalParameterEditRecorder: @MainActor @Sendable (PedalControlGroup, String, Double, Double) -> Void {
get { self[PedalParameterEditRecorderKey.self] }
set { self[PedalParameterEditRecorderKey.self] = newValue }
}
}
@@ -33,9 +33,15 @@ struct PedalSelectorKnobView: View {
/// rebuild for `rebuildsOnChange` selectors. `nil` for plain live-value selectors. /// rebuild for `rebuildsOnChange` selectors. `nil` for plain live-value selectors.
private let onCommit: (() -> Void)? private let onCommit: (() -> Void)?
/// Records one undo checkpoint per drag that changes the stop. Installed by ``PedalView``.
@Environment(\.pedalParameterEditRecorder) private var recordEdit
// MARK: - Drag state // MARK: - Drag state
@State private var dragStartIndex: Int = 0 @State private var dragStartIndex: Int = 0
/// Node value captured when a drag begins — the undo checkpoint's "before" (read from the node,
/// not the stop table, so it can't index out of range if the stops change).
@State private var dragStartValue: Double = 0
@State private var dragInProgress: Bool = false @State private var dragInProgress: Bool = false
// MARK: - Init // MARK: - Init
@@ -94,6 +100,7 @@ struct PedalSelectorKnobView: View {
if !dragInProgress { if !dragInProgress {
dragInProgress = true dragInProgress = true
dragStartIndex = currentIndex dragStartIndex = currentIndex
dragStartValue = selector.node.value
} }
let delta: CGFloat = gesture.translation.height // down = positive let delta: CGFloat = gesture.translation.height // down = positive
// Up should advance (increase index), so subtract the downward delta. // Up should advance (increase index), so subtract the downward delta.
@@ -107,7 +114,15 @@ struct PedalSelectorKnobView: View {
.onEnded { _ in .onEnded { _ in
let changed: Bool = currentIndex != dragStartIndex let changed: Bool = currentIndex != dragStartIndex
dragInProgress = false dragInProgress = false
if changed { onCommit?() } if changed {
onCommit?()
// A rebuildsOnChange selector alters graph topology: it is NOT recorded as a
// parameter edit (and isn't undoable yet — recording it would fight the
// structural restore's live-value merge). Only plain live-value selectors record.
if !selector.rebuildsOnChange {
recordEdit(.selector, selector.label, dragStartValue, selector.node.value)
}
}
} }
} }
@@ -56,6 +56,9 @@ public struct PedalSwitchView: View {
@Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool @Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool
/// Records one undo checkpoint per committed change. Installed by ``PedalView``; no-op elsewhere.
@Environment(\.pedalParameterEditRecorder) private var recordEdit
// MARK: - Init // MARK: - Init
/// Creates a segmented switch view. /// Creates a segmented switch view.
@@ -105,9 +108,18 @@ public struct PedalSwitchView: View {
private func segment(option: PedalSwitch.Option, isActive: Bool) -> some View { private func segment(option: PedalSwitch.Option, isActive: Bool) -> some View {
Button(action: { Button(action: {
let changed: Bool = option.value != pedalSwitch.node.value let oldValue: Double = pedalSwitch.node.value
let changed: Bool = option.value != oldValue
pedalSwitch.node.update(option.value) pedalSwitch.node.update(option.value)
if changed { onCommit?() } if changed {
onCommit?()
// A rebuildsOnChange switch alters graph topology: it is NOT recorded as a parameter
// edit (and isn't undoable yet — recording it would fight the structural restore's
// live-value merge). Only plain live-value switches become parameter edits.
if !pedalSwitch.rebuildsOnChange {
recordEdit(.switch, pedalSwitch.label, oldValue, option.value)
}
}
}) { }) {
Text(option.title) Text(option.title)
.font(.system(size: PedalSwitchView.fontSize, weight: .semibold)) .font(.system(size: PedalSwitchView.fontSize, weight: .semibold))
+52 -5
View File
@@ -246,6 +246,9 @@ struct TempoSyncKnobView: View {
let knob: PedalKnob let knob: PedalKnob
let param: TempoSyncableParam let param: TempoSyncableParam
/// Undo coordinator injected by the host; `nil` outside the builder.
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
/// Presentation flag for the division-picker popover. /// Presentation flag for the division-picker popover.
@State private var showDivisionPicker: Bool = false @State private var showDivisionPicker: Bool = false
@@ -270,6 +273,18 @@ struct TempoSyncKnobView: View {
VStack(spacing: TempoSyncKnobView.cellSpacing) { VStack(spacing: TempoSyncKnobView.cellSpacing) {
ParameterKnob(knob.label, node: knob.node, range: knob.range) ParameterKnob(knob.label, node: knob.node, range: knob.range)
.onEditingEnded { previous, newValue in
// Only reachable when free (synced knobs are disabled), so a recorded edit is a
// genuine manual turn of this time/rate knob.
undo?.recordParameterEdit(
label: knob.label,
pedalID: pedal.id,
group: .knob,
controlLabel: knob.label,
oldValue: previous,
newValue: newValue
)
}
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
.disabled(isSynced) .disabled(isSynced)
.opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0) .opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0)
@@ -513,6 +528,9 @@ public struct PedalView: View {
/// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off. /// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off.
@Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool @Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool
/// Undo coordinator injected by the host; `nil` outside the builder (edits aren't recorded).
@Environment(UndoCoordinator.self) private var undo: UndoCoordinator?
// MARK: - Init // MARK: - Init
/// Creates a stompbox pedal view for the given pedal. /// Creates a stompbox pedal view for the given pedal.
@@ -597,6 +615,18 @@ public struct PedalView: View {
PedalInfoView(pedal: pedal) PedalInfoView(pedal: pedal)
.presentationDetents([.medium, .large]) .presentationDetents([.medium, .large])
} }
// Let the self-contained control views (switch / selector / slider) record one undo
// checkpoint per edit. Captures this pedal's id + the coordinator; a no-op when `undo` is nil.
.environment(\.pedalParameterEditRecorder) { @MainActor [pedal, undo] (group: PedalControlGroup, label: String, oldValue: Double, newValue: Double) in
undo?.recordParameterEdit(
label: label,
pedalID: pedal.id,
group: group,
controlLabel: label,
oldValue: oldValue,
newValue: newValue
)
}
} }
// MARK: - Content layouts // MARK: - Content layouts
@@ -670,7 +700,7 @@ public struct PedalView: View {
Spacer(minLength: 0) Spacer(minLength: 0)
ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in
let knob: PedalKnob = knobPair.element let knob: PedalKnob = knobPair.element
ParameterKnob(knob.label, node: knob.node, range: knob.range) recordingKnob(knob)
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
} }
Spacer(minLength: 0) Spacer(minLength: 0)
@@ -866,7 +896,7 @@ public struct PedalView: View {
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
HStack(alignment: .top, spacing: PedalView.advancedPopoverSpacing) { HStack(alignment: .top, spacing: PedalView.advancedPopoverSpacing) {
ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in
ParameterKnob(knobPair.element.label, node: knobPair.element.node, range: knobPair.element.range) recordingKnob(knobPair.element, group: .advancedKnob)
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
} }
} }
@@ -924,11 +954,28 @@ public struct PedalView: View {
if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) { if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) {
TempoSyncKnobView(pedal: pedal, knob: knob, param: param) TempoSyncKnobView(pedal: pedal, knob: knob, param: param)
} else { } else {
ParameterKnob(knob.label, node: knob.node, range: knob.range) recordingKnob(knob)
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
} }
} }
/// A ``ParameterKnob`` that records one undo checkpoint per drag (via the coordinator) when the
/// user finishes turning it. The control is addressed by the pedal's id, its group, and its
/// label so undo re-resolves the live node even after an intervening rebuild.
private func recordingKnob(_ knob: PedalKnob, group: PedalControlGroup = .knob) -> ParameterKnob {
ParameterKnob(knob.label, node: knob.node, range: knob.range)
.onEditingEnded { previous, newValue in
undo?.recordParameterEdit(
label: knob.label,
pedalID: pedal.id,
group: group,
controlLabel: knob.label,
oldValue: previous,
newValue: newValue
)
}
}
/// The tempo-syncable descriptor whose parameter node backs `knob`, or `nil` if the knob is /// 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. /// not syncable. Matched by `UIParamNode` identity so it is robust to label changes.
private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? { private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? {
@@ -1141,7 +1188,7 @@ public struct PedalView: View {
@ViewBuilder @ViewBuilder
private var levelControl: some View { private var levelControl: some View {
if let level: PedalKnob = pedal.knobs.last { if let level: PedalKnob = pedal.knobs.last {
ParameterKnob(level.label, node: level.node, range: level.range) recordingKnob(level)
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
} }
} }
@@ -1152,7 +1199,7 @@ public struct PedalView: View {
@ViewBuilder @ViewBuilder
private var mixControl: some View { private var mixControl: some View {
if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last { if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last {
ParameterKnob(mix.label, node: mix.node, range: mix.range) recordingKnob(mix)
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
} }
} }
@@ -89,6 +89,11 @@ public struct ShoeGazeBuilderView: View {
/// engine already exposes an input channel, where live input is selected directly. /// engine already exposes an input channel, where live input is selected directly.
private let onEnableLiveInput: (() -> Void)? private let onEnableLiveInput: (() -> Void)?
/// Multi-level undo / redo for structural edits (add / remove / move pedals, boards, routing).
/// Supplied by the host app so the same instance also backs the macOS Edit-menu items. `nil` in
/// lightweight hosts (previews): edits then run directly, without recording history.
private let undo: UndoCoordinator?
/// Index of the board currently being edited. /// Index of the board currently being edited.
@State private var selectedBoardIndex: Int = 0 @State private var selectedBoardIndex: Int = 0
@@ -179,6 +184,10 @@ public struct ShoeGazeBuilderView: View {
/// bottom sheets so the board canvas gets the full screen. /// bottom sheets so the board canvas gets the full screen.
@State private var showRigsSheet: Bool = false @State private var showRigsSheet: Bool = false
@State private var showPaletteSheet: Bool = false @State private var showPaletteSheet: Bool = false
/// When `true`, the next palette pick is added to the pre-board chain rather than a board.
@State private var addToPreBoard: Bool = false
/// When `true`, the next palette pick is added to the post-board chain rather than a board.
@State private var addToPostBoard: Bool = false
@State private var showSettingsSheet: Bool = false @State private var showSettingsSheet: Bool = false
/// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header. /// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header.
@@ -229,13 +238,15 @@ public struct ShoeGazeBuilderView: View {
library: RigLibraryStore, library: RigLibraryStore,
hardwareSampleRate: @escaping () -> Double? = { nil }, hardwareSampleRate: @escaping () -> Double? = { nil },
onEnableLiveInput: (() -> Void)? = nil, onEnableLiveInput: (() -> Void)? = nil,
midi: MIDIController? = nil midi: MIDIController? = nil,
undo: UndoCoordinator? = nil
) { ) {
self.shoeGaze = shoeGaze self.shoeGaze = shoeGaze
self.library = library self.library = library
self.hardwareSampleRate = hardwareSampleRate self.hardwareSampleRate = hardwareSampleRate
self.onEnableLiveInput = onEnableLiveInput self.onEnableLiveInput = onEnableLiveInput
self.midi = midi self.midi = midi
self.undo = undo
} }
// MARK: - Body // MARK: - Body
@@ -578,7 +589,9 @@ public struct ShoeGazeBuilderView: View {
/// Hosts the compact Add-pedal palette sheet on its own node. /// Hosts the compact Add-pedal palette sheet on its own node.
private var paletteSheetAnchor: some View { private var paletteSheetAnchor: some View {
Color.clear Color.clear
.sheet(isPresented: $showPaletteSheet) { // Reset the pre/post-board routing flags on any dismissal (incl. swipe-to-dismiss), so a
// later board-level "+" never misroutes its pick into a pre- or post-board chain.
.sheet(isPresented: $showPaletteSheet, onDismiss: { addToPreBoard = false; addToPostBoard = false }) {
paletteSheet paletteSheet
} }
} }
@@ -713,9 +726,23 @@ public struct ShoeGazeBuilderView: View {
} }
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
ControlMappingLegend() ControlMappingLegend()
// Pre-board, the board canvas and post-board share a single vertical scroller, so the whole
// signal path reads top-to-bottom as one page (on macOS and iOS alike) instead of pinning
// the board and clipping the pre/post strips.
ScrollView(.vertical, showsIndicators: true) {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
preBoardStrip
boardArea boardArea
postBoardStrip
}
.frame(maxWidth: .infinity, alignment: .topLeading)
}
.frame(maxHeight: .infinity)
} }
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
// Make the undo coordinator reachable to every board / palette subview so their structural
// edits record history. Optional-object injection: `nil` resolves `@Environment(...)` to nil.
.environment(undo)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled) .environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
// Feed the rig's control map into the board tree so each pedal can draw its mapping strip. // 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. // Reading `shoeGaze.midiMap` here (observable) refreshes every strip when a binding changes.
@@ -818,6 +845,8 @@ public struct ShoeGazeBuilderView: View {
private var compactRigControlsRow: some View { private var compactRigControlsRow: some View {
ScrollView(.horizontal, showsIndicators: false) { ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) { HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
undoButton
redoButton
rigBypassButton rigBypassButton
rigMuteButton rigMuteButton
inputMuteButton inputMuteButton
@@ -829,6 +858,35 @@ public struct ShoeGazeBuilderView: View {
} }
} }
/// Undo of the last structural edit. Shown on iOS (where there is no Edit menu); disabled when
/// the undo stack is empty. macOS drives undo from the Edit menu (⌘Z) instead.
private var undoButton: some View {
Button {
undo?.undo()
} label: {
Image(systemName: "arrow.uturn.backward")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(.gray)
.disabled(!(undo?.canUndo ?? false))
.help("Undo the last edit")
}
/// Redo of the last undone structural edit. iOS counterpart to the Edit-menu ⇧⌘Z.
private var redoButton: some View {
Button {
undo?.redo()
} label: {
Image(systemName: "arrow.uturn.forward")
.font(.subheadline)
}
.buttonStyle(.bordered)
.tint(.gray)
.disabled(!(undo?.canRedo ?? false))
.help("Redo the last undone edit")
}
/// The composition-panel row: buttons that open the Rigs / Pedals / Settings sheets. /// The composition-panel row: buttons that open the Rigs / Pedals / Settings sheets.
private var compactPanelRow: some View { private var compactPanelRow: some View {
ScrollView(.horizontal, showsIndicators: false) { ScrollView(.horizontal, showsIndicators: false) {
@@ -897,7 +955,7 @@ public struct ShoeGazeBuilderView: View {
.foregroundStyle(Color.white) .foregroundStyle(Color.white)
Spacer() Spacer()
pedalFilterMenu pedalFilterMenu
Button("Done") { showPaletteSheet = false } Button("Done") { addToPreBoard = false; addToPostBoard = false; showPaletteSheet = false }
.fontWeight(.semibold) .fontWeight(.semibold)
} }
.padding() .padding()
@@ -909,8 +967,25 @@ public struct ShoeGazeBuilderView: View {
axis: .vertical, axis: .vertical,
filter: $pedalFilter, filter: $pedalFilter,
showsFilterMenu: false, showsFilterMenu: false,
onAdd: { type in addPedal(type: type); showPaletteSheet = false }, onAdd: { type in
onRouting: { action in performRouting(action); showPaletteSheet = false } if addToPreBoard {
addPrePedal(type: type)
} else if addToPostBoard {
addPostPedal(type: type)
} else {
addPedal(type: type)
}
addToPreBoard = false
addToPostBoard = false
showPaletteSheet = false
},
onRouting: { action in
// Routing regions belong to a board, never the linear pre- or post-board chain.
addToPreBoard = false
addToPostBoard = false
performRouting(action)
showPaletteSheet = false
}
) )
.padding() .padding()
} }
@@ -1057,6 +1132,8 @@ public struct ShoeGazeBuilderView: View {
crossfadeSeconds: $crossfadeSeconds, crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() } onAddBoard: { addBoard() }
) )
// Sheet content gets a fresh environment, so re-inject the coordinator here.
.environment(undo)
.presentationDetents([.medium, .large]) .presentationDetents([.medium, .large])
} }
} }
@@ -1339,16 +1416,202 @@ public struct ShoeGazeBuilderView: View {
} }
} }
// MARK: - Pre-board strip
/// The shared pre-board processing chain, shown above the boards. Hidden to a thin "+ Pre" button
/// when empty; otherwise a horizontal row of pre-pedals over a divider marking that it feeds all
/// boards. Pre-pedals carry their own undo (knob edits) via the injected coordinator.
@ViewBuilder
private var preBoardStrip: some View {
let prePedals: [Pedal] = shoeGaze.preBoardPedals
if prePedals.isEmpty {
HStack {
Button {
addToPreBoard = true
showPaletteSheet = true
} label: {
Label("Pre-board", systemImage: "plus").font(.caption)
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a pre-board pedal — processes the input once, feeding every board")
Spacer()
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
} else {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack {
Text("Pre-board").font(.caption).bold().foregroundStyle(Color.white)
Spacer()
Button {
addToPreBoard = true
showPaletteSheet = true
} label: {
Image(systemName: "plus")
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a pre-board pedal")
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
// Key by the pedal's stable id — a pre-board edit rebuilds the chain into new
// instances, so an offset key would bind a card to a torn-down pedal.
ForEach(Array(prePedals.enumerated()), id: \.element.id) { pair in
PedalView(pedal: pair.element)
.overlay(alignment: .topTrailing) {
Button(role: .destructive) {
removePreBoardPedal(at: pair.offset)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.title3)
.foregroundStyle(Color.white, Color.black.opacity(0.55))
}
.buttonStyle(.plain)
.padding(4)
.help("Remove this pre-board pedal")
}
}
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
}
HStack(spacing: 6) {
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
Text("feeds all boards")
.font(.caption2)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
.fixedSize()
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
}
.environment(undo)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
}
}
private func addPrePedal(type: String) {
do {
try editing("Add \(type) (pre-board)") { try shoeGaze.appendPrePedal(PedalType(type)) }
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPrePedal failed: \(error)")
reportError("Couldn’t add \(type)", error)
}
}
private func removePreBoardPedal(at index: Int) {
do {
try editing("Remove pre-board pedal") { try shoeGaze.removePrePedal(at: index) }
autosave()
} catch {
print("[ShoeGazeBuilderView] removePrePedal failed: \(error)")
reportError("Couldn’t remove pre-board pedal", error)
}
}
// MARK: - Post-board chain
/// The post-board chain strip, shown below the boards. Mirrors ``preBoardStrip``: hidden (just a
/// "+Post" button) when empty, a horizontal pedal strip otherwise. The post-chain processes the
/// summed board mix once before the hardware output — global reverb, a bus limiter, a final EQ.
@ViewBuilder
private var postBoardStrip: some View {
let postPedals: [Pedal] = shoeGaze.postBoardPedals
if postPedals.isEmpty {
HStack {
Button {
addToPostBoard = true
showPaletteSheet = true
} label: {
Label("Post-board", systemImage: "plus").font(.caption)
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a post-board pedal — processes the summed board mix before the output")
Spacer()
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
} else {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
HStack(spacing: 6) {
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
Text("from board mix")
.font(.caption2)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
.fixedSize()
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
HStack {
Text("Post-board").font(.caption).bold().foregroundStyle(Color.white)
Spacer()
Button {
addToPostBoard = true
showPaletteSheet = true
} label: {
Image(systemName: "plus")
}
.buttonStyle(.bordered)
.tint(.gray)
.help("Add a post-board pedal")
}
ScrollView(.horizontal, showsIndicators: false) {
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
// Key by the pedal's stable id — a post-board edit rebuilds the chain into new
// instances, so an offset key would bind a card to a torn-down pedal.
ForEach(Array(postPedals.enumerated()), id: \.element.id) { pair in
PedalView(pedal: pair.element)
.overlay(alignment: .topTrailing) {
Button(role: .destructive) {
removePostBoardPedal(at: pair.offset)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.title3)
.foregroundStyle(Color.white, Color.black.opacity(0.55))
}
.buttonStyle(.plain)
.padding(4)
.help("Remove this post-board pedal")
}
}
}
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
}
}
.environment(undo)
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
}
}
private func addPostPedal(type: String) {
do {
try editing("Add \(type) (post-board)") { try shoeGaze.appendPostPedal(PedalType(type)) }
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPostPedal failed: \(error)")
reportError("Couldn’t add \(type)", error)
}
}
private func removePostBoardPedal(at index: Int) {
do {
try editing("Remove post-board pedal") { try shoeGaze.removePostPedal(at: index) }
autosave()
} catch {
print("[ShoeGazeBuilderView] removePostPedal failed: \(error)")
reportError("Couldn’t remove post-board pedal", error)
}
}
// MARK: - Board area // MARK: - Board area
private var boardArea: some View { private var boardArea: some View {
// Vertically center the signal-flow board in the available space. // Content-sized so it flows inside the shared pre/board/post vertical scroller (scrolls
VStack(spacing: 0) { // horizontally for a long chain; a tall parallel split grows the page). No vertical centering —
Spacer(minLength: 0) // the board sits in signal-flow order between the pre-board and post-board strips.
BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex) BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex, sizesToContent: true)
Spacer(minLength: 0) .frame(maxWidth: .infinity, alignment: .leading)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} }
/// Performs a routing action from the palette against the selected board. /// Performs a routing action from the palette against the selected board.
@@ -1357,9 +1620,9 @@ public struct ShoeGazeBuilderView: View {
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex] let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
do { do {
switch action { switch action {
case .stereoSplit: _ = try shoeGaze.appendStereoSplit(to: board) case .stereoSplit: try editing("Add Stereo Split") { _ = try shoeGaze.appendStereoSplit(to: board) }
case .parallelSplit: _ = try shoeGaze.appendParallelSplit(to: board) case .parallelSplit: try editing("Add Parallel Split") { _ = try shoeGaze.appendParallelSplit(to: board) }
case .mergeToMono: _ = try shoeGaze.appendMergeToMono(to: board) case .mergeToMono: try editing("Add Merge to Mono") { _ = try shoeGaze.appendMergeToMono(to: board) }
case .chainRouter: break // multi-board routing; not handled in the single-board builder case .chainRouter: break // multi-board routing; not handled in the single-board builder
} }
} catch { } catch {
@@ -1401,11 +1664,22 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Actions // MARK: - Actions
/// Runs a structural edit through the undo coordinator (recording a checkpoint when it changes
/// the rig), or directly when no coordinator is present. Keep the closure to the mutation itself
/// so the before/after snapshots bracket exactly the edit.
@discardableResult
private func editing<T>(_ label: String, _ action: () throws -> T) rethrows -> T {
if let undo: UndoCoordinator = undo {
return try undo.perform(label, action)
}
return try action()
}
private func addPedal(type: String) { private func addPedal(type: String) {
guard !shoeGaze.boards.isEmpty else { return } guard !shoeGaze.boards.isEmpty else { return }
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex] let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
do { do {
_ = try shoeGaze.appendPedal(PedalType(type), to: board) try editing("Add \(type)") { try shoeGaze.appendPedal(PedalType(type), to: board) }
autosave() autosave()
} catch { } catch {
print("[ShoeGazeBuilderView] appendPedal failed: \(error)") print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
@@ -1416,9 +1690,11 @@ public struct ShoeGazeBuilderView: View {
private func addBoard() { private func addBoard() {
var created: PedalBoard? var created: PedalBoard?
do { do {
try editing("Add Board") {
let board: PedalBoard = try shoeGaze.addBoard() let board: PedalBoard = try shoeGaze.addBoard()
created = board created = board
try shoeGaze.finalizeBoard(board) try shoeGaze.finalizeBoard(board)
}
selectedBoardIndex = shoeGaze.boards.count - 1 selectedBoardIndex = shoeGaze.boards.count - 1
autosave() autosave()
} catch { } catch {
@@ -1444,6 +1720,9 @@ public struct ShoeGazeBuilderView: View {
let wasRunning: Bool = shoeGaze.engine.isRunning let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() } if wasRunning { shoeGaze.engine.stop() }
// Recorded as one undoable checkpoint: undo restores the whole pre-clear rig (boards +
// MIDI bindings). The snapshot is captured at the top of this block, before the mutations.
editing("Clear Board") {
// Clearing the rig discards its MIDI bindings — they are addressed positionally and // Clearing the rig discards its MIDI bindings — they are addressed positionally and
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't // belong to the rig being cleared. Reset before rebuilding so stale bindings can't
// re-resolve onto the fresh board's pedals. // re-resolve onto the fresh board's pedals.
@@ -1460,6 +1739,7 @@ public struct ShoeGazeBuilderView: View {
} catch { } catch {
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)") print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
} }
}
selectedBoardIndex = 0 selectedBoardIndex = 0
if wasRunning { try? shoeGaze.engine.start() } if wasRunning { try? shoeGaze.engine.start() }
@@ -1525,8 +1805,8 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Board-switch shortcuts // MARK: - Board-switch shortcuts
/// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the /// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the
/// edit target, plus ⌘M to toggle the rig mute. Kept at zero opacity so the shortcuts stay /// edit target, plus ⌘Z / ⇧⌘Z (undo / redo), ⌘M (rig mute), and ⌘⇧1…⌘⇧0 (set-list rigs) on
/// active without showing chrome. /// iOS/iPadOS. Kept at zero opacity so the shortcuts stay active without showing chrome.
private var boardSwitchShortcuts: some View { private var boardSwitchShortcuts: some View {
ZStack { ZStack {
ForEach(0 ..< min(ShoeGazeBuilderView.maxBoardShortcuts, shoeGaze.boards.count), id: \.self) { index in ForEach(0 ..< min(ShoeGazeBuilderView.maxBoardShortcuts, shoeGaze.boards.count), id: \.self) { index in
@@ -1535,11 +1815,18 @@ public struct ShoeGazeBuilderView: View {
Button("Switch to Board \(index + 1)") { switchToBoard(index) } Button("Switch to Board \(index + 1)") { switchToBoard(index) }
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command) .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
} }
// ⌘Z toggles rig mute on iOS/iPadOS hardware keyboards. On macOS the Board menu item // ⌘Z / ⇧⌘Z are Undo / Redo on iOS/iPadOS hardware keyboards; rig mute moves to ⌘M so the
// owns the ⌘Z equivalent, so it is not also bound here (a double-bound event is ambiguous). // standard undo chord is free. On macOS the Edit / Board menus own these equivalents, so
// they are not also bound here (a double-bound event is ambiguous).
#if !os(macOS) #if !os(macOS)
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() } Button("Undo") { undo?.undo() }
.keyboardShortcut("z", modifiers: .command) .keyboardShortcut("z", modifiers: .command)
.disabled(!(undo?.canUndo ?? false))
Button("Redo") { undo?.redo() }
.keyboardShortcut("z", modifiers: [.command, .shift])
.disabled(!(undo?.canRedo ?? false))
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() }
.keyboardShortcut("m", modifiers: .command)
// ⌘⇧1…⌘⇧9 + ⌘⇧0 load set-list rigs 1…10. macOS binds these via the Rigs ▸ Set List menu // ⌘⇧1…⌘⇧9 + ⌘⇧0 load set-list rigs 1…10. macOS binds these via the Rigs ▸ Set List menu
// instead, so they are not also bound here. // instead, so they are not also bound here.
ForEach(0 ..< ShoeGazeBuilderView.maxRigShortcuts, id: \.self) { slot in ForEach(0 ..< ShoeGazeBuilderView.maxRigShortcuts, id: \.self) { slot in
@@ -1646,6 +1933,10 @@ public struct ShoeGazeBuilderView: View {
} catch { } catch {
print("[ShoeGazeBuilderView] loadEntry failed: \(error)") print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
} }
// Switching to a different rig is not an undoable edit — discard the previous rig's history
// so an undo can't restore a different document's topology. Unconditional: `loadRig` tears
// the old rig down even when it throws, so the prior history is invalid either way.
undo?.clear()
if wasRunning { try? shoeGaze.engine.start() } if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle() transportTick.toggle()
} }
@@ -1847,6 +2138,8 @@ public struct ShoeGazeBuilderView: View {
print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)") print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)")
} }
selectedBoardIndex = 0 selectedBoardIndex = 0
// A brand-new rig is a fresh document — drop any prior undo history.
undo?.clear()
if wasRunning { try? shoeGaze.engine.start() } if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle() transportTick.toggle()
persist(shoeGaze.captureEntry(name: name)) persist(shoeGaze.captureEntry(name: name))
@@ -70,6 +70,9 @@ public struct ShoeGazeView: View {
private let shoeGaze: ShoeGaze private let shoeGaze: ShoeGaze
private let hardwareSampleRate: () -> Double? private let hardwareSampleRate: () -> Double?
/// Multi-level undo / redo for board edits made from this view, injected into the board bar.
@State private var undo: UndoCoordinator
/// Bumped on each transport button press to force a re-read of the engine's /// Bumped on each transport button press to force a re-read of the engine's
/// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning` /// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning`
/// directly (the single source of truth) rather than a private mirror that could /// directly (the single source of truth) rather than a private mirror that could
@@ -102,6 +105,7 @@ public struct ShoeGazeView: View {
) { ) {
self.shoeGaze = shoeGaze self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate self.hardwareSampleRate = hardwareSampleRate
self._undo = State(initialValue: UndoCoordinator(shoeGaze: shoeGaze))
} }
// MARK: - Body // MARK: - Body
@@ -118,6 +122,7 @@ public struct ShoeGazeView: View {
crossfadeSeconds: $crossfadeSeconds, crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() } onAddBoard: { addBoard() }
) )
.environment(undo)
Divider() Divider()
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
boardList boardList
@@ -249,7 +254,7 @@ public struct ShoeGazeView: View {
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
let board: PedalBoard = pair.element let board: PedalBoard = pair.element
PedalBoardView(board: board) { PedalBoardView(board: board) {
shoeGaze.removeBoard(board) undo.perform("Remove Board") { shoeGaze.removeBoard(board) }
} }
} }
} }
@@ -293,10 +298,12 @@ public struct ShoeGazeView: View {
private func addBoard() { private func addBoard() {
var createdBoard: PedalBoard? var createdBoard: PedalBoard?
do { do {
try undo.perform("Add Board") {
let board: PedalBoard = try shoeGaze.addBoard() let board: PedalBoard = try shoeGaze.addBoard()
createdBoard = board createdBoard = board
try board.add(OverdrivePedal()) try board.add(OverdrivePedal())
try shoeGaze.finalizeBoard(board) try shoeGaze.finalizeBoard(board)
}
} catch { } catch {
if let board: PedalBoard = createdBoard { if let board: PedalBoard = createdBoard {
shoeGaze.removeBoard(board) shoeGaze.removeBoard(board)
@@ -7,6 +7,7 @@
import SwiftUI import SwiftUI
import LyrebirdUI import LyrebirdUI
import LyrebirdSynth import LyrebirdSynth
import LyrebirdShoeGaze
/// A vertical fader bound to a single ``UIParamNode``. /// A vertical fader bound to a single ``UIParamNode``.
/// ///
@@ -49,6 +50,13 @@ struct VerticalParameterSlider: View {
private let node: UIParamNode private let node: UIParamNode
private let range: ClosedRange<Double> private let range: ClosedRange<Double>
/// Records one undo checkpoint per drag. Installed by ``PedalView``; no-op elsewhere.
@Environment(\.pedalParameterEditRecorder) private var recordEdit
/// Node value captured when a drag begins, for the undo checkpoint's "before".
@State private var dragStartValue: Double = 0
@State private var dragInProgress: Bool = false
// MARK: - Init // MARK: - Init
/// Creates a vertical fader. /// Creates a vertical fader.
@@ -141,8 +149,16 @@ struct VerticalParameterSlider: View {
.gesture( .gesture(
DragGesture(minimumDistance: 0) DragGesture(minimumDistance: 0)
.onChanged { drag in .onChanged { drag in
if !dragInProgress {
dragInProgress = true
dragStartValue = node.value
}
updateValue(forY: drag.location.y, height: height) updateValue(forY: drag.location.y, height: height)
} }
.onEnded { _ in
dragInProgress = false
recordEdit(.slider, label, dragStartValue, node.value)
}
) )
} }
.frame(width: VerticalParameterSlider.controlWidth, height: VerticalParameterSlider.trackHeight) .frame(width: VerticalParameterSlider.controlWidth, height: VerticalParameterSlider.trackHeight)
@@ -382,6 +382,25 @@ struct BoardEditAPITests {
#expect(edited.width == 2, "board should remain stereo") #expect(edited.width == 2, "board should remain stereo")
} }
// MARK: - Board identity is stable across edits
@Test func editingPreservesBoardIdentity() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// MIDI bindings address a board by its `id`; a pedal edit rebuilds the board and must keep it.
let originalID: UUID = board.id
let afterAppend: PedalBoard = try sg.appendPedal(.reverb, to: board)
#expect(afterAppend.id == originalID, "append must not regenerate the board id")
let afterMove: PedalBoard = try sg.movePedal(from: 0, to: 2, in: afterAppend)
#expect(afterMove.id == originalID, "move must not regenerate the board id")
let afterRemove: PedalBoard = try sg.removePedal(at: 0, from: afterMove)
#expect(afterRemove.id == originalID, "remove must not regenerate the board id")
}
// MARK: - Input source switching // MARK: - Input source switching
@Test func setInputSourcePreservesRigAndRewiresInput() throws { @Test func setInputSourcePreservesRigAndRewiresInput() throws {
@@ -0,0 +1,313 @@
// FreezVerbPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A steady sine whose level can be muted mid-render via its `gain` parameter — lets a test silence
/// the live input while a snapshot is held, to prove the pad sustains from the freeze and not from
/// the ongoing signal.
@MainActor
private final class GatedSineSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
@UIParam var gain: Double = 0.5
init(targetBus: Int, freq: Double) {
self.targetBus = targetBus
self.freq = freq
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: freq) * $gain)
}
}
@MainActor
@Suite("FreezVerbPedal")
struct FreezVerbPedalTests {
private let sampleRate: Double = 44_100.0
private let sineHz: Double = 220.0
// MARK: - One-shot NRT render (no mid-render control)
private func render(
duration: Double,
configure: (FreezVerbPedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: GatedSineSource = GatedSineSource(targetBus: srcBus.index, freq: sineHz)
let pedal: FreezVerbPedal = FreezVerbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
// MARK: - Block-stepped render with mid-render freeze / mute control
/// Steps the engine block-by-block, invoking `onFrame` before each block so a test can engage the
/// freeze or mute the source at chosen frames. Returns the left output channel.
private func stepRender(
totalFrames: Int,
blockSize: Int,
configure: (FreezVerbPedal) -> Void,
onFrame: (_ frame: Int, _ source: GatedSineSource, _ pedal: FreezVerbPedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let numControlBuses: Int = 512
let driver: OfflineDriver = OfflineDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: GatedSineSource = GatedSineSource(targetBus: srcBus.index, freq: sineHz)
let pedal: FreezVerbPedal = FreezVerbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
let noInput: [[Float]] = []
var left: [Float] = []
left.reserveCapacity(totalFrames)
var frame: Int = 0
while frame < totalFrames {
onFrame(frame, source, pedal)
engine.processBlock(inputSamples: noInput)
left.append(contentsOf: engine.audioBuses[0])
frame += blockSize
}
engine.stop()
return left
}
// MARK: - Analysis
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
let a: Int = max(0, loFrame)
let b: Int = min(hiFrame, samples.count)
guard b > a else { return 0.0 }
var sum: Double = 0.0
for i: Int in a ..< b {
let v: Double = Double(samples[i])
sum += v * v
}
return (sum / Double(b - a)).squareRoot()
}
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
let a: Int = max(1, lo)
let b: Int = min(hi, x.count)
guard b > a else { return 0.0 }
var m: Double = 0.0
for i: Int in a ..< b {
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
if d > m { m = d }
}
return m
}
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
// Unfrozen, the dry signal passes straight through — output is never silent.
let out: [Float] = try render(duration: 1.0) { _ in }
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "Freeze output was silent")
}
@Test func renderIsDeterministic() throws {
// No RNG anywhere in the graph, so two identical renders are bit-identical.
let a: [Float] = try render(duration: 1.0) { pedal in pedal.verb = 0.6; pedal.tone = 0.4 }
let b: [Float] = try render(duration: 1.0) { pedal in pedal.verb = 0.6; pedal.tone = 0.4 }
#expect(a == b, "deterministic freeze-reverb renders of the same setting should be bit-identical")
}
@Test func snapshotSustainsAfterInputStops() throws {
// The defining behaviour: engage Freeze while a tone plays, then MUTE the input. A held
// spectral snapshot keeps ringing; without the freeze the pad gate is shut, so once the dry
// input is gone the output falls silent. Compare the two in the same late window.
let blockSize: Int = 512
let totalFrames: Int = Int(1.6 * sampleRate)
let freezeFrame: Int = Int(0.45 * sampleRate)
let muteFrame: Int = Int(0.75 * sampleRate)
let windowLo: Int = Int(1.1 * sampleRate)
let windowHi: Int = Int(1.5 * sampleRate)
let frozen: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.verb = 0.6; pedal.tone = 0.5; pedal.rise = 0.05
} onFrame: { frame, source, pedal in
if frame >= freezeFrame, !pedal.holding { pedal.toggleFreeze() }
if frame >= muteFrame { source.gain = 0.0 }
}
let control: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.verb = 0.6; pedal.tone = 0.5; pedal.rise = 0.05
} onFrame: { frame, source, _ in
// Never freeze; mute at the same frame.
if frame >= muteFrame { source.gain = 0.0 }
}
let heldTail: Double = rms(frozen, loFrame: windowLo, hiFrame: windowHi)
let unfrozenTail: Double = rms(control, loFrame: windowLo, hiFrame: windowHi)
#expect(heldTail > 1.0e-3, "a held snapshot should still ring after the input stops, tail RMS \(heldTail)")
#expect(heldTail > unfrozenTail * 10.0,
"frozen tail \(heldTail) should dwarf the unfrozen tail \(unfrozenTail) once the input is muted")
}
@Test func releaseFadesThePadOut() throws {
// Freeze, mute the input, then release: after the Rise fade the held pad should fall away,
// leaving the late window far quieter than while it was held.
let blockSize: Int = 512
let totalFrames: Int = Int(2.0 * sampleRate)
let freezeFrame: Int = Int(0.4 * sampleRate)
let muteFrame: Int = Int(0.7 * sampleRate)
let releaseFrame: Int = Int(1.1 * sampleRate)
let heldLo: Int = Int(0.95 * sampleRate)
let heldHi: Int = Int(1.05 * sampleRate)
let afterLo: Int = Int(1.7 * sampleRate)
let afterHi: Int = Int(1.95 * sampleRate)
var froze: Bool = false
var released: Bool = false
let out: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.verb = 0.5; pedal.tone = 0.5; pedal.rise = 0.1
} onFrame: { frame, source, pedal in
if frame >= freezeFrame, !froze { pedal.toggleFreeze(); froze = true }
if frame >= muteFrame { source.gain = 0.0 }
if frame >= releaseFrame, froze, !released { pedal.toggleFreeze(); released = true }
}
let heldRMS: Double = rms(out, loFrame: heldLo, hiFrame: heldHi)
let afterRMS: Double = rms(out, loFrame: afterLo, hiFrame: afterHi)
#expect(heldRMS > 1.0e-3, "pad should be audible while held, got \(heldRMS)")
#expect(afterRMS < heldRMS * 0.5, "releasing should fade the pad out: after \(afterRMS) vs held \(heldRMS)")
}
// MARK: - Bypass
@Test func bypassSwitchIsClickFree() throws {
let blockSize: Int = 512
let totalFrames: Int = Int(0.6 * sampleRate)
let flipFrame: Int = Int(0.35 * sampleRate)
// Steady-state window ends before the flip; a settle margin after it covers the fade tail.
let steadyLo: Int = Int(0.22 * sampleRate)
let steadyHi: Int = Int(0.33 * sampleRate)
let settleMargin: Int = Int(0.045 * sampleRate)
let left: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.verb = 0.5
} onFrame: { frame, _, pedal in
if frame >= flipFrame { pedal.bypass = 1.0 }
}
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi)
let fadeFrames: Int = Int(0.03 * sampleRate)
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + settleMargin)
#expect(transStep <= steadyStep * 4.0,
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
}
// MARK: - Wiring
@Test func exposesControls() throws {
let pedal: FreezVerbPedal = FreezVerbPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Verb", "Tone", "Rise"])
#expect(pedal.effectTransportButtons.map { $0.label } == ["Freeze"])
#expect(pedal.showsMixControl == false)
}
@Test func freezeTogglesHoldState() throws {
// The transport latch flips the held state without needing a running engine.
let pedal: FreezVerbPedal = FreezVerbPedal()
#expect(pedal.holding == false)
pedal.toggleFreeze()
#expect(pedal.holding == true)
#expect(pedal.frozen == 1.0)
pedal.toggleFreeze()
#expect(pedal.holding == false)
#expect(pedal.frozen == 0.0)
}
@Test func presetRoundTripPreservesControls() throws {
let pedal: FreezVerbPedal = FreezVerbPedal()
pedal.verb = 0.33
pedal.tone = 0.8
pedal.rise = 1.5
let state: PedalState = pedal.captureState()
let restored: FreezVerbPedal = FreezVerbPedal()
restored.applyState(state)
#expect(restored.verb == 0.33)
#expect(restored.tone == 0.8)
#expect(restored.rise == 1.5)
}
@Test func heldSnapshotIsNotPersisted() throws {
// `frozen` is transport state, not a preset control: a pedal captured mid-freeze must restore
// released, with no phantom pad blooming on load.
let pedal: FreezVerbPedal = FreezVerbPedal()
pedal.verb = 0.4
pedal.toggleFreeze()
#expect(pedal.holding == true)
#expect(pedal.frozen == 1.0)
let state: PedalState = pedal.captureState()
let restored: FreezVerbPedal = FreezVerbPedal()
restored.applyState(state)
#expect(restored.frozen == 0.0, "a held snapshot must not persist into a preset")
#expect(restored.holding == false)
#expect(restored.verb == 0.4)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "FreezVerb")
#expect(pedal is FreezVerbPedal)
}
}
@@ -353,4 +353,34 @@ struct MIDIControllerPCTests {
#expect(looper.isTrackMuted(0), "mapped Program Change should tap (mute) the selected recorded track") #expect(looper.isTrackMuted(0), "mapped Program Change should tap (mute) the selected recorded track")
} }
} }
@Test func tunedVerbAndFreezVerbExposeAPrimaryTransport() {
// Unconditional conformance — the `as` is a compile-time proof the pedals are transport-mappable.
let tunedVerb: any MIDITransportPedal = TunedVerbPedal()
let freezVerb: any MIDITransportPedal = FreezVerbPedal()
#expect(tunedVerb.midiTransportName == "Capture")
#expect(freezVerb.midiTransportName == "Freeze")
}
@Test func mappedProgramChangeTogglesTunedVerbCapture() throws {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url) }
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
let tuned: TunedVerbPedal = TunedVerbPedal()
try board.add(tuned)
try sg.finalizeBoard(board)
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
withExtendedLifetime(sg) {
controller.armSwitchLearn(.pedalAction(pedalID: tuned.id, kind: .pedalPrimaryTransport))
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // learn only
#expect(tuned.captured < 0.5, "learn must not toggle Capture")
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // fire
#expect(tuned.captured > 0.5, "a mapped Program Change toggles Capture on")
controller.ingestForTesting(.programChange(channel: 0, program: 3)) // fire again
#expect(tuned.captured < 0.5, "a second press toggles Capture off")
}
}
} }
@@ -0,0 +1,170 @@
// PostBoardChainTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Post-board chain")
struct PostBoardChainTests {
private func makeRig(
boardCount: Int,
duration: Double = 0.1
) throws -> (ShoeGaze, SynthesisEngine, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
for _ in 0 ..< boardCount {
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
try sg.finalizeBoard(board)
}
return (sg, engine, url)
}
private func render(_ engine: SynthesisEngine, _ url: URL) throws -> [Float] {
try engine.start()
return readStereoCAF(url: url)
}
@Test func postBoardChainProcessesTheMixAndRenders() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
#expect(sg.postBoardStates.count == 1)
#expect(sg.postBoardPedals.count == 1, "the live post-chain holds the added pedal")
#expect(sg.boards.count == 2, "the boards are left in place")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "a post-board pedal keeps the summed mix flowing to output")
}
@Test func aClosedPostBoardVolumeSilencesTheOutput() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.volume)
// Close the post-board volume (position 0 = silent) before start → the final output is silent,
// proving the post-chain sits in the output path after the board mix.
let volume: Pedal = try #require(sg.postBoardPedals.first)
let state: PedalState = volume.captureState()
try #require(!state.knobValues.isEmpty)
volume.applyState(
PedalState(id: state.id, type: state.type, knobValues: [0.0],
switchValues: state.switchValues, bypass: state.bypass)
)
let samples: [Float] = try render(engine, url)
#expect(!hasNonSilentOutput(samples), "a closed post-board volume silences the whole rig output")
}
@Test func removingTheLastPostPedalRestoresDirectOutput() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
#expect(sg.postBoardPedals.count == 1)
try sg.removePostPedal(at: 0)
#expect(sg.postBoardStates.isEmpty)
#expect(sg.postBoardPedals.isEmpty, "the post-chain is gone")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "the rig renders straight to hardware again")
}
@Test func addingABoardWhileAPostChainExistsKeepsOutputFlowing() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
// Add a second board AFTER the post-chain exists. The post-chain sits at the tail of the main
// group, so the new master (spliced nearer the head) evaluates before it with no rebuild.
let second: PedalBoard = try sg.addBoard()
try second.add(DelayPedal())
try sg.finalizeBoard(second)
#expect(sg.boards.count == 2)
#expect(sg.postBoardPedals.count == 1, "the post-chain survives the board add")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "both boards reach output through the re-ordered post-chain")
}
@Test func postChainEvaluatesAfterEveryBoardMasterNotJustTheLast() throws {
// The naive anchor was `outputMasters.last` — the *last-finalized* board. But board taps are
// spliced `.after(feedNode)`, so a later board evaluates EARLIER; `outputMasters.last` is the
// first-evaluated master, and a post-chain placed after it reads the mix before the other
// boards write it. Here we silence the last-finalized board and keep the first one audible:
// if the post-chain ran before board 0's master, the mix would be empty and the output silent.
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
// Close the LAST-finalized board's master; only the first board feeds the mix now.
let lastBoardGain: UIParamNode = try #require(sg.boards[1].masterGainNode)
lastBoardGain.update(0.0)
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples),
"the first board must still reach the output through a tail-ordered post-chain")
}
@Test func insertMoveAndRemoveOrderThePostChain() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
try sg.insertPostPedal(.volume, at: 0)
#expect(sg.postBoardStates.map { $0.type } == ["Volume", "Reverb"], "insert lands at the index")
// SwiftUI `toOffset` semantics — move the Reverb (index 1) to the front.
try sg.movePostPedal(from: 1, to: 0)
#expect(sg.postBoardStates.map { $0.type } == ["Reverb", "Volume"], "move reorders the chain")
try sg.removePostPedal(at: 0)
#expect(sg.postBoardStates.map { $0.type } == ["Volume"], "remove drops the indexed pedal")
#expect(sg.postBoardPedals.map { $0.id } == sg.postBoardStates.map { $0.id },
"live pedals track the states in order")
}
@Test func postBoardChainRoundTripsThroughSaveLoad() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPostPedal(.reverb)
let knob: PedalKnob = try #require(sg.postBoardPedals.first?.knobs.first)
let sentinel: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.44
knob.node.update(sentinel)
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
try sg.saveRig(to: preset)
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url2) }
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
try sg2.loadRig(from: preset)
#expect(sg2.postBoardStates.map { $0.type } == ["Reverb"], "post-chain round-trips")
#expect(sg2.postBoardPedals.count == 1, "the reloaded post-chain is live")
let reloadedKnob: Double = try #require(sg2.postBoardPedals.first?.captureState().knobValues.first)
#expect(abs(reloadedKnob - sentinel) < 1e-9, "a post-pedal knob tweak survives save/load")
try engine2.start()
#expect(hasNonSilentOutput(readStereoCAF(url: url2)), "reloaded post-board rig renders")
}
@Test func oldRigWithoutPostChainDecodesToEmpty() throws {
let state: ShoeGazeState = ShoeGazeState(boards: [])
#expect(state.postChain == nil)
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.postChain == nil, "absent/nil postChain stays nil")
}
}
@@ -0,0 +1,137 @@
// PreBoardChainTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Pre-board chain")
struct PreBoardChainTests {
/// Builds an NRT-backed `ShoeGaze` with `boardCount` single-Overdrive boards.
private func makeRig(
boardCount: Int,
duration: Double = 0.1
) throws -> (ShoeGaze, SynthesisEngine, URL) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: duration, numAudioBuses: 256)
let sg: ShoeGaze = ShoeGaze(engine: engine)
for _ in 0 ..< boardCount {
let board: PedalBoard = try sg.addBoard()
try board.add(OverdrivePedal())
try sg.finalizeBoard(board)
}
return (sg, engine, url)
}
private func render(_ engine: SynthesisEngine, _ url: URL) throws -> [Float] {
try engine.start()
return readStereoCAF(url: url)
}
@Test func preBoardChainRendersAndFeedsBoards() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
#expect(sg.preBoardStates.count == 1)
#expect(sg.preBoardPedals.count == 1, "the live pre-chain holds the added pedal")
#expect(sg.boards.count == 2, "pre-board edit leaves the boards in place")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "a pre-board pedal keeps the signal flowing to the boards")
}
@Test func aClosedPreBoardVolumeSilencesEveryBoard() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 2)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.volume)
// Close the pre-board volume (position 0 = silent) before start, so it is delivered flat.
let volume: Pedal = try #require(sg.preBoardPedals.first)
let state: PedalState = volume.captureState()
try #require(!state.knobValues.isEmpty)
volume.applyState(
PedalState(id: state.id, type: state.type, knobValues: [0.0],
switchValues: state.switchValues, bypass: state.bypass)
)
let samples: [Float] = try render(engine, url)
#expect(!hasNonSilentOutput(samples), "a closed pre-board volume silences the feed to every board")
}
@Test func removingTheLastPrePedalRestoresTheDirectFeed() throws {
let (sg, engine, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
#expect(sg.preBoardPedals.count == 1)
try sg.removePrePedal(at: 0)
#expect(sg.preBoardStates.isEmpty)
#expect(sg.preBoardPedals.isEmpty, "the pre-chain is gone")
let samples: [Float] = try render(engine, url)
#expect(hasNonSilentOutput(samples), "the board renders from the direct feed again")
}
@Test func preBoardChainRoundTripsThroughSaveLoad() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
try sg.appendPrePedal(.delay)
#expect(sg.preBoardStates.map { $0.type } == ["Overdrive", "Delay"])
// Tweak the LIVE first pre-pedal's knob — the save must capture it, not the stale default.
let knob: PedalKnob = try #require(sg.preBoardPedals.first?.knobs.first)
let sentinel: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.41
knob.node.update(sentinel)
let preset: URL = FileManager.default.temporaryDirectory
.appendingPathComponent(UUID().uuidString + ".json")
defer { try? FileManager.default.removeItem(at: preset) }
try sg.saveRig(to: preset)
let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 256)
defer { try? FileManager.default.removeItem(at: url2) }
let sg2: ShoeGaze = ShoeGaze(engine: engine2)
try sg2.loadRig(from: preset)
#expect(sg2.preBoardStates.map { $0.type } == ["Overdrive", "Delay"], "pre-chain round-trips")
#expect(sg2.preBoardPedals.count == 2, "the reloaded pre-chain is live")
let reloadedKnob: Double = try #require(sg2.preBoardPedals.first?.captureState().knobValues.first)
#expect(abs(reloadedKnob - sentinel) < 1e-9, "a pre-pedal knob tweak survives save/load")
try engine2.start()
#expect(hasNonSilentOutput(readStereoCAF(url: url2)), "reloaded pre-board rig renders")
}
@Test func addingASecondPrePedalKeepsTheFirstsLiveKnob() throws {
let (sg, _, url): (ShoeGaze, SynthesisEngine, URL) = try makeRig(boardCount: 1)
defer { try? FileManager.default.removeItem(at: url) }
try sg.appendPrePedal(.overdrive)
let knob: PedalKnob = try #require(sg.preBoardPedals.first?.knobs.first)
let sentinel: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.37
knob.node.update(sentinel)
// Adding a second pre-pedal rebuilds the whole pre-chain; the first pedal's live knob must be
// folded into the rebuild, not reset to its default.
try sg.appendPrePedal(.delay)
let firstKnob: Double = try #require(sg.preBoardPedals.first?.captureState().knobValues.first)
#expect(abs(firstKnob - sentinel) < 1e-9, "a prior pre-pedal's live knob survives adding another")
}
@Test func oldRigWithoutPreChainDecodesToEmpty() throws {
// A ShoeGazeState encoded without the preChain key (older rig) decodes to no pre-board chain.
let state: ShoeGazeState = ShoeGazeState(boards: [])
#expect(state.preChain == nil)
let data: Data = try JSONEncoder().encode(state)
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
#expect(decoded.preChain == nil, "absent/nil preChain stays nil")
}
}
@@ -0,0 +1,350 @@
// TunedVerbPedalTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
/// A source that crossfades between two tones under a `morph` parameter, so a test can capture the
/// filter on tone A, then switch to tone B and show the locked spectrum shapes B differently than
/// live tracking would.
@MainActor
private final class TwoToneSource: SynthesizerBase {
private let targetBus: Int
private let freqA: Double
private let freqB: Double
/// `0` = tone A, `1` = tone B.
@UIParam var morph: Double = 0.0
init(targetBus: Int, freqA: Double, freqB: Double) {
self.targetBus = targetBus
self.freqA = freqA
self.freqB = freqB
super.init()
}
override func build() {
let a: BinaryOpGenerator = OscSin.Audio(freq: freqA, mul: 0.5) * (1.0 - $morph)
let b: BinaryOpGenerator = OscSin.Audio(freq: freqB, mul: 0.5) * $morph
output(bus: targetBus, source: a + b)
}
}
/// A steady sine for the non-silent / determinism / pan / bypass checks.
@MainActor
private final class TestSineSource: SynthesizerBase {
private let targetBus: Int
private let freq: Double
init(targetBus: Int, freq: Double) {
self.targetBus = targetBus
self.freq = freq
super.init()
}
override func build() {
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5))
}
}
@MainActor
@Suite("TunedVerbPedal")
struct TunedVerbPedalTests {
private let sampleRate: Double = 44_100.0
private let toneHz: Double = 220.0
// MARK: - One-shot NRT render
private func render(
duration: Double,
configure: (TunedVerbPedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
numAudioBuses: numAudioBuses
)
defer { try? FileManager.default.removeItem(at: url) }
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz)
let pedal: TunedVerbPedal = TunedVerbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
return readStereoCAF(url: url)
}
// MARK: - Block-stepped render (mid-render capture / input morph)
private func stepRender(
totalFrames: Int,
blockSize: Int,
configure: (TunedVerbPedal) -> Void,
onFrame: (_ frame: Int, _ source: TwoToneSource, _ pedal: TunedVerbPedal) -> Void
) throws -> [Float] {
let numAudioBuses: Int = 64
let numControlBuses: Int = 512
let driver: OfflineDriver = OfflineDriver()
let engine: SynthesisEngine = SynthesisEngine(
blockSize: blockSize,
sampleRate: sampleRate,
numOutputChannels: 2,
numInputChannels: 0,
numAudioBuses: numAudioBuses,
numControlBuses: numControlBuses,
driver: driver
)
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 2)
defer {
engine.busAllocator.releaseAudioBus(srcBus)
engine.busAllocator.releaseAudioBus(dstBus)
}
let source: TwoToneSource = TwoToneSource(targetBus: srcBus.index, freqA: 180.0, freqB: 900.0)
let pedal: TunedVerbPedal = TunedVerbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
configure(pedal)
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
try engine.add(source)
try engine.add(pedal, position: NodePosition.after(source))
try engine.add(master, position: NodePosition.after(pedal))
try engine.start()
let noInput: [[Float]] = []
var left: [Float] = []
left.reserveCapacity(totalFrames)
var frame: Int = 0
while frame < totalFrames {
onFrame(frame, source, pedal)
engine.processBlock(inputSamples: noInput)
left.append(contentsOf: engine.audioBuses[0])
frame += blockSize
}
engine.stop()
return left
}
// MARK: - Analysis
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
let a: Int = max(0, loFrame)
let b: Int = min(hiFrame, samples.count)
guard b > a else { return 0.0 }
var sum: Double = 0.0
for i: Int in a ..< b { let v: Double = Double(samples[i]); sum += v * v }
return (sum / Double(b - a)).squareRoot()
}
private func rmsDiff(_ a: [Float], _ b: [Float], loFrame: Int, hiFrame: Int) -> Double {
let lo: Int = max(0, loFrame)
let hi: Int = min(hiFrame, min(a.count, b.count))
guard hi > lo else { return 0.0 }
var sum: Double = 0.0
for i: Int in lo ..< hi { let d: Double = Double(a[i]) - Double(b[i]); sum += d * d }
return (sum / Double(hi - lo)).squareRoot()
}
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
let a: Int = max(1, lo)
let b: Int = min(hi, x.count)
guard b > a else { return 0.0 }
var m: Double = 0.0
for i: Int in a ..< b { let d: Double = abs(Double(x[i]) - Double(x[i - 1])); if d > m { m = d } }
return m
}
// MARK: - Behaviour
@Test func buildsAndProducesNonSilentOutput() throws {
let out: [Float] = try render(duration: 0.8) { _ in }
#expect(!out.isEmpty)
#expect(hasNonSilentOutput(out), "TunedVerb output was silent")
}
@Test func renderIsDeterministic() throws {
let a: [Float] = try render(duration: 0.8) { pedal in pedal.time = 4.0; pedal.damp = 0.4 }
let b: [Float] = try render(duration: 0.8) { pedal in pedal.time = 4.0; pedal.damp = 0.4 }
#expect(a == b, "deterministic capture-reverb renders of the same setting should be bit-identical")
}
@Test func panShiftsTheLeftLeg() throws {
// Fully wet, the output follows the panned wash — but the wash only exists after a capture, so
// capture early, then measure. Hard left fills the left leg; hard right nearly empties it.
// (`stepRender` returns the left output bus; the right is board-wired live.)
let blockSize: Int = 512
let totalFrames: Int = Int(0.8 * sampleRate)
let captureFrame: Int = Int(0.1 * sampleRate)
let windowLo: Int = Int(0.4 * sampleRate)
func leftLeg(pan: Double) throws -> [Float] {
var captured: Bool = false
return try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.mix = 1.0; pedal.pan = pan; pedal.time = 2.0
} onFrame: { frame, _, pedal in
if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true }
}
}
let hardLeft: [Float] = try leftLeg(pan: -1.0)
let hardRight: [Float] = try leftLeg(pan: 1.0)
let leftRMS: Double = rms(hardLeft, loFrame: windowLo, hiFrame: hardLeft.count)
let rightRMS: Double = rms(hardRight, loFrame: windowLo, hiFrame: hardRight.count)
#expect(leftRMS > rightRMS * 3.0,
"panning hard left should fill the left leg far more than hard right: L \(leftRMS) vs R \(rightRMS)")
}
@Test func wetIsSilentUntilCaptureThenAudible() throws {
// Core contract: with no captured moment there is no filter template, so a fully-wet TunedVerb
// must output silence — not the live pass-through poured into the reverb. After the Capture
// footswitch fires, the wash appears. Fully wet (mix 1.0) so the only output is the gated wash.
let blockSize: Int = 512
let totalFrames: Int = Int(1.4 * sampleRate)
let captureFrame: Int = Int(0.5 * sampleRate)
var captured: Bool = false
let out: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.mix = 1.0; pedal.time = 1.0
} onFrame: { frame, _, pedal in
if frame >= captureFrame, !captured { pedal.toggleCapture(); captured = true }
}
// Before capture: fully-wet output must be silent (reverb fed zero).
let preRMS: Double = rms(out, loFrame: 0, hiFrame: captureFrame - blockSize)
// Well after capture (give the reverb time to build): audible.
let postRMS: Double = rms(out, loFrame: captureFrame + Int(0.4 * sampleRate), hiFrame: out.count)
#expect(preRMS < 1.0e-6, "an uncaptured fully-wet TunedVerb must be silent, got \(preRMS)")
#expect(postRMS > 1.0e-4, "after Capture the wash must be audible, got \(postRMS)")
}
@Test func captureLocksTheFilterSoAChangedInputIsShapedDifferently() throws {
// Which moment you capture determines the filter. Capture on tone A then morph to B (the wash
// on B is shaped by A's spectrum) versus morph to B first then capture on B (shaped by B's own
// spectrum). Both are audible — the wash exists only after a capture — but the two locked
// templates mask the ongoing tone-B input differently, so the renders diverge.
let blockSize: Int = 512
let totalFrames: Int = Int(1.4 * sampleRate)
let windowLo: Int = Int(0.95 * sampleRate)
let windowHi: Int = Int(1.35 * sampleRate)
// Locked on tone A, then morphed to B.
var capturedA: Bool = false
let lockedOnA: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.mix = 1.0; pedal.time = 3.0
} onFrame: { frame, source, pedal in
if frame >= Int(0.4 * sampleRate), !capturedA { pedal.toggleCapture(); capturedA = true }
if frame >= Int(0.6 * sampleRate) { source.morph = 1.0 } // switch to tone B after capture
}
// Morphed to B first, then locked on B.
var capturedB: Bool = false
let lockedOnB: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.mix = 1.0; pedal.time = 3.0
} onFrame: { frame, source, pedal in
if frame >= Int(0.2 * sampleRate) { source.morph = 1.0 } // switch to tone B first
if frame >= Int(0.4 * sampleRate), !capturedB { pedal.toggleCapture(); capturedB = true }
}
let signal: Double = rms(lockedOnB, loFrame: windowLo, hiFrame: windowHi)
let diff: Double = rmsDiff(lockedOnA, lockedOnB, loFrame: windowLo, hiFrame: windowHi)
#expect(signal > 1.0e-4, "a captured render should be audible on tone B, got \(signal)")
#expect(diff > signal * 0.25,
"locking a different moment should shape the input differently: diff \(diff) vs signal \(signal)")
}
// MARK: - Bypass
@Test func bypassSwitchIsClickFree() throws {
let blockSize: Int = 512
let totalFrames: Int = Int(0.6 * sampleRate)
let flipFrame: Int = Int(0.35 * sampleRate)
let steadyLo: Int = Int(0.22 * sampleRate)
let steadyHi: Int = Int(0.33 * sampleRate)
let settleMargin: Int = Int(0.045 * sampleRate)
let left: [Float] = try stepRender(totalFrames: totalFrames, blockSize: blockSize) { pedal in
pedal.mix = 0.5
} onFrame: { frame, _, pedal in
if frame >= flipFrame { pedal.bypass = 1.0 }
}
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi)
let fadeFrames: Int = Int(0.03 * sampleRate)
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + settleMargin)
#expect(transStep <= steadyStep * 4.0,
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
}
// MARK: - Wiring
@Test func exposesControls() throws {
let pedal: TunedVerbPedal = TunedVerbPedal()
#expect(pedal.effectKnobs.map { $0.label } == ["Time", "Damp", "Pan"])
#expect(pedal.effectTransportButtons.map { $0.label } == ["Capture"])
#expect(pedal.channelKind == .widener)
}
@Test func captureTogglesHoldState() throws {
let pedal: TunedVerbPedal = TunedVerbPedal()
#expect(pedal.holding == false)
pedal.toggleCapture()
#expect(pedal.holding == true)
#expect(pedal.captured == 1.0)
pedal.toggleCapture()
#expect(pedal.holding == false)
#expect(pedal.captured == 0.0)
}
@Test func presetRoundTripPreservesControls() throws {
let pedal: TunedVerbPedal = TunedVerbPedal()
pedal.time = 8.5
pedal.damp = 0.7
pedal.pan = -0.6
let state: PedalState = pedal.captureState()
let restored: TunedVerbPedal = TunedVerbPedal()
restored.applyState(state)
#expect(restored.time == 8.5)
#expect(restored.damp == 0.7)
#expect(restored.pan == -0.6)
}
@Test func capturedStateIsNotPersisted() throws {
// `captured` is transport state, not a preset control.
let pedal: TunedVerbPedal = TunedVerbPedal()
pedal.toggleCapture()
#expect(pedal.captured == 1.0)
let state: PedalState = pedal.captureState()
let restored: TunedVerbPedal = TunedVerbPedal()
restored.applyState(state)
#expect(restored.captured == 0.0, "a locked filter must not persist into a preset")
#expect(restored.holding == false)
}
@Test func registeredInBuiltInRegistry() throws {
let pedal: Pedal? = PedalRegistry.makePedal(type: "TunedVerb")
#expect(pedal is TunedVerbPedal)
}
}
@@ -0,0 +1,476 @@
// UndoCoordinatorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Undo coordinator")
struct UndoCoordinatorTests {
/// Builds an NRT-backed `ShoeGaze` with a single finalized board of the given pedal types, plus a
/// coordinator bound to it.
private func makeRig(
pedals: [String],
depth: Int = UndoCoordinator.defaultDepth,
numAudioBuses: Int = 128,
duration: Double = 0.05
) throws -> (ShoeGaze, UndoCoordinator, URL, PedalBoard) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
numAudioBuses: numAudioBuses
)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
for type: String in pedals {
guard let pedal: Pedal = PedalRegistry.makePedal(type: type) else { continue }
try board.add(pedal)
}
try sg.finalizeBoard(board)
let undo: UndoCoordinator = UndoCoordinator(shoeGaze: sg, depth: depth)
return (sg, undo, url, board)
}
/// Current pedal display names on the rig's first board (read from the live `boards` array, since
/// an undo/redo restore replaces board instances wholesale).
private func names(_ sg: ShoeGaze) -> [String] {
guard let board: PedalBoard = sg.boards.first else { return [] }
return board.pedals.map { $0.displayName }
}
// MARK: - Undo / redo of an add
@Test func undoRemovesAnAddedPedalAndRedoBringsItBack() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(undo.canUndo == false)
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
#expect(names(sg) == ["Overdrive", "Delay", "Reverb"])
#expect(undo.canUndo == true)
#expect(undo.undoActionLabel == "Add Reverb")
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay"], "undo should remove the added pedal")
#expect(undo.canUndo == false)
#expect(undo.canRedo == true)
#expect(undo.redoActionLabel == "Add Reverb")
undo.redo()
#expect(names(sg) == ["Overdrive", "Delay", "Reverb"], "redo should re-add the pedal")
#expect(undo.canUndo == true)
#expect(undo.canRedo == false)
}
// MARK: - Undo of a remove restores parameter values
@Test func undoOfARemoveRestoresThePedalWithItsKnobValues() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// Give the Delay a distinctive first-knob value well inside its range.
let delay: Pedal = board.pedals[1]
let knobRange: ClosedRange<Double> = try #require(delay.knobs.first?.range)
let sentinel: Double = knobRange.lowerBound + (knobRange.upperBound - knobRange.lowerBound) * 0.37
let original: PedalState = delay.captureState()
var newKnobs: [Double] = original.knobValues
try #require(!newKnobs.isEmpty)
newKnobs[0] = sentinel
delay.applyState(
PedalState(
type: original.type,
knobValues: newKnobs,
switchValues: original.switchValues,
bypass: original.bypass
)
)
#expect(abs(board.pedals[1].captureState().knobValues[0] - sentinel) < 1e-9)
try undo.perform("Remove Delay") { try sg.removePedal(at: 1, from: board) }
#expect(names(sg) == ["Overdrive"])
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay"], "undo should bring the removed pedal back")
let restored: Double = try #require(sg.boards.first?.pedals[1].captureState().knobValues.first)
#expect(abs(restored - sentinel) < 1e-9, "the restored pedal should keep its knob value")
}
// MARK: - Undo of a move
@Test func undoReversesAMove() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Move pedal") { try sg.movePedal(from: 0, to: 3, in: board) }
#expect(names(sg) == ["Delay", "Reverb", "Overdrive"])
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay", "Reverb"], "undo should restore the original order")
}
// MARK: - No-op edits record nothing
@Test func aNoOpEditRecordsNoUndoCheckpoint() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// Moving index 0 to offset 0 leaves the chain unchanged.
try undo.perform("Move pedal") { try sg.movePedal(from: 0, to: 0, in: board) }
#expect(undo.canUndo == false, "a no-op edit should not create an undo entry")
}
// MARK: - A new edit clears the redo stack
@Test func aNewEditClearsRedo() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
undo.undo()
#expect(undo.canRedo == true)
let liveBoard: PedalBoard = try #require(sg.boards.first)
try undo.perform("Add Delay") { try sg.appendPedal(.delay, to: liveBoard) }
#expect(undo.canRedo == false, "a fresh edit should discard the redo stack")
#expect(names(sg) == ["Overdrive", "Delay"])
}
// MARK: - Board-level ops
@Test func undoReversesABoardRemoval() throws {
let (sg, undo, url, _): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
let second: PedalBoard = try sg.addBoard()
try sg.finalizeBoard(second)
#expect(sg.boards.count == 2)
undo.perform("Remove Board") { sg.removeBoard(second) }
#expect(sg.boards.count == 1)
undo.undo()
#expect(sg.boards.count == 2, "undo should restore the removed board")
}
// MARK: - Depth cap
@Test func depthCapDropsOldestHistory() throws {
let cap: Int = 3
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"], depth: cap)
defer { try? FileManager.default.removeItem(at: url) }
// Five successive appends; only the last `cap` remain undoable.
let types: [PedalType] = [.reverb, .delay, .tremolo, .chorus, .flanger]
var current: PedalBoard = board
for type: PedalType in types {
try undo.perform("Add \(type.rawValue)") { try sg.appendPedal(type, to: current) }
current = try #require(sg.boards.first)
}
#expect(names(sg).count == 6)
// Undo exactly `cap` times — all that history holds.
for _ in 0 ..< cap { undo.undo() }
#expect(undo.canUndo == false, "history beyond the depth cap should have been dropped")
// Three undone appends leaves the two oldest adds (reverb, delay) plus the seed Overdrive.
#expect(names(sg) == ["Overdrive", "Reverb", "Delay"])
}
// MARK: - Clear
// MARK: - Undo preserves parameter edits made after the checkpoint
@Test func undoOfAnAddKeepsALaterKnobEditOnASurvivingPedal() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
// AFTER the add, the player turns the Delay's first knob. Undoing the add must not revert it.
let liveBoard: PedalBoard = try #require(sg.boards.first)
let delay: Pedal = liveBoard.pedals[1]
let knobRange: ClosedRange<Double> = try #require(delay.knobs.first?.range)
let sentinel: Double = knobRange.lowerBound + (knobRange.upperBound - knobRange.lowerBound) * 0.42
let delayState: PedalState = delay.captureState()
var newKnobs: [Double] = delayState.knobValues
try #require(!newKnobs.isEmpty)
newKnobs[0] = sentinel
delay.applyState(
PedalState(
id: delayState.id, // keep the pedal's identity, as a real knob turn (via the node) would
type: delayState.type,
knobValues: newKnobs,
switchValues: delayState.switchValues,
bypass: delayState.bypass
)
)
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay"], "undo removes the added Reverb")
let delayKnob: Double = try #require(sg.boards.first?.pedals[1].captureState().knobValues.first)
#expect(abs(delayKnob - sentinel) < 1e-9, "a knob turned after the edit must survive the undo")
}
// MARK: - Undo is surgical (does not tear down untouched boards)
@Test func undoOfAnEditLeavesOtherBoardsUntouched() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
let secondBoard: PedalBoard = try sg.addBoard()
try secondBoard.add(DelayPedal())
try sg.finalizeBoard(secondBoard)
let secondBoardInstance: PedalBoard = try #require(sg.boards.last)
// Edit the FIRST board, then undo it.
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
undo.undo()
// A whole-rig teardown would rebuild every board; the surgical restore must leave the
// untouched second board as the very same instance.
#expect(sg.boards.last === secondBoardInstance, "an unrelated board must not be rebuilt by undo")
#expect(names(sg) == ["Overdrive"], "the edited board is restored")
}
// MARK: - Undo of a multi-board wipe re-adds every board
@Test func undoOfAClearStyleWipeReAddsAllBoards() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
let second: PedalBoard = try sg.addBoard()
try second.add(ReverbPedal())
try sg.finalizeBoard(second)
#expect(sg.boards.count == 2)
_ = board
// A Clear-style wipe: remove every board, seed one empty board — as one checkpoint.
undo.perform("Clear Board") {
for existing: PedalBoard in Array(sg.boards) { sg.removeBoard(existing) }
if let fresh: PedalBoard = try? sg.addBoard() {
try? sg.finalizeBoard(fresh)
}
}
#expect(sg.boards.count == 1)
#expect(names(sg) == [], "the seeded board is empty")
undo.undo()
#expect(sg.boards.count == 2, "undo re-adds every wiped board")
#expect(names(sg) == ["Overdrive", "Delay"], "first board restored with its pedals")
#expect(sg.boards.last?.pedals.map { $0.displayName } == ["Reverb"], "second board restored too")
}
// MARK: - Parameter (knob) undo / redo
@Test func parameterUndoSetsTheKnobBackAndRedoReapplies() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
let pedal: Pedal = board.pedals[0]
let knob: PedalKnob = try #require(pedal.knobs.first)
let oldValue: Double = knob.node.value
let newValue: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.63
try #require(abs(newValue - oldValue) > 1e-9)
// The vendored knob would call node.update as the drag runs; simulate the settled value.
knob.node.update(newValue)
undo.recordParameterEdit(
label: knob.label, pedalID: pedal.id, group: .knob,
controlLabel: knob.label, oldValue: oldValue, newValue: newValue
)
#expect(undo.canUndo == true)
#expect(undo.undoActionLabel == knob.label)
undo.undo()
#expect(abs(knob.node.value - oldValue) < 1e-9, "undo restores the previous knob value")
undo.redo()
#expect(abs(knob.node.value - newValue) < 1e-9, "redo re-applies the new value")
}
@Test func parameterUndoResolvesTheLiveNodeAfterARebuild() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
let pedalID: UUID = board.pedals[0].id
let knob: PedalKnob = try #require(board.pedals[0].knobs.first)
let knobLabel: String = knob.label
let oldValue: Double = knob.node.value
let newValue: Double = knob.range.lowerBound + (knob.range.upperBound - knob.range.lowerBound) * 0.55
knob.node.update(newValue)
undo.recordParameterEdit(
label: knobLabel, pedalID: pedalID, group: .knob,
controlLabel: knobLabel, oldValue: oldValue, newValue: newValue
)
// A later structural edit rebuilds the board, replacing the pedal's live node (same id).
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
// Undo the structural edit, then the parameter edit; the latter must re-resolve the fresh node.
undo.undo() // removes Reverb (rebuild)
undo.undo() // the knob edit — resolve the live Overdrive by id and set it back
let livePedal: Pedal = try #require(sg.pedal(id: pedalID))
let liveKnob: PedalKnob = try #require(livePedal.knobs.first { $0.label == knobLabel })
#expect(abs(liveKnob.node.value - oldValue) < 1e-9, "param undo resolves the live node after a rebuild")
}
// MARK: - Parameter undo for sliders / switches / selectors
@Test func parameterUndoForASlider() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Graphic EQ"])
defer { try? FileManager.default.removeItem(at: url) }
let pedal: Pedal = board.pedals[0]
let slider: PedalSlider = try #require(pedal.effectSliders.first)
let oldValue: Double = slider.node.value
let newValue: Double = slider.range.lowerBound + (slider.range.upperBound - slider.range.lowerBound) * 0.3
try #require(abs(newValue - oldValue) > 1e-9)
slider.node.update(newValue)
undo.recordParameterEdit(label: slider.label, pedalID: pedal.id, group: .slider,
controlLabel: slider.label, oldValue: oldValue, newValue: newValue)
undo.undo()
#expect(abs(slider.node.value - oldValue) < 1e-9)
undo.redo()
#expect(abs(slider.node.value - newValue) < 1e-9)
}
@Test func parameterUndoForASwitch() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Sixties Combo"])
defer { try? FileManager.default.removeItem(at: url) }
let pedal: Pedal = board.pedals[0]
let sw: PedalSwitch = try #require(pedal.effectSwitches.first)
let oldValue: Double = sw.node.value
let newValue: Double = try #require(sw.options.first { abs($0.value - oldValue) > 1e-9 }?.value)
sw.node.update(newValue)
undo.recordParameterEdit(label: sw.label, pedalID: pedal.id, group: .switch,
controlLabel: sw.label, oldValue: oldValue, newValue: newValue)
undo.undo()
#expect(abs(sw.node.value - oldValue) < 1e-9)
undo.redo()
#expect(abs(sw.node.value - newValue) < 1e-9)
}
@Test func parameterUndoForASelector() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Karplus Resonator"])
defer { try? FileManager.default.removeItem(at: url) }
let pedal: Pedal = board.pedals[0]
let selector: PedalSelectorKnob = try #require(pedal.effectSelectors.first)
let oldValue: Double = selector.node.value
let newValue: Double = try #require(selector.stops.first { abs($0.value - oldValue) > 1e-9 }?.value)
selector.node.update(newValue)
undo.recordParameterEdit(label: selector.label, pedalID: pedal.id, group: .selector,
controlLabel: selector.label, oldValue: oldValue, newValue: newValue)
undo.undo()
#expect(abs(selector.node.value - oldValue) < 1e-9)
undo.redo()
#expect(abs(selector.node.value - newValue) < 1e-9)
}
// MARK: - Undo of a pre-board edit
@Test func undoOfAddPrePedalRemovesItAndRedoBringsItBack() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
_ = board
try undo.perform("Add pre-pedal") { try sg.appendPrePedal(.reverb) }
#expect(sg.preBoardStates.map { $0.type } == ["Reverb"])
#expect(names(sg) == ["Overdrive"], "the board is untouched by a pre-board edit")
undo.undo()
#expect(sg.preBoardStates.isEmpty, "undo removes the pre-board pedal")
#expect(names(sg) == ["Overdrive"], "the board survives the pre-board undo")
undo.redo()
#expect(sg.preBoardStates.map { $0.type } == ["Reverb"], "redo re-adds the pre-board pedal")
}
// MARK: - Undo of a post-board edit
@Test func undoOfAddPostPedalRemovesItAndRedoBringsItBack() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
_ = board
try undo.perform("Add post-pedal") { try sg.appendPostPedal(.reverb) }
#expect(sg.postBoardStates.map { $0.type } == ["Reverb"])
#expect(names(sg) == ["Overdrive"], "the board is untouched by a post-board edit")
undo.undo()
#expect(sg.postBoardStates.isEmpty, "undo removes the post-board pedal")
#expect(names(sg) == ["Overdrive"], "the board survives the post-board undo")
undo.redo()
#expect(sg.postBoardStates.map { $0.type } == ["Reverb"], "redo re-adds the post-board pedal")
}
// MARK: - Parameter resolution relies on unique labels per group
@Test func controlLabelsAreUniqueWithinEachGroupAcrossTheCatalogue() throws {
// `applyParameter` resolves a control by (pedal id, group, label), so labels must be unique
// within a group on every pedal — otherwise an undo could land on the wrong control.
func duplicates(_ labels: [String]) -> [String] {
Dictionary(grouping: labels, by: { $0 }).filter { $0.value.count > 1 }.map { $0.key }
}
for type: String in PedalRegistry.builtIn.keys.sorted() {
guard let pedal: Pedal = PedalRegistry.makePedal(type: type) else { continue }
#expect(duplicates(pedal.knobs.map { $0.label }).isEmpty, "\(type): duplicate knob labels")
#expect(duplicates(pedal.advancedKnobs.map { $0.label }).isEmpty, "\(type): duplicate advancedKnob labels")
#expect(duplicates(pedal.effectSliders.map { $0.label }).isEmpty, "\(type): duplicate slider labels")
#expect(duplicates(pedal.effectSwitches.map { $0.label }).isEmpty, "\(type): duplicate switch labels")
#expect(duplicates(pedal.effectSelectors.map { $0.label }).isEmpty, "\(type): duplicate selector labels")
}
}
// MARK: - A throwing action records nothing
@Test func aThrowingActionRecordsNoCheckpoint() throws {
let (_, undo, url, _): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
struct EditFailure: Error {}
#expect(throws: EditFailure.self) {
try undo.perform("Doomed Edit") { throw EditFailure() }
}
#expect(undo.canUndo == false, "a throwing edit must not create an undo entry")
}
@Test func clearDiscardsAllHistory() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
undo.undo()
#expect(undo.canRedo == true)
undo.clear()
#expect(undo.canUndo == false)
#expect(undo.canRedo == false)
#expect(undo.undoActionLabel == nil)
#expect(undo.redoActionLabel == nil)
}
}