// 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) } }