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>
This commit is contained in:
@@ -83,7 +83,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
)
|
||||
super.init()
|
||||
|
||||
seedInitialBoard()
|
||||
// Restore the autosaved rig if there is one; otherwise seed a default board.
|
||||
if !RigStore.restore(into: shoeGaze) {
|
||||
seedInitialBoard()
|
||||
}
|
||||
}
|
||||
|
||||
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
|
||||
@@ -134,9 +137,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
RigStore.save(shoeGaze)
|
||||
engine.stop()
|
||||
}
|
||||
|
||||
func applicationDidResignActive(_ notification: Notification) {
|
||||
// Persist on every deactivation too, so state survives an unexpected exit.
|
||||
RigStore.save(shoeGaze)
|
||||
}
|
||||
|
||||
// MARK: - Main menu
|
||||
|
||||
/// Builds a minimal menu bar: an application menu with About / Hide / Quit (⌘Q).
|
||||
|
||||
@@ -19,6 +19,7 @@ import LyrebirdShoeGazeUI
|
||||
struct ShoeGazeBuilderiOSApp: App {
|
||||
|
||||
@State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel()
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
@@ -33,5 +34,9 @@ struct ShoeGazeBuilderiOSApp: App {
|
||||
}
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
// Persist the rig whenever the app leaves the foreground.
|
||||
if phase != .active { model.save() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,15 +61,17 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
self.iosDriver = built.driver
|
||||
self.shoeGaze = built.shoeGaze
|
||||
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
board.label = "Board 1"
|
||||
try shoeGaze.appendPedal(ShoeGazeBuilderiOSAppModel.seedPedalType, to: board)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderiOS] seed board failed: \(error)")
|
||||
// Restore the autosaved rig if there is one; otherwise seed a default board.
|
||||
if !RigStore.restore(into: shoeGaze) {
|
||||
seedFallbackBoard()
|
||||
}
|
||||
}
|
||||
|
||||
/// Persists the current rig. Call when the app moves to the background.
|
||||
func save() {
|
||||
RigStore.save(shoeGaze)
|
||||
}
|
||||
|
||||
// MARK: - Audio session / engine construction
|
||||
|
||||
/// Activates the play-and-record audio session once. Idempotent; safe to call before each
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
// RigStore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Autosaves the current rig to disk and restores it on launch, so a board survives app restarts.
|
||||
///
|
||||
/// Writes the same JSON produced by `ShoeGaze.rigData()` to a fixed file in the user's
|
||||
/// Application Support directory. Callers save on app background/terminate (and after notable
|
||||
/// edits) and restore once at startup, before seeding any default board.
|
||||
@MainActor
|
||||
public enum RigStore {
|
||||
|
||||
private static let folderName: String = "ShoeGaze"
|
||||
private static let fileName: String = "autosave-rig.json"
|
||||
|
||||
/// Location of the autosave file, creating the containing folder if needed. `nil` if the
|
||||
/// Application Support directory can't be resolved.
|
||||
public static var autosaveURL: URL? {
|
||||
let fileManager: FileManager = FileManager.default
|
||||
guard let base: URL = try? fileManager.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
) else { return nil }
|
||||
let dir: URL = base.appendingPathComponent(folderName, isDirectory: true)
|
||||
try? fileManager.createDirectory(at: dir, withIntermediateDirectories: true)
|
||||
return dir.appendingPathComponent(fileName)
|
||||
}
|
||||
|
||||
/// Writes the rig's current state to the autosave file. Returns `false` on any failure.
|
||||
@discardableResult
|
||||
public static func save(_ shoeGaze: ShoeGaze) -> Bool {
|
||||
guard let url: URL = autosaveURL else { return false }
|
||||
do {
|
||||
let data: Data = try shoeGaze.rigData()
|
||||
try data.write(to: url, options: .atomic)
|
||||
return true
|
||||
} catch {
|
||||
print("[RigStore] autosave failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet.
|
||||
///
|
||||
/// - Returns: `true` if an autosave existed and produced at least one board; `false` if there
|
||||
/// was nothing to restore or the load failed (in which case the caller should seed a default).
|
||||
@discardableResult
|
||||
public static func restore(into shoeGaze: ShoeGaze) -> Bool {
|
||||
guard let url: URL = autosaveURL,
|
||||
FileManager.default.fileExists(atPath: url.path) else { return false }
|
||||
do {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
try shoeGaze.loadRig(from: data)
|
||||
return !shoeGaze.boards.isEmpty
|
||||
} catch {
|
||||
print("[RigStore] restore failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes the autosave file (e.g. after the user clears the board without saving).
|
||||
public static func clear() {
|
||||
guard let url: URL = autosaveURL else { return }
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
}
|
||||
@@ -87,11 +87,18 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
|
||||
@State private var showBoardsSheet: Bool = false
|
||||
|
||||
#if !os(macOS)
|
||||
/// iOS file-dialog presentation flags + the document to export. (macOS uses the File menu.)
|
||||
@State private var showImporter: 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
|
||||
@@ -164,6 +171,25 @@ public struct ShoeGazeBuilderView: View {
|
||||
// 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: {
|
||||
@@ -173,7 +199,6 @@ public struct ShoeGazeBuilderView: View {
|
||||
#if !os(macOS)
|
||||
.background(rigImportAnchor)
|
||||
.background(recordingFolderImportAnchor)
|
||||
.background(rigExportAnchor)
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -194,6 +219,28 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -210,21 +257,6 @@ public struct ShoeGazeBuilderView: View {
|
||||
handleRecordingFolderImport(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts the rig-save (`.json`) exporter on its own node.
|
||||
private var rigExportAnchor: some View {
|
||||
Color.clear
|
||||
.fileExporter(
|
||||
isPresented: $showExporter,
|
||||
document: exportDocument,
|
||||
contentType: .json,
|
||||
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
|
||||
) { result in
|
||||
if case .failure(let error) = result {
|
||||
print("[ShoeGazeBuilderView] export failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Transport row
|
||||
@@ -282,13 +314,18 @@ public struct ShoeGazeBuilderView: View {
|
||||
.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, Save/Load live in the app's File menu (see the app shell's AppDelegate);
|
||||
// on iOS they stay in-view, driven by fileExporter/fileImporter.
|
||||
#if !os(macOS)
|
||||
// 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
|
||||
@@ -374,6 +411,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
|
||||
do {
|
||||
_ = try shoeGaze.appendPedal(PedalType(type), to: board)
|
||||
autosave()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
|
||||
}
|
||||
@@ -386,12 +424,38 @@ public struct ShoeGazeBuilderView: View {
|
||||
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
|
||||
@@ -490,9 +554,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
|
||||
// MARK: - Save / Load (iOS)
|
||||
|
||||
// On macOS, Save/Load are driven from the app's File menu (the app shell owns the
|
||||
// NSSavePanel/NSOpenPanel and calls `shoeGaze.saveRig`/`loadRig` directly). On iOS they are
|
||||
// in-view, presenting `fileExporter`/`fileImporter`.
|
||||
// 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 {
|
||||
@@ -537,7 +601,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
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())
|
||||
@@ -547,6 +613,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
private func loadAction() {
|
||||
showImporter = true
|
||||
}
|
||||
@@ -559,6 +626,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
do {
|
||||
try shoeGaze.loadRig(from: url)
|
||||
selectedBoardIndex = 0
|
||||
autosave()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// RigStoreTests.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("RigStore")
|
||||
struct RigStoreTests {
|
||||
|
||||
@Test func savesAndRestoresAcrossInstances() throws {
|
||||
RigStore.clear()
|
||||
defer { RigStore.clear() }
|
||||
|
||||
// Build a rig and autosave it.
|
||||
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: urlA) }
|
||||
let a: ShoeGaze = ShoeGaze(engine: engineA)
|
||||
let lead: PedalBoard = try a.addBoard()
|
||||
lead.label = "Lead"
|
||||
try a.appendPedal(.overdrive, to: lead)
|
||||
try a.finalizeBoard(lead)
|
||||
let clean: PedalBoard = try a.addBoard()
|
||||
clean.label = "Clean"
|
||||
try a.appendPedal(.graphicEQ, to: clean)
|
||||
try a.finalizeBoard(clean)
|
||||
#expect(RigStore.save(a))
|
||||
|
||||
// A fresh, boardless instance restores the autosaved rig.
|
||||
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: urlB) }
|
||||
let b: ShoeGaze = ShoeGaze(engine: engineB)
|
||||
#expect(RigStore.restore(into: b))
|
||||
#expect(b.boards.count == 2)
|
||||
#expect(b.boards.first?.label == "Lead")
|
||||
#expect(b.boards.last?.label == "Clean")
|
||||
}
|
||||
|
||||
@Test func restoreReturnsFalseWhenNoAutosave() throws {
|
||||
RigStore.clear()
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
#expect(!RigStore.restore(into: sg), "restore should report nothing to load after clear()")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user