// 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: /// - kind: The pedal type, e.g. ``PedalType/overdrive``. Its `rawValue` 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( _ kind: PedalType, to board: PedalBoard, lane: PedalLane = .main ) throws -> PedalBoard { let type: String = kind.rawValue 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)) } /// Inserts a pedal of the given type at `index` within a lane, shifting later pedals along. /// /// `index` addresses the lane's own pedal order (`board.pedals` for ``PedalLane/main``; the /// branch's pedal list for a branch lane) and follows insert-before semantics: the new pedal /// lands immediately before the pedal currently at `index`. An `index` equal to the lane's pedal /// count appends to the end (same placement as ``appendPedal(_:to:lane:)``). The pedal is created /// at its constructor defaults and the board is rebuilt via ``rebuildBoard(_:from:)``. /// /// - 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: /// - kind: The pedal type. Its `rawValue` must be a key in `PedalRegistry.builtIn`. /// - index: Insert-before position in the lane's pedal order. Valid range `0...laneCount`. /// - board: The board to edit. Must have been returned by `addBoard()` on this instance. /// - lane: Which lane to insert into. Defaults to ``PedalLane/main``. /// - Returns: The rebuilt board occupying the same slot in `boards`. /// - Throws: `ShoeGazeError.unknownPedalType`, `.pedalIndexOutOfRange`, `.notABranchRegion`, or /// any error from ``rebuildBoard(_:from:)``. @discardableResult public func insertPedal( _ kind: PedalType, at index: Int, to board: PedalBoard, lane: PedalLane = .main ) throws -> PedalBoard { let type: String = kind.rawValue 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: let pedalPositions: [Int] = linearPedalSegmentIndices(segments) guard index >= 0 && index <= pedalPositions.count else { throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: pedalPositions.count) } if index < pedalPositions.count { segments.insert(.pedal(newState), at: pedalPositions[index]) } else if let lastPedalIndex: Int = pedalPositions.last { // Inserting at the end: land right after the last linear pedal, before any trailing // routing node — mirrors `appendPedal`'s placement rule. segments.insert(.pedal(newState), at: lastPedalIndex + 1) } else { segments.append(.pedal(newState)) } 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.insert(newState, at: index) } } 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)) } /// Moves a pedal from one lane to another (e.g. the main chain into a stereo-unzip lane, or /// between branches), preserving its parameter values. The moved pedal is appended to the end /// of the destination lane. /// /// - Parameters: /// - sourceLane: The lane the pedal currently lives in. /// - sourceIndex: The pedal's index within `sourceLane`. /// - destinationLane: The lane to move the pedal into. /// - board: The board to edit. /// - Returns: The rebuilt board occupying the same slot in `boards`. /// - Throws: `ShoeGazeError.pedalIndexOutOfRange`, `.notABranchRegion`, or any rebuild error. @discardableResult public func movePedal( from sourceLane: PedalLane, at sourceIndex: Int, to destinationLane: PedalLane, in board: PedalBoard ) throws -> PedalBoard { var segments: [BoardSegmentState] = board.captureState().segments // 1. Remove the pedal from its source lane, capturing its full state. Removing a main // pedal deletes a top-level segment; record where so the destination region index can // be corrected if it sat after the removal. let moved: PedalState var removedTopLevelIndex: Int? switch sourceLane { case .main: let positions: [Int] = linearPedalSegmentIndices(segments) guard sourceIndex >= 0, sourceIndex < positions.count else { throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count) } let absolute: Int = positions[sourceIndex] guard case .pedal(let state) = segments[absolute] else { throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: positions.count) } moved = state segments.remove(at: absolute) removedTopLevelIndex = absolute case .left, .right: var captured: PedalState? try mutateBranch(&segments, lane: sourceLane) { branch in guard sourceIndex >= 0, sourceIndex < branch.count else { throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: branch.count) } captured = branch.remove(at: sourceIndex) } guard let capturedState: PedalState = captured else { throw ShoeGazeError.pedalIndexOutOfRange(index: sourceIndex, count: 0) } moved = capturedState } // 2. Correct the destination region index if a top-level segment before it was removed. var destination: PedalLane = destinationLane if let region: Int = destinationLane.regionIndex, let removed: Int = removedTopLevelIndex, removed < region { destination = destinationLane.isLeftBranch ? .left(region: region - 1) : .right(region: region - 1) } // 3. Append the moved pedal to the destination lane. switch destination { case .main: let positions: [Int] = linearPedalSegmentIndices(segments) if let lastPedal: Int = positions.last { segments.insert(.pedal(moved), at: lastPedal + 1) } else { segments.append(.pedal(moved)) } case .left, .right: try mutateBranch(&segments, lane: destination) { branch in branch.append(moved) } } 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)) } /// Inserts an empty stereo-unzip region immediately after the segment at `topLevelIndex`, /// splitting the stereo signal at that point into two independently editable L/R lanes. /// /// Used by the per-pedal "Split L/R" toggle: pass the stereo pedal's segment index. No board- /// level width guard is needed — `rebuildSegments` replays segments in order, so /// `unzipStereo()`'s own `width == 2` check validates the *local* width at the insertion point; /// an invalid insert throws and the atomic `rebuildBoard` leaves the existing board intact. /// /// - Parameters: /// - topLevelIndex: Segment index (in `captureState().segments`) after which to insert. /// - board: The board to edit. /// - Returns: The rebuilt board occupying the same slot in `boards`. /// - Throws: `ShoeGazeError.pedalIndexOutOfRange` for a bad index; /// `ShoeGazeError.cannotUnzipMonoChain` if the signal at that point is mono; any rebuild error. @discardableResult public func insertStereoUnzip(afterSegment topLevelIndex: Int, in 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.insert( .stereoUnzip(StereoUnzipState(left: [], right: [], route: .stereo)), at: topLevelIndex + 1 ) return try rebuildBoard(board, from: BoardState(label: board.label, segments: segments)) } /// Returns `true` when the segment immediately after `topLevelIndex` is a stereo-unzip region — /// i.e. the "Split L/R" toggle for the pedal at `topLevelIndex` is on. public func isStereoUnzip(afterSegment topLevelIndex: Int, in board: PedalBoard) -> Bool { let segments: [BoardSegmentState] = board.captureState().segments let next: Int = topLevelIndex + 1 guard next >= 0 && next < segments.count else { return false } if case .stereoUnzip = segments[next] { return true } return false } /// 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 .stereoUnzip(let state): var left: [PedalState] = state.left var right: [PedalState] = state.right if isLeft { try transform(&left) } else { try transform(&right) } segments[region] = .stereoUnzip(StereoUnzipState(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) } }