Files
ShoeGaze/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift
T
josh 0d17ed260b Persist board across restarts + Clear button with save prompt
Persistence (macOS + iOS):
- RigStore autosaves the rig (rigData JSON) to Application Support and restores
  it on launch. App models restore-or-seed at init; macOS saves on terminate +
  resignActive, iOS saves on scenePhase leaving .active. The builder also
  autosaves after structural edits (add board/pedal, load, clear).

Clear (both platforms):
- A Clear button in the builder opens a confirmation dialog: Save & Clear /
  Clear Without Saving / Cancel. Clear removes all boards and seeds one fresh
  empty board, then autosaves. Save & Clear triggers the save mechanism and only
  clears once the save completes (cancelling the save leaves the rig intact).
- The rig-save exporter is now cross-platform (was iOS-only) so Save and the
  Save & Clear flow work on macOS too; macOS keeps its File-menu Load.

Tests: RigStore save/restore round-trip across instances; restore is a no-op
with no autosave. 186 tests pass.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-26 18:54:03 -07:00

650 lines
27 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ShoeGazeBuilderView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(AppKit)
import AppKit
#endif
import SwiftUI
import UniformTypeIdentifiers
import LyrebirdSynth
import LyrebirdUI
import LyrebirdShoeGaze
/// A self-contained pedalboard builder: browse all pedals, build a board by adding / removing /
/// reordering pedals, tweak live controls, choose the input source, start the chain, and save or
/// load a board setup.
///
/// This view ties together ``PedalPaletteView`` (the catalog) and ``BoardBuilderView`` (the
/// editable chain) with a transport bar, an input-source picker, a board selector, and save/load.
/// It is the shared screen hosted by both the macOS and iOS builder app shells.
///
/// Save/load uses an `NSSavePanel`/`NSOpenPanel` on macOS and `.fileExporter`/`.fileImporter` on
/// iOS, both reading/writing the JSON produced by `ShoeGaze.rigData()` / consumed by
/// `loadRig(from:)`. Loading and input-source changes stop the engine first (they rebuild the
/// graph) and restart it if it was running.
///
/// ## Usage
///
/// ```swift
/// ShoeGazeBuilderView(shoeGaze: shoeGaze)
/// ```
public struct ShoeGazeBuilderView: View {
// MARK: - Layout constants
private static let outerPadding: CGFloat = 16
private static let sectionSpacing: CGFloat = 12
private static let rowSpacing: CGFloat = 10
private static let dividerOpacity: Double = 0.12
private static let labelOpacity: Double = 0.65
private static let minWidth: CGFloat = 720
private static let minHeight: CGFloat = 460
private static let sidebarWidth: CGFloat = 168
private static let columnSpacing: CGFloat = 14
private static let backgroundRed: Double = 0.08
private static let backgroundGreen: Double = 0.07
private static let backgroundBlue: Double = 0.06
private static let testLoopTag: Int = -1
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
private static let maxBoardShortcuts: Int = 9
private static let defaultRigFileName: String = "ShoeGazeRig"
private static let recordDotSize: CGFloat = 9
private static let folderLabelOpacity: Double = 0.55
// MARK: - Properties
private let shoeGaze: ShoeGaze
private let hardwareSampleRate: () -> Double?
/// Host hook to enable live input when the current engine has no input channel (iOS).
/// The host requests microphone access and rebuilds the engine with one input channel,
/// preserving the rig, then swaps in a new `ShoeGaze`. `nil` on platforms (macOS) whose
/// engine already exposes an input channel, where live input is selected directly.
private let onEnableLiveInput: (() -> Void)?
/// Index of the board currently being edited.
@State private var selectedBoardIndex: Int = 0
/// Crossfade duration (seconds) applied to board switches in the board bar.
@State private var crossfadeSeconds: Double = 0.3
/// Bumped on transport/edit actions to force a re-read of `engine.isRunning`.
@State private var transportTick: Bool = false
/// Shown when live input is selected but microphone access is denied/restricted.
@State private var showMicDeniedAlert: Bool = false
/// Guards the one-time input-source restore in `.onAppear`.
@State private var didRestoreInput: Bool = false
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
@State private var showBoardsSheet: Bool = false
/// Confirmation dialog for the Clear action, and a flag to clear once a chosen save completes.
@State private var showClearDialog: Bool = false
@State private var pendingClearAfterSave: Bool = false
/// Rig-save export state. Cross-platform: the in-view exporter backs both the Save action and
/// the "Save & Clear" flow on macOS and iOS (macOS additionally has a File-menu Save).
@State private var showExporter: Bool = false
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
#if !os(macOS)
/// iOS file-dialog presentation flags. (macOS uses the File menu for load + recording folder.)
@State private var showImporter: Bool = false
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
@State private var showRecordingFolderImporter: Bool = false
#endif
// MARK: - Init
/// Creates a builder view.
///
/// - Parameters:
/// - shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The caller should
/// create at least one board before presenting this view.
/// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by
/// the engine-config Start to warn on a mismatch. Defaults to `nil`.
/// - onEnableLiveInput: Host hook invoked when the user requests live input but the engine
/// has no input channel (iOS). The host should request microphone access, rebuild the
/// engine with one input channel (preserving the rig), and select live input. Defaults to
/// `nil` — on macOS the engine already has an input channel, so live input is selected
/// directly without a rebuild.
public init(
shoeGaze: ShoeGaze,
hardwareSampleRate: @escaping () -> Double? = { nil },
onEnableLiveInput: (() -> Void)? = nil
) {
self.shoeGaze = shoeGaze
self.hardwareSampleRate = hardwareSampleRate
self.onEnableLiveInput = onEnableLiveInput
}
// MARK: - Body
public var body: some View {
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
transportRow
ioRow
#if !os(macOS)
recordingRow
#endif
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
BoardBarView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
paletteSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
// Scope + CPU meters sit under the pedal palette, matching its width.
ShoeGazeScopeView(shoeGaze: shoeGaze)
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
LyrebirdStatusView(engine: shoeGaze.engine)
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
}
.padding(ShoeGazeBuilderView.outerPadding)
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
.background(
Color(
red: ShoeGazeBuilderView.backgroundRed,
green: ShoeGazeBuilderView.backgroundGreen,
blue: ShoeGazeBuilderView.backgroundBlue
)
)
.background(boardSwitchShortcuts)
.onAppear { restoreInputSelection() }
// Each presentation (sheet / importers / exporter / alert) lives on its own anchor
// node. SwiftUI reliably drives only one presentation per view node, so stacking them
// all on the root view silently swallowed some (e.g. the iOS Load file importer).
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.confirmationDialog(
"Clear all boards?",
isPresented: $showClearDialog,
titleVisibility: .visible
) {
Button("Save & Clear") {
pendingClearAfterSave = true
saveAction()
}
Button("Clear Without Saving", role: .destructive) {
performClear()
}
Button("Cancel", role: .cancel) {
pendingClearAfterSave = false
}
} message: {
Text("This removes every pedal and board. Save your current setup first?")
}
.alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) {
Button("OK", role: .cancel) { }
} message: {
Text("Live input needs microphone access. Enable it in System Settings › Privacy & "
+ "Security › Microphone, then select the input again.")
}
#if !os(macOS)
.background(rigImportAnchor)
.background(recordingFolderImportAnchor)
#endif
}
// MARK: - Presentation anchors
/// Hosts the board-manager sheet on its own node so it does not collide with the file
/// importers / exporter (one presentation per view node).
private var boardsSheetAnchor: some View {
Color.clear
.sheet(isPresented: $showBoardsSheet) {
BoardsSheetView(
shoeGaze: shoeGaze,
editingBoardIndex: $selectedBoardIndex,
crossfadeSeconds: $crossfadeSeconds,
onAddBoard: { addBoard() }
)
.presentationDetents([.medium, .large])
}
}
/// Hosts the rig-save (`.json`) exporter on its own node. Cross-platform: backs both the
/// Save action and the "Save & Clear" flow. On a successful save during "Save & Clear", the
/// pending clear runs; cancelling the save leaves the boards untouched.
private var rigExportAnchor: some View {
Color.clear
.fileExporter(
isPresented: $showExporter,
document: exportDocument,
contentType: .json,
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
) { result in
switch result {
case .failure(let error):
print("[ShoeGazeBuilderView] export failed: \(error)")
pendingClearAfterSave = false
case .success:
if pendingClearAfterSave { performClear() }
pendingClearAfterSave = false
}
}
}
#if !os(macOS)
/// Hosts the rig-load (`.json`) importer on its own node.
private var rigImportAnchor: some View {
Color.clear
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
handleImport(result)
}
}
/// Hosts the recording-folder importer on its own node.
private var recordingFolderImportAnchor: some View {
Color.clear
.fileImporter(isPresented: $showRecordingFolderImporter, allowedContentTypes: [.folder]) { result in
handleRecordingFolderImport(result)
}
}
#endif
// MARK: - Transport row
private var transportRow: some View {
_ = transportTick
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("ShoeGaze Builder")
.font(.title2).bold()
.foregroundStyle(Color.white)
if shoeGaze.isRecording {
// Recording indicator (both platforms; recording is driven from the macOS Record
// menu or the iOS controls below).
HStack(spacing: 4) {
Circle()
.fill(Color.red)
.frame(width: ShoeGazeBuilderView.recordDotSize, height: ShoeGazeBuilderView.recordDotSize)
Text("REC")
.font(.caption.monospaced())
.foregroundStyle(Color.red)
}
}
Spacer()
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
)
}
}
// MARK: - Input + board + save/load row
private var ioRow: some View {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Text("Input:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Input", selection: inputBinding) {
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
if shoeGaze.engine.numInputChannels > 0 {
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
Text("In \(channel)").tag(channel)
}
} else if onEnableLiveInput != nil {
// No input channel yet: offer live input; selecting it asks the host to
// request mic access and rebuild the engine with one (channel 0).
Text("Live Input").tag(0)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
Button("Boards…") { showBoardsSheet = true }
.buttonStyle(.bordered).tint(.orange)
.help("Rename, reorder, or delete boards")
Button("Clear") { showClearDialog = true }
.buttonStyle(.bordered).tint(.red)
.help("Remove all boards (with the option to save first)")
Spacer()
// On macOS, Load lives in the app's File menu (see the app shell's AppDelegate); on
// iOS it stays in-view via fileImporter. Save is in-view on both (cross-platform
// exporter) so the "Save & Clear" flow works everywhere.
Button("Save…") { saveAction() }
.buttonStyle(.bordered).tint(.blue)
#if !os(macOS)
Button("Load…") { loadAction() }
.buttonStyle(.bordered).tint(.blue)
#endif
}
}
// MARK: - Palette sidebar
private var paletteSidebar: some View {
ScrollView(.vertical, showsIndicators: true) {
PedalPaletteView(
onAdd: { type in addPedal(type: type) },
onRouting: { action in performRouting(action) }
)
.padding(.trailing, 2)
}
.frame(width: ShoeGazeBuilderView.sidebarWidth)
}
// MARK: - Board area
private var boardArea: some View {
// Vertically center the signal-flow board in the available space.
VStack(spacing: 0) {
Spacer(minLength: 0)
BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex)
Spacer(minLength: 0)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
/// Performs a routing action from the palette against the selected board.
private func performRouting(_ action: PedalPaletteView.RoutingAction) {
guard !shoeGaze.boards.isEmpty else { return }
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 .chainRouter: break // multi-board routing; not handled in the single-board builder
}
} catch {
print("[ShoeGazeBuilderView] routing \(action) failed: \(error)")
}
}
/// `selectedBoardIndex` clamped to a valid board (or `0`); guards against deletes/loads that
/// change the board count out from under the picker.
private var clampedBoardIndex: Int {
guard !shoeGaze.boards.isEmpty else { return 0 }
return min(max(selectedBoardIndex, 0), shoeGaze.boards.count - 1)
}
// MARK: - Input binding
private var inputBinding: Binding<Int> {
Binding(
get: {
switch shoeGaze.inputSource {
case .testLoop: return ShoeGazeBuilderView.testLoopTag
case .liveInput(let channel): return channel
}
},
set: { newValue in
if newValue == ShoeGazeBuilderView.testLoopTag {
switchInput(to: .testLoop)
} else if newValue < shoeGaze.engine.numInputChannels {
switchInput(to: .liveInput(channel: newValue))
} else if let onEnableLiveInput {
// Requested a channel the current engine doesn't have (iOS, 0 channels):
// hand off to the host to grant mic + rebuild with an input channel.
onEnableLiveInput()
}
}
)
}
// MARK: - Actions
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)
autosave()
} catch {
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
}
}
private func addBoard() {
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
created = board
try shoeGaze.finalizeBoard(board)
selectedBoardIndex = shoeGaze.boards.count - 1
autosave()
} catch {
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
}
}
/// Persists the current rig to the autosave file. Called after structural edits so state
/// survives a restart even without an explicit Save; the app shells also save on background.
private func autosave() {
RigStore.save(shoeGaze)
}
/// Removes every board, then seeds one fresh empty board so the builder is never boardless.
/// Resets the edit target and autosaves the cleared state.
private func performClear() {
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
for board: PedalBoard in Array(shoeGaze.boards) {
shoeGaze.removeBoard(board)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
try shoeGaze.finalizeBoard(board)
} catch {
print("[ShoeGazeBuilderView] clear failed to seed a fresh board: \(error)")
}
selectedBoardIndex = 0
autosave()
transportTick.toggle()
}
/// Switches input source, stopping/restarting the engine around the graph rebuild.
///
/// Live input requires microphone authorisation first — without it macOS feeds the AUHAL
/// input silent zeros. The request is asynchronous, so when the source is `.liveInput` the
/// actual switch is deferred until the grant resolves; a denial falls back to the test loop.
private func switchInput(to source: InputSource) {
guard case .liveInput = source else {
applyInputSource(source)
return
}
MicrophonePermission.request { granted in
if !granted { showMicDeniedAlert = true }
applyInputSource(granted ? source : .testLoop)
}
}
/// Applies an input-source change, stopping/restarting the engine around the graph rebuild.
private func applyInputSource(_ source: InputSource) {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
do {
try shoeGaze.setInputSource(source)
persistInputSelection(source)
} catch {
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
}
if wasRunning {
try? shoeGaze.engine.start()
}
transportTick.toggle()
}
// MARK: - Input persistence
/// Saves the current input choice so it is restored on the next launch.
private func persistInputSelection(_ source: InputSource) {
let value: Int
switch source {
case .testLoop:
value = ShoeGazeBuilderView.testLoopTag
case .liveInput(let channel):
value = channel
}
UserDefaults.standard.set(value, forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
}
/// Restores the saved input choice once on appear. With no saved choice, defaults to live
/// input when the microphone is already authorised and the engine has an input channel —
/// otherwise stays on the test loop. A saved live channel that no longer fits the engine, or
/// a since-revoked permission, falls back to the test loop via `switchInput(to:)`.
private func restoreInputSelection() {
guard !didRestoreInput else { return }
didRestoreInput = true
let defaults: UserDefaults = UserDefaults.standard
if defaults.object(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey) != nil {
let stored: Int = defaults.integer(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
if stored >= 0, stored < shoeGaze.engine.numInputChannels {
switchInput(to: .liveInput(channel: stored))
} else if stored >= 0, shoeGaze.engine.numInputChannels == 0,
MicrophonePermission.isAuthorized, let onEnableLiveInput {
// iOS: a live choice was saved and the mic is already authorised — rebuild the
// engine with an input channel silently (no prompt, since access is granted).
onEnableLiveInput()
}
// A test-loop choice (or live with no host hook / no permission) leaves the test loop.
} else if MicrophonePermission.isAuthorized, shoeGaze.engine.numInputChannels > 0 {
// First launch with no saved choice but mic already granted → default to live input.
switchInput(to: .liveInput(channel: 0))
}
}
// MARK: - Board-switch shortcuts
/// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the
/// edit target. 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
Button("") { switchToBoard(index) }
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
}
}
.opacity(0)
.frame(width: 0, height: 0)
.accessibilityHidden(true)
}
/// Solos board `index` (a live amp-channel-style switch) and makes it the edit target.
private func switchToBoard(_ index: Int) {
guard index < shoeGaze.boards.count else { return }
selectedBoardIndex = index
let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeBuilderView.maxCrossfadeSeconds)
shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds)
}
// MARK: - Save / Load (iOS)
// Save is in-view on both platforms (cross-platform fileExporter) so "Save & Clear" works
// everywhere. Load is the macOS File menu / iOS fileImporter; recording controls are iOS
// in-view (macOS uses the Record menu).
#if !os(macOS)
/// iOS recording controls: choose an output folder, then start/stop recording.
private var recordingRow: some View {
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
Button("Recording Folder…") { showRecordingFolderImporter = true }
.buttonStyle(.bordered).tint(.blue)
Text(shoeGaze.recordingFolder?.lastPathComponent ?? "No folder")
.font(.caption)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.folderLabelOpacity))
.lineLimit(1)
.truncationMode(.middle)
Spacer()
Button(shoeGaze.isRecording ? "Stop Recording" : "Record") {
toggleRecording()
}
.buttonStyle(.borderedProminent)
.tint(shoeGaze.isRecording ? .red : .accentColor)
.disabled(shoeGaze.recordingFolder == nil && !shoeGaze.isRecording)
}
}
private func toggleRecording() {
if shoeGaze.isRecording {
shoeGaze.stopRecording()
} else {
do { try shoeGaze.startRecording() }
catch { print("[ShoeGazeBuilderView] startRecording() failed: \(error)") }
}
}
private func handleRecordingFolderImport(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
// A `.fileImporter` folder URL is security-scoped on iOS; keep access open for the
// session so the recorder can write into it.
if url.startAccessingSecurityScopedResource() {
shoeGaze.recordingFolder = url
} else {
print("[ShoeGazeBuilderView] could not access recording folder")
}
case .failure(let error):
print("[ShoeGazeBuilderView] recording folder pick failed: \(error)")
}
}
#endif
/// Presents the cross-platform rig-save exporter (also used by the "Save & Clear" flow).
private func saveAction() {
do {
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
showExporter = true
} catch {
print("[ShoeGazeBuilderView] rigData failed: \(error)")
}
}
#if !os(macOS)
private func loadAction() {
showImporter = true
}
/// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the
/// board selection to a valid index (load replaces all boards).
private func loadRig(from url: URL) {
let wasRunning: Bool = shoeGaze.engine.isRunning
if wasRunning { shoeGaze.engine.stop() }
do {
try shoeGaze.loadRig(from: url)
selectedBoardIndex = 0
autosave()
} catch {
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
}
if wasRunning { try? shoeGaze.engine.start() }
transportTick.toggle()
}
private func handleImport(_ result: Result<URL, Error>) {
switch result {
case .success(let url):
// A `.fileImporter` URL is security-scoped on iOS; access must be started to read it.
let scoped: Bool = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
loadRig(from: url)
case .failure(let error):
print("[ShoeGazeBuilderView] import failed: \(error)")
}
}
#endif
}