diff --git a/Sources/LyrebirdShoeGaze/Presets/RigStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigStore.swift index 515d19b..52172e7 100644 --- a/Sources/LyrebirdShoeGaze/Presets/RigStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/RigStore.swift @@ -32,12 +32,26 @@ public enum RigStore { return dir.appendingPathComponent(fileName) } - /// Writes the rig's current state to the autosave file. Returns `false` on any failure. + /// The autosave file payload: the working graph plus the id of the rig-library entry it derives + /// from, written together so the two can never drift apart. + private struct AutosaveEnvelope: Codable { + let currentRigID: UUID? + let state: ShoeGazeState + } + + /// Writes the rig's current state — plus its source-rig id (``ShoeGaze/currentRigID``) — 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() + let envelope: AutosaveEnvelope = AutosaveEnvelope( + currentRigID: shoeGaze.currentRigID, + state: shoeGaze.captureState() + ) + let encoder: JSONEncoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + let data: Data = try encoder.encode(envelope) try data.write(to: url, options: .atomic) return true } catch { @@ -46,7 +60,11 @@ public enum RigStore { } } - /// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet. + /// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet, and sets + /// ``ShoeGaze/currentRigID`` from the envelope so the highlight matches the restored graph. + /// + /// Decodes the current envelope format; falls back to a bare `ShoeGazeState` (pre-envelope + /// autosaves), in which case `currentRigID` is left `nil`. /// /// - 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). @@ -56,7 +74,16 @@ public enum RigStore { FileManager.default.fileExists(atPath: url.path) else { return false } do { let data: Data = try Data(contentsOf: url) - try shoeGaze.loadRig(from: data) + let decoder: JSONDecoder = JSONDecoder() + if let envelope: AutosaveEnvelope = try? decoder.decode(AutosaveEnvelope.self, from: data) { + try shoeGaze.loadRig(from: envelope.state) + shoeGaze.currentRigID = envelope.currentRigID + } else { + // Pre-envelope autosave: a bare ShoeGazeState with no recorded source rig. + let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) + try shoeGaze.loadRig(from: state) + shoeGaze.currentRigID = nil + } return !shoeGaze.boards.isEmpty } catch { print("[RigStore] restore failed: \(error)") diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index a225350..d0b1818 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -71,6 +71,12 @@ public final class ShoeGaze { /// Read and mutated by `MIDIController`; survives an input-source switch (same rig). public var midiMap: MIDIMap? + /// The id of the rig-library entry this working session derives from, or `nil` for an unsaved + /// session. Session provenance only — NOT part of a saved/exported rig; it is written into the + /// autosave envelope (see `RigStore`) alongside the graph so the sidebar highlight and the + /// restored graph can never diverge. The UI mirrors this into the rig-library selection. + public var currentRigID: UUID? + // MARK: - Recording state /// The folder into which `startRecording()` writes timestamped WAV files. diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index af88b34..8c3f876 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -43,10 +43,9 @@ public enum RigLibraryBootstrap { let entry: RigEntry = shoeGaze.captureEntry(name: seedName) do { try store.save(entry) - UserDefaults.standard.set( - entry.id.uuidString, - forKey: ShoeGazeBuilderView.currentRigDefaultsKey - ) + // The seeded entry was captured from the working graph, so it is the session's source + // rig — record it so the sidebar highlights it and the autosave envelope carries it. + shoeGaze.currentRigID = entry.id } catch { print("[RigLibraryBootstrap] seeding library failed: \(error)") } diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 3123a17..04ef8da 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -56,9 +56,6 @@ public struct ShoeGazeBuilderView: View { 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. @@ -116,10 +113,14 @@ public struct ShoeGazeBuilderView: View { /// 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 + /// + /// Backed by ``ShoeGaze/currentRigID`` (the single source of truth), so it is persisted inside + /// the autosave envelope together with the graph and restored consistently — the highlight can + /// never drift from the loaded rig. `@Observable` drives sidebar updates when it changes. + private var currentRigID: UUID? { + get { shoeGaze.currentRigID } + nonmutating set { shoeGaze.currentRigID = newValue } + } /// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate). @State private var namePrompt: RigNamePrompt? @@ -220,17 +221,14 @@ public struct ShoeGazeBuilderView: View { .background(boardSwitchShortcuts) .onAppear { restoreInputSelection() - restoreCurrentRig() syncIdleTimer() maybeWarnICloudUnavailable() } .onDisappear { releaseIdleTimer() } .onChange(of: transportTick) { syncIdleTimer() } .onChange(of: library.isLoaded) { - restoreCurrentRig() maybeWarnICloudUnavailable() } - .onChange(of: currentRigID) { persistCurrentRigID() } .background(boardsSheetAnchor) .background(rigExportAnchor) .background(rigImportAnchor) @@ -333,7 +331,7 @@ public struct ShoeGazeBuilderView: View { private var rigSidebar: some View { RigLibrarySidebarView( store: library, - currentRigID: $currentRigID, + currentRigID: Binding(get: { shoeGaze.currentRigID }, set: { shoeGaze.currentRigID = $0 }), onSelect: { entry in requestLoad(entry) }, onNew: { promptNewRig() }, onSave: { saveCurrentRig() }, @@ -718,10 +716,9 @@ public struct ShoeGazeBuilderView: View { /// 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() { + // The autosave envelope records `shoeGaze.currentRigID` alongside the graph, so the highlight + // and the restored graph stay consistent without any separate bookkeeping. RigStore.save(shoeGaze) - // Pair the current-rig id with every graph write so the persisted highlight can never drift - // from the autosaved graph (the source of the highlight/graph mismatch on restart). - persistCurrentRigID() } /// Removes every board, then seeds one fresh empty board so the builder is never boardless. @@ -897,33 +894,6 @@ public struct ShoeGazeBuilderView: View { // MARK: - Rig library - /// Highlights the rig the working session derives from, once the library has loaded. Runs once. - /// - /// The current rig id is written paired with every autosave (see ``autosave()``), so the stored - /// id always tracks the loaded graph — including after edits such as learning a MIDI binding, - /// which change the graph but not which saved rig it came from. Only highlights 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) {