From e1ec98413dd6a696c1e402323ec047cb41a9aca1 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Mon, 22 Jun 2026 09:31:57 -0700 Subject: [PATCH] Add board edit API: lane-addressed pedal/region editing Core support for interactively building and editing a board, all via the existing capture-BoardState -> mutate -> rebuildBoard path (no RT-graph surgery): - PedalLane addresses the main chain or a stereo/parallel branch. - appendPedal/removePedal/movePedal gain a `lane:` parameter (default .main, so existing call sites are unchanged). - appendStereoSplit/appendParallelSplit/appendMergeToMono/removeSegment insert and remove branch regions; split/merge guarded by tail width. - setInputSource preserves the rig across an input-source change. - rebuildAllBoards / loadRig(from:Data) / rigData added; loadRig is now atomic (teardown-on-failure) so a failed load leaves an empty rig. - Expose PedalBoard.orderedSegments and BoardSegment publicly so a UI can walk live board structure; index aligns with captureState().segments. - InputSource: Equatable. New errors: unknownPedalType, pedalIndexOutOfRange, cannotSplitStereoChain, cannotMergeMonoChain, notABranchRegion. Tests cover append/remove/move on main and branch lanes, region add/remove, width guards, move-to-end before trailing regions, input switch, and knob/bypass/branch value persistence through save/load. Co-Authored-By: Claude Opus 4.8 --- Sources/LyrebirdShoeGaze/BoardSegment.swift | 7 +- .../LyrebirdShoeGaze/Input/InputSource.swift | 2 +- Sources/LyrebirdShoeGaze/PedalBoard.swift | 6 +- .../LyrebirdShoeGaze/Presets/PedalLane.swift | 37 ++ .../Presets/ShoeGaze+Edit.swift | 302 ++++++++++++ .../Presets/ShoeGaze+Preset.swift | 80 +++- Sources/LyrebirdShoeGaze/ShoeGazeError.swift | 32 ++ .../BoardEditAPITests.swift | 442 ++++++++++++++++++ 8 files changed, 886 insertions(+), 22 deletions(-) create mode 100644 Sources/LyrebirdShoeGaze/Presets/PedalLane.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift create mode 100644 Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift diff --git a/Sources/LyrebirdShoeGaze/BoardSegment.swift b/Sources/LyrebirdShoeGaze/BoardSegment.swift index 7e011a7..b6eb0a4 100644 --- a/Sources/LyrebirdShoeGaze/BoardSegment.swift +++ b/Sources/LyrebirdShoeGaze/BoardSegment.swift @@ -10,7 +10,12 @@ /// `PedalBoard` records these as pedals and split regions are added, so a board can be /// serialized and rebuilt faithfully rather than as a flat pedal list. Branch pedals live /// inside their section objects, not as separate segments. -enum BoardSegment { +/// +/// Public so a UI can walk a board's live structure in signal-flow order (each element carries +/// the live `Pedal` / section object). The index of a segment within `PedalBoard.orderedSegments` +/// matches its index in `captureState().segments`, which is the region index used by the +/// lane-addressed edit API (see ``PedalLane``). +public enum BoardSegment { /// A single linear pedal in the main chain. case pedal(Pedal) diff --git a/Sources/LyrebirdShoeGaze/Input/InputSource.swift b/Sources/LyrebirdShoeGaze/Input/InputSource.swift index 4bedcb9..e5feded 100644 --- a/Sources/LyrebirdShoeGaze/Input/InputSource.swift +++ b/Sources/LyrebirdShoeGaze/Input/InputSource.swift @@ -14,7 +14,7 @@ import LyrebirdSynth /// the zero-based hardware input channel index (`0` = first input). It maps to engine /// audio-bus index `numOutputChannels + channel` (hardware input buses follow the /// output buses). Requires the engine to be created with `numInputChannels > channel`. -public enum InputSource { +public enum InputSource: Equatable { /// Synthesized test signal — no hardware required. case testLoop /// Live hardware input from the given zero-based input channel. The engine must be diff --git a/Sources/LyrebirdShoeGaze/PedalBoard.swift b/Sources/LyrebirdShoeGaze/PedalBoard.swift index ae3e3af..dad6cf5 100644 --- a/Sources/LyrebirdShoeGaze/PedalBoard.swift +++ b/Sources/LyrebirdShoeGaze/PedalBoard.swift @@ -122,8 +122,10 @@ public final class PedalBoard { private var branchChains: [BranchChain] = [] /// Ordered signal-chain segments (pedals + split regions) in signal-flow order. Used to - /// capture full board topology for serialization. Maintained by `add`/`split`/`splitStereo`. - private(set) var orderedSegments: [BoardSegment] = [] + /// capture full board topology for serialization and to drive signal-flow UIs. Maintained by + /// `add`/`split`/`splitStereo`. A segment's index here matches its index in + /// `captureState().segments` — the region index used by the lane-addressed edit API. + public private(set) var orderedSegments: [BoardSegment] = [] // MARK: - Init diff --git a/Sources/LyrebirdShoeGaze/Presets/PedalLane.swift b/Sources/LyrebirdShoeGaze/Presets/PedalLane.swift new file mode 100644 index 0000000..ffecbe2 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PedalLane.swift @@ -0,0 +1,37 @@ +// PedalLane.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +/// Addresses where a linear pedal edit applies: the board's main chain, or one branch of a +/// split region (stereo split or parallel section). +/// +/// `region` is the index of the region's segment within the board's top-level segment list +/// (`board.captureState().segments`). For a `.stereoSplit` segment, `.left`/`.right` map to its +/// left/right branches; for a `.parallel` segment they map to branch A/B. +public enum PedalLane: Equatable, Sendable { + + /// The board's top-level linear chain (the `.pedal` segments). + case main + + /// The left branch (stereo) / branch A (parallel) of the region segment at `region`. + case left(region: Int) + + /// The right branch (stereo) / branch B (parallel) of the region segment at `region`. + case right(region: Int) + + /// The region segment index this lane targets, or `nil` for ``main``. + public var regionIndex: Int? { + switch self { + case .main: return nil + case .left(let region), .right(let region): return region + } + } + + /// `true` for the left / A branch; `false` for the right / B branch. `false` for ``main``. + public var isLeftBranch: Bool { + if case .left = self { return true } + return false + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift new file mode 100644 index 0000000..4c956ef --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Edit.swift @@ -0,0 +1,302 @@ +// ShoeGaze+Edit.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +extension ShoeGaze { + + // MARK: - Linear pedal editing + + /// Appends a pedal of the given type to the end of a lane. + /// + /// The pedal is created at its constructor defaults (empty saved parameters) and the board is + /// rebuilt via ``rebuildBoard(_:from:)``. For ``PedalLane/main`` the pedal joins the top-level + /// linear chain (after the last `.pedal` segment), preserving any branch regions; for a branch + /// lane it is appended to that branch of the addressed region segment. + /// + /// - Important: Editing rebuilds the board through the same path as preset load; safe on a + /// running engine with at most one block of glitch (see ``rebuildBoard(_:from:)``). + /// + /// - Parameters: + /// - type: The pedal's `displayName`, e.g. `"Overdrive"`. Must be a key in `PedalRegistry.builtIn`. + /// - board: The board to edit. Must have been returned by `addBoard()` on this instance. + /// - lane: Where to append. Defaults to ``PedalLane/main``. + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.unknownPedalType`, `.notABranchRegion`, `.pedalIndexOutOfRange`, or + /// any error from ``rebuildBoard(_:from:)``. + @discardableResult + public func appendPedal( + type: String, + to board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + guard PedalRegistry.builtIn[type] != nil else { + throw ShoeGazeError.unknownPedalType(type) + } + let newState: PedalState = PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0) + + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + // Insert after the last linear pedal so the new pedal joins the linear chain rather + // than landing after a trailing split region; append to the end if there are none. + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + if let lastPedalIndex: Int = pedalPositions.last { + segments.insert(.pedal(newState), at: lastPedalIndex + 1) + } else { + segments.append(.pedal(newState)) + } + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + branch.append(newState) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Removes the pedal at `index` within a lane. + /// + /// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the + /// branch's pedal list for a branch lane). The board is rebuilt, preserving everything else. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error. + @discardableResult + public func removePedal( + at index: Int, + from board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + guard index >= 0 && index < pedalPositions.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: pedalPositions.count) + } + segments.remove(at: pedalPositions[index]) + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + guard index >= 0 && index < branch.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: branch.count) + } + branch.remove(at: index) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Moves the pedal at `sourceIndex` to `destinationIndex` within a lane. + /// + /// Indices address the lane's own pedal order. `destinationIndex` follows SwiftUI + /// `List.onMove` semantics (insert-before index in the original coordinate space). + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error. + @discardableResult + public func movePedal( + from sourceIndex: Int, + to destinationIndex: Int, + in board: PedalBoard, + lane: PedalLane = .main + ) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + switch lane { + case .main: + try moveMainPedal(&segments, from: sourceIndex, to: destinationIndex) + case .left, .right: + try mutateBranch(&segments, lane: lane) { branch in + try Self.moveWithinArray(&branch, from: sourceIndex, to: destinationIndex) + } + } + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + // MARK: - Branch regions + + /// Appends an empty stereo split region (two independently authored L/R lanes) to the board. + /// + /// Requires the board's tail to be mono — a stereo split fans a mono signal into two branches + /// (see `PedalBoard.splitStereo()`). Add pedals to each lane with `appendPedal(... lane:)`. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.cannotSplitStereoChain` when the tail is already stereo; any + /// rebuild error. + @discardableResult + public func appendStereoSplit(to board: PedalBoard) throws -> PedalBoard { + guard board.width == 1 else { throw ShoeGazeError.cannotSplitStereoChain } + var segments: [BoardSegmentState] = board.captureState().segments + segments.append(.stereoSplit(StereoSplitState(left: [], right: [], route: .stereo))) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Appends an empty parallel section (two A/B branches summed back to one signal) to the board. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: Any error from ``rebuildBoard(_:from:)``. + @discardableResult + public func appendParallelSplit(to board: PedalBoard) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + segments.append(.parallel(ParallelSectionState(branchA: [], branchB: [], mode: .both))) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Appends a merge-to-mono node, collapsing a stereo tail back to mono. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.cannotMergeMonoChain` when the tail is already mono; any rebuild error. + @discardableResult + public func appendMergeToMono(to board: PedalBoard) throws -> PedalBoard { + guard board.width == 2 else { throw ShoeGazeError.cannotMergeMonoChain } + var segments: [BoardSegmentState] = board.captureState().segments + segments.append(.mergeToMono) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + /// Removes the top-level segment (a linear pedal, a split region, or a merge node) at + /// `topLevelIndex` — its index within `board.captureState().segments`. + /// + /// - Returns: The rebuilt board occupying the same slot in `boards`. + /// - Throws: `ShoeGazeError.pedalIndexOutOfRange` when the index is invalid; any rebuild error. + @discardableResult + public func removeSegment(at topLevelIndex: Int, from board: PedalBoard) throws -> PedalBoard { + var segments: [BoardSegmentState] = board.captureState().segments + guard topLevelIndex >= 0 && topLevelIndex < segments.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: topLevelIndex, count: segments.count) + } + segments.remove(at: topLevelIndex) + return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) + } + + // MARK: - Input source switching + + /// Changes the input source while preserving the current rig. + /// + /// `addBoard()` wires the input source (test loop or hardware pass-through) into each board at + /// creation time, so switching the source means recreating that wiring. This captures the full + /// rig, tears it down, sets `inputSource`, and rebuilds every board from the snapshot — + /// preserving labels, pedals, and split-region topology. No-op when the source is unchanged. + /// + /// - Important: Call with the engine **stopped** (the same teardown/rebuild caveat as + /// ``loadRig(from:)``). Switching to `.liveInput` requires enough engine input channels. + /// Reconstruction is atomic: on any failure the rig is torn down and the error rethrown. + /// + /// - Parameter newSource: The input source to switch to. + /// - Throws: `ShoeGazeError.liveInputRequiresInputChannels` / `inputChannelOutOfRange`, + /// `BusAllocatorError.noFreeBus`, or `EngineAddError` from board reconstruction. + public func setInputSource(_ newSource: InputSource) throws { + if newSource == inputSource { return } + + let snapshot: ShoeGazeState = captureState() + teardown() + inputSource = newSource + try rebuildAllBoards(from: snapshot) + } + + // MARK: - Helpers + + /// Returns the absolute indices, within `segments`, of the `.pedal` segments in order. The + /// position of an entry in the returned array is its linear pedal index (`board.pedals` order). + private func linearPedalSegmentIndices(_ segments: [BoardSegmentState]) -> [Int] { + var indices: [Int] = [] + for (absoluteIndex, segment) in segments.enumerated() { + if case .pedal = segment { indices.append(absoluteIndex) } + } + return indices + } + + /// Mutates the branch pedal list addressed by `lane` in place, rebuilding the region's enum + /// case. Throws `notABranchRegion` if the addressed segment is not a split/parallel region. + private func mutateBranch( + _ segments: inout [BoardSegmentState], + lane: PedalLane, + _ transform: (inout [PedalState]) throws -> Void + ) throws { + // Callers only reach this for `.left`/`.right`; `.main` has no region and is handled + // separately. Treat a `.main` lane here as a programming error rather than a silent no-op. + guard let region: Int = lane.regionIndex else { + assertionFailure("mutateBranch called with the .main lane") + return + } + guard region >= 0 && region < segments.count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: region, count: segments.count) + } + let isLeft: Bool = lane.isLeftBranch + switch segments[region] { + case .stereoSplit(let state): + var left: [PedalState] = state.left + var right: [PedalState] = state.right + if isLeft { try transform(&left) } else { try transform(&right) } + segments[region] = .stereoSplit(StereoSplitState(left: left, right: right, route: state.route)) + case .parallel(let state): + var branchA: [PedalState] = state.branchA + var branchB: [PedalState] = state.branchB + if isLeft { try transform(&branchA) } else { try transform(&branchB) } + segments[region] = .parallel( + ParallelSectionState(branchA: branchA, branchB: branchB, mode: state.mode) + ) + default: + throw ShoeGazeError.notABranchRegion(index: region) + } + } + + /// Moves a `.pedal` within the top-level chain, preserving interleaved branch regions. + private func moveMainPedal( + _ segments: inout [BoardSegmentState], + from sourceIndex: Int, + to destinationIndex: Int + ) throws { + let pedalPositions: [Int] = linearPedalSegmentIndices(segments) + let pedalCount: Int = pedalPositions.count + guard sourceIndex >= 0 && sourceIndex < pedalCount else { + throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: pedalCount) + } + guard destinationIndex >= 0 && destinationIndex <= pedalCount else { + throw ShoeGazeError.pedalIndexOutOfRange(index: destinationIndex, count: pedalCount) + } + + let movedSegment: BoardSegmentState = segments.remove(at: pedalPositions[sourceIndex]) + let remainingPositions: [Int] = linearPedalSegmentIndices(segments) + // SwiftUI `toOffset` is an insert-before index in the original space; after removing the + // source, slots above it shift down by one. + let adjustedDestination: Int = destinationIndex > sourceIndex + ? destinationIndex - 1 + : destinationIndex + let insertionAbsolute: Int + if adjustedDestination < remainingPositions.count { + insertionAbsolute = remainingPositions[adjustedDestination] + } else if let lastPedalAbsolute: Int = remainingPositions.last { + // Moving to the end of the linear chain: land immediately after the last linear pedal, + // BEFORE any trailing routing nodes (a stereo split or mergeToMono), so a pedal never + // jumps past a width-conversion node. Mirrors `appendPedal`'s insert-after-last rule. + insertionAbsolute = lastPedalAbsolute + 1 + } else { + insertionAbsolute = segments.count + } + segments.insert(movedSegment, at: insertionAbsolute) + } + + /// Moves an element within a contiguous array using SwiftUI `List.onMove` (`toOffset`) semantics. + private static func moveWithinArray( + _ array: inout [T], + from sourceIndex: Int, + to destinationIndex: Int + ) throws { + let count: Int = array.count + guard sourceIndex >= 0 && sourceIndex < count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: count) + } + guard destinationIndex >= 0 && destinationIndex <= count else { + throw ShoeGazeError.pedalIndexOutOfRange(index: destinationIndex, count: count) + } + // Manual move with SwiftUI `toOffset` semantics (insert-before in the original space): + // remove the source, then insert at the destination shifted down by one when it was past + // the source. Avoids depending on SwiftUI's `move(fromOffsets:toOffset:)` in the core module. + let element: T = array.remove(at: sourceIndex) + let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex + array.insert(element, at: insertionIndex) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 3229518..cc25a0f 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -31,10 +31,65 @@ extension ShoeGaze { /// - Parameter url: Destination file URL. The directory must already exist. /// - Throws: Any error from `JSONEncoder` or `Data.write(to:options:)`. public func saveRig(to url: URL) throws { + try rigData().write(to: url, options: .atomic) + } + + /// Encodes the current rig to pretty-printed JSON `Data`. + /// + /// Same payload `saveRig(to:)` writes to disk; exposed for callers that need the bytes + /// directly (e.g. a SwiftUI `fileExporter` `FileDocument` on iOS). + /// + /// - Returns: The encoded `ShoeGazeState` JSON. + /// - Throws: Any error from `JSONEncoder`. + public func rigData() throws -> Data { let encoder: JSONEncoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - let data: Data = try encoder.encode(captureState()) - try data.write(to: url, options: .atomic) + return try encoder.encode(captureState()) + } + + /// Loads a rig from in-memory JSON `Data` and rebuilds the engine graph. + /// + /// Identical to ``loadRig(from:)`` but reads from `Data` rather than a file URL — convenient + /// for a SwiftUI `fileImporter` that has already read the document, or for tests. + /// + /// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``. + /// - Parameter data: JSON produced by ``rigData()`` / ``saveRig(to:)``. + /// - Throws: `JSONDecoder` errors, `PresetError.unsupportedVersion`, or any board-build error. + public func loadRig(from data: Data) throws { + let decoder: JSONDecoder = JSONDecoder() + let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) + guard state.version <= presetFormatVersion else { + throw PresetError.unsupportedVersion(state.version) + } + + teardown() + try rebuildAllBoards(from: state) + } + + /// Rebuilds every board from a snapshot with all-or-nothing semantics. + /// + /// The caller is responsible for tearing down any existing rig first. On any failure while + /// reconstructing a board, the partially-built rig is torn down and the error rethrown, so + /// callers never observe a half-built rig — a board that fails on iteration N does not leave + /// boards `0..=` the board's linear pedal count. `index` is the offending index; `count` + /// is the number of linear pedals on the board. + case pedalIndexOutOfRange(index: Int, count: Int) + + /// Thrown by `appendStereoSplit(to:)` when the board's tail is already stereo (width 2). A + /// stereo split fans a mono tail into two branches; narrow the chain with a `Merge to Mono` + /// first. (See `PedalBoard.splitStereo()`.) + case cannotSplitStereoChain + + /// Thrown by `appendMergeToMono(to:)` when the board's tail is already mono (width 1) — there + /// is no stereo signal to collapse. + case cannotMergeMonoChain + + /// Thrown by the lane-addressed edit API when the segment at the given top-level index is not a + /// branch region (stereo split or parallel section). `index` is the offending segment index. + case notABranchRegion(index: Int) + // MARK: - LocalizedError public var errorDescription: String? { @@ -64,6 +86,16 @@ public enum ShoeGazeError: Error, LocalizedError, Equatable, Sendable { return "ShoeGaze: could not open recording file '\(url.lastPathComponent)'." case .stereoWidthExceeded: return "PedalBoard: chain is already stereo (width 2); cannot add another widener. Use mergeToMono() first." + case .unknownPedalType(let type): + return "ShoeGaze: '\(type)' is not a known pedal type; cannot add it to the board." + case .pedalIndexOutOfRange(let index, let count): + return "ShoeGaze: pedal index \(index) is out of range; the board has \(count) linear pedal(s)." + case .cannotSplitStereoChain: + return "ShoeGaze: cannot add a stereo split; the chain is already stereo. Merge to mono first." + case .cannotMergeMonoChain: + return "ShoeGaze: the chain is already mono; there is no stereo signal to merge." + case .notABranchRegion(let index): + return "ShoeGaze: segment \(index) is not a branch region (stereo split or parallel section)." } } } diff --git a/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift new file mode 100644 index 0000000..dd3ca30 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/BoardEditAPITests.swift @@ -0,0 +1,442 @@ +// BoardEditAPITests.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("Board edit API") +struct BoardEditAPITests { + + /// Builds an NRT-backed `ShoeGaze` with a single finalized board of the given pedal types. + private func makeRig( + pedals: [String], + numAudioBuses: Int = 128 + ) throws -> (ShoeGaze, SynthesisEngine, URL, PedalBoard) { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, + 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) + return (sg, engine, url, board) + } + + /// Starts the engine (NRT render to file) and returns the rendered stereo samples. + private func render(_ engine: SynthesisEngine, _ url: URL) throws -> [Float] { + try engine.start() + return readStereoCAF(url: url) + } + + private func names(_ board: PedalBoard) -> [String] { + board.pedals.map { $0.displayName } + } + + // MARK: - Append + + @Test func appendAddsPedalAtEndAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + let edited: PedalBoard = try sg.appendPedal(type: "Reverb", to: board) + #expect(names(edited) == ["Overdrive", "Delay", "Reverb"]) + #expect(sg.boards.count == 1, "append should not change board count") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "edited board should still render audio") + } + + @Test func appendUnknownTypeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.unknownPedalType("Nope")) { + try sg.appendPedal(type: "Nope", to: board) + } + } + + // MARK: - Remove + + @Test func removeDeletesLinearPedalAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + let edited: PedalBoard = try sg.removePedal(at: 1, from: board) + #expect(names(edited) == ["Overdrive", "Reverb"]) + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "board should still render after removal") + } + + @Test func removeOutOfRangeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 5, count: 1)) { + try sg.removePedal(at: 5, from: board) + } + } + + // MARK: - Move + + @Test func moveReordersLinearPedalsAndRenders() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay", "Reverb"]) + defer { try? FileManager.default.removeItem(at: url) } + + // SwiftUI List.onMove convention: move row 0 to offset 2 in [OD, Delay, Reverb] + // → [Delay, Overdrive, Reverb]. + let edited: PedalBoard = try sg.movePedal(from: 0, to: 2, in: board) + #expect(names(edited) == ["Delay", "Overdrive", "Reverb"]) + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "board should still render after reorder") + } + + @Test func moveOutOfRangeThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.pedalIndexOutOfRange(index: 5, count: 2)) { + try sg.movePedal(from: 5, to: 0, in: board) + } + } + + // MARK: - Branch preservation + + @Test func editingLinearPedalPreservesStereoSplitRegion() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url) } + + let sg: ShoeGaze = ShoeGaze(engine: engine) + let board: PedalBoard = try sg.addBoard() + try board.add(OverdrivePedal()) + let section: StereoSplitSection = try board.splitStereo() + try section.left.add(DelayPedal()) + try section.right.add(PingPongDelayPedal()) + try board.collectStereo(section) + section.route = .rightOnly + try sg.finalizeBoard(board) + + // Append a linear pedal; the stereo split region must survive untouched. + let edited: PedalBoard = try sg.appendPedal(type: "Fuzz", to: board) + #expect(names(edited).contains("Fuzz"), "appended linear pedal should be present") + + let after: BoardState = edited.captureState() + guard case .stereoSplit(let stereoState)? = after.segments.first(where: { + if case .stereoSplit = $0 { return true } else { return false } + }) else { + Issue.record("Stereo split segment lost after a linear edit") + return + } + #expect(stereoState.route == .rightOnly, "route should be preserved across the edit") + #expect(stereoState.left.first?.type == "Delay", "left branch pedal preserved") + #expect(stereoState.right.first?.type == "Ping-Pong", "right branch pedal preserved") + #expect(edited.width == 2, "board should remain stereo") + } + + // MARK: - Input source switching + + @Test func setInputSourcePreservesRigAndRewiresInput() throws { + let (engine, url): (SynthesisEngine, URL) = makeNRTEngine( + duration: 0.1, + numInputChannels: 2, + numAudioBuses: 128 + ) + defer { try? FileManager.default.removeItem(at: url) } + + let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop) + let board: PedalBoard = try sg.addBoard() + try board.add(OverdrivePedal()) + try board.add(DelayPedal()) + try sg.finalizeBoard(board) + + try sg.setInputSource(.liveInput(channel: 0)) + + #expect(sg.inputSource == .liveInput(channel: 0), "input source should be updated") + #expect(sg.boards.count == 1, "rig board count preserved") + #expect(names(sg.boards[0]) == ["Overdrive", "Delay"], "pedals preserved across switch") + } + + @Test func setInputSourceToSameValueIsNoOp() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + let boardBefore: PedalBoard = sg.boards[0] + try sg.setInputSource(.testLoop) // already .testLoop + #expect(sg.boards[0] === boardBefore, "no-op switch should not rebuild the board") + _ = board + } + + @Test func setInputSourceToLiveWithoutInputChannelsThrowsAndLeavesEmptyRig() throws { + // Engine created with no input channels: switching to .liveInput must throw and, because + // reconstruction is atomic, leave no partially-rebuilt rig behind. + let (sg, _, url, _): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) // makeNRTEngine defaults to 0 inputs + defer { try? FileManager.default.removeItem(at: url) } + + #expect(throws: ShoeGazeError.liveInputRequiresInputChannels) { + try sg.setInputSource(.liveInput(channel: 0)) + } + #expect(sg.boards.isEmpty, "failed input switch should leave an empty rig, not a partial one") + } + + // MARK: - Branch regions (stereo split / parallel) via lane addressing + + private func stereoState(_ board: PedalBoard) -> StereoSplitState? { + for segment: BoardSegmentState in board.captureState().segments { + if case .stereoSplit(let state) = segment { return state } + } + return nil + } + + @Test func appendStereoSplitThenFillLanesIndependently() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + // The split region is the second top-level segment (after the Overdrive pedal). + let region: Int = 1 + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: region)) + live = try sg.appendPedal(type: "Reverb", to: live, lane: .right(region: region)) + + guard let state: StereoSplitState = stereoState(live) else { + Issue.record("No stereo split segment after building one") + return + } + #expect(state.left.map { $0.type } == ["Delay"], "left lane should hold Delay") + #expect(state.right.map { $0.type } == ["Reverb"], "right lane should hold Reverb") + #expect(live.width == 2, "board should be stereo after a collected split") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "stereo-split board should render audio") + } + + @Test func removePedalFromBranchLane() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + live = try sg.appendPedal(type: "Fuzz", to: live, lane: .left(region: 1)) + live = try sg.removePedal(at: 0, from: live, lane: .left(region: 1)) + + #expect(stereoState(live)?.left.map { $0.type } == ["Fuzz"], "left lane should drop Delay") + } + + @Test func appendStereoSplitOnStereoChainThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + // Octave Splitter is a widener → board becomes stereo; a second split is then invalid. + let live: PedalBoard = try sg.appendPedal(type: "Octave Splitter", to: board) + #expect(live.width == 2, "widener should make the board stereo") + #expect(throws: ShoeGazeError.cannotSplitStereoChain) { + try sg.appendStereoSplit(to: live) + } + } + + @Test func removeSegmentDropsRegion() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + #expect(stereoState(live) != nil, "split region present before removal") + + live = try sg.removeSegment(at: 1, from: live) + #expect(stereoState(live) == nil, "split region removed") + #expect(live.width == 1, "board back to mono after removing the split") + #expect(names(live) == ["Overdrive"], "linear chain intact") + } + + @Test func appendMergeToMonoOnMonoChainThrows() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + #expect(throws: ShoeGazeError.cannotMergeMonoChain) { + try sg.appendMergeToMono(to: board) + } + } + + @Test func moveMainPedalToEndLandsBeforeTrailingRegion() throws { + // Board: [Overdrive, Delay, ]. Moving Overdrive to the end of the linear + // chain must land it after Delay but BEFORE the split region — not after it. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) // segment index 2 + // Linear pedals are [Overdrive, Delay]; move index 0 to the end (offset 2). + live = try sg.movePedal(from: 0, to: 2, in: live, lane: .main) + + #expect(names(live) == ["Delay", "Overdrive"], "Overdrive should follow Delay in the chain") + // The split region must remain the LAST top-level segment. + guard case .stereoSplit = live.captureState().segments.last else { + Issue.record("Stereo split should remain the trailing segment; pedal jumped past it") + return + } + } + + @Test func parallelSplitBranchEditing() throws { + let (sg, engine, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendParallelSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + live = try sg.appendPedal(type: "Fuzz", to: live, lane: .right(region: 1)) + + var foundParallel: Bool = false + for segment: BoardSegmentState in live.captureState().segments { + if case .parallel(let p) = segment { + foundParallel = true + #expect(p.branchA.map { $0.type } == ["Delay"]) + #expect(p.branchB.map { $0.type } == ["Fuzz"]) + } + } + #expect(foundParallel, "parallel region should exist") + + let samples: [Float] = try render(engine, url) + #expect(hasNonSilentOutput(samples), "parallel board should render audio") + } + + // MARK: - Save / load round-trip on an edited board + + @Test func overdriveDriveEightPersistsAcrossSaveAndReload() throws { + // The user's exact scenario: set Overdrive Drive to 8, save the board, reload it (into + // the SAME manager — what the builder's Load… button does), expect Drive == 8. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + guard let overdrive: OverdrivePedal = board.pedals.first as? OverdrivePedal else { + Issue.record("Expected an Overdrive") + return + } + overdrive.drive = 8.0 + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + // Reload into the same instance (mirrors ShoeGazeBuilderView.loadAction). + try sg.loadRig(from: preset) + + guard let reloaded: OverdrivePedal = sg.boards.first?.pedals.first as? OverdrivePedal else { + Issue.record("Overdrive not present after reload") + return + } + #expect(abs(reloaded.drive - 8.0) < 1e-9, "Drive should reload as 8, got \(reloaded.drive)") + } + + @Test func knobAndBypassEditsPersistThroughSaveLoad() throws { + // Mimic the builder UI path: edits go through the knob's UIParamNode (node.update), + // not the @UIParam stored property. Then save to a file and load into a fresh manager. + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + let pedal: Pedal = board.pedals[0] + let driveValue: Double = 9.0 + pedal.knobs[0].node.update(driveValue) // "Drive" via the node, as a UI knob would + pedal.bypass = 1.0 + + 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: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + let restored: Pedal = sg2.boards[0].pedals[0] + #expect(abs(restored.knobs[0].node.value - driveValue) < 1e-9, "drive should persist") + #expect(restored.bypass == 1.0, "bypass should persist") + } + + @Test func branchPedalKnobValuesPersistThroughSaveLoad() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive"]) + defer { try? FileManager.default.removeItem(at: url) } + + var live: PedalBoard = try sg.appendStereoSplit(to: board) + live = try sg.appendPedal(type: "Delay", to: live, lane: .left(region: 1)) + + // Edit the branch pedal's first knob via the node path. + guard let stereo: StereoSplitSection = live.stereoSplitSections.first, + let delay: Pedal = stereo.left.pedals.first else { + Issue.record("No branch Delay pedal") + return + } + let knobValue: Double = 0.42 + delay.knobs[0].node.update(knobValue) + + 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: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + guard let stereo2: StereoSplitSection = sg2.boards[0].stereoSplitSections.first, + let delay2: Pedal = stereo2.left.pedals.first else { + Issue.record("Branch Delay not restored") + return + } + #expect(abs(delay2.knobs[0].node.value - knobValue) < 1e-9, "branch knob should persist") + } + + @Test func editedBoardRoundTripsThroughFile() throws { + let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) = + try makeRig(pedals: ["Overdrive", "Delay"]) + defer { try? FileManager.default.removeItem(at: url) } + + try sg.appendPedal(type: "Reverb", to: board) + try sg.removePedal(at: 0, from: sg.boards[0]) // drop Overdrive → [Delay, Reverb] + + let preset: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString + ".json") + defer { try? FileManager.default.removeItem(at: preset) } + try sg.saveRig(to: preset) + + // Fresh manager + engine; load and verify the edited chain restored and renders. + let (engine2, url2): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128) + defer { try? FileManager.default.removeItem(at: url2) } + let sg2: ShoeGaze = ShoeGaze(engine: engine2) + try sg2.loadRig(from: preset) + + #expect(sg2.boards.count == 1) + #expect(names(sg2.boards[0]) == ["Delay", "Reverb"], "edited chain should round-trip") + + let samples: [Float] = try render(engine2, url2) + #expect(hasNonSilentOutput(samples), "loaded edited rig should render audio") + } +}