Files
ShoeGaze/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift
T
josh 9e09eb284a Add .shoegaze document type and rig/board sharing
Introduce a single shareable document type for rigs and boards:

- ShoeGazeDocument: versioned JSON envelope wrapping either a RigArchive
  (one or many rigs) or a BoardVersion, with a tolerant decoder that also
  reads the legacy bare-RigArchive and bare-ShoeGazeState shapes.
- Register the .shoegaze UTType (net.realizedsound.shoegaze, conforms to
  public.json) in all four demo app Info.plists.
- Migrate library export/import onto the envelope: exportDocumentData() and
  a decoder-tolerant importArchive(); RigFileDocument and the Builder
  exporter/importer now use .shoegaze. Internal per-rig and board-version
  files stay app-private JSON.
- Add OS share-sheet entries via SwiftUI ShareLink: Share per rig in the
  library sidebar, Share per version in the board editor, backed by the
  Transferable wrappers RigShareItem / BoardShareItem.

Tests: ShoeGazeDocument round-trip and legacy decode, library .shoegaze
export/import round-trip, and a board-document-imports-no-rigs case.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 17:49:20 -07:00

563 lines
24 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. Resolved during ``start()`` for an auto-resolving store.
public private(set) var isICloud: Bool
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
/// ``start()`` for an auto-resolving store (before any writes, so no migration is needed).
public private(set) var directory: URL
/// `false` until the first load completes. Views can show a loading state and callers should
/// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a
/// first-launch seed would race a not-yet-loaded iCloud library.
public private(set) var isLoaded: Bool = false
// 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] = []
/// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the
/// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the
/// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on
/// the same file — in submission order.
@ObservationIgnored private let ioQueue: DispatchQueue =
DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility)
/// File extension of a stored rig.
private nonisolated static let fileExtension: String = "json"
/// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and
/// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer.
private let autoResolve: Bool
// MARK: - Init
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
/// directory; `start()` will not re-resolve the location.
///
/// - 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
self.autoResolve = false
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
/// Creates an auto-resolving store. Constructed instantly with a local placeholder directory;
/// ``start()`` resolves the real iCloud-or-local location off the main thread before loading.
public init() {
self.directory = RigLibraryLocation.localDirectory()
self.isICloud = false
self.autoResolve = true
}
// MARK: - Lifecycle
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
/// known. Safe to call once after construction.
public func start() async {
if autoResolve {
let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain()
directory = resolved.directory
isICloud = resolved.isICloud
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
}
if isICloud {
startMetadataQuery()
}
await reload()
isLoaded = true
}
/// Re-reads the library directory off the main thread and republishes `entries`. Ordered after
/// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops
/// the just-saved rig.
public func reload() async {
let dir: URL = directory
let coordinated: Bool = isICloud
let loaded: [RigEntry] = await withCheckedContinuation { continuation in
ioQueue.async {
continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated))
}
}
entries = RigLibraryStore.sorted(loaded)
}
/// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup
/// never runs on the main thread.
private static func resolveOffMain() async -> RigLibraryLocation.Resolved {
await withCheckedContinuation { continuation in
DispatchQueue.global(qos: .userInitiated).async {
continuation.resume(returning: RigLibraryLocation.resolve())
}
}
}
/// 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` errors (encoding happens synchronously). The actual file write runs
/// asynchronously on a background queue and only logs on failure — call
/// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination).
public func save(_ entry: RigEntry) throws {
// Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then
// update the in-memory list immediately and push the disk write to the background queue.
let data: Data = try encode(entry)
let target: URL = fileURL(for: entry)
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
upsert(entry)
ioQueue.async {
// Remove any prior file for this id first (a rename changes the name-prefixed filename).
if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory),
stale.standardizedFileURL != target.standardizedFileURL {
try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated)
}
do {
try RigLibraryStore.writeData(data, to: target, coordinated: coordinated)
} catch {
print("[RigLibraryStore] save write failed: \(error)")
}
}
}
/// Deletes `entry` from memory immediately and removes its file on the background queue.
///
/// - Parameter entry: The rig entry to remove.
/// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are
/// logged on the background queue.
public func delete(_ entry: RigEntry) throws {
entries.removeAll { $0.id == entry.id }
let directory: URL = self.directory
let id: UUID = entry.id
let coordinated: Bool = isICloud
ioQueue.async {
if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) {
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
catch { print("[RigLibraryStore] delete failed: \(error)") }
}
}
}
/// Clears the library in memory immediately and removes every rig file on the background queue.
///
/// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are
/// logged on the background queue.
public func eraseAll() throws {
entries.removeAll()
let directory: URL = self.directory
let coordinated: Bool = isICloud
ioQueue.async {
for url: URL in RigLibraryStore.rigFileURLs(in: directory) {
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") }
}
}
}
/// Blocks until all queued background writes/deletes have completed.
///
/// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure
/// the last save reaches disk before exit). Avoid calling on the main thread during normal use —
/// that would reintroduce the very stall this design removes.
public func flushPendingWrites() {
ioQueue.sync { }
}
/// 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.
///
/// Retained for callers and tests that want the bare archive bytes. The user-facing
/// export/share path uses ``exportDocumentData()``, which wraps the same rigs in a
/// ``ShoeGazeDocument`` envelope (the `.shoegaze` file type).
///
/// - Returns: Pretty-printed archive bytes.
/// - Throws: `JSONEncoder` errors.
public func exportArchiveData() throws -> Data {
let archive: RigArchive = RigArchive(rigs: entries)
return try RigLibraryStore.makeEncoder().encode(archive)
}
/// Encodes the entire library as a ``ShoeGazeDocument`` for export to a `.shoegaze` file.
///
/// This is the format written by the library's **Export** action and shared via the system
/// share sheet. ``importArchive(from:)`` reads it back, and also still accepts the bare
/// ``RigArchive`` and legacy single-rig shapes.
///
/// - Returns: Pretty-printed `.shoegaze` document bytes.
/// - Throws: `JSONEncoder` errors.
public func exportDocumentData() throws -> Data {
try ShoeGazeDocument(rigs: entries).data()
}
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
/// added.
///
/// Accepts a ``ShoeGazeDocument`` (the `.shoegaze` file type), a bare ``RigArchive`` (the prior
/// multi-rig export), or a legacy single-rig file (a bare ``ShoeGazeState``), which is imported
/// as one entry named `legacyRigName`. A document carrying a board rather than rigs contributes
/// no entries. 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 nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
var loaded: [RigEntry] = []
let decoder: JSONDecoder = makeDecoder()
for url: URL in rigFileURLs(in: directory) {
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
loaded.append(entry)
}
return 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,
RigLibraryStore.isInLibrary(url, directory: directory) else { continue }
let status: String? =
item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent {
try? fileManager.startDownloadingUbiquitousItem(at: url)
}
}
// Re-read off the main thread; the in-memory list republishes when it completes.
Task { await self.reload() }
}
// 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. `static` so the
/// background I/O queue can call it without touching actor state.
private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? {
let suffix: String = "-\(id.uuidString).\(fileExtension)"
return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) }
}
/// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded).
private nonisolated static func rigFileURLs(in directory: URL) -> [URL] {
let contents: [URL] = (try? FileManager.default.contentsOfDirectory(
at: directory,
includingPropertiesForKeys: nil,
options: .skipsHiddenFiles
)) ?? []
return contents.filter { $0.pathExtension == fileExtension }
}
/// Whether `url` is a rig file directly inside `directory`.
private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool {
url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL
&& url.pathExtension == fileExtension
}
// MARK: - Coordinated I/O (background-queue safe)
/// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed.
private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws {
guard coordinated else {
try data.write(to: url, options: .atomic)
return
}
try coordinateWriting(url, options: .forReplacing) { target in
try data.write(to: target, options: .atomic)
}
}
/// Reads the contents of `url`, coordinating the read when iCloud-backed.
private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data {
guard coordinated else {
return try Data(contentsOf: url)
}
var result: Data = Data()
try coordinateReading(url, options: .withoutChanges) { target in
result = try Data(contentsOf: target)
}
return result
}
/// Removes `url`, coordinating the delete when iCloud-backed.
private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws {
guard coordinated else {
try FileManager.default.removeItem(at: url)
return
}
try coordinateWriting(url, options: .forDeleting) { target in
try FileManager.default.removeItem(at: target)
}
}
/// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error
/// and any error thrown by `body`.
private nonisolated static func coordinateWriting(
_ 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 }
}
/// Runs `body` inside an `NSFileCoordinator` read block.
private nonisolated static func coordinateReading(
_ 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 RigLibraryStore.makeEncoder().encode(entry)
}
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
private nonisolated static func makeEncoder() -> JSONEncoder {
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
encoder.dateEncodingStrategy = .secondsSince1970
return encoder
}
/// A JSON decoder matching ``makeEncoder()``.
private nonisolated static func makeDecoder() -> JSONDecoder {
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
return decoder
}
/// Decodes import bytes into rig entries, accepting the `.shoegaze` ``ShoeGazeDocument``
/// envelope plus the bare ``RigArchive`` and legacy ``ShoeGazeState`` shapes (see
/// ``ShoeGazeDocument/decoded(from:legacyRigName:)``). A board-carrying document yields no rigs.
private func decodeImportable(
_ data: Data,
legacyRigName: String
) throws -> [RigEntry] {
let document: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data, legacyRigName: legacyRigName)
return document.rigEntries ?? []
}
// 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
}
}
}