// 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 /// Width of the scope/CPU block in the bottom strip — matches `BoardBarView`'s Solo/Blend/All /// control column so the scope aligns under it. private static let scopeWidth: CGFloat = 188 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" /// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be /// highlighted on the next launch. Read by the app shells to seed `initialRigID`. public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID" /// 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 /// Default filename offered when exporting the whole library as an archive. private static let defaultArchiveFileName: String = "ShoeGaze Library" /// Extra width reserved for the rig-library sidebar on top of the builder's minimum width. private static let librarySidebarReserve: CGFloat = 216 private static let recordDotSize: CGFloat = 9 private static let folderLabelOpacity: Double = 0.55 // MARK: - Properties private let shoeGaze: ShoeGaze private let library: RigLibraryStore 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. @State private var showClearDialog: Bool = false /// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives /// the sidebar highlight and decides whether Save overwrites or prompts for a name. @State private var currentRigID: UUID? /// Guards the one-time `currentRigID` seed from `initialRigID` on appear. @State private var didRestoreRig: Bool = false /// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate). @State private var namePrompt: RigNamePrompt? /// Confirmation dialog for the "Erase All Rigs" library action. @State private var showEraseAllDialog: Bool = false /// Save-before-switch prompt: the rig the user asked to switch to while the current rig has /// unsaved changes, and the flag presenting the dialog. @State private var pendingSwitchEntry: RigEntry? @State private var showSwitchSaveDialog: Bool = false /// Archive export state. Cross-platform: backs the sidebar's Export Archive and the /// "Save & Clear" flow is separate (it saves to the library, not a file). @State private var showExporter: Bool = false @State private var exportDocument: RigFileDocument = RigFileDocument(data: Data()) /// Archive import state (cross-platform). @State private var showImporter: Bool = false #if !os(macOS) /// 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. /// - library: The rig library store. The host should `start()` it (e.g. via /// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the /// persisted current rig once the library has loaded. public init( shoeGaze: ShoeGaze, library: RigLibraryStore, hardwareSampleRate: @escaping () -> Double? = { nil }, onEnableLiveInput: (() -> Void)? = nil ) { self.shoeGaze = shoeGaze self.library = library self.hardwareSampleRate = hardwareSampleRate self.onEnableLiveInput = onEnableLiveInput } // MARK: - Body public var body: some View { HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) { rigSidebar Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) builderColumn } .padding(ShoeGazeBuilderView.outerPadding) .frame( minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve, minHeight: ShoeGazeBuilderView.minHeight ) .background( Color( red: ShoeGazeBuilderView.backgroundRed, green: ShoeGazeBuilderView.backgroundGreen, blue: ShoeGazeBuilderView.backgroundBlue ) ) // The builder is always dark-themed; force the dark scheme so system controls (nav title, // steppers, the Record button) use light text instead of black-on-dark in light mode. .preferredColorScheme(.dark) .background(boardSwitchShortcuts) .onAppear { restoreInputSelection() restoreCurrentRig() } .onChange(of: library.isLoaded) { restoreCurrentRig() } .onChange(of: currentRigID) { persistCurrentRigID() } .background(boardsSheetAnchor) .background(rigExportAnchor) .background(rigImportAnchor) .rigNamePrompt($namePrompt) .confirmationDialog( "Erase all rigs?", isPresented: $showEraseAllDialog, titleVisibility: .visible ) { Button("Erase All Rigs", role: .destructive) { eraseAllRigs() } Button("Cancel", role: .cancel) { } } message: { Text("This permanently removes every saved rig from the library" + (library.isICloud ? " on all your devices." : ".")) } .confirmationDialog( "Save changes to the current rig?", isPresented: $showSwitchSaveDialog, titleVisibility: .visible, presenting: pendingSwitchEntry ) { target in Button("Save") { pendingSwitchEntry = nil saveCurrentRig(then: { loadEntry(target) }) } Button("Don't Save", role: .destructive) { pendingSwitchEntry = nil loadEntry(target) } Button("Cancel", role: .cancel) { pendingSwitchEntry = nil } } message: { target in Text("Switching to \"\(target.name)\" will discard unsaved changes to the current rig.") } .onReceive(NotificationCenter.default.publisher(for: .shoeGazeSaveRig)) { _ in saveCurrentRig() } .onReceive(NotificationCenter.default.publisher(for: .shoeGazeNewRig)) { _ in promptNewRig() } .confirmationDialog( "Clear all boards?", isPresented: $showClearDialog, titleVisibility: .visible ) { Button("Save & Clear") { saveCurrentRig(then: { performClear() }) } Button("Clear Without Saving", role: .destructive) { performClear() } Button("Cancel", role: .cancel) { } } 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(recordingFolderImportAnchor) #endif } /// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/ /// delete/erase and archive import/export. Selecting a rig replaces the current session. private var rigSidebar: some View { RigLibrarySidebarView( store: library, currentRigID: $currentRigID, onSelect: { entry in requestLoad(entry) }, onNew: { promptNewRig() }, onSave: { saveCurrentRig() }, onSaveAs: { promptSaveAs() }, onDuplicate: { entry in promptDuplicate(entry) }, onRename: { entry in promptRename(entry) }, onDelete: { entry in deleteEntry(entry) }, onEraseAll: { showEraseAllDialog = true }, onImportArchive: { showImporter = true }, onExportArchive: { exportArchiveAction() } ) } /// The main builder column: transport, IO, the scope-plus-mixer/picker top section, then the /// board canvas. private var builderColumn: some View { VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { transportRow ioRow #if !os(macOS) recordingRow #endif Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) topSection Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) boardArea } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } /// Top section: the scope + CPU meters on the left (sized to align with the mixer's /// Solo/Blend/All control column), and a right column stacking the board mixer over the /// horizontal pedal picker. private var topSection: some View { HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) { VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) { ShoeGazeScopeView(shoeGaze: shoeGaze) LyrebirdStatusView(engine: shoeGaze.engine) } .frame(width: ShoeGazeBuilderView.scopeWidth, alignment: .leading) Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { BoardBarView( shoeGaze: shoeGaze, editingBoardIndex: $selectedBoardIndex, crossfadeSeconds: $crossfadeSeconds, onAddBoard: { addBoard() } ) Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) pedalPickerRow } .frame(maxWidth: .infinity, alignment: .leading) } .fixedSize(horizontal: false, vertical: true) } /// A compact horizontal pedal-picker strip (sits below the board mixer in the top section). private var pedalPickerRow: some View { ScrollView(.horizontal, showsIndicators: true) { PedalPaletteView( axis: .horizontal, onAdd: { type in addPedal(type: type) }, onRouting: { action in performRouting(action) } ) .padding(.bottom, 2) } .fixedSize(horizontal: false, vertical: true) } // 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 archive-export (`.json`) exporter on its own node. Writes the whole library as one /// ``RigArchive`` file for backup or transfer. private var rigExportAnchor: some View { Color.clear .fileExporter( isPresented: $showExporter, document: exportDocument, contentType: .json, defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName ) { result in if case .failure(let error) = result { print("[ShoeGazeBuilderView] archive export failed: \(error)") } } } /// Hosts the archive-import (`.json`) importer on its own node (cross-platform). Accepts a /// ``RigArchive`` or a legacy single-rig file; imported rigs are added to the library. private var rigImportAnchor: some View { Color.clear .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in handleArchiveImport(result) } } #if !os(macOS) /// 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.. { 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() { // Stop around the rebuild so removing every board and immediately re-adding a fresh one // can't reuse a bus a just-removed master is still draining (one-block glitch). let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } // 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 if wasRunning { try? shoeGaze.engine.start() } 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: - Recording (iOS) // 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) { 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 // MARK: - Rig library /// Highlights the persisted current rig once the library has loaded. Runs once; only sets the /// highlight when nothing is selected yet and the saved id still exists in the library. private func restoreCurrentRig() { guard !didRestoreRig, library.isLoaded else { return } didRestoreRig = true guard currentRigID == nil, let stored: String = UserDefaults.standard.string( forKey: ShoeGazeBuilderView.currentRigDefaultsKey), let id: UUID = UUID(uuidString: stored), library.entries.contains(where: { $0.id == id }) else { return } currentRigID = id } /// Persists `currentRigID` so the same rig is highlighted on the next launch. private func persistCurrentRigID() { let defaults: UserDefaults = UserDefaults.standard if let id: UUID = currentRigID { defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey) } else { defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey) } } /// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine /// around the rebuild, resets the board selection, and records the entry as current. private func loadEntry(_ entry: RigEntry) { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } do { try shoeGaze.loadRig(from: entry.state) currentRigID = entry.id selectedBoardIndex = 0 autosave() } catch { print("[ShoeGazeBuilderView] loadEntry failed: \(error)") } if wasRunning { try? shoeGaze.engine.start() } transportTick.toggle() } /// Switches to `entry`, prompting to save first when the current rig has unsaved changes. /// No-op when `entry` is already the current rig. private func requestLoad(_ entry: RigEntry) { guard entry.id != currentRigID else { return } if isCurrentRigDirty() { pendingSwitchEntry = entry showSwitchSaveDialog = true } else { loadEntry(entry) } } /// Whether the working rig differs from the library entry it was loaded from. A working rig with /// no backing entry counts as dirty when it has any boards. private func isCurrentRigDirty() -> Bool { guard let id: UUID = currentRigID, let entry: RigEntry = library.entries.first(where: { $0.id == id }) else { return !shoeGaze.boards.isEmpty } return shoeGaze.captureState() != entry.state } /// Saves the current session over the loaded library entry, or prompts for a name when no entry /// is loaded (a new, never-saved rig). /// /// - Parameter completion: Runs only after a successful save (e.g. clear the boards, or load the /// rig the user was switching to). Cancelling the name prompt cancels it too — no save, no /// follow-up. private func saveCurrentRig(then completion: @escaping () -> Void = { }) { guard let id: UUID = currentRigID, let existing: RigEntry = library.entries.first(where: { $0.id == id }) else { // No current entry — prompt for a name; the follow-up runs only on commit. namePrompt = RigNamePrompt( title: "Save Rig As", initialText: currentRigName() ?? defaultNewRigName(), confirmLabel: "Save" ) { name in persist(shoeGaze.captureEntry(name: name), then: completion) } return } persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion) } /// Prompts for a name, then creates a brand-new empty rig (one empty board) and selects it. private func promptNewRig() { namePrompt = RigNamePrompt( title: "New Rig", initialText: defaultNewRigName(), confirmLabel: "Create" ) { name in createNewRig(named: name) } } /// Prompts for a name and saves the current session as a new library entry (new id). private func promptSaveAs() { namePrompt = RigNamePrompt( title: "Save Rig As", initialText: currentRigName() ?? defaultNewRigName(), confirmLabel: "Save" ) { name in persist(shoeGaze.captureEntry(name: name)) } } /// Prompts for a name and duplicates `entry`, loading the copy as the current rig. private func promptDuplicate(_ entry: RigEntry) { namePrompt = RigNamePrompt( title: "Duplicate Rig", initialText: "\(entry.name) copy", confirmLabel: "Duplicate" ) { name in do { let copy: RigEntry = try library.duplicate(entry, newName: name) loadEntry(copy) } catch { print("[ShoeGazeBuilderView] duplicate failed: \(error)") } } } /// Prompts for a new name and renames `entry` in the library. private func promptRename(_ entry: RigEntry) { namePrompt = RigNamePrompt( title: "Rename Rig", initialText: entry.name, confirmLabel: "Rename" ) { name in do { _ = try library.rename(entry, to: name) } catch { print("[ShoeGazeBuilderView] rename failed: \(error)") } } } /// Deletes `entry` from the library. Clears the current-rig marker if it was the loaded rig. private func deleteEntry(_ entry: RigEntry) { do { try library.delete(entry) if currentRigID == entry.id { currentRigID = nil } } catch { print("[ShoeGazeBuilderView] delete failed: \(error)") } } /// Erases the entire library and clears the current-rig marker. private func eraseAllRigs() { do { try library.eraseAll() currentRigID = nil } catch { print("[ShoeGazeBuilderView] eraseAll failed: \(error)") } } /// Captures the current session into the whole-library archive exporter. private func exportArchiveAction() { do { exportDocument = RigFileDocument(data: try library.exportArchiveData()) showExporter = true } catch { print("[ShoeGazeBuilderView] exportArchiveData failed: \(error)") } } /// Imports an archive (or legacy single-rig file) into the library. private func handleArchiveImport(_ result: Result) { switch result { case .success(let url): // A `.fileImporter` URL is security-scoped; access must be started to read it. let scoped: Bool = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } do { let data: Data = try Data(contentsOf: url) _ = try library.importArchive(from: data) } catch { print("[ShoeGazeBuilderView] archive import failed: \(error)") } case .failure(let error): print("[ShoeGazeBuilderView] archive import pick failed: \(error)") } } /// Persists `entry`, marks it current, and runs `completion` (e.g. the "Save & Clear" clear). private func persist( _ entry: RigEntry, then completion: () -> Void = { } ) { do { try library.save(entry) currentRigID = entry.id // Only run the follow-up (e.g. the "Save & Clear" clear) once the save succeeded — // otherwise a failed save would still wipe the boards, losing the rig. completion() } catch { print("[ShoeGazeBuilderView] save failed: \(error)") } } /// Creates a fresh single-board rig, saves it under `name`, and makes it current. private func createNewRig(named name: String) { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } // Replace the working graph with a single empty board. 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] createNewRig seed failed: \(error)") } selectedBoardIndex = 0 if wasRunning { try? shoeGaze.engine.start() } transportTick.toggle() persist(shoeGaze.captureEntry(name: name)) } /// The name of the currently loaded library entry, if any. private func currentRigName() -> String? { guard let id: UUID = currentRigID else { return nil } return library.entries.first(where: { $0.id == id })?.name } /// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names. private func defaultNewRigName() -> String { let base: String = "Rig" let existing: Set = Set(library.entries.map(\.name)) var index: Int = library.entries.count + 1 while existing.contains("\(base) \(index)") { index += 1 } return "\(base) \(index)" } }