Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f5b70edc7 | |||
| a8bd0242a3 |
+2
-2
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7",
|
||||
"version" : "2.2.0"
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -55,6 +55,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
private let shoeGaze: ShoeGaze
|
||||
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
|
||||
/// started at launch.
|
||||
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).
|
||||
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
|
||||
/// library order each time it opens (via `menuNeedsUpdate(_:)`).
|
||||
private var setListMenu: NSMenu?
|
||||
@@ -109,6 +118,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
self.coreDriver = coreDriver
|
||||
self.engine = engine
|
||||
self.shoeGaze = shoeGaze
|
||||
self.undo = UndoCoordinator(shoeGaze: shoeGaze)
|
||||
self.midi = MIDIController(engine: engine, shoeGaze: shoeGaze)
|
||||
self.window = LyrebirdWindow(
|
||||
title: "ShoeGaze Builder — Lyrebird Pedalboard",
|
||||
@@ -158,12 +168,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
let driver: CoreAudioDriver = coreDriver
|
||||
let rigLibrary: RigLibraryStore = library
|
||||
let midiController: MIDIController = midi
|
||||
let undoCoordinator: UndoCoordinator = undo
|
||||
window.open {
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: session,
|
||||
library: rigLibrary,
|
||||
hardwareSampleRate: { driver.deviceSampleRate },
|
||||
midi: midiController
|
||||
midi: midiController,
|
||||
undo: undoCoordinator
|
||||
)
|
||||
}
|
||||
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: "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.
|
||||
let boardMenuItem: NSMenuItem = NSMenuItem()
|
||||
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.
|
||||
addItem(to: boardMenu, title: "Add Board", action: #selector(addBoardAction(_:)), key: "b")
|
||||
boardMenu.addItem(NSMenuItem.separator())
|
||||
// ⌘Z 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.
|
||||
// ⌘M toggles rig mute (a hard silence of all output; distinct from Bypass Rig's dry
|
||||
// passthrough). ⌘Z / ⇧⌘Z are Undo / Redo (Edit menu); the in-window view binds ⌘M on iOS.
|
||||
self.muteMenuItem = addItem(
|
||||
to: boardMenu,
|
||||
title: "Mute Rig",
|
||||
action: #selector(toggleMuteAction(_:)),
|
||||
key: "z"
|
||||
key: "m"
|
||||
)
|
||||
// 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.
|
||||
@@ -401,6 +433,28 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
|
||||
// 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``.
|
||||
@objc private func showHelpAction(_ sender: Any?) {
|
||||
let helpWidth: CGFloat = 560
|
||||
@@ -476,9 +530,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
@objc private func addBoardAction(_ sender: Any?) {
|
||||
var created: PedalBoard?
|
||||
do {
|
||||
// Record as an undo checkpoint, matching the in-window Add Board.
|
||||
try undo.perform("Add Board") {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
created = board
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
}
|
||||
} catch {
|
||||
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
|
||||
print("[ShoeGazeBuilder] addBoard failed: \(error)")
|
||||
@@ -547,6 +604,23 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
menuItem.state = shoeGaze.rigBypassed ? .on : .off
|
||||
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) {
|
||||
// A slot is live only when the library actually holds a rig at that position.
|
||||
return menuItem.tag < library.entries.count
|
||||
|
||||
@@ -31,7 +31,8 @@ struct ShoeGazeBuilderiOSApp: App {
|
||||
library: model.library,
|
||||
hardwareSampleRate: { model.hardwareSampleRate },
|
||||
onEnableLiveInput: { model.enableLiveInput() },
|
||||
midi: model.midi
|
||||
midi: model.midi,
|
||||
undo: model.undo
|
||||
)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.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.
|
||||
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 iosDriver: iOSAudioDriver
|
||||
|
||||
@@ -70,6 +74,7 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
self.engine = built.engine
|
||||
self.iosDriver = built.driver
|
||||
self.shoeGaze = shoeGaze
|
||||
self.undo = UndoCoordinator(shoeGaze: shoeGaze)
|
||||
|
||||
// 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
|
||||
@@ -197,6 +202,8 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
self.engine = rebuilt.engine
|
||||
self.iosDriver = rebuilt.driver
|
||||
self.shoeGaze = rebuilt.shoeGaze
|
||||
// Bind undo to the new session; history resets across the engine rebuild.
|
||||
self.undo = UndoCoordinator(shoeGaze: rebuilt.shoeGaze)
|
||||
|
||||
do {
|
||||
// Teardown already happened, so a restore failure can only recover by seeding.
|
||||
|
||||
+3
-3
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "c8855e41a403b5b1fccd9ccb4b3ef4d75c4307590ae6a0b8e985e71c41011e09",
|
||||
"originHash" : "6094cf70541e0593db7264ad9c75576ce239a5a5885ca4b783b5444793b6fee5",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7",
|
||||
"version" : "2.2.0"
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ let package = Package(
|
||||
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
|
||||
],
|
||||
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: [
|
||||
// Both targets depend on the core `Lyrebird` product AND `LyrebirdUI`.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "13b4323e9d41dfdff1c6aeac595cff272eb4eee9cc1a3146483bdaf8543bc103",
|
||||
"originHash" : "9e278ce69e19f7dabaaaed1b75fb6112a02ece1e30e2aad82c12942c5ddeb192",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54",
|
||||
"version" : "2.0.0"
|
||||
"revision" : "9f244b19394f6352b0a1dcf532cf142b86e41c30",
|
||||
"version" : "2.3.0"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -56,7 +56,7 @@ extension ShoeGaze {
|
||||
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.
|
||||
@@ -117,7 +117,7 @@ extension ShoeGaze {
|
||||
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.
|
||||
@@ -149,7 +149,7 @@ extension ShoeGaze {
|
||||
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.
|
||||
@@ -175,7 +175,7 @@ extension ShoeGaze {
|
||||
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
|
||||
@@ -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
|
||||
@@ -270,7 +270,7 @@ extension ShoeGaze {
|
||||
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))
|
||||
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`,
|
||||
@@ -297,7 +297,7 @@ extension ShoeGaze {
|
||||
.stereoUnzip(StereoUnzipState(left: [], right: [], route: .stereo)),
|
||||
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 —
|
||||
@@ -318,7 +318,7 @@ extension ShoeGaze {
|
||||
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))
|
||||
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.
|
||||
@@ -330,7 +330,7 @@ extension ShoeGaze {
|
||||
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))
|
||||
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
|
||||
@@ -345,7 +345,7 @@ extension ShoeGaze {
|
||||
throw ShoeGazeError.pedalIndexOutOfRange(index: topLevelIndex, count: segments.count)
|
||||
}
|
||||
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
|
||||
|
||||
@@ -238,6 +238,13 @@ public final class ShoeGaze {
|
||||
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.
|
||||
private func allPedals() -> [Pedal] {
|
||||
var result: [Pedal] = []
|
||||
|
||||
@@ -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,377 @@
|
||||
// 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) {
|
||||
// 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 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
|
||||
|
||||
// MARK: - Init
|
||||
@@ -248,7 +251,11 @@ public struct BoardBarView: View {
|
||||
}
|
||||
Divider()
|
||||
Button("Delete Board", role: .destructive) {
|
||||
if let undo: UndoCoordinator = undo {
|
||||
undo.perform("Remove Board") { shoeGaze.removeBoard(board) }
|
||||
} else {
|
||||
shoeGaze.removeBoard(board)
|
||||
}
|
||||
clampEditingIndex()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,6 +63,10 @@ public struct BoardFlowView: View {
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let boardIndex: Int
|
||||
|
||||
/// 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.
|
||||
@State private var dropTarget: String?
|
||||
|
||||
@@ -293,12 +297,12 @@ public struct BoardFlowView: View {
|
||||
do {
|
||||
if split {
|
||||
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 {
|
||||
// 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.
|
||||
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 {
|
||||
print("[BoardFlowView] split toggle failed: \(error)")
|
||||
@@ -507,7 +511,7 @@ public struct BoardFlowView: View {
|
||||
sourceIndex = index
|
||||
}
|
||||
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
|
||||
} catch {
|
||||
print("[BoardFlowView] cross-lane move failed: \(error)")
|
||||
@@ -522,15 +526,25 @@ public struct BoardFlowView: View {
|
||||
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) {
|
||||
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)") }
|
||||
}
|
||||
|
||||
private func insert(type: String, at index: Int, lane: PedalLane) {
|
||||
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)") }
|
||||
}
|
||||
|
||||
@@ -539,20 +553,20 @@ public struct BoardFlowView: View {
|
||||
// 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.
|
||||
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)") }
|
||||
}
|
||||
|
||||
private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) {
|
||||
guard source != target, let board: PedalBoard = board else { return }
|
||||
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)") }
|
||||
}
|
||||
|
||||
private func removePedal(at index: Int, lane: PedalLane) {
|
||||
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)") }
|
||||
}
|
||||
|
||||
@@ -563,7 +577,7 @@ public struct BoardFlowView: View {
|
||||
|
||||
private func removeSegment(at segmentIndex: Int) {
|
||||
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)") }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ public struct BoardsSheetView: View {
|
||||
private let onAddBoard: () -> Void
|
||||
|
||||
@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
|
||||
|
||||
// MARK: - Init
|
||||
@@ -219,14 +222,25 @@ public struct BoardsSheetView: View {
|
||||
// SwiftUI's destination is the insertion point in the pre-move list; moveBoard
|
||||
// removes first, so shift down by one when moving forward.
|
||||
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)
|
||||
}
|
||||
clampEditingIndex()
|
||||
}
|
||||
|
||||
private func deleteBoards(_ offsets: IndexSet) {
|
||||
let remove: () -> Void = {
|
||||
for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count {
|
||||
shoeGaze.removeBoard(shoeGaze.boards[index])
|
||||
}
|
||||
}
|
||||
if let undo: UndoCoordinator = undo {
|
||||
undo.perform("Remove Board", remove)
|
||||
} else {
|
||||
remove()
|
||||
}
|
||||
clampEditingIndex()
|
||||
}
|
||||
|
||||
|
||||
@@ -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 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.",
|
||||
"⌘Z mutes and unmutes the whole rig — a hard silence of all output (distinct "
|
||||
+ "from Bypass Rig, which passes your dry signal through).",
|
||||
"⌘Z undoes the last board edit and ⇧⌘Z redoes it — add / remove / move a pedal, "
|
||||
+ "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, "
|
||||
+ "⌘I Import Archive, ⌘B Add Board, ⇧⌘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 "
|
||||
+ "hardware keyboard attached.",
|
||||
+ "⌘I Import Archive, Edit ▸ Undo / Redo (⌘Z / ⇧⌘Z), ⌘B Add Board, "
|
||||
+ "⇧⌘R Start / Stop Recording, ⌘? Help, and Rigs ▸ Set List (the ⌘⇧ rig slots).",
|
||||
"The board and set-list shortcuts, plus ⌘Z / ⇧⌘Z (undo / redo) and ⌘M (mute), "
|
||||
+ "also work on iOS / iPadOS with a hardware keyboard attached.",
|
||||
]
|
||||
)
|
||||
topicSection(
|
||||
|
||||
@@ -23,3 +23,20 @@ extension EnvironmentValues {
|
||||
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.
|
||||
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
|
||||
|
||||
@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
|
||||
|
||||
// MARK: - Init
|
||||
@@ -94,6 +100,7 @@ struct PedalSelectorKnobView: View {
|
||||
if !dragInProgress {
|
||||
dragInProgress = true
|
||||
dragStartIndex = currentIndex
|
||||
dragStartValue = selector.node.value
|
||||
}
|
||||
let delta: CGFloat = gesture.translation.height // down = positive
|
||||
// Up should advance (increase index), so subtract the downward delta.
|
||||
@@ -107,7 +114,15 @@ struct PedalSelectorKnobView: View {
|
||||
.onEnded { _ in
|
||||
let changed: Bool = currentIndex != dragStartIndex
|
||||
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
|
||||
|
||||
/// Records one undo checkpoint per committed change. Installed by ``PedalView``; no-op elsewhere.
|
||||
@Environment(\.pedalParameterEditRecorder) private var recordEdit
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a segmented switch view.
|
||||
@@ -105,9 +108,18 @@ public struct PedalSwitchView: View {
|
||||
|
||||
private func segment(option: PedalSwitch.Option, isActive: Bool) -> some View {
|
||||
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)
|
||||
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)
|
||||
.font(.system(size: PedalSwitchView.fontSize, weight: .semibold))
|
||||
|
||||
@@ -246,6 +246,9 @@ struct TempoSyncKnobView: View {
|
||||
let knob: PedalKnob
|
||||
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.
|
||||
@State private var showDivisionPicker: Bool = false
|
||||
|
||||
@@ -270,6 +273,18 @@ struct TempoSyncKnobView: View {
|
||||
|
||||
VStack(spacing: TempoSyncKnobView.cellSpacing) {
|
||||
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)
|
||||
.disabled(isSynced)
|
||||
.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.
|
||||
@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
|
||||
|
||||
/// Creates a stompbox pedal view for the given pedal.
|
||||
@@ -597,6 +615,18 @@ public struct PedalView: View {
|
||||
PedalInfoView(pedal: pedal)
|
||||
.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
|
||||
@@ -670,7 +700,7 @@ public struct PedalView: View {
|
||||
Spacer(minLength: 0)
|
||||
ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in
|
||||
let knob: PedalKnob = knobPair.element
|
||||
ParameterKnob(knob.label, node: knob.node, range: knob.range)
|
||||
recordingKnob(knob)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
@@ -866,7 +896,7 @@ public struct PedalView: View {
|
||||
ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in
|
||||
HStack(alignment: .top, spacing: PedalView.advancedPopoverSpacing) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -924,11 +954,28 @@ public struct PedalView: View {
|
||||
if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) {
|
||||
TempoSyncKnobView(pedal: pedal, knob: knob, param: param)
|
||||
} else {
|
||||
ParameterKnob(knob.label, node: knob.node, range: knob.range)
|
||||
recordingKnob(knob)
|
||||
.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
|
||||
/// not syncable. Matched by `UIParamNode` identity so it is robust to label changes.
|
||||
private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? {
|
||||
@@ -1141,7 +1188,7 @@ public struct PedalView: View {
|
||||
@ViewBuilder
|
||||
private var levelControl: some View {
|
||||
if let level: PedalKnob = pedal.knobs.last {
|
||||
ParameterKnob(level.label, node: level.node, range: level.range)
|
||||
recordingKnob(level)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
@@ -1152,7 +1199,7 @@ public struct PedalView: View {
|
||||
@ViewBuilder
|
||||
private var mixControl: some View {
|
||||
if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last {
|
||||
ParameterKnob(mix.label, node: mix.node, range: mix.range)
|
||||
recordingKnob(mix)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +89,11 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// engine already exposes an input channel, where live input is selected directly.
|
||||
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.
|
||||
@State private var selectedBoardIndex: Int = 0
|
||||
|
||||
@@ -229,13 +234,15 @@ public struct ShoeGazeBuilderView: View {
|
||||
library: RigLibraryStore,
|
||||
hardwareSampleRate: @escaping () -> Double? = { nil },
|
||||
onEnableLiveInput: (() -> Void)? = nil,
|
||||
midi: MIDIController? = nil
|
||||
midi: MIDIController? = nil,
|
||||
undo: UndoCoordinator? = nil
|
||||
) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.library = library
|
||||
self.hardwareSampleRate = hardwareSampleRate
|
||||
self.onEnableLiveInput = onEnableLiveInput
|
||||
self.midi = midi
|
||||
self.undo = undo
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
@@ -716,6 +723,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
boardArea
|
||||
}
|
||||
.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)
|
||||
// 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.
|
||||
@@ -818,6 +828,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
private var compactRigControlsRow: some View {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||||
undoButton
|
||||
redoButton
|
||||
rigBypassButton
|
||||
rigMuteButton
|
||||
inputMuteButton
|
||||
@@ -829,6 +841,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.
|
||||
private var compactPanelRow: some View {
|
||||
ScrollView(.horizontal, showsIndicators: false) {
|
||||
@@ -1057,6 +1098,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
crossfadeSeconds: $crossfadeSeconds,
|
||||
onAddBoard: { addBoard() }
|
||||
)
|
||||
// Sheet content gets a fresh environment, so re-inject the coordinator here.
|
||||
.environment(undo)
|
||||
.presentationDetents([.medium, .large])
|
||||
}
|
||||
}
|
||||
@@ -1357,9 +1400,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
|
||||
do {
|
||||
switch action {
|
||||
case .stereoSplit: _ = try shoeGaze.appendStereoSplit(to: board)
|
||||
case .parallelSplit: _ = try shoeGaze.appendParallelSplit(to: board)
|
||||
case .mergeToMono: _ = try shoeGaze.appendMergeToMono(to: board)
|
||||
case .stereoSplit: try editing("Add Stereo Split") { _ = try shoeGaze.appendStereoSplit(to: board) }
|
||||
case .parallelSplit: try editing("Add Parallel Split") { _ = try shoeGaze.appendParallelSplit(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
|
||||
}
|
||||
} catch {
|
||||
@@ -1401,11 +1444,22 @@ public struct ShoeGazeBuilderView: View {
|
||||
|
||||
// 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) {
|
||||
guard !shoeGaze.boards.isEmpty else { return }
|
||||
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
|
||||
do {
|
||||
_ = try shoeGaze.appendPedal(PedalType(type), to: board)
|
||||
try editing("Add \(type)") { try shoeGaze.appendPedal(PedalType(type), to: board) }
|
||||
autosave()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
|
||||
@@ -1416,9 +1470,11 @@ public struct ShoeGazeBuilderView: View {
|
||||
private func addBoard() {
|
||||
var created: PedalBoard?
|
||||
do {
|
||||
try editing("Add Board") {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
created = board
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
}
|
||||
selectedBoardIndex = shoeGaze.boards.count - 1
|
||||
autosave()
|
||||
} catch {
|
||||
@@ -1444,6 +1500,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||
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
|
||||
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
|
||||
// re-resolve onto the fresh board's pedals.
|
||||
@@ -1460,6 +1519,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
|
||||
}
|
||||
}
|
||||
selectedBoardIndex = 0
|
||||
|
||||
if wasRunning { try? shoeGaze.engine.start() }
|
||||
@@ -1525,8 +1585,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
// MARK: - Board-switch shortcuts
|
||||
|
||||
/// 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
|
||||
/// active without showing chrome.
|
||||
/// edit target, plus ⌘Z / ⇧⌘Z (undo / redo), ⌘M (rig mute), and ⌘⇧1…⌘⇧0 (set-list rigs) on
|
||||
/// iOS/iPadOS. Kept at zero opacity so the shortcuts stay active without showing chrome.
|
||||
private var boardSwitchShortcuts: some View {
|
||||
ZStack {
|
||||
ForEach(0 ..< min(ShoeGazeBuilderView.maxBoardShortcuts, shoeGaze.boards.count), id: \.self) { index in
|
||||
@@ -1535,11 +1595,18 @@ public struct ShoeGazeBuilderView: View {
|
||||
Button("Switch to Board \(index + 1)") { switchToBoard(index) }
|
||||
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
|
||||
}
|
||||
// ⌘Z toggles rig mute on iOS/iPadOS hardware keyboards. On macOS the Board menu item
|
||||
// owns the ⌘Z equivalent, so it is not also bound here (a double-bound event is ambiguous).
|
||||
// ⌘Z / ⇧⌘Z are Undo / Redo on iOS/iPadOS hardware keyboards; rig mute moves to ⌘M so the
|
||||
// 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)
|
||||
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() }
|
||||
Button("Undo") { undo?.undo() }
|
||||
.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
|
||||
// instead, so they are not also bound here.
|
||||
ForEach(0 ..< ShoeGazeBuilderView.maxRigShortcuts, id: \.self) { slot in
|
||||
@@ -1646,6 +1713,10 @@ public struct ShoeGazeBuilderView: View {
|
||||
} catch {
|
||||
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() }
|
||||
transportTick.toggle()
|
||||
}
|
||||
@@ -1847,6 +1918,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)")
|
||||
}
|
||||
selectedBoardIndex = 0
|
||||
// A brand-new rig is a fresh document — drop any prior undo history.
|
||||
undo?.clear()
|
||||
if wasRunning { try? shoeGaze.engine.start() }
|
||||
transportTick.toggle()
|
||||
persist(shoeGaze.captureEntry(name: name))
|
||||
|
||||
@@ -70,6 +70,9 @@ public struct ShoeGazeView: View {
|
||||
private let shoeGaze: ShoeGaze
|
||||
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
|
||||
/// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning`
|
||||
/// 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.hardwareSampleRate = hardwareSampleRate
|
||||
self._undo = State(initialValue: UndoCoordinator(shoeGaze: shoeGaze))
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
@@ -118,6 +122,7 @@ public struct ShoeGazeView: View {
|
||||
crossfadeSeconds: $crossfadeSeconds,
|
||||
onAddBoard: { addBoard() }
|
||||
)
|
||||
.environment(undo)
|
||||
Divider()
|
||||
.overlay(Color.white.opacity(ShoeGazeView.dividerOpacity))
|
||||
boardList
|
||||
@@ -249,7 +254,7 @@ public struct ShoeGazeView: View {
|
||||
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
|
||||
let board: PedalBoard = pair.element
|
||||
PedalBoardView(board: board) {
|
||||
shoeGaze.removeBoard(board)
|
||||
undo.perform("Remove Board") { shoeGaze.removeBoard(board) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,10 +298,12 @@ public struct ShoeGazeView: View {
|
||||
private func addBoard() {
|
||||
var createdBoard: PedalBoard?
|
||||
do {
|
||||
try undo.perform("Add Board") {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
createdBoard = board
|
||||
try board.add(OverdrivePedal())
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
}
|
||||
} catch {
|
||||
if let board: PedalBoard = createdBoard {
|
||||
shoeGaze.removeBoard(board)
|
||||
|
||||
@@ -49,6 +49,13 @@ struct VerticalParameterSlider: View {
|
||||
private let node: UIParamNode
|
||||
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
|
||||
|
||||
/// Creates a vertical fader.
|
||||
@@ -141,8 +148,16 @@ struct VerticalParameterSlider: View {
|
||||
.gesture(
|
||||
DragGesture(minimumDistance: 0)
|
||||
.onChanged { drag in
|
||||
if !dragInProgress {
|
||||
dragInProgress = true
|
||||
dragStartValue = node.value
|
||||
}
|
||||
updateValue(forY: drag.location.y, height: height)
|
||||
}
|
||||
.onEnded { _ in
|
||||
dragInProgress = false
|
||||
recordEdit(.slider, label, dragStartValue, node.value)
|
||||
}
|
||||
)
|
||||
}
|
||||
.frame(width: VerticalParameterSlider.controlWidth, height: VerticalParameterSlider.trackHeight)
|
||||
|
||||
@@ -382,6 +382,25 @@ struct BoardEditAPITests {
|
||||
#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
|
||||
|
||||
@Test func setInputSourcePreservesRigAndRewiresInput() throws {
|
||||
|
||||
@@ -0,0 +1,436 @@
|
||||
// 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: - 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user