// 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" /// Test-only override for ``autosaveURL``. When non-`nil`, all autosave reads/writes use this /// path instead of the real Application Support location — so a test suite never overwrites or /// deletes the user's actual autosaved rig. Production code leaves this `nil`. /// /// - Important: Any test that calls `save`/`restore`/`clear` **must** set this to a temporary /// file first (and reset it after), or it will clobber the running app's autosave. public static var autosaveURLOverride: URL? /// Location of the autosave file, creating the containing folder if needed. `nil` if the /// Application Support directory can't be resolved. Returns ``autosaveURLOverride`` verbatim /// when set (tests). public static var autosaveURL: URL? { if let override: URL = autosaveURLOverride { return override } 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) } /// 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 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 { print("[RigStore] autosave failed: \(error)") return false } } /// 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). @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) 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)") 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) } }