Make rig library loads/resolve fully off-main
Move the remaining synchronous main-thread I/O off the main actor: - RigLibraryStore now constructs instantly with a local placeholder and exposes an awaitable async start(): it resolves the iCloud-or-local location off-main (the blocking ubiquity lookup), loads entries off-main via the shared ioQueue (so a reload can't drop a just-saved rig), then sets isLoaded. reload() is async; iCloud metadata updates re-read via it. - Seeding moves into RigLibraryBootstrap.start(_:seedFrom:), which seeds a "Default" rig only AFTER the (possibly iCloud) library has loaded and is still empty — preventing a duplicate "Default" on every synced device on first launch. - Sidebar shows a Loading state until isLoaded; the builder restores the persisted current-rig highlight when isLoaded flips true (initialRigID param dropped). - Shells construct the store synchronously and start it asynchronously (macOS via Task in didFinishLaunching; iOS via .task). Codec + file helpers are nonisolated static so background work needs no actor hop. - Tests await store.start(). Full suite: 206 passing. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -55,9 +55,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
private let shoeGaze: ShoeGaze
|
private let shoeGaze: ShoeGaze
|
||||||
private let window: LyrebirdWindow
|
private let window: LyrebirdWindow
|
||||||
|
|
||||||
/// The rig library and the entry to highlight at launch; built in `init`.
|
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
|
||||||
private let library: RigLibraryStore
|
private let library: RigLibraryStore
|
||||||
private let initialRigID: UUID?
|
|
||||||
|
|
||||||
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
|
/// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state.
|
||||||
private var recordMenuItem: NSMenuItem?
|
private var recordMenuItem: NSMenuItem?
|
||||||
@@ -88,14 +87,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
)
|
)
|
||||||
|
|
||||||
// Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or
|
// Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or
|
||||||
// seed a board), then bootstrap the rig library from it — all operating on `shoeGaze`, not
|
// seed a board) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super).
|
||||||
// on `self` methods (which aren't available pre-`super.init`).
|
|
||||||
if !RigStore.restore(into: shoeGaze) {
|
if !RigStore.restore(into: shoeGaze) {
|
||||||
AppDelegate.seedInitialBoard(into: shoeGaze)
|
AppDelegate.seedInitialBoard(into: shoeGaze)
|
||||||
}
|
}
|
||||||
let bootstrap: RigLibraryBootstrap.Result = RigLibraryBootstrap.make(for: shoeGaze)
|
// The library constructs instantly; it resolves iCloud + loads asynchronously after launch.
|
||||||
self.library = bootstrap.store
|
self.library = RigLibraryBootstrap.makeStore()
|
||||||
self.initialRigID = bootstrap.initialRigID
|
|
||||||
|
|
||||||
super.init()
|
super.init()
|
||||||
}
|
}
|
||||||
@@ -120,16 +117,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
|||||||
let session: ShoeGaze = shoeGaze
|
let session: ShoeGaze = shoeGaze
|
||||||
let driver: CoreAudioDriver = coreDriver
|
let driver: CoreAudioDriver = coreDriver
|
||||||
let rigLibrary: RigLibraryStore = library
|
let rigLibrary: RigLibraryStore = library
|
||||||
let startupRigID: UUID? = initialRigID
|
|
||||||
window.open {
|
window.open {
|
||||||
ShoeGazeBuilderView(
|
ShoeGazeBuilderView(
|
||||||
shoeGaze: session,
|
shoeGaze: session,
|
||||||
library: rigLibrary,
|
library: rigLibrary,
|
||||||
initialRigID: startupRigID,
|
|
||||||
hardwareSampleRate: { driver.deviceSampleRate }
|
hardwareSampleRate: { driver.deviceSampleRate }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
anchorWindowLeft()
|
anchorWindowLeft()
|
||||||
|
|
||||||
|
// Resolve iCloud + load the library off the main thread, then seed from the working rig if
|
||||||
|
// it is still empty (first run).
|
||||||
|
let rigSession: ShoeGaze = shoeGaze
|
||||||
|
Task { await RigLibraryBootstrap.start(rigLibrary, seedFrom: rigSession) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to
|
/// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to
|
||||||
|
|||||||
@@ -27,12 +27,12 @@ struct ShoeGazeBuilderiOSApp: App {
|
|||||||
ShoeGazeBuilderView(
|
ShoeGazeBuilderView(
|
||||||
shoeGaze: model.shoeGaze,
|
shoeGaze: model.shoeGaze,
|
||||||
library: model.library,
|
library: model.library,
|
||||||
initialRigID: model.initialRigID,
|
|
||||||
hardwareSampleRate: { model.hardwareSampleRate },
|
hardwareSampleRate: { model.hardwareSampleRate },
|
||||||
onEnableLiveInput: { model.enableLiveInput() }
|
onEnableLiveInput: { model.enableLiveInput() }
|
||||||
)
|
)
|
||||||
.navigationTitle("ShoeGaze Builder")
|
.navigationTitle("ShoeGaze Builder")
|
||||||
.navigationBarTitleDisplayMode(.inline)
|
.navigationBarTitleDisplayMode(.inline)
|
||||||
|
.task { await model.startLibrary() }
|
||||||
}
|
}
|
||||||
.onDisappear { model.stop() }
|
.onDisappear { model.stop() }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,14 +56,10 @@ final class ShoeGazeBuilderiOSAppModel {
|
|||||||
/// The sample rate the audio session actually committed to (for the config mismatch warning).
|
/// The sample rate the audio session actually committed to (for the config mismatch warning).
|
||||||
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
|
var hardwareSampleRate: Double? { iosDriver.sessionSampleRate }
|
||||||
|
|
||||||
/// The library entry to highlight as current on this launch (and after an engine rebuild),
|
/// Resolves iCloud + loads the library off the main thread, then seeds it from the working rig
|
||||||
/// resolved live from the persisted id so a mid-session selection survives a rebuild.
|
/// on first run. Call once from the app's `.task`. Safe to call again (no-op once non-empty).
|
||||||
var initialRigID: UUID? {
|
func startLibrary() async {
|
||||||
guard let stored: String = UserDefaults.standard.string(
|
await RigLibraryBootstrap.start(library, seedFrom: shoeGaze)
|
||||||
forKey: ShoeGazeBuilderView.currentRigDefaultsKey),
|
|
||||||
let id: UUID = UUID(uuidString: stored),
|
|
||||||
library.entries.contains(where: { $0.id == id }) else { return nil }
|
|
||||||
return id
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Init
|
// MARK: - Init
|
||||||
@@ -84,8 +80,9 @@ final class ShoeGazeBuilderiOSAppModel {
|
|||||||
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
|
ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bootstrap the rig library (iCloud-or-local), seeding it from the working rig on first run.
|
// Construct the library instantly; it resolves iCloud + loads asynchronously via
|
||||||
self.library = RigLibraryBootstrap.make(for: shoeGaze).store
|
// startLibrary() from the app's .task.
|
||||||
|
self.library = RigLibraryBootstrap.makeStore()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Persists the current rig. Call when the app moves to the background.
|
/// Persists the current rig. Call when the app moves to the background.
|
||||||
|
|||||||
@@ -47,11 +47,17 @@ public final class RigLibraryStore {
|
|||||||
public private(set) var entries: [RigEntry] = []
|
public private(set) var entries: [RigEntry] = []
|
||||||
|
|
||||||
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
|
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
|
||||||
/// local-only fallback.
|
/// local-only fallback. Resolved during ``start()`` for an auto-resolving store.
|
||||||
public let isICloud: Bool
|
public private(set) var isICloud: Bool
|
||||||
|
|
||||||
/// The directory holding the per-rig JSON files.
|
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
|
||||||
public let directory: URL
|
/// ``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
|
// MARK: - Private
|
||||||
|
|
||||||
@@ -71,10 +77,14 @@ public final class RigLibraryStore {
|
|||||||
/// File extension of a stored rig.
|
/// File extension of a stored rig.
|
||||||
private nonisolated static let fileExtension: String = "json"
|
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
|
// MARK: - Init
|
||||||
|
|
||||||
/// Creates a store rooted at an explicit directory. Designated initializer; used directly by
|
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
|
||||||
/// tests with a temporary directory and `isICloud: false`.
|
/// directory; `start()` will not re-resolve the location.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
|
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
|
||||||
@@ -86,25 +96,60 @@ public final class RigLibraryStore {
|
|||||||
) {
|
) {
|
||||||
self.directory = directory
|
self.directory = directory
|
||||||
self.isICloud = isICloud
|
self.isICloud = isICloud
|
||||||
|
self.autoResolve = false
|
||||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a store from a resolved ``RigLibraryLocation``.
|
/// 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.
|
||||||
/// - Parameter resolved: The directory + iCloud flag from `RigLibraryLocation.resolve()`.
|
public init() {
|
||||||
public convenience init(resolved: RigLibraryLocation.Resolved) {
|
self.directory = RigLibraryLocation.localDirectory()
|
||||||
self.init(directory: resolved.directory, isICloud: resolved.isICloud)
|
self.isICloud = false
|
||||||
|
self.autoResolve = true
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Lifecycle
|
// MARK: - Lifecycle
|
||||||
|
|
||||||
/// Loads the current library contents and, when iCloud-backed, begins watching for remote
|
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
|
||||||
/// changes. Safe to call once after construction.
|
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
|
||||||
public func start() {
|
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
|
||||||
reloadFromDirectory()
|
/// 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 {
|
if isICloud {
|
||||||
startMetadataQuery()
|
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;
|
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
|
||||||
@@ -239,7 +284,7 @@ public final class RigLibraryStore {
|
|||||||
/// - Throws: `JSONEncoder` errors.
|
/// - Throws: `JSONEncoder` errors.
|
||||||
public func exportArchiveData() throws -> Data {
|
public func exportArchiveData() throws -> Data {
|
||||||
let archive: RigArchive = RigArchive(rigs: entries)
|
let archive: RigArchive = RigArchive(rigs: entries)
|
||||||
return try makeEncoder().encode(archive)
|
return try RigLibraryStore.makeEncoder().encode(archive)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
|
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
|
||||||
@@ -281,17 +326,15 @@ public final class RigLibraryStore {
|
|||||||
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
|
/// 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
|
/// 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.
|
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
|
||||||
private func reloadFromDirectory() {
|
private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
|
||||||
var loaded: [RigEntry] = []
|
var loaded: [RigEntry] = []
|
||||||
let decoder: JSONDecoder = makeDecoder()
|
let decoder: JSONDecoder = makeDecoder()
|
||||||
for url: URL in RigLibraryStore.rigFileURLs(in: directory) {
|
for url: URL in rigFileURLs(in: directory) {
|
||||||
guard let data: Data = try? RigLibraryStore.readData(at: url, coordinated: isICloud) else {
|
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
|
||||||
continue
|
|
||||||
}
|
|
||||||
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
|
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
|
||||||
loaded.append(entry)
|
loaded.append(entry)
|
||||||
}
|
}
|
||||||
entries = RigLibraryStore.sorted(loaded)
|
return loaded
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - iCloud metadata query
|
// MARK: - iCloud metadata query
|
||||||
@@ -341,7 +384,8 @@ public final class RigLibraryStore {
|
|||||||
try? fileManager.startDownloadingUbiquitousItem(at: url)
|
try? fileManager.startDownloadingUbiquitousItem(at: url)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
reloadFromDirectory()
|
// Re-read off the main thread; the in-memory list republishes when it completes.
|
||||||
|
Task { await self.reload() }
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - File helpers
|
// MARK: - File helpers
|
||||||
@@ -450,11 +494,11 @@ public final class RigLibraryStore {
|
|||||||
|
|
||||||
/// Encodes a single entry as a per-rig file would store it.
|
/// Encodes a single entry as a per-rig file would store it.
|
||||||
private func encode(_ entry: RigEntry) throws -> Data {
|
private func encode(_ entry: RigEntry) throws -> Data {
|
||||||
try makeEncoder().encode(entry)
|
try RigLibraryStore.makeEncoder().encode(entry)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
|
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
|
||||||
private func makeEncoder() -> JSONEncoder {
|
private nonisolated static func makeEncoder() -> JSONEncoder {
|
||||||
let encoder: JSONEncoder = JSONEncoder()
|
let encoder: JSONEncoder = JSONEncoder()
|
||||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||||
encoder.dateEncodingStrategy = .secondsSince1970
|
encoder.dateEncodingStrategy = .secondsSince1970
|
||||||
@@ -462,7 +506,7 @@ public final class RigLibraryStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A JSON decoder matching ``makeEncoder()``.
|
/// A JSON decoder matching ``makeEncoder()``.
|
||||||
private func makeDecoder() -> JSONDecoder {
|
private nonisolated static func makeDecoder() -> JSONDecoder {
|
||||||
let decoder: JSONDecoder = JSONDecoder()
|
let decoder: JSONDecoder = JSONDecoder()
|
||||||
decoder.dateDecodingStrategy = .secondsSince1970
|
decoder.dateDecodingStrategy = .secondsSince1970
|
||||||
return decoder
|
return decoder
|
||||||
@@ -474,7 +518,7 @@ public final class RigLibraryStore {
|
|||||||
_ data: Data,
|
_ data: Data,
|
||||||
legacyRigName: String
|
legacyRigName: String
|
||||||
) throws -> [RigEntry] {
|
) throws -> [RigEntry] {
|
||||||
let decoder: JSONDecoder = makeDecoder()
|
let decoder: JSONDecoder = RigLibraryStore.makeDecoder()
|
||||||
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
|
if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) {
|
||||||
return archive.rigs
|
return archive.rigs
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,61 +7,48 @@
|
|||||||
import Foundation
|
import Foundation
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
|
||||||
/// One-call setup of the rig library for an app shell.
|
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
|
||||||
///
|
///
|
||||||
/// Resolves the (iCloud-or-local) library location, constructs and starts a ``RigLibraryStore``,
|
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
|
||||||
/// seeds it with the current working rig the first time it is empty (so the listing is never blank
|
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
|
||||||
/// and the user's existing setup becomes their first saved rig), and reports which entry should be
|
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
|
||||||
/// highlighted as the current rig on this launch.
|
/// library from the current working rig **only after** the real (possibly iCloud) contents are
|
||||||
|
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
|
||||||
@MainActor
|
@MainActor
|
||||||
public enum RigLibraryBootstrap {
|
public enum RigLibraryBootstrap {
|
||||||
|
|
||||||
/// The result of bootstrapping: a started store and the rig to highlight at launch.
|
/// Creates an auto-resolving store. Construct this synchronously at launch; call
|
||||||
public struct Result {
|
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
|
||||||
public let store: RigLibraryStore
|
public static func makeStore() -> RigLibraryStore {
|
||||||
public let initialRigID: UUID?
|
RigLibraryStore()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds and starts the rig library for `shoeGaze`.
|
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
|
||||||
///
|
/// empty after loading (first run). Idempotent enough to call once at launch.
|
||||||
/// - Important: Resolving the iCloud container performs blocking I/O. Call this once at app
|
|
||||||
/// startup; it is acceptable there but should not be called repeatedly.
|
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
|
/// - store: The store from ``makeStore()``.
|
||||||
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
|
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
|
||||||
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
|
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
|
||||||
/// - Returns: The started store and the entry id to seed the builder's current-rig highlight.
|
public static func start(
|
||||||
public static func make(
|
_ store: RigLibraryStore,
|
||||||
for shoeGaze: ShoeGaze,
|
seedFrom shoeGaze: ShoeGaze,
|
||||||
seedName: String = "Default"
|
seedName: String = "Default"
|
||||||
) -> Result {
|
) async {
|
||||||
let resolved: RigLibraryLocation.Resolved = RigLibraryLocation.resolve()
|
await store.start()
|
||||||
let store: RigLibraryStore = RigLibraryStore(resolved: resolved)
|
|
||||||
store.start()
|
|
||||||
|
|
||||||
let defaults: UserDefaults = UserDefaults.standard
|
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
|
||||||
let key: String = ShoeGazeBuilderView.currentRigDefaultsKey
|
// genuine first run, not a not-yet-synced one.
|
||||||
|
guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return }
|
||||||
// First run with an empty library: capture the current working rig as the first entry and
|
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
|
||||||
// remember it as current.
|
do {
|
||||||
if store.entries.isEmpty, !shoeGaze.boards.isEmpty {
|
try store.save(entry)
|
||||||
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
|
UserDefaults.standard.set(
|
||||||
do {
|
entry.id.uuidString,
|
||||||
try store.save(entry)
|
forKey: ShoeGazeBuilderView.currentRigDefaultsKey
|
||||||
defaults.set(entry.id.uuidString, forKey: key)
|
)
|
||||||
} catch {
|
} catch {
|
||||||
print("[RigLibraryBootstrap] seeding library failed: \(error)")
|
print("[RigLibraryBootstrap] seeding library failed: \(error)")
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Resolve the highlight only if the remembered id still exists in the library.
|
|
||||||
let initial: UUID? = {
|
|
||||||
guard let stored: String = defaults.string(forKey: key),
|
|
||||||
let id: UUID = UUID(uuidString: stored),
|
|
||||||
store.entries.contains(where: { $0.id == id }) else { return nil }
|
|
||||||
return id
|
|
||||||
}()
|
|
||||||
|
|
||||||
return Result(store: store, initialRigID: initial)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,7 +84,15 @@ struct RigLibrarySidebarView: View {
|
|||||||
private var rigList: some View {
|
private var rigList: some View {
|
||||||
ScrollView(.vertical, showsIndicators: true) {
|
ScrollView(.vertical, showsIndicators: true) {
|
||||||
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||||
if store.entries.isEmpty {
|
if !store.isLoaded {
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
ProgressView().controlSize(.small)
|
||||||
|
Text("Loading…")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||||
|
}
|
||||||
|
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||||
|
} else if store.entries.isEmpty {
|
||||||
Text("No saved rigs yet.\nTap New or Save to add one.")
|
Text("No saved rigs yet.\nTap New or Save to add one.")
|
||||||
.font(.caption)
|
.font(.caption)
|
||||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||||
|
|||||||
@@ -68,7 +68,6 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
|
|
||||||
private let shoeGaze: ShoeGaze
|
private let shoeGaze: ShoeGaze
|
||||||
private let library: RigLibraryStore
|
private let library: RigLibraryStore
|
||||||
private let initialRigID: UUID?
|
|
||||||
private let hardwareSampleRate: () -> Double?
|
private let hardwareSampleRate: () -> Double?
|
||||||
|
|
||||||
/// Host hook to enable live input when the current engine has no input channel (iOS).
|
/// Host hook to enable live input when the current engine has no input channel (iOS).
|
||||||
@@ -143,20 +142,17 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
/// engine with one input channel (preserving the rig), and select live input. Defaults to
|
/// engine with one input channel (preserving the rig), and select live input. Defaults to
|
||||||
/// `nil` — on macOS the engine already has an input channel, so live input is selected
|
/// `nil` — on macOS the engine already has an input channel, so live input is selected
|
||||||
/// directly without a rebuild.
|
/// directly without a rebuild.
|
||||||
/// - library: The rig library store, already `start()`ed by the host. Backs the left-hand
|
/// - library: The rig library store. The host should `start()` it (e.g. via
|
||||||
/// rig listing and all save / load / archive actions.
|
/// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the
|
||||||
/// - initialRigID: The library entry the host restored into `shoeGaze` at launch, if any, so
|
/// persisted current rig once the library has loaded.
|
||||||
/// the sidebar can highlight it as the current rig. Defaults to `nil`.
|
|
||||||
public init(
|
public init(
|
||||||
shoeGaze: ShoeGaze,
|
shoeGaze: ShoeGaze,
|
||||||
library: RigLibraryStore,
|
library: RigLibraryStore,
|
||||||
initialRigID: UUID? = nil,
|
|
||||||
hardwareSampleRate: @escaping () -> Double? = { nil },
|
hardwareSampleRate: @escaping () -> Double? = { nil },
|
||||||
onEnableLiveInput: (() -> Void)? = nil
|
onEnableLiveInput: (() -> Void)? = nil
|
||||||
) {
|
) {
|
||||||
self.shoeGaze = shoeGaze
|
self.shoeGaze = shoeGaze
|
||||||
self.library = library
|
self.library = library
|
||||||
self.initialRigID = initialRigID
|
|
||||||
self.hardwareSampleRate = hardwareSampleRate
|
self.hardwareSampleRate = hardwareSampleRate
|
||||||
self.onEnableLiveInput = onEnableLiveInput
|
self.onEnableLiveInput = onEnableLiveInput
|
||||||
}
|
}
|
||||||
@@ -186,6 +182,7 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
restoreInputSelection()
|
restoreInputSelection()
|
||||||
restoreCurrentRig()
|
restoreCurrentRig()
|
||||||
}
|
}
|
||||||
|
.onChange(of: library.isLoaded) { restoreCurrentRig() }
|
||||||
.onChange(of: currentRigID) { persistCurrentRigID() }
|
.onChange(of: currentRigID) { persistCurrentRigID() }
|
||||||
.background(boardsSheetAnchor)
|
.background(boardsSheetAnchor)
|
||||||
.background(rigExportAnchor)
|
.background(rigExportAnchor)
|
||||||
@@ -695,11 +692,17 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
|
|
||||||
// MARK: - Rig library
|
// MARK: - Rig library
|
||||||
|
|
||||||
/// Seeds `currentRigID` from the entry the host restored at launch, once.
|
/// Highlights the persisted current rig once the library has loaded. Runs once; only sets the
|
||||||
|
/// highlight when nothing is selected yet and the saved id still exists in the library.
|
||||||
private func restoreCurrentRig() {
|
private func restoreCurrentRig() {
|
||||||
guard !didRestoreRig else { return }
|
guard !didRestoreRig, library.isLoaded else { return }
|
||||||
didRestoreRig = true
|
didRestoreRig = true
|
||||||
currentRigID = initialRigID
|
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.
|
/// Persists `currentRigID` so the same rig is highlighted on the next launch.
|
||||||
|
|||||||
@@ -19,10 +19,10 @@ struct RigLibraryStoreTests {
|
|||||||
return url
|
return url
|
||||||
}
|
}
|
||||||
|
|
||||||
private func makeStore() -> (RigLibraryStore, URL) {
|
private func makeStore() async -> (RigLibraryStore, URL) {
|
||||||
let dir: URL = makeTempDirectory()
|
let dir: URL = makeTempDirectory()
|
||||||
let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||||
store.start()
|
await store.start()
|
||||||
return (store, dir)
|
return (store, dir)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,8 +30,8 @@ struct RigLibraryStoreTests {
|
|||||||
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
|
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func saveAddsEntryAndReloadsAcrossInstances() throws {
|
@Test func saveAddsEntryAndReloadsAcrossInstances() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
try store.save(makeEntry("Ambient"))
|
try store.save(makeEntry("Ambient"))
|
||||||
@@ -43,13 +43,13 @@ struct RigLibraryStoreTests {
|
|||||||
store.flushPendingWrites()
|
store.flushPendingWrites()
|
||||||
// A fresh store over the same directory sees the persisted files.
|
// A fresh store over the same directory sees the persisted files.
|
||||||
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||||
reopened.start()
|
await reopened.start()
|
||||||
#expect(reopened.entries.count == 2)
|
#expect(reopened.entries.count == 2)
|
||||||
#expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"])
|
#expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func saveSameIdReplacesInPlace() throws {
|
@Test func saveSameIdReplacesInPlace() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
let entry: RigEntry = makeEntry("Original")
|
let entry: RigEntry = makeEntry("Original")
|
||||||
@@ -67,8 +67,8 @@ struct RigLibraryStoreTests {
|
|||||||
#expect(files.count == 1, "rename must not leave the old-name file behind")
|
#expect(files.count == 1, "rename must not leave the old-name file behind")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func renameKeepsIdChangesName() throws {
|
@Test func renameKeepsIdChangesName() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
let entry: RigEntry = makeEntry("Before")
|
let entry: RigEntry = makeEntry("Before")
|
||||||
@@ -79,8 +79,8 @@ struct RigLibraryStoreTests {
|
|||||||
store.flushPendingWrites()
|
store.flushPendingWrites()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func duplicateCreatesIndependentEntry() throws {
|
@Test func duplicateCreatesIndependentEntry() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
let entry: RigEntry = makeEntry("Base")
|
let entry: RigEntry = makeEntry("Base")
|
||||||
@@ -91,8 +91,8 @@ struct RigLibraryStoreTests {
|
|||||||
store.flushPendingWrites()
|
store.flushPendingWrites()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func deleteRemovesFileAndEntry() throws {
|
@Test func deleteRemovesFileAndEntry() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
let entry: RigEntry = makeEntry("Doomed")
|
let entry: RigEntry = makeEntry("Doomed")
|
||||||
@@ -107,8 +107,8 @@ struct RigLibraryStoreTests {
|
|||||||
#expect(files.isEmpty)
|
#expect(files.isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func eraseAllClearsLibrary() throws {
|
@Test func eraseAllClearsLibrary() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
try store.save(makeEntry("A"))
|
try store.save(makeEntry("A"))
|
||||||
@@ -119,12 +119,12 @@ struct RigLibraryStoreTests {
|
|||||||
|
|
||||||
store.flushPendingWrites()
|
store.flushPendingWrites()
|
||||||
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||||
reopened.start()
|
await reopened.start()
|
||||||
#expect(reopened.entries.isEmpty)
|
#expect(reopened.entries.isEmpty)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func exportThenImportRoundTrips() throws {
|
@Test func exportThenImportRoundTrips() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
try store.save(makeEntry("One"))
|
try store.save(makeEntry("One"))
|
||||||
@@ -132,7 +132,7 @@ struct RigLibraryStoreTests {
|
|||||||
let archiveData: Data = try store.exportArchiveData()
|
let archiveData: Data = try store.exportArchiveData()
|
||||||
|
|
||||||
// Import into a fresh, empty store.
|
// Import into a fresh, empty store.
|
||||||
let (other, otherDir): (RigLibraryStore, URL) = makeStore()
|
let (other, otherDir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: otherDir) }
|
defer { try? FileManager.default.removeItem(at: otherDir) }
|
||||||
let added: Int = try other.importArchive(from: archiveData)
|
let added: Int = try other.importArchive(from: archiveData)
|
||||||
#expect(added == 2)
|
#expect(added == 2)
|
||||||
@@ -141,8 +141,8 @@ struct RigLibraryStoreTests {
|
|||||||
other.flushPendingWrites()
|
other.flushPendingWrites()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func importColludingIdGetsFreshId() throws {
|
@Test func importColludingIdGetsFreshId() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
let entry: RigEntry = makeEntry("Shared")
|
let entry: RigEntry = makeEntry("Shared")
|
||||||
@@ -157,8 +157,8 @@ struct RigLibraryStoreTests {
|
|||||||
store.flushPendingWrites()
|
store.flushPendingWrites()
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func importLegacySingleRigFile() throws {
|
@Test func importLegacySingleRigFile() async throws {
|
||||||
let (store, dir): (RigLibraryStore, URL) = makeStore()
|
let (store, dir): (RigLibraryStore, URL) = await makeStore()
|
||||||
defer { try? FileManager.default.removeItem(at: dir) }
|
defer { try? FileManager.default.removeItem(at: dir) }
|
||||||
|
|
||||||
// A legacy file is a bare ShoeGazeState (no `rigs` array).
|
// A legacy file is a bare ShoeGazeState (no `rigs` array).
|
||||||
|
|||||||
@@ -60,16 +60,19 @@ still works; the sidebar shows the `icloud.slash` glyph.
|
|||||||
|
|
||||||
### Known limitations / deferred (from pre-PR review)
|
### Known limitations / deferred (from pre-PR review)
|
||||||
|
|
||||||
- **Background writes.** Save/delete/erase update the in-memory `entries` on the main actor
|
- **Off-main I/O end to end.** Save/delete/erase update the in-memory `entries` on the main actor
|
||||||
instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a
|
instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a
|
||||||
serial background queue (`ioQueue`). `flushPendingWrites()` drains it (used by tests and at app
|
serial background queue (`ioQueue`). Location resolution (`RigLibraryLocation.resolve()`, the
|
||||||
termination / iOS background). This removed the save-time UI stall.
|
blocking ubiquity lookup) and the initial/refresh *reads* now also run off the main thread:
|
||||||
- **Remaining main-thread I/O.** `RigLibraryLocation.resolve()` still does a blocking ubiquity
|
`RigLibraryStore` constructs instantly with a local placeholder, and `await start()` resolves the
|
||||||
lookup (short-circuited to local when no iCloud account is signed in), and the *reads* in
|
real iCloud-or-local location, loads via `ioQueue`, then sets `isLoaded`. Reads share `ioQueue`
|
||||||
`reloadFromDirectory()` (launch + iCloud metadata updates) are still synchronous on the main
|
with writes, so a reload never drops a just-saved rig. `flushPendingWrites()` drains the queue
|
||||||
actor. A full fix needs an async resolve + a loading state in the builder, and must move seeding
|
(tests, app termination / iOS background).
|
||||||
*after* the iCloud state is known — otherwise a first-launch seed races the synced library and
|
- **Loading + correct first-run seeding.** The sidebar shows a "Loading…" state until `isLoaded`.
|
||||||
creates a spurious "Default" rig on every device. Deferred deliberately.
|
`RigLibraryBootstrap.start(_:seedFrom:)` seeds the working rig as "Default" **only after** the
|
||||||
|
(possibly iCloud) library has loaded and is still empty — so a first launch on a device that
|
||||||
|
already has synced rigs does not create a duplicate "Default" everywhere. The builder restores the
|
||||||
|
persisted current-rig highlight once `isLoaded` flips true.
|
||||||
- **`eraseAll()`** clears the in-memory list even if a file deletion fails (it still throws the
|
- **`eraseAll()`** clears the in-memory list even if a file deletion fails (it still throws the
|
||||||
first error). A re-`start()` re-scans and re-surfaces any undeleted rigs, so state self-heals.
|
first error). A re-`start()` re-scans and re-surfaces any undeleted rigs, so state self-heals.
|
||||||
- Possible later work: conflict UI for simultaneous multi-device edits; the async-resolve redesign
|
- Possible later work: conflict UI for simultaneous multi-device edits; the async-resolve redesign
|
||||||
|
|||||||
Reference in New Issue
Block a user