Files
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

403 lines
19 KiB
Swift

// 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
}
}