dc42db0c59
Replace the single hand-saved rig file with a managed library of named rigs persisted in app storage and synced across devices and both builder apps via a shared iCloud container (iCloud.net.realizedsound.ShoeGazeData), falling back to local storage when iCloud is unavailable. Core (LyrebirdShoeGaze/Presets): - RigEntry: named, timestamped ShoeGazeState (a whole multi-board rig). - RigArchive: portable multi-rig JSON bundle for backup/transfer; legacy single-rig files import as a one-rig archive. - RigLibraryStore (@MainActor @Observable): one JSON file per rig, with NSFileCoordinator writes and NSMetadataQuery live remote-change watching. - RigLibraryLocation: iCloud-or-local directory resolver (skips the slow ubiquity lookup when no iCloud account is signed in). - ShoeGaze.loadRig(from: ShoeGazeState) + captureEntry; shared filename sanitizer factored out of BoardVersionStore. UI (LyrebirdShoeGazeUI): - RigLibrarySidebarView: persistent left listing with new/save/save-as/ duplicate/rename/delete/erase-all and archive import/export. - RigNamePrompt; RigLibraryBootstrap one-call shell setup. - ShoeGazeBuilderView: sidebar wired in; selecting a rig replaces the session; File menu / sidebar do whole-library archive import/export. Shells/entitlements: both builder targets own+start the store and carry the iCloud Documents entitlement; NSUbiquitousContainers exposes the rigs in the Files app. (macOS pbxproj also carries a pre-existing 1.0->1.1.1 version bump.) Tests: RigEntry/RigArchive round-trip + RigLibraryStore CRUD/import/export (15 new; full suite 206 passing). Provisioning (manual, not done here): enable the iCloud container on both App IDs and select it in Signing & Capabilities for both targets. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
476 lines
19 KiB
Swift
476 lines
19 KiB
Swift
// RigLibraryStore.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
import Foundation
|
|
import Observation
|
|
|
|
/// The user's library of saved rigs, persisted as one JSON file per rig and (when available)
|
|
/// synced across devices and apps through a shared iCloud container.
|
|
///
|
|
/// `RigLibraryStore` is `@Observable`, so SwiftUI views refresh automatically as `entries`
|
|
/// changes — whether the change came from a local edit or from a remote iCloud update. All
|
|
/// mutations run on the main actor.
|
|
///
|
|
/// ## Storage model
|
|
///
|
|
/// Each ``RigEntry`` is written as a separate pretty-printed JSON file named
|
|
/// `<sanitized-name>-<id>.json` (see ``sanitizePresetFilename(_:maxLength:)``) inside the
|
|
/// directory resolved by ``RigLibraryLocation``. One file per rig keeps iCloud merges
|
|
/// conflict-free at rig granularity: editing rig A never rewrites rig B's file.
|
|
///
|
|
/// When the directory is an iCloud ubiquity container, reads and writes are wrapped in
|
|
/// `NSFileCoordinator`, and an `NSMetadataQuery` watches for remote changes so a rig saved on one
|
|
/// device appears on another without relaunching. Call ``start()`` once after construction to load
|
|
/// the current contents and begin watching.
|
|
///
|
|
/// ## Typical usage
|
|
///
|
|
/// ```swift
|
|
/// // Off the main thread at launch (the ubiquity lookup blocks):
|
|
/// let resolved = RigLibraryLocation.resolve()
|
|
/// // Back on the main actor:
|
|
/// let store = RigLibraryStore(resolved: resolved)
|
|
/// store.start()
|
|
/// // …
|
|
/// try store.save(shoeGaze.captureEntry(name: "Ambient Wash"))
|
|
/// ```
|
|
@MainActor
|
|
@Observable
|
|
public final class RigLibraryStore {
|
|
|
|
// MARK: - State
|
|
|
|
/// All known rigs, sorted by name (case-insensitive), then most-recently-saved first.
|
|
public private(set) var entries: [RigEntry] = []
|
|
|
|
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
|
|
/// local-only fallback.
|
|
public let isICloud: Bool
|
|
|
|
/// The directory holding the per-rig JSON files.
|
|
public let directory: URL
|
|
|
|
// MARK: - Private
|
|
|
|
/// Live query over the iCloud documents scope; `nil` when local-only or not yet started.
|
|
@ObservationIgnored private var metadataQuery: NSMetadataQuery?
|
|
|
|
/// Retained NotificationCenter tokens for the metadata-query observers.
|
|
@ObservationIgnored private var observerTokens: [NSObjectProtocol] = []
|
|
|
|
/// File extension of a stored rig.
|
|
private static let fileExtension: String = "json"
|
|
|
|
// MARK: - Init
|
|
|
|
/// Creates a store rooted at an explicit directory. Designated initializer; used directly by
|
|
/// tests with a temporary directory and `isICloud: false`.
|
|
///
|
|
/// - Parameters:
|
|
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
|
|
/// - isICloud: Whether `directory` is an iCloud ubiquity container (enables coordination and
|
|
/// remote-change watching).
|
|
public init(
|
|
directory: URL,
|
|
isICloud: Bool
|
|
) {
|
|
self.directory = directory
|
|
self.isICloud = isICloud
|
|
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
|
}
|
|
|
|
/// Creates a store from a resolved ``RigLibraryLocation``.
|
|
///
|
|
/// - Parameter resolved: The directory + iCloud flag from `RigLibraryLocation.resolve()`.
|
|
public convenience init(resolved: RigLibraryLocation.Resolved) {
|
|
self.init(directory: resolved.directory, isICloud: resolved.isICloud)
|
|
}
|
|
|
|
// MARK: - Lifecycle
|
|
|
|
/// Loads the current library contents and, when iCloud-backed, begins watching for remote
|
|
/// changes. Safe to call once after construction.
|
|
public func start() {
|
|
reloadFromDirectory()
|
|
if isICloud {
|
|
startMetadataQuery()
|
|
}
|
|
}
|
|
|
|
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
|
|
/// the store otherwise lives for the app's lifetime.
|
|
public func stop() {
|
|
metadataQuery?.stop()
|
|
metadataQuery = nil
|
|
for token: NSObjectProtocol in observerTokens {
|
|
NotificationCenter.default.removeObserver(token)
|
|
}
|
|
observerTokens.removeAll()
|
|
}
|
|
|
|
// MARK: - Mutations
|
|
|
|
/// Saves `entry`, writing its JSON file and updating `entries` in memory.
|
|
///
|
|
/// If an entry with the same `id` already exists, its file and in-memory record are replaced
|
|
/// (the on-disk filename also updates if the name changed). Use this both to add a brand-new
|
|
/// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`).
|
|
///
|
|
/// - Parameter entry: The rig entry to persist.
|
|
/// - Throws: `JSONEncoder`, `NSFileCoordinator`, or write errors.
|
|
public func save(_ entry: RigEntry) throws {
|
|
// Replacing an existing id whose name changed leaves a stale file behind — remove any
|
|
// current file for this id first, then write under the (possibly new) name.
|
|
if let stale: URL = existingFileURL(for: entry.id) {
|
|
removeFileIfPresent(at: stale)
|
|
}
|
|
let data: Data = try encode(entry)
|
|
try writeData(data, to: fileURL(for: entry))
|
|
upsert(entry)
|
|
}
|
|
|
|
/// Deletes `entry` from disk and memory. No-op if its file is already gone.
|
|
///
|
|
/// - Parameter entry: The rig entry to remove.
|
|
/// - Throws: `NSFileCoordinator` or removal errors other than "file not found".
|
|
public func delete(_ entry: RigEntry) throws {
|
|
if let url: URL = existingFileURL(for: entry.id) {
|
|
try removeFile(at: url)
|
|
}
|
|
entries.removeAll { $0.id == entry.id }
|
|
}
|
|
|
|
/// Deletes **every** rig in the library, from disk and memory.
|
|
///
|
|
/// Removes all `*.json` files in the directory. A failure on one file propagates after the
|
|
/// remaining files have been attempted, so a single locked file cannot strand the rest.
|
|
///
|
|
/// - Throws: The first removal error encountered, after attempting all files.
|
|
public func eraseAll() throws {
|
|
var firstError: Error?
|
|
for url: URL in rigFileURLs() {
|
|
do {
|
|
try removeFile(at: url)
|
|
} catch {
|
|
if firstError == nil { firstError = error }
|
|
}
|
|
}
|
|
entries.removeAll()
|
|
if let firstError: Error = firstError { throw firstError }
|
|
}
|
|
|
|
/// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it,
|
|
/// and returns it.
|
|
///
|
|
/// - Parameters:
|
|
/// - entry: The rig to copy.
|
|
/// - newName: The copy's name.
|
|
/// - Returns: The newly created entry.
|
|
/// - Throws: Any error from ``save(_:)``.
|
|
@discardableResult
|
|
public func duplicate(
|
|
_ entry: RigEntry,
|
|
newName: String
|
|
) throws -> RigEntry {
|
|
let copy: RigEntry = entry.duplicated(name: newName)
|
|
try save(copy)
|
|
return copy
|
|
}
|
|
|
|
/// Renames `entry` to `newName`, keeping its `id`, and returns the updated entry.
|
|
///
|
|
/// - Parameters:
|
|
/// - entry: The rig to rename.
|
|
/// - newName: The new name.
|
|
/// - Returns: The renamed entry.
|
|
/// - Throws: Any error from ``save(_:)``.
|
|
@discardableResult
|
|
public func rename(
|
|
_ entry: RigEntry,
|
|
to newName: String
|
|
) throws -> RigEntry {
|
|
let renamed: RigEntry = entry.renamed(to: newName)
|
|
try save(renamed)
|
|
return renamed
|
|
}
|
|
|
|
// MARK: - Archive import / export
|
|
|
|
/// Encodes the entire library as a single ``RigArchive`` JSON document for export.
|
|
///
|
|
/// - Returns: Pretty-printed archive bytes suitable for a `fileExporter` / `NSSavePanel`.
|
|
/// - Throws: `JSONEncoder` errors.
|
|
public func exportArchiveData() throws -> Data {
|
|
let archive: RigArchive = RigArchive(rigs: entries)
|
|
return try makeEncoder().encode(archive)
|
|
}
|
|
|
|
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
|
|
/// added.
|
|
///
|
|
/// Accepts either a ``RigArchive`` (the multi-rig export format) or a legacy single-rig file
|
|
/// (a bare ``ShoeGazeState``), which is imported as one entry named `legacyRigName`. Imported
|
|
/// entries whose `id` already exists in the library are given a fresh `id` so an import never
|
|
/// silently overwrites an existing rig.
|
|
///
|
|
/// - Parameters:
|
|
/// - data: Archive or legacy-rig JSON bytes.
|
|
/// - legacyRigName: Name to use when importing a legacy single-rig file. Defaults to
|
|
/// `"Imported Rig"`.
|
|
/// - Returns: The number of rigs added to the library.
|
|
/// - Throws: `JSONDecoder` errors when `data` is neither an archive nor a legacy rig, or any
|
|
/// error from ``save(_:)``.
|
|
@discardableResult
|
|
public func importArchive(
|
|
from data: Data,
|
|
legacyRigName: String = "Imported Rig"
|
|
) throws -> Int {
|
|
let imported: [RigEntry] = try decodeImportable(data, legacyRigName: legacyRigName)
|
|
let existingIDs: Set<UUID> = Set(entries.map(\.id))
|
|
var added: Int = 0
|
|
for entry: RigEntry in imported {
|
|
// Avoid clobbering an existing rig that happens to share this id.
|
|
let toSave: RigEntry = existingIDs.contains(entry.id)
|
|
? entry.duplicated(name: entry.name, date: entry.savedAt)
|
|
: entry
|
|
try save(toSave)
|
|
added += 1
|
|
}
|
|
return added
|
|
}
|
|
|
|
// MARK: - Loading from disk
|
|
|
|
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
|
|
/// skipped so one bad file never blocks the rest. Not-yet-downloaded iCloud placeholders (which
|
|
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
|
|
private func reloadFromDirectory() {
|
|
var loaded: [RigEntry] = []
|
|
for url: URL in rigFileURLs() {
|
|
guard let data: Data = try? readData(at: url) else { continue }
|
|
guard let entry: RigEntry = try? makeDecoder().decode(RigEntry.self, from: data) else {
|
|
continue
|
|
}
|
|
loaded.append(entry)
|
|
}
|
|
entries = RigLibraryStore.sorted(loaded)
|
|
}
|
|
|
|
// MARK: - iCloud metadata query
|
|
|
|
/// Starts the live query over the iCloud documents scope and wires update handlers.
|
|
private func startMetadataQuery() {
|
|
guard metadataQuery == nil else { return }
|
|
let query: NSMetadataQuery = NSMetadataQuery()
|
|
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
|
|
query.predicate = NSPredicate(
|
|
format: "%K LIKE %@",
|
|
NSMetadataItemFSNameKey,
|
|
"*.\(RigLibraryStore.fileExtension)"
|
|
)
|
|
|
|
let center: NotificationCenter = NotificationCenter.default
|
|
let handler: @Sendable (Notification) -> Void = { [weak self] _ in
|
|
// queue: .main delivers on the main thread; we are a main-actor type.
|
|
MainActor.assumeIsolated { self?.handleMetadataUpdate() }
|
|
}
|
|
observerTokens.append(center.addObserver(
|
|
forName: .NSMetadataQueryDidFinishGathering, object: query, queue: .main, using: handler
|
|
))
|
|
observerTokens.append(center.addObserver(
|
|
forName: .NSMetadataQueryDidUpdate, object: query, queue: .main, using: handler
|
|
))
|
|
|
|
metadataQuery = query
|
|
query.start()
|
|
}
|
|
|
|
/// Handles a metadata-query result: triggers downloads for any rig files not yet present
|
|
/// locally, then rescans the directory for whatever is now readable.
|
|
private func handleMetadataUpdate() {
|
|
guard let query: NSMetadataQuery = metadataQuery else { return }
|
|
query.disableUpdates()
|
|
defer { query.enableUpdates() }
|
|
|
|
let fileManager: FileManager = FileManager.default
|
|
for index: Int in 0..<query.resultCount {
|
|
guard let item: NSMetadataItem = query.result(at: index) as? NSMetadataItem,
|
|
let url: URL = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
|
|
isInLibrary(url) else { continue }
|
|
let status: String? =
|
|
item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
|
|
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent {
|
|
try? fileManager.startDownloadingUbiquitousItem(at: url)
|
|
}
|
|
}
|
|
reloadFromDirectory()
|
|
}
|
|
|
|
// MARK: - File helpers
|
|
|
|
/// The write URL for `entry`: `<sanitized-name>-<id>.json` inside the library directory.
|
|
private func fileURL(for entry: RigEntry) -> URL {
|
|
let sanitized: String = sanitizePresetFilename(entry.name)
|
|
let filename: String = "\(sanitized)-\(entry.id.uuidString).\(RigLibraryStore.fileExtension)"
|
|
return directory.appendingPathComponent(filename)
|
|
}
|
|
|
|
/// Finds the existing file for `id` by matching the `-<uuid>.json` suffix, so renames (which
|
|
/// change the name prefix) are still located. `nil` if no file is present.
|
|
private func existingFileURL(for id: UUID) -> URL? {
|
|
let suffix: String = "-\(id.uuidString).\(RigLibraryStore.fileExtension)"
|
|
return rigFileURLs().first { $0.lastPathComponent.hasSuffix(suffix) }
|
|
}
|
|
|
|
/// All `*.json` files currently in the directory (hidden iCloud placeholders excluded).
|
|
private func rigFileURLs() -> [URL] {
|
|
let contents: [URL] = (try? FileManager.default.contentsOfDirectory(
|
|
at: directory,
|
|
includingPropertiesForKeys: nil,
|
|
options: .skipsHiddenFiles
|
|
)) ?? []
|
|
return contents.filter { $0.pathExtension == RigLibraryStore.fileExtension }
|
|
}
|
|
|
|
/// Whether `url` is a rig file inside this library's directory.
|
|
private func isInLibrary(_ url: URL) -> Bool {
|
|
url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL
|
|
&& url.pathExtension == RigLibraryStore.fileExtension
|
|
}
|
|
|
|
// MARK: - Coordinated I/O
|
|
|
|
/// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed.
|
|
private func writeData(_ data: Data, to url: URL) throws {
|
|
guard isICloud else {
|
|
try data.write(to: url, options: .atomic)
|
|
return
|
|
}
|
|
try coordinate(url, options: .forReplacing) { target in
|
|
try data.write(to: target, options: .atomic)
|
|
}
|
|
}
|
|
|
|
/// Reads the contents of `url`, coordinating the read when iCloud-backed.
|
|
private func readData(at url: URL) throws -> Data {
|
|
guard isICloud else {
|
|
return try Data(contentsOf: url)
|
|
}
|
|
var result: Data = Data()
|
|
try coordinate(url, options: .withoutChanges) { target in
|
|
result = try Data(contentsOf: target)
|
|
}
|
|
return result
|
|
}
|
|
|
|
/// Removes `url`, coordinating the delete when iCloud-backed.
|
|
private func removeFile(at url: URL) throws {
|
|
guard isICloud else {
|
|
try FileManager.default.removeItem(at: url)
|
|
return
|
|
}
|
|
try coordinate(url, options: .forDeleting) { target in
|
|
try FileManager.default.removeItem(at: target)
|
|
}
|
|
}
|
|
|
|
/// Best-effort remove that swallows "file not found" and other errors — used before a replacing
|
|
/// write where a missing prior file is expected.
|
|
private func removeFileIfPresent(at url: URL) {
|
|
try? removeFile(at: url)
|
|
}
|
|
|
|
/// Runs `body` inside an `NSFileCoordinator` block, surfacing both the coordinator's error and
|
|
/// any error thrown by `body`.
|
|
private func coordinate(
|
|
_ url: URL,
|
|
options: NSFileCoordinator.WritingOptions,
|
|
_ body: (URL) throws -> Void
|
|
) throws {
|
|
let coordinator: NSFileCoordinator = NSFileCoordinator()
|
|
var coordinatorError: NSError?
|
|
var thrown: Error?
|
|
coordinator.coordinate(writingItemAt: url, options: options, error: &coordinatorError) { target in
|
|
do { try body(target) } catch { thrown = error }
|
|
}
|
|
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
|
|
if let thrown: Error = thrown { throw thrown }
|
|
}
|
|
|
|
/// Coordinated read overload (uses the reading coordinator path).
|
|
private func coordinate(
|
|
_ url: URL,
|
|
options: NSFileCoordinator.ReadingOptions,
|
|
_ body: (URL) throws -> Void
|
|
) throws {
|
|
let coordinator: NSFileCoordinator = NSFileCoordinator()
|
|
var coordinatorError: NSError?
|
|
var thrown: Error?
|
|
coordinator.coordinate(readingItemAt: url, options: options, error: &coordinatorError) { target in
|
|
do { try body(target) } catch { thrown = error }
|
|
}
|
|
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
|
|
if let thrown: Error = thrown { throw thrown }
|
|
}
|
|
|
|
// MARK: - Codec
|
|
|
|
/// Encodes a single entry as a per-rig file would store it.
|
|
private func encode(_ entry: RigEntry) throws -> Data {
|
|
try makeEncoder().encode(entry)
|
|
}
|
|
|
|
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
|
|
private func makeEncoder() -> JSONEncoder {
|
|
let encoder: JSONEncoder = JSONEncoder()
|
|
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
|
encoder.dateEncodingStrategy = .secondsSince1970
|
|
return encoder
|
|
}
|
|
|
|
/// A JSON decoder matching ``makeEncoder()``.
|
|
private func makeDecoder() -> JSONDecoder {
|
|
let decoder: JSONDecoder = JSONDecoder()
|
|
decoder.dateDecodingStrategy = .secondsSince1970
|
|
return decoder
|
|
}
|
|
|
|
/// Decodes import bytes as a ``RigArchive`` first, falling back to a legacy single-rig
|
|
/// ``ShoeGazeState``.
|
|
private func decodeImportable(
|
|
_ data: Data,
|
|
legacyRigName: String
|
|
) throws -> [RigEntry] {
|
|
let decoder: JSONDecoder = makeDecoder()
|
|
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
|
|
return archive.rigs
|
|
}
|
|
// A legacy single-rig file is a bare ShoeGazeState (no `rigs` array). Decode and wrap.
|
|
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
|
|
return [RigEntry(name: legacyRigName, state: state)]
|
|
}
|
|
|
|
// MARK: - In-memory helpers
|
|
|
|
/// Inserts or replaces `entry` in `entries` by `id`, keeping the list sorted.
|
|
private func upsert(_ entry: RigEntry) {
|
|
var next: [RigEntry] = entries.filter { $0.id != entry.id }
|
|
next.append(entry)
|
|
entries = RigLibraryStore.sorted(next)
|
|
}
|
|
|
|
/// Sorts entries by name (case-insensitive), then most-recently-saved first, then id for a
|
|
/// fully deterministic order.
|
|
private static func sorted(_ entries: [RigEntry]) -> [RigEntry] {
|
|
entries.sorted { lhs, rhs in
|
|
let byName: ComparisonResult = lhs.name.localizedCaseInsensitiveCompare(rhs.name)
|
|
if byName != .orderedSame { return byName == .orderedAscending }
|
|
if lhs.savedAt != rhs.savedAt { return lhs.savedAt > rhs.savedAt }
|
|
return lhs.id.uuidString < rhs.id.uuidString
|
|
}
|
|
}
|
|
}
|