From dc42db0c594395781bce3b047c7e37240bb34fb2 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 17:56:10 -0700 Subject: [PATCH] Add iCloud-synced rig library 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 --- .../ShoeGazeBuilder.xcodeproj/project.pbxproj | 8 +- Demo/ShoeGazeBuilder/AppDelegate.swift | 67 ++- Demo/ShoeGazeBuilder/Info.plist | 12 + .../ShoeGazeBuilder.entitlements | 12 + .../project.pbxproj | 2 + Demo/ShoeGazeBuilderiOS/Info.plist | 12 + .../ShoeGazeBuilderiOS.entitlements | 18 + .../ShoeGazeBuilderiOSApp.swift | 2 + .../ShoeGazeBuilderiOSAppModel.swift | 31 +- README.md | 3 +- .../Presets/BoardVersionStore.swift | 53 +- .../Presets/PresetFilename.swift | 65 +++ .../LyrebirdShoeGaze/Presets/RigArchive.swift | 44 ++ .../LyrebirdShoeGaze/Presets/RigEntry.swift | 98 ++++ .../Presets/RigLibraryLocation.swift | 96 ++++ .../Presets/RigLibraryStore.swift | 475 ++++++++++++++++++ .../Presets/ShoeGaze+Preset.swift | 31 ++ .../RigLibraryBootstrap.swift | 67 +++ .../RigLibrarySidebarView.swift | 159 ++++++ .../LyrebirdShoeGazeUI/RigNamePrompt.swift | 71 +++ .../ShoeGazeBuilderView.swift | 432 ++++++++++++---- .../RigArchiveTests.swift | 43 ++ .../LyrebirdShoeGazeTests/RigEntryTests.swift | 55 ++ .../RigLibraryStoreTests.swift | 162 ++++++ docs/plans/1.2-rig-library.md | 69 +++ 25 files changed, 1895 insertions(+), 192 deletions(-) create mode 100644 Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements create mode 100644 Sources/LyrebirdShoeGaze/Presets/PresetFilename.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/RigArchive.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/RigEntry.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/RigLibraryLocation.swift create mode 100644 Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift create mode 100644 Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift create mode 100644 Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift create mode 100644 Sources/LyrebirdShoeGazeUI/RigNamePrompt.swift create mode 100644 Tests/LyrebirdShoeGazeTests/RigArchiveTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/RigEntryTests.swift create mode 100644 Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift create mode 100644 docs/plans/1.2-rig-library.md diff --git a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj index 9808f45..1ed3449 100644 --- a/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilder.xcodeproj/project.pbxproj @@ -163,7 +163,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 4; DEAD_CODE_STRIPPING = YES; DEBUG_INFORMATION_FORMAT = dwarf; DEVELOPMENT_TEAM = HE5VJFE9E4; @@ -176,7 +176,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.0; - MARKETING_VERSION = 1.0; + MARKETING_VERSION = 1.1.1; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; @@ -194,7 +194,7 @@ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 3; + CURRENT_PROJECT_VERSION = 4; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = HE5VJFE9E4; ENABLE_HARDENED_RUNTIME = YES; @@ -206,7 +206,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.0; - MARKETING_VERSION = 1.0; + MARKETING_VERSION = 1.1.1; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder; PRODUCT_NAME = "$(TARGET_NAME)"; SWIFT_EMIT_LOC_STRINGS = YES; diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index 05001f1..b8ec574 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -55,11 +55,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate { private let shoeGaze: ShoeGaze private let window: LyrebirdWindow + /// The rig library and the entry to highlight at launch; built in `init`. + private let library: RigLibraryStore + private let initialRigID: UUID? + /// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state. private var recordMenuItem: NSMenuItem? - /// Default file name offered by the Save panel. - private static let defaultRigFileName: String = "ShoeGazeRig" + /// Default file name offered by the archive Export panel. + private static let defaultArchiveFileName: String = "ShoeGaze Library" // MARK: - Init @@ -73,24 +77,31 @@ final class AppDelegate: NSObject, NSApplicationDelegate { numAudioBuses: AppDelegate.numAudioBuses, driver: coreDriver ) + let shoeGaze: ShoeGaze = ShoeGaze(engine: engine) self.coreDriver = coreDriver self.engine = engine - self.shoeGaze = ShoeGaze(engine: engine) + self.shoeGaze = shoeGaze self.window = LyrebirdWindow( title: "ShoeGaze Builder — Lyrebird Pedalboard", width: AppDelegate.windowWidth, height: AppDelegate.windowHeight ) - super.init() - // Restore the autosaved rig if there is one; otherwise seed a default board. + // 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 + // on `self` methods (which aren't available pre-`super.init`). if !RigStore.restore(into: shoeGaze) { - seedInitialBoard() + AppDelegate.seedInitialBoard(into: shoeGaze) } + let bootstrap: RigLibraryBootstrap.Result = RigLibraryBootstrap.make(for: shoeGaze) + self.library = bootstrap.store + self.initialRigID = bootstrap.initialRigID + + super.init() } /// Seeds one board with a single pedal so the builder opens with an audible starting point. - private func seedInitialBoard() { + private static func seedInitialBoard(into shoeGaze: ShoeGaze) { var created: PedalBoard? do { let board: PedalBoard = try shoeGaze.addBoard() @@ -108,8 +119,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate { installMainMenu() let session: ShoeGaze = shoeGaze let driver: CoreAudioDriver = coreDriver + let rigLibrary: RigLibraryStore = library + let startupRigID: UUID? = initialRigID window.open { - ShoeGazeBuilderView(shoeGaze: session, hardwareSampleRate: { driver.deviceSampleRate }) + ShoeGazeBuilderView( + shoeGaze: session, + library: rigLibrary, + initialRigID: startupRigID, + hardwareSampleRate: { driver.deviceSampleRate } + ) } anchorWindowLeft() } @@ -180,8 +198,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { mainMenu.addItem(fileMenuItem) let fileMenu: NSMenu = NSMenu(title: "File") fileMenuItem.submenu = fileMenu - addItem(to: fileMenu, title: "Save Rig…", action: #selector(saveRigAction(_:)), key: "s") - addItem(to: fileMenu, title: "Load Rig…", action: #selector(loadRigAction(_:)), key: "o") + // The rig library (saved rigs) lives in the in-window sidebar; the File menu handles the + // whole-library archive: a single file holding every rig, for backup or transfer. + addItem(to: fileMenu, title: "Export Archive…", action: #selector(exportArchiveAction(_:)), key: "e") + addItem(to: fileMenu, title: "Import Archive…", action: #selector(importArchiveAction(_:)), key: "i") // Board menu — add board + transport. let boardMenuItem: NSMenuItem = NSMenuItem() @@ -230,34 +250,33 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Menu actions - @objc private func saveRigAction(_ sender: Any?) { + @objc private func exportArchiveAction(_ sender: Any?) { let panel: NSSavePanel = NSSavePanel() panel.allowedContentTypes = [.json] - panel.nameFieldStringValue = "\(AppDelegate.defaultRigFileName).json" + panel.nameFieldStringValue = "\(AppDelegate.defaultArchiveFileName).json" panel.canCreateDirectories = true - let session: ShoeGaze = shoeGaze + let rigLibrary: RigLibraryStore = library panel.begin { response in guard response == .OK, let url: URL = panel.url else { return } - do { try session.saveRig(to: url) } - catch { print("[ShoeGazeBuilder] saveRig failed: \(error)") } + do { try rigLibrary.exportArchiveData().write(to: url, options: .atomic) } + catch { print("[ShoeGazeBuilder] export archive failed: \(error)") } } } - @objc private func loadRigAction(_ sender: Any?) { + @objc private func importArchiveAction(_ sender: Any?) { let panel: NSOpenPanel = NSOpenPanel() panel.allowedContentTypes = [.json] panel.canChooseDirectories = false panel.allowsMultipleSelection = false - let session: ShoeGaze = shoeGaze - let activeEngine: SynthesisEngine = engine + let rigLibrary: RigLibraryStore = library panel.begin { response in guard response == .OK, let url: URL = panel.url else { return } - // loadRig rebuilds the graph; stop the engine around it and restart if it was running. - let wasRunning: Bool = activeEngine.isRunning - if wasRunning { activeEngine.stop() } - do { try session.loadRig(from: url) } - catch { print("[ShoeGazeBuilder] loadRig failed: \(error)") } - if wasRunning { try? activeEngine.start() } + do { + let data: Data = try Data(contentsOf: url) + _ = try rigLibrary.importArchive(from: data) + } catch { + print("[ShoeGazeBuilder] import archive failed: \(error)") + } } } diff --git a/Demo/ShoeGazeBuilder/Info.plist b/Demo/ShoeGazeBuilder/Info.plist index 40ba3db..a0e3b88 100644 --- a/Demo/ShoeGazeBuilder/Info.plist +++ b/Demo/ShoeGazeBuilder/Info.plist @@ -28,5 +28,17 @@ ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode. NSPrincipalClass NSApplication + NSUbiquitousContainers + + iCloud.net.realizedsound.ShoeGazeData + + NSUbiquitousContainerIsDocumentScopePublic + + NSUbiquitousContainerName + ShoeGaze + NSUbiquitousContainerSupportedFolderLevels + Any + + diff --git a/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements b/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements index b572d9c..1ba0231 100644 --- a/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements +++ b/Demo/ShoeGazeBuilder/ShoeGazeBuilder.entitlements @@ -4,5 +4,17 @@ com.apple.security.device.audio-input + com.apple.developer.icloud-container-identifiers + + iCloud.net.realizedsound.ShoeGazeData + + com.apple.developer.icloud-services + + CloudDocuments + + com.apple.developer.ubiquity-container-identifiers + + iCloud.net.realizedsound.ShoeGazeData + diff --git a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj index 7867140..23e2fea 100644 --- a/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj +++ b/Demo/ShoeGazeBuilderiOS.xcodeproj/project.pbxproj @@ -169,6 +169,7 @@ "$(inherited)", "@executable_path/Frameworks", ); + CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; @@ -194,6 +195,7 @@ "$(inherited)", "@executable_path/Frameworks", ); + CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements; PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS; PRODUCT_NAME = "$(TARGET_NAME)"; SDKROOT = iphoneos; diff --git a/Demo/ShoeGazeBuilderiOS/Info.plist b/Demo/ShoeGazeBuilderiOS/Info.plist index 8f4d222..3abdfe3 100644 --- a/Demo/ShoeGazeBuilderiOS/Info.plist +++ b/Demo/ShoeGazeBuilderiOS/Info.plist @@ -41,5 +41,17 @@ UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight + NSUbiquitousContainers + + iCloud.net.realizedsound.ShoeGazeData + + NSUbiquitousContainerIsDocumentScopePublic + + NSUbiquitousContainerName + ShoeGaze + NSUbiquitousContainerSupportedFolderLevels + Any + + diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements new file mode 100644 index 0000000..b291d84 --- /dev/null +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements @@ -0,0 +1,18 @@ + + + + + com.apple.developer.icloud-container-identifiers + + iCloud.net.realizedsound.ShoeGazeData + + com.apple.developer.icloud-services + + CloudDocuments + + com.apple.developer.ubiquity-container-identifiers + + iCloud.net.realizedsound.ShoeGazeData + + + diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift index 4c7e945..56d635f 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift @@ -26,6 +26,8 @@ struct ShoeGazeBuilderiOSApp: App { NavigationStack { ShoeGazeBuilderView( shoeGaze: model.shoeGaze, + library: model.library, + initialRigID: model.initialRigID, hardwareSampleRate: { model.hardwareSampleRate }, onEnableLiveInput: { model.enableLiveInput() } ) diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index f891582..83fac10 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -8,6 +8,7 @@ import AVFoundation import Observation import LyrebirdSynth import LyrebirdShoeGaze +import LyrebirdShoeGazeUI /// Observable model owning the `SynthesisEngine` and `ShoeGaze` session for the iOS builder. /// @@ -48,23 +49,43 @@ final class ShoeGazeBuilderiOSAppModel { private var engine: SynthesisEngine private var iosDriver: iOSAudioDriver + /// The shared rig library (iCloud-or-local). Independent of the engine, so it survives the + /// live-input engine rebuild. + private(set) var library: RigLibraryStore + /// The sample rate the audio session actually committed to (for the config mismatch warning). var hardwareSampleRate: Double? { iosDriver.sessionSampleRate } + /// The library entry to highlight as current on this launch (and after an engine rebuild), + /// resolved live from the persisted id so a mid-session selection survives a rebuild. + var initialRigID: UUID? { + guard let stored: String = UserDefaults.standard.string( + forKey: ShoeGazeBuilderView.currentRigDefaultsKey), + let id: UUID = UUID(uuidString: stored), + library.entries.contains(where: { $0.id == id }) else { return nil } + return id + } + // MARK: - Init init() { ShoeGazeBuilderiOSAppModel.configureAudioSession() let built: (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) = ShoeGazeBuilderiOSAppModel.buildEngine(inputChannels: ShoeGazeBuilderiOSAppModel.inputChannels) + let shoeGaze: ShoeGaze = built.shoeGaze self.engine = built.engine self.iosDriver = built.driver - self.shoeGaze = built.shoeGaze + self.shoeGaze = shoeGaze - // Restore the autosaved rig if there is one; otherwise seed a default board. + // Restore the autosaved working rig if there is one; otherwise seed a default board. Operate + // on the local `shoeGaze`, not `self.shoeGaze`: self may not be touched until every stored + // property (including `library`) is initialized. if !RigStore.restore(into: shoeGaze) { - seedFallbackBoard() + ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze) } + + // Bootstrap the rig library (iCloud-or-local), seeding it from the working rig on first run. + self.library = RigLibraryBootstrap.make(for: shoeGaze).store } /// Persists the current rig. Call when the app moves to the background. @@ -158,7 +179,7 @@ final class ShoeGazeBuilderiOSAppModel { try shoeGaze.loadRig(from: snapshot) } catch { print("[ShoeGazeBuilderiOS] rig restore after rebuild failed: \(error)") - seedFallbackBoard() + ShoeGazeBuilderiOSAppModel.seedFallbackBoard(into: shoeGaze) } selectLiveInputAndPersist() @@ -180,7 +201,7 @@ final class ShoeGazeBuilderiOSAppModel { } /// Seeds a single default board so the rig is never empty after a failed restore. - private func seedFallbackBoard() { + private static func seedFallbackBoard(into shoeGaze: ShoeGaze) { do { let board: PedalBoard = try shoeGaze.addBoard() board.label = "Board 1" diff --git a/README.md b/README.md index d2a9ee3..4baa589 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,8 @@ signal (no hardware needed) or on live guitar through an audio input. style) or **Blend** any subset, each with its own level and a click-free crossfade. - **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or stereo lanes, and merge back to mono. -- **Save / load rigs** as JSON, on both platforms. +- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across + your devices and both apps via iCloud, with JSON archive import/export for backup. - **Recording** — capture your output to timestamped files. - **Test signal or live input** — a built-in arpeggiated test loop (shared across all boards so they stay phase-locked) or a hardware input channel. diff --git a/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift b/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift index 9db2220..f82c9ee 100644 --- a/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/BoardVersionStore.swift @@ -98,7 +98,7 @@ public final class BoardVersionStore { _ version: BoardVersion, in directory: URL ) throws { - let sanitized: String = sanitizeFilename(version.name) + let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength) let filename: String = "\(sanitized)-\(version.id.uuidString).json" let fileURL: URL = directory.appendingPathComponent(filename) do { @@ -134,7 +134,7 @@ public final class BoardVersionStore { attributes: nil ) - let sanitized: String = sanitizeFilename(version.name) + let sanitized: String = sanitizePresetFilename(version.name, maxLength: maxNameLength) let filename: String = "\(sanitized)-\(version.id.uuidString).json" let fileURL: URL = directory.appendingPathComponent(filename) @@ -236,53 +236,4 @@ public final class BoardVersionStore { /// Maximum UTF-8 byte length for the sanitised name prefix before the `-.json` /// suffix is appended, so the full filename stays well under the 255-byte component limit. private let maxNameLength: Int = 200 - - /// Sanitises a string so it is safe as a file-system component on HFS+ and APFS. - /// - /// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace characters with underscores. - /// - Replaces a leading `.` (which would produce hidden-file or `.`/`..` names) with an - /// underscore. - /// - Trims leading and trailing underscores that resulted from whitespace or separator - /// substitution (cosmetic only — the result is always safe even before trimming). - /// - Caps the UTF-8 byte length of the result at `maxNameLength` so the full filename - /// (`-.json`, 54 extra bytes) cannot exceed the 255-byte component limit. - /// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely - /// to separator characters after substitution. - private func sanitizeFilename(_ name: String) -> String { - let replacementCharacter: Character = "_" - let forbiddenCharacters: Set = ["/", "\\", ":", "\0"] - - var sanitized: String = name.map { character -> Character in - if character.isWhitespace || forbiddenCharacters.contains(character) { - return replacementCharacter - } - return character - }.reduce(into: "") { $0.append($1) } - - // Replace a leading dot so the filename is never `.`, `..`, or a hidden file. - if sanitized.first == "." { - sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_") - } - - // Trim whitespace-replacement underscores at both ends (cosmetic). - sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_")) - - // Treat all-empty or all-separator results as unnamed. - guard !sanitized.isEmpty else { return "unnamed" } - - // Cap to maxNameLength UTF-8 bytes so the full filename stays within 255 bytes. - if sanitized.utf8.count > maxNameLength { - var truncated: String = "" - var byteCount: Int = 0 - for scalar: Unicode.Scalar in sanitized.unicodeScalars { - let encodedLength: Int = UTF8.width(scalar) - guard byteCount + encodedLength <= maxNameLength else { break } - truncated.unicodeScalars.append(scalar) - byteCount += encodedLength - } - sanitized = truncated - } - - return sanitized.isEmpty ? "unnamed" : sanitized - } } diff --git a/Sources/LyrebirdShoeGaze/Presets/PresetFilename.swift b/Sources/LyrebirdShoeGaze/Presets/PresetFilename.swift new file mode 100644 index 0000000..889abd0 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/PresetFilename.swift @@ -0,0 +1,65 @@ +// PresetFilename.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Sanitises a user-supplied name so it is safe as a file-system component on HFS+ and APFS. +/// +/// Shared by the preset stores (`BoardVersionStore`, `RigLibraryStore`) so every on-disk preset +/// filename follows one scheme: `-.json`. +/// +/// - Replaces `/`, `\`, `:`, NUL (`\0`), and all whitespace with underscores. +/// - Replaces a leading `.` (which would produce a hidden file or `.`/`..`) with an underscore. +/// - Trims leading and trailing underscores that resulted from the substitutions (cosmetic). +/// - Caps the UTF-8 byte length of the result at `maxLength` so the full filename +/// (`-.json`, 54 extra bytes) stays within the 255-byte component limit. +/// - Returns `"unnamed"` when the input is empty, all-whitespace, or reduces entirely to +/// separator characters after substitution. +/// +/// - Parameters: +/// - name: The raw, user-supplied name. +/// - maxLength: Maximum UTF-8 byte length of the sanitised prefix. Defaults to `200`. +/// - Returns: A file-system-safe name, never empty. +func sanitizePresetFilename( + _ name: String, + maxLength: Int = 200 +) -> String { + let replacementCharacter: Character = "_" + let forbiddenCharacters: Set = ["/", "\\", ":", "\0"] + + var sanitized: String = name.map { character -> Character in + if character.isWhitespace || forbiddenCharacters.contains(character) { + return replacementCharacter + } + return character + }.reduce(into: "") { $0.append($1) } + + // Replace a leading dot so the filename is never `.`, `..`, or a hidden file. + if sanitized.first == "." { + sanitized.replaceSubrange(sanitized.startIndex...sanitized.startIndex, with: "_") + } + + // Trim whitespace-replacement underscores at both ends (cosmetic). + sanitized = sanitized.trimmingCharacters(in: CharacterSet(charactersIn: "_")) + + // Treat all-empty or all-separator results as unnamed. + guard !sanitized.isEmpty else { return "unnamed" } + + // Cap to maxLength UTF-8 bytes so the full filename stays within 255 bytes. + if sanitized.utf8.count > maxLength { + var truncated: String = "" + var byteCount: Int = 0 + for scalar: Unicode.Scalar in sanitized.unicodeScalars { + let encodedLength: Int = UTF8.width(scalar) + guard byteCount + encodedLength <= maxLength else { break } + truncated.unicodeScalars.append(scalar) + byteCount += encodedLength + } + sanitized = truncated + } + + return sanitized.isEmpty ? "unnamed" : sanitized +} diff --git a/Sources/LyrebirdShoeGaze/Presets/RigArchive.swift b/Sources/LyrebirdShoeGaze/Presets/RigArchive.swift new file mode 100644 index 0000000..e78c54e --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/RigArchive.swift @@ -0,0 +1,44 @@ +// RigArchive.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Format version written into every exported ``RigArchive``. +/// +/// Increment when the archive schema changes in a way that requires migration on load. +public let rigArchiveFormatVersion: Int = 1 + +/// A portable bundle of one or more ``RigEntry`` rigs in a single JSON document. +/// +/// `RigArchive` is the hand-editable, shareable file format used by the library's +/// **Export Archive** / **Import Archive** actions — the way to back up or move an entire +/// collection of rigs as one file. It is the multi-rig successor to the old single-rig file +/// save/load: a legacy single-rig file (a bare ``ShoeGazeState``) is still importable and is +/// treated as a one-rig archive (see `RigLibraryStore.importArchive`). +/// +/// The document is written pretty-printed with sorted keys, so it stays readable and editable by +/// hand. `Date` values inside each ``RigEntry`` are encoded as `secondsSince1970`. +public struct RigArchive: Codable, Equatable { + + /// Archive format version. Written as `rigArchiveFormatVersion` at export time. + public let version: Int + + /// The rigs contained in this archive, in listing order. + public let rigs: [RigEntry] + + /// Creates a rig archive. + /// + /// - Parameters: + /// - version: Archive format version. Defaults to `rigArchiveFormatVersion`. + /// - rigs: The rigs to bundle. + public init( + version: Int = rigArchiveFormatVersion, + rigs: [RigEntry] + ) { + self.version = version + self.rigs = rigs + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/RigEntry.swift b/Sources/LyrebirdShoeGaze/Presets/RigEntry.swift new file mode 100644 index 0000000..1c95da8 --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/RigEntry.swift @@ -0,0 +1,98 @@ +// RigEntry.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// A named, timestamped rig in the user's library. +/// +/// `RigEntry` is the unit stored and retrieved by `RigLibraryStore`. Each entry pairs a complete +/// ``ShoeGazeState`` snapshot (every board and its pedals) with a human-readable `name` +/// (e.g. `"Ambient Wash"`) and a `savedAt` timestamp. It is the rig-level analogue of +/// `BoardVersion`, which captures a single board. +/// +/// `RigEntry` is `Codable` so it round-trips through the per-rig JSON files written by +/// `RigLibraryStore` and through the bundled ``RigArchive`` export. It is `Identifiable` +/// (via `UUID`) for direct use in SwiftUI `List` / `ForEach`, and `Equatable` for round-trip tests. +/// +/// ## Typical usage +/// +/// ```swift +/// let entry = shoeGaze.captureEntry(name: "Ambient Wash") +/// try store.save(entry) +/// // later … +/// try shoeGaze.loadRig(from: entry.state) +/// ``` +public struct RigEntry: Codable, Identifiable, Equatable { + + /// Stable unique identifier for this entry. Also seeds the on-disk filename. + public let id: UUID + + /// Human-readable name (e.g. `"Ambient Wash"`, `"Live Set A"`). + public let name: String + + /// Date and time at which this entry was last saved, at **whole-second precision**. + /// + /// Rounded to the nearest second at init so it survives a JSON `secondsSince1970` + /// round-trip exactly — otherwise the fractional `Double` text form loses precision and + /// breaks `Equatable` after a `RigLibraryStore` write/load cycle. + public let savedAt: Date + + /// The full rig snapshot — every board, segment, and pedal parameter. + public let state: ShoeGazeState + + /// Creates a rig library entry. + /// + /// - Parameters: + /// - id: Stable unique identifier. Defaults to a newly generated `UUID()`. + /// - name: Human-readable name for this rig. + /// - savedAt: Save timestamp. Defaults to `Date()` (now). Rounded to the nearest + /// whole second so persistence round-trips are lossless. + /// - state: The ``ShoeGazeState`` rig snapshot to store. + public init( + id: UUID = UUID(), + name: String, + savedAt: Date = Date(), + state: ShoeGazeState + ) { + self.id = id + self.name = name + // Round to whole seconds: a fractional Date loses precision through the JSON + // `secondsSince1970` Double text form, which would break `Equatable` after a + // disk round-trip. + self.savedAt = Date(timeIntervalSince1970: savedAt.timeIntervalSince1970.rounded()) + self.state = state + } + + /// Returns a copy of this entry with a new `name`, a fresh `id`, and `savedAt` updated to + /// `date`. Used by the library's "duplicate" action so a copied rig becomes an independent + /// entry rather than overwriting the original's file. + /// + /// - Parameters: + /// - name: The new entry's name. + /// - date: The new save timestamp. Defaults to `Date()` (now). + /// - Returns: A new `RigEntry` carrying the same `state` under a new identity. + public func duplicated( + name: String, + date: Date = Date() + ) -> RigEntry { + RigEntry(id: UUID(), name: name, savedAt: date, state: state) + } + + /// Returns a copy of this entry with a new `name` and `savedAt` updated to `date`, keeping + /// the same `id`. Used by the library's "rename" action so the entry's identity and file + /// association are preserved. + /// + /// - Parameters: + /// - name: The new name. + /// - date: The new save timestamp. Defaults to `Date()` (now). + /// - Returns: A new `RigEntry` with the same `id` and `state` under the new name. + public func renamed( + to name: String, + date: Date = Date() + ) -> RigEntry { + RigEntry(id: id, name: name, savedAt: date, state: state) + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/RigLibraryLocation.swift b/Sources/LyrebirdShoeGaze/Presets/RigLibraryLocation.swift new file mode 100644 index 0000000..b83dbcf --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/RigLibraryLocation.swift @@ -0,0 +1,96 @@ +// RigLibraryLocation.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Resolves where the rig library lives on disk: the shared iCloud container when available, +/// otherwise a local Application Support folder. +/// +/// Both the macOS and iOS builder apps declare the **same** iCloud container +/// (``containerIdentifier``) in their entitlements — even though their bundle identifiers differ — +/// so a single rig library is shared across a user's devices and across both apps. When iCloud is +/// unavailable (not signed in, entitlement missing, or running in a context without provisioning) +/// the library falls back to a local folder and simply does not sync. +public enum RigLibraryLocation { + + /// The shared iCloud container identifier. Both builder targets must list this exact value in + /// `com.apple.developer.icloud-container-identifiers` / `ubiquity-container-identifiers`, and + /// the container must be enabled on both App IDs in the developer account. + public static let containerIdentifier: String = "iCloud.net.realizedsound.ShoeGazeData" + + /// Subfolder (inside the container's `Documents/` or inside Application Support) holding the + /// per-rig JSON files. + private static let rigsFolderName: String = "Rigs" + + /// Local Application Support namespace, matching `BoardVersionStore.defaultDirectory()`. + private static let localFolderName: String = "LyrebirdShoeGaze" + + /// iCloud documents subfolder. Storing rigs under `Documents/` (rather than the container root) + /// makes them eligible to appear in the Files app when `NSUbiquitousContainers` is configured. + private static let documentsFolderName: String = "Documents" + + /// A resolved library directory and whether it is backed by iCloud. + public struct Resolved: Equatable { + + /// The directory holding per-rig JSON files (created if needed). + public let directory: URL + + /// `true` when `directory` is inside the iCloud ubiquity container (sync active); + /// `false` for the local Application Support fallback. + public let isICloud: Bool + } + + /// Resolves the rig library directory, preferring iCloud. + /// + /// - Important: When an iCloud account is signed in, + /// `FileManager.url(forUbiquityContainerIdentifier:)` performs **blocking** I/O that can be + /// slow on its first call. Prefer calling this **once at app startup, off the main thread**. + /// When no iCloud account is present, the cheap `ubiquityIdentityToken` check short-circuits + /// straight to the local fallback without the blocking call. The created directory is returned + /// ready to use. + /// + /// - Parameter containerIdentifier: The ubiquity container to use. Defaults to + /// ``containerIdentifier``. + /// - Returns: The resolved directory and whether iCloud backing is active. + public static func resolve( + containerIdentifier identifier: String = containerIdentifier + ) -> Resolved { + let fileManager: FileManager = FileManager.default + // No iCloud account signed in → skip the potentially-slow container lookup entirely. + guard fileManager.ubiquityIdentityToken != nil else { + return Resolved(directory: localDirectory(), isICloud: false) + } + if let container: URL = fileManager.url(forUbiquityContainerIdentifier: identifier) { + let directory: URL = container + .appendingPathComponent(documentsFolderName, isDirectory: true) + .appendingPathComponent(rigsFolderName, isDirectory: true) + try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + return Resolved(directory: directory, isICloud: true) + } + return Resolved(directory: localDirectory(), isICloud: false) + } + + /// The local (non-iCloud) rig library directory, created if needed. + /// + /// Falls back to a folder in the system temporary directory if Application Support cannot be + /// resolved. Used as the iCloud-unavailable fallback and directly by tests. + /// + /// - Returns: A local `URL` for the rigs directory. + public static func localDirectory() -> URL { + let fileManager: FileManager = FileManager.default + let base: URL = (try? fileManager.url( + for: .applicationSupportDirectory, + in: .userDomainMask, + appropriateFor: nil, + create: true + )) ?? fileManager.temporaryDirectory + let directory: URL = base + .appendingPathComponent(localFolderName, isDirectory: true) + .appendingPathComponent(rigsFolderName, isDirectory: true) + try? fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + return directory + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift new file mode 100644 index 0000000..bd782bc --- /dev/null +++ b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift @@ -0,0 +1,475 @@ +// 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 +/// `-.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 = 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..-.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 `-.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 + } + } +} diff --git a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift index 31f735e..642ad7e 100644 --- a/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift +++ b/Sources/LyrebirdShoeGaze/Presets/ShoeGaze+Preset.swift @@ -21,6 +21,23 @@ extension ShoeGaze { return ShoeGazeState(boards: boardStates) } + /// Captures the current rig as a named ``RigEntry`` suitable for the rig library. + /// + /// Wraps ``captureState()`` with a name, a fresh `id`, and a `savedAt` timestamp. The engine + /// graph is not modified; this is a read-only operation. + /// + /// - Parameters: + /// - name: Human-readable name for the entry (e.g. `"Ambient Wash"`). + /// - id: Stable identifier. Defaults to a newly generated `UUID()`; pass an existing entry's + /// `id` to overwrite that entry in place. + /// - Returns: A ``RigEntry`` reflecting the current rig. + public func captureEntry( + name: String, + id: UUID = UUID() + ) -> RigEntry { + RigEntry(id: id, name: name, state: captureState()) + } + // MARK: - Save / Load /// Saves the current rig to a JSON file at `url`. @@ -58,6 +75,20 @@ extension ShoeGaze { public func loadRig(from data: Data) throws { let decoder: JSONDecoder = JSONDecoder() let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data) + try loadRig(from: state) + } + + /// Rebuilds the engine graph from an already-decoded ``ShoeGazeState``. + /// + /// Shared core of the `Data` / `URL` loaders, and the entry point the rig library uses to + /// recall a stored ``RigEntry`` (`loadRig(from: entry.state)`) without re-encoding. Rejects a + /// snapshot whose `version` exceeds `presetFormatVersion`, tears down the current rig, then + /// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``. + /// + /// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``. + /// - Parameter state: The rig snapshot to restore. + /// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error. + public func loadRig(from state: ShoeGazeState) throws { guard state.version <= presetFormatVersion else { throw PresetError.unsupportedVersion(state.version) } diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift new file mode 100644 index 0000000..c367786 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -0,0 +1,67 @@ +// RigLibraryBootstrap.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation +import LyrebirdShoeGaze + +/// One-call setup of the rig library for an app shell. +/// +/// Resolves the (iCloud-or-local) library location, constructs and starts a ``RigLibraryStore``, +/// seeds it with the current working rig the first time it is empty (so the listing is never blank +/// and the user's existing setup becomes their first saved rig), and reports which entry should be +/// highlighted as the current rig on this launch. +@MainActor +public enum RigLibraryBootstrap { + + /// The result of bootstrapping: a started store and the rig to highlight at launch. + public struct Result { + public let store: RigLibraryStore + public let initialRigID: UUID? + } + + /// Builds and starts the rig library for `shoeGaze`. + /// + /// - 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: + /// - shoeGaze: The session whose current rig seeds the library when it is first empty. + /// - 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 make( + for shoeGaze: ShoeGaze, + seedName: String = "Default" + ) -> Result { + let resolved: RigLibraryLocation.Resolved = RigLibraryLocation.resolve() + let store: RigLibraryStore = RigLibraryStore(resolved: resolved) + store.start() + + let defaults: UserDefaults = UserDefaults.standard + let key: String = ShoeGazeBuilderView.currentRigDefaultsKey + + // First run with an empty library: capture the current working rig as the first entry and + // remember it as current. + if store.entries.isEmpty, !shoeGaze.boards.isEmpty { + let entry: RigEntry = shoeGaze.captureEntry(name: seedName) + do { + try store.save(entry) + defaults.set(entry.id.uuidString, forKey: key) + } catch { + 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) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift new file mode 100644 index 0000000..348cb9e --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -0,0 +1,159 @@ +// RigLibrarySidebarView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze + +/// The rig library: a persistent left-hand listing of every saved rig, with controls to start a +/// new rig, save / save-as, duplicate, rename, delete, erase all, and import / export an archive. +/// +/// Selecting a rig replaces the current working session (the host stops the engine, rebuilds the +/// graph, and restarts). This view is purely presentational — every action is delegated to the +/// host (`ShoeGazeBuilderView`) via closures so engine lifecycle and naming prompts stay in one +/// place. +struct RigLibrarySidebarView: View { + + // MARK: - Layout constants + + private static let width: CGFloat = 200 + private static let rowSpacing: CGFloat = 4 + private static let rowPadding: CGFloat = 8 + private static let rowCorner: CGFloat = 6 + private static let selectedOpacity: Double = 0.22 + private static let subtitleOpacity: Double = 0.5 + private static let headerOpacity: Double = 0.65 + private static let emptyOpacity: Double = 0.4 + + // MARK: - Inputs + + let store: RigLibraryStore + + /// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. + @Binding var currentRigID: UUID? + + let onSelect: (RigEntry) -> Void + let onNew: () -> Void + let onSave: () -> Void + let onSaveAs: () -> Void + let onDuplicate: (RigEntry) -> Void + let onRename: (RigEntry) -> Void + let onDelete: (RigEntry) -> Void + let onEraseAll: () -> Void + let onImportArchive: () -> Void + let onExportArchive: () -> Void + + private static let timestampFormat: Date.FormatStyle = + Date.FormatStyle(date: .abbreviated, time: .shortened) + + // MARK: - Body + + var body: some View { + VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { + header + Divider().overlay(Color.white.opacity(0.12)) + rigList + Divider().overlay(Color.white.opacity(0.12)) + actionBar + } + .frame(width: RigLibrarySidebarView.width) + } + + // MARK: - Header + + private var header: some View { + HStack(spacing: 6) { + Text("Rigs") + .font(.headline) + .foregroundStyle(Color.white) + Spacer() + // Cloud icon when the library is iCloud-backed; a slash when local-only. + Image(systemName: store.isICloud ? "icloud" : "icloud.slash") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity)) + .help(store.isICloud + ? "Synced with iCloud across your devices" + : "iCloud unavailable — rigs are stored on this device only") + } + } + + // MARK: - List + + private var rigList: some View { + ScrollView(.vertical, showsIndicators: true) { + LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { + if store.entries.isEmpty { + Text("No saved rigs yet.\nTap New or Save to add one.") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) + .padding(.vertical, RigLibrarySidebarView.rowPadding) + } + ForEach(store.entries) { entry in + rigRow(entry) + } + } + } + .frame(maxHeight: .infinity) + } + + private func rigRow(_ entry: RigEntry) -> some View { + let isSelected: Bool = entry.id == currentRigID + return Button { + onSelect(entry) + } label: { + VStack(alignment: .leading, spacing: 2) { + Text(entry.name) + .font(.subheadline) + .foregroundStyle(Color.white) + .lineLimit(1) + Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat)) + .font(.caption2) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity)) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(RigLibrarySidebarView.rowPadding) + .background( + RoundedRectangle(cornerRadius: RigLibrarySidebarView.rowCorner) + .fill(Color.orange.opacity(isSelected ? RigLibrarySidebarView.selectedOpacity : 0)) + ) + } + .buttonStyle(.plain) + .contextMenu { + Button("Rename…") { onRename(entry) } + Button("Duplicate…") { onDuplicate(entry) } + Divider() + Button("Delete", role: .destructive) { onDelete(entry) } + } + } + + // MARK: - Action bar + + private var actionBar: some View { + HStack(spacing: 6) { + Button { onNew() } label: { Image(systemName: "plus") } + .help("New rig") + Button { onSave() } label: { Image(systemName: "square.and.arrow.down") } + .help("Save the current rig") + Button { onSaveAs() } label: { Image(systemName: "doc.on.doc") } + .help("Save the current rig as a new entry") + Spacer() + Menu { + Button("Import Archive…") { onImportArchive() } + Button("Export Archive…") { onExportArchive() } + Divider() + Button("Erase All Rigs…", role: .destructive) { onEraseAll() } + } label: { + Image(systemName: "ellipsis.circle") + } + .menuStyle(.borderlessButton) + .fixedSize() + .help("Archive and library options") + } + .buttonStyle(.bordered) + .tint(.orange) + .padding(.top, 2) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigNamePrompt.swift b/Sources/LyrebirdShoeGazeUI/RigNamePrompt.swift new file mode 100644 index 0000000..22c2658 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigNamePrompt.swift @@ -0,0 +1,71 @@ +// RigNamePrompt.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI + +/// A request to prompt the user for a rig name (New, Save As, Rename, Duplicate). +/// +/// Presented via the ``SwiftUI/View/rigNamePrompt(_:)`` modifier. Setting a non-`nil` value shows a +/// text-entry alert seeded with `initialText`; committing a non-empty, trimmed name invokes +/// `onCommit`. Cancelling dismisses without calling `onCommit`. +struct RigNamePrompt: Identifiable { + + let id: UUID = UUID() + + /// Alert title, e.g. `"Save Rig As"`. + let title: String + + /// Text the field is pre-filled with (e.g. the existing name for a rename). + let initialText: String + + /// Confirm-button label, e.g. `"Save"` or `"Rename"`. + let confirmLabel: String + + /// Invoked with the trimmed, non-empty name when the user confirms. + let onCommit: (String) -> Void +} + +private struct RigNamePromptModifier: ViewModifier { + + @Binding var prompt: RigNamePrompt? + @State private var text: String = "" + + func body(content: Content) -> some View { + content + .onChange(of: prompt?.id) { + // Seed the field whenever a new prompt is presented. + text = prompt?.initialText ?? "" + } + .alert( + prompt?.title ?? "", + isPresented: isPresented, + presenting: prompt + ) { active in + TextField("Name", text: $text) + Button(active.confirmLabel) { + let trimmed: String = text.trimmingCharacters(in: .whitespacesAndNewlines) + if !trimmed.isEmpty { active.onCommit(trimmed) } + } + Button("Cancel", role: .cancel) { } + } + } + + private var isPresented: Binding { + Binding( + get: { prompt != nil }, + set: { presented in if !presented { prompt = nil } } + ) + } +} + +extension View { + + /// Presents a rig-name entry alert driven by `prompt`. Set the binding to a ``RigNamePrompt`` + /// to show it; it clears itself on dismiss. + func rigNamePrompt(_ prompt: Binding) -> some View { + modifier(RigNamePromptModifier(prompt: prompt)) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index e86737b..47d2358 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -50,17 +50,25 @@ public struct ShoeGazeBuilderView: View { private static let testLoopTag: Int = -1 /// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel). private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection" + /// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be + /// highlighted on the next launch. Read by the app shells to seed `initialRigID`. + public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID" /// Maximum crossfade duration honoured by board-switch keyboard shortcuts. private static let maxCrossfadeSeconds: Double = 10.0 /// Highest board reachable via a ⌘-number switch shortcut. private static let maxBoardShortcuts: Int = 9 - private static let defaultRigFileName: String = "ShoeGazeRig" + /// Default filename offered when exporting the whole library as an archive. + private static let defaultArchiveFileName: String = "ShoeGaze Library" + /// Extra width reserved for the rig-library sidebar on top of the builder's minimum width. + private static let librarySidebarReserve: CGFloat = 216 private static let recordDotSize: CGFloat = 9 private static let folderLabelOpacity: Double = 0.55 // MARK: - Properties private let shoeGaze: ShoeGaze + private let library: RigLibraryStore + private let initialRigID: UUID? private let hardwareSampleRate: () -> Double? /// Host hook to enable live input when the current engine has no input channel (iOS). @@ -87,18 +95,31 @@ public struct ShoeGazeBuilderView: View { /// Presentation flag for the board-manager sheet (rename / reorder / delete). @State private var showBoardsSheet: Bool = false - /// Confirmation dialog for the Clear action, and a flag to clear once a chosen save completes. + /// Confirmation dialog for the Clear action. @State private var showClearDialog: Bool = false - @State private var pendingClearAfterSave: Bool = false - /// Rig-save export state. Cross-platform: the in-view exporter backs both the Save action and - /// the "Save & Clear" flow on macOS and iOS (macOS additionally has a File-menu Save). + /// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives + /// the sidebar highlight and decides whether Save overwrites or prompts for a name. + @State private var currentRigID: UUID? + + /// Guards the one-time `currentRigID` seed from `initialRigID` on appear. + @State private var didRestoreRig: Bool = false + + /// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate). + @State private var namePrompt: RigNamePrompt? + + /// Confirmation dialog for the "Erase All Rigs" library action. + @State private var showEraseAllDialog: Bool = false + + /// Archive export state. Cross-platform: backs the sidebar's Export Archive and the + /// "Save & Clear" flow is separate (it saves to the library, not a file). @State private var showExporter: Bool = false @State private var exportDocument: RigFileDocument = RigFileDocument(data: Data()) - #if !os(macOS) - /// iOS file-dialog presentation flags. (macOS uses the File menu for load + recording folder.) + /// Archive import state (cross-platform). @State private var showImporter: Bool = false + + #if !os(macOS) /// iOS recording-folder picker presentation flag. (macOS uses the Record menu.) @State private var showRecordingFolderImporter: Bool = false #endif @@ -117,12 +138,20 @@ public struct ShoeGazeBuilderView: View { /// 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 /// directly without a rebuild. + /// - library: The rig library store, already `start()`ed by the host. Backs the left-hand + /// rig listing and all save / load / archive actions. + /// - initialRigID: The library entry the host restored into `shoeGaze` at launch, if any, so + /// the sidebar can highlight it as the current rig. Defaults to `nil`. public init( shoeGaze: ShoeGaze, + library: RigLibraryStore, + initialRigID: UUID? = nil, hardwareSampleRate: @escaping () -> Double? = { nil }, onEnableLiveInput: (() -> Void)? = nil ) { self.shoeGaze = shoeGaze + self.library = library + self.initialRigID = initialRigID self.hardwareSampleRate = hardwareSampleRate self.onEnableLiveInput = onEnableLiveInput } @@ -130,6 +159,91 @@ public struct ShoeGazeBuilderView: View { // MARK: - Body public var body: some View { + HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) { + rigSidebar + Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) + builderColumn + } + .padding(ShoeGazeBuilderView.outerPadding) + .frame( + minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve, + minHeight: ShoeGazeBuilderView.minHeight + ) + .background( + Color( + red: ShoeGazeBuilderView.backgroundRed, + green: ShoeGazeBuilderView.backgroundGreen, + blue: ShoeGazeBuilderView.backgroundBlue + ) + ) + .background(boardSwitchShortcuts) + .onAppear { + restoreInputSelection() + restoreCurrentRig() + } + .onChange(of: currentRigID) { persistCurrentRigID() } + .background(boardsSheetAnchor) + .background(rigExportAnchor) + .background(rigImportAnchor) + .rigNamePrompt($namePrompt) + .confirmationDialog( + "Erase all rigs?", + isPresented: $showEraseAllDialog, + titleVisibility: .visible + ) { + Button("Erase All Rigs", role: .destructive) { eraseAllRigs() } + Button("Cancel", role: .cancel) { } + } message: { + Text("This permanently removes every saved rig from the library" + + (library.isICloud ? " on all your devices." : ".")) + } + .confirmationDialog( + "Clear all boards?", + isPresented: $showClearDialog, + titleVisibility: .visible + ) { + Button("Save & Clear") { + saveCurrentRig(thenClear: true) + } + Button("Clear Without Saving", role: .destructive) { + performClear() + } + Button("Cancel", role: .cancel) { } + } message: { + Text("This removes every pedal and board. Save your current setup first?") + } + .alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) { + Button("OK", role: .cancel) { } + } message: { + Text("Live input needs microphone access. Enable it in System Settings › Privacy & " + + "Security › Microphone, then select the input again.") + } + #if !os(macOS) + .background(recordingFolderImportAnchor) + #endif + } + + /// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/ + /// delete/erase and archive import/export. Selecting a rig replaces the current session. + private var rigSidebar: some View { + RigLibrarySidebarView( + store: library, + currentRigID: $currentRigID, + onSelect: { entry in loadEntry(entry) }, + onNew: { promptNewRig() }, + onSave: { saveCurrentRig() }, + onSaveAs: { promptSaveAs() }, + onDuplicate: { entry in promptDuplicate(entry) }, + onRename: { entry in promptRename(entry) }, + onDelete: { entry in deleteEntry(entry) }, + onEraseAll: { showEraseAllDialog = true }, + onImportArchive: { showImporter = true }, + onExportArchive: { exportArchiveAction() } + ) + } + + /// The main builder column: transport, IO, boards, palette, board area, scope, and status. + private var builderColumn: some View { VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { transportRow ioRow @@ -156,50 +270,7 @@ public struct ShoeGazeBuilderView: View { LyrebirdStatusView(engine: shoeGaze.engine) .frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading) } - .padding(ShoeGazeBuilderView.outerPadding) - .frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight) - .background( - Color( - red: ShoeGazeBuilderView.backgroundRed, - green: ShoeGazeBuilderView.backgroundGreen, - blue: ShoeGazeBuilderView.backgroundBlue - ) - ) - .background(boardSwitchShortcuts) - .onAppear { restoreInputSelection() } - // Each presentation (sheet / importers / exporter / alert) lives on its own anchor - // node. SwiftUI reliably drives only one presentation per view node, so stacking them - // all on the root view silently swallowed some (e.g. the iOS Load file importer). - .background(boardsSheetAnchor) - .background(rigExportAnchor) - .confirmationDialog( - "Clear all boards?", - isPresented: $showClearDialog, - titleVisibility: .visible - ) { - Button("Save & Clear") { - pendingClearAfterSave = true - saveAction() - } - Button("Clear Without Saving", role: .destructive) { - performClear() - } - Button("Cancel", role: .cancel) { - pendingClearAfterSave = false - } - } message: { - Text("This removes every pedal and board. Save your current setup first?") - } - .alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) { - Button("OK", role: .cancel) { } - } message: { - Text("Live input needs microphone access. Enable it in System Settings › Privacy & " - + "Security › Microphone, then select the input again.") - } - #if !os(macOS) - .background(rigImportAnchor) - .background(recordingFolderImportAnchor) - #endif + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } // MARK: - Presentation anchors @@ -219,37 +290,32 @@ public struct ShoeGazeBuilderView: View { } } - /// Hosts the rig-save (`.json`) exporter on its own node. Cross-platform: backs both the - /// Save action and the "Save & Clear" flow. On a successful save during "Save & Clear", the - /// pending clear runs; cancelling the save leaves the boards untouched. + /// Hosts the archive-export (`.json`) exporter on its own node. Writes the whole library as one + /// ``RigArchive`` file for backup or transfer. private var rigExportAnchor: some View { Color.clear .fileExporter( isPresented: $showExporter, document: exportDocument, contentType: .json, - defaultFilename: ShoeGazeBuilderView.defaultRigFileName + defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName ) { result in - switch result { - case .failure(let error): - print("[ShoeGazeBuilderView] export failed: \(error)") - pendingClearAfterSave = false - case .success: - if pendingClearAfterSave { performClear() } - pendingClearAfterSave = false + if case .failure(let error) = result { + print("[ShoeGazeBuilderView] archive export failed: \(error)") } } } - #if !os(macOS) - /// Hosts the rig-load (`.json`) importer on its own node. + /// Hosts the archive-import (`.json`) importer on its own node (cross-platform). Accepts a + /// ``RigArchive`` or a legacy single-rig file; imported rigs are added to the library. private var rigImportAnchor: some View { Color.clear .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in - handleImport(result) + handleArchiveImport(result) } } + #if !os(macOS) /// Hosts the recording-folder importer on its own node. private var recordingFolderImportAnchor: some View { Color.clear @@ -316,19 +382,9 @@ public struct ShoeGazeBuilderView: View { Button("Clear") { showClearDialog = true } .buttonStyle(.bordered).tint(.red) - .help("Remove all boards (with the option to save first)") + .help("Remove all boards in the current rig (with the option to save first)") Spacer() - - // On macOS, Load lives in the app's File menu (see the app shell's AppDelegate); on - // iOS it stays in-view via fileImporter. Save is in-view on both (cross-platform - // exporter) so the "Save & Clear" flow works everywhere. - Button("Save…") { saveAction() } - .buttonStyle(.bordered).tint(.blue) - #if !os(macOS) - Button("Load…") { loadAction() } - .buttonStyle(.bordered).tint(.blue) - #endif } } @@ -559,11 +615,9 @@ public struct ShoeGazeBuilderView: View { shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds) } - // MARK: - Save / Load (iOS) + // MARK: - Recording (iOS) - // Save is in-view on both platforms (cross-platform fileExporter) so "Save & Clear" works - // everywhere. Load is the macOS File menu / iOS fileImporter; recording controls are iOS - // in-view (macOS uses the Record menu). + // Recording controls are iOS in-view (macOS uses the Record menu). #if !os(macOS) /// iOS recording controls: choose an output folder, then start/stop recording. private var recordingRow: some View { @@ -610,47 +664,211 @@ public struct ShoeGazeBuilderView: View { } #endif - /// Presents the cross-platform rig-save exporter (also used by the "Save & Clear" flow). - private func saveAction() { - do { - exportDocument = RigFileDocument(data: try shoeGaze.rigData()) - showExporter = true - } catch { - print("[ShoeGazeBuilderView] rigData failed: \(error)") + // MARK: - Rig library + + /// Seeds `currentRigID` from the entry the host restored at launch, once. + private func restoreCurrentRig() { + guard !didRestoreRig else { return } + didRestoreRig = true + currentRigID = initialRigID + } + + /// Persists `currentRigID` so the same rig is highlighted on the next launch. + private func persistCurrentRigID() { + let defaults: UserDefaults = UserDefaults.standard + if let id: UUID = currentRigID { + defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey) + } else { + defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey) } } - #if !os(macOS) - private func loadAction() { - showImporter = true - } - - /// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the - /// board selection to a valid index (load replaces all boards). - private func loadRig(from url: URL) { + /// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine + /// around the rebuild, resets the board selection, and records the entry as current. + private func loadEntry(_ entry: RigEntry) { let wasRunning: Bool = shoeGaze.engine.isRunning if wasRunning { shoeGaze.engine.stop() } do { - try shoeGaze.loadRig(from: url) + try shoeGaze.loadRig(from: entry.state) + currentRigID = entry.id selectedBoardIndex = 0 autosave() } catch { - print("[ShoeGazeBuilderView] loadRig failed: \(error)") + print("[ShoeGazeBuilderView] loadEntry failed: \(error)") } if wasRunning { try? shoeGaze.engine.start() } transportTick.toggle() } - private func handleImport(_ result: Result) { - switch result { - case .success(let url): - // A `.fileImporter` URL is security-scoped on iOS; access must be started to read it. - let scoped: Bool = url.startAccessingSecurityScopedResource() - defer { if scoped { url.stopAccessingSecurityScopedResource() } } - loadRig(from: url) - case .failure(let error): - print("[ShoeGazeBuilderView] import failed: \(error)") + /// Saves the current session over the loaded library entry, or prompts for a name when no entry + /// is loaded (a new, never-saved rig). + /// + /// - Parameter thenClear: When `true`, clears the boards after a successful save (the + /// "Save & Clear" flow). Cancelling the name prompt cancels the clear too — no save, no clear. + private func saveCurrentRig(thenClear: Bool = false) { + let completion: () -> Void = thenClear ? { performClear() } : { } + guard let id: UUID = currentRigID, + let existing: RigEntry = library.entries.first(where: { $0.id == id }) else { + // No current entry — prompt for a name; the clear (if any) runs only on commit. + namePrompt = RigNamePrompt( + title: "Save Rig As", + initialText: currentRigName() ?? defaultNewRigName(), + confirmLabel: "Save" + ) { name in + persist(shoeGaze.captureEntry(name: name), then: completion) + } + return + } + persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion) + } + + /// Prompts for a name, then creates a brand-new empty rig (one empty board) and selects it. + private func promptNewRig() { + namePrompt = RigNamePrompt( + title: "New Rig", + initialText: defaultNewRigName(), + confirmLabel: "Create" + ) { name in + createNewRig(named: name) } } - #endif + + /// Prompts for a name and saves the current session as a new library entry (new id). + private func promptSaveAs() { + namePrompt = RigNamePrompt( + title: "Save Rig As", + initialText: currentRigName() ?? defaultNewRigName(), + confirmLabel: "Save" + ) { name in + persist(shoeGaze.captureEntry(name: name)) + } + } + + /// Prompts for a name and duplicates `entry`, loading the copy as the current rig. + private func promptDuplicate(_ entry: RigEntry) { + namePrompt = RigNamePrompt( + title: "Duplicate Rig", + initialText: "\(entry.name) copy", + confirmLabel: "Duplicate" + ) { name in + do { + let copy: RigEntry = try library.duplicate(entry, newName: name) + loadEntry(copy) + } catch { + print("[ShoeGazeBuilderView] duplicate failed: \(error)") + } + } + } + + /// Prompts for a new name and renames `entry` in the library. + private func promptRename(_ entry: RigEntry) { + namePrompt = RigNamePrompt( + title: "Rename Rig", + initialText: entry.name, + confirmLabel: "Rename" + ) { name in + do { _ = try library.rename(entry, to: name) } + catch { print("[ShoeGazeBuilderView] rename failed: \(error)") } + } + } + + /// Deletes `entry` from the library. Clears the current-rig marker if it was the loaded rig. + private func deleteEntry(_ entry: RigEntry) { + do { + try library.delete(entry) + if currentRigID == entry.id { currentRigID = nil } + } catch { + print("[ShoeGazeBuilderView] delete failed: \(error)") + } + } + + /// Erases the entire library and clears the current-rig marker. + private func eraseAllRigs() { + do { + try library.eraseAll() + currentRigID = nil + } catch { + print("[ShoeGazeBuilderView] eraseAll failed: \(error)") + } + } + + /// Captures the current session into the whole-library archive exporter. + private func exportArchiveAction() { + do { + exportDocument = RigFileDocument(data: try library.exportArchiveData()) + showExporter = true + } catch { + print("[ShoeGazeBuilderView] exportArchiveData failed: \(error)") + } + } + + /// Imports an archive (or legacy single-rig file) into the library. + private func handleArchiveImport(_ result: Result) { + switch result { + case .success(let url): + // A `.fileImporter` URL is security-scoped; access must be started to read it. + let scoped: Bool = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + do { + let data: Data = try Data(contentsOf: url) + _ = try library.importArchive(from: data) + } catch { + print("[ShoeGazeBuilderView] archive import failed: \(error)") + } + case .failure(let error): + print("[ShoeGazeBuilderView] archive import pick failed: \(error)") + } + } + + /// Persists `entry`, marks it current, and runs `completion` (e.g. the "Save & Clear" clear). + private func persist( + _ entry: RigEntry, + then completion: () -> Void = { } + ) { + do { + try library.save(entry) + currentRigID = entry.id + // Only run the follow-up (e.g. the "Save & Clear" clear) once the save succeeded — + // otherwise a failed save would still wipe the boards, losing the rig. + completion() + } catch { + print("[ShoeGazeBuilderView] save failed: \(error)") + } + } + + /// Creates a fresh single-board rig, saves it under `name`, and makes it current. + private func createNewRig(named name: String) { + let wasRunning: Bool = shoeGaze.engine.isRunning + if wasRunning { shoeGaze.engine.stop() } + // Replace the working graph with a single empty board. + for board: PedalBoard in Array(shoeGaze.boards) { + shoeGaze.removeBoard(board) + } + do { + let board: PedalBoard = try shoeGaze.addBoard() + board.label = "Board 1" + try shoeGaze.finalizeBoard(board) + } catch { + print("[ShoeGazeBuilderView] createNewRig seed failed: \(error)") + } + selectedBoardIndex = 0 + if wasRunning { try? shoeGaze.engine.start() } + transportTick.toggle() + persist(shoeGaze.captureEntry(name: name)) + } + + /// The name of the currently loaded library entry, if any. + private func currentRigName() -> String? { + guard let id: UUID = currentRigID else { return nil } + return library.entries.first(where: { $0.id == id })?.name + } + + /// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names. + private func defaultNewRigName() -> String { + let base: String = "Rig" + let existing: Set = Set(library.entries.map(\.name)) + var index: Int = library.entries.count + 1 + while existing.contains("\(base) \(index)") { index += 1 } + return "\(base) \(index)" + } } diff --git a/Tests/LyrebirdShoeGazeTests/RigArchiveTests.swift b/Tests/LyrebirdShoeGazeTests/RigArchiveTests.swift new file mode 100644 index 0000000..573b020 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/RigArchiveTests.swift @@ -0,0 +1,43 @@ +// RigArchiveTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable import LyrebirdShoeGaze + +@Suite("RigArchive") +struct RigArchiveTests { + + private func makeEntry(_ name: String) -> RigEntry { + RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])])) + } + + @Test func jsonRoundTripIsLossless() throws { + let archive: RigArchive = RigArchive(rigs: [makeEntry("A"), makeEntry("B")]) + + let encoder: JSONEncoder = JSONEncoder() + encoder.dateEncodingStrategy = .secondsSince1970 + let decoder: JSONDecoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + let data: Data = try encoder.encode(archive) + let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data) + #expect(decoded == archive) + #expect(decoded.version == rigArchiveFormatVersion) + #expect(decoded.rigs.count == 2) + } + + @Test func emptyArchiveRoundTrips() throws { + let archive: RigArchive = RigArchive(rigs: []) + let encoder: JSONEncoder = JSONEncoder() + encoder.dateEncodingStrategy = .secondsSince1970 + let decoder: JSONDecoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + let data: Data = try encoder.encode(archive) + let decoded: RigArchive = try decoder.decode(RigArchive.self, from: data) + #expect(decoded.rigs.isEmpty) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/RigEntryTests.swift b/Tests/LyrebirdShoeGazeTests/RigEntryTests.swift new file mode 100644 index 0000000..9b4a6ad --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/RigEntryTests.swift @@ -0,0 +1,55 @@ +// RigEntryTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable import LyrebirdShoeGaze + +@Suite("RigEntry") +struct RigEntryTests { + + /// A minimal two-board rig state for snapshotting without an engine. + private func makeState() -> ShoeGazeState { + let board: BoardState = BoardState(label: "Lead", segments: []) + let other: BoardState = BoardState(label: "Clean", segments: []) + return ShoeGazeState(boards: [board, other]) + } + + @Test func jsonRoundTripIsLossless() throws { + let entry: RigEntry = RigEntry(name: "Ambient Wash", state: makeState()) + + let encoder: JSONEncoder = JSONEncoder() + encoder.dateEncodingStrategy = .secondsSince1970 + let decoder: JSONDecoder = JSONDecoder() + decoder.dateDecodingStrategy = .secondsSince1970 + + let data: Data = try encoder.encode(entry) + let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data) + #expect(decoded == entry) + } + + @Test func savedAtIsRoundedToWholeSeconds() { + let fractional: Date = Date(timeIntervalSince1970: 1_700_000_000.789) + let entry: RigEntry = RigEntry(name: "x", savedAt: fractional, state: makeState()) + #expect(entry.savedAt.timeIntervalSince1970 == 1_700_000_001) + } + + @Test func duplicatedGetsNewIdSameState() { + let original: RigEntry = RigEntry(name: "A", state: makeState()) + let copy: RigEntry = original.duplicated(name: "A copy") + #expect(copy.id != original.id) + #expect(copy.name == "A copy") + #expect(copy.state == original.state) + } + + @Test func renamedKeepsIdSameState() { + let original: RigEntry = RigEntry(name: "A", state: makeState()) + let renamed: RigEntry = original.renamed(to: "B") + #expect(renamed.id == original.id) + #expect(renamed.name == "B") + #expect(renamed.state == original.state) + } +} diff --git a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift new file mode 100644 index 0000000..2275a93 --- /dev/null +++ b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift @@ -0,0 +1,162 @@ +// RigLibraryStoreTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +@testable import LyrebirdShoeGaze + +@MainActor +@Suite("RigLibraryStore") +struct RigLibraryStoreTests { + + /// A fresh, unique temp directory for an isolated, local (non-iCloud) store. + private func makeTempDirectory() -> URL { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent("RigLibraryTests-\(UUID().uuidString)", isDirectory: true) + return url + } + + private func makeStore() -> (RigLibraryStore, URL) { + let dir: URL = makeTempDirectory() + let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) + store.start() + return (store, dir) + } + + private func makeEntry(_ name: String) -> RigEntry { + RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])])) + } + + @Test func saveAddsEntryAndReloadsAcrossInstances() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + try store.save(makeEntry("Ambient")) + try store.save(makeEntry("Crunch")) + #expect(store.entries.count == 2) + // Sorted by name, case-insensitive. + #expect(store.entries.map(\.name) == ["Ambient", "Crunch"]) + + // A fresh store over the same directory sees the persisted files. + let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) + reopened.start() + #expect(reopened.entries.count == 2) + #expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"]) + } + + @Test func saveSameIdReplacesInPlace() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + let entry: RigEntry = makeEntry("Original") + try store.save(entry) + // Overwrite under the same id with a new name — no duplicate file should remain. + try store.save(entry.renamed(to: "Renamed")) + + #expect(store.entries.count == 1) + #expect(store.entries.first?.name == "Renamed") + + let files: [URL] = try FileManager.default.contentsOfDirectory( + at: dir, includingPropertiesForKeys: nil + ).filter { $0.pathExtension == "json" } + #expect(files.count == 1, "rename must not leave the old-name file behind") + } + + @Test func renameKeepsIdChangesName() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + let entry: RigEntry = makeEntry("Before") + try store.save(entry) + let renamed: RigEntry = try store.rename(entry, to: "After") + #expect(renamed.id == entry.id) + #expect(store.entries.map(\.name) == ["After"]) + } + + @Test func duplicateCreatesIndependentEntry() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + let entry: RigEntry = makeEntry("Base") + try store.save(entry) + let copy: RigEntry = try store.duplicate(entry, newName: "Base 2") + #expect(copy.id != entry.id) + #expect(store.entries.count == 2) + } + + @Test func deleteRemovesFileAndEntry() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + let entry: RigEntry = makeEntry("Doomed") + try store.save(entry) + try store.delete(entry) + #expect(store.entries.isEmpty) + + let files: [URL] = try FileManager.default.contentsOfDirectory( + at: dir, includingPropertiesForKeys: nil + ).filter { $0.pathExtension == "json" } + #expect(files.isEmpty) + } + + @Test func eraseAllClearsLibrary() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + try store.save(makeEntry("A")) + try store.save(makeEntry("B")) + try store.save(makeEntry("C")) + try store.eraseAll() + #expect(store.entries.isEmpty) + + let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) + reopened.start() + #expect(reopened.entries.isEmpty) + } + + @Test func exportThenImportRoundTrips() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + try store.save(makeEntry("One")) + try store.save(makeEntry("Two")) + let archiveData: Data = try store.exportArchiveData() + + // Import into a fresh, empty store. + let (other, otherDir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: otherDir) } + let added: Int = try other.importArchive(from: archiveData) + #expect(added == 2) + #expect(other.entries.map(\.name) == ["One", "Two"]) + } + + @Test func importColludingIdGetsFreshId() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + let entry: RigEntry = makeEntry("Shared") + try store.save(entry) + + // An archive carrying the SAME id must not overwrite the existing rig on import. + let archive: RigArchive = RigArchive(rigs: [entry]) + let data: Data = try JSONEncoder().encode(archive) + let added: Int = try store.importArchive(from: data) + #expect(added == 1) + #expect(store.entries.count == 2, "colliding id should be imported as a new entry") + } + + @Test func importLegacySingleRigFile() throws { + let (store, dir): (RigLibraryStore, URL) = makeStore() + defer { try? FileManager.default.removeItem(at: dir) } + + // A legacy file is a bare ShoeGazeState (no `rigs` array). + let legacyState: ShoeGazeState = ShoeGazeState(boards: [BoardState(label: "Legacy", segments: [])]) + let data: Data = try JSONEncoder().encode(legacyState) + let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered") + #expect(added == 1) + #expect(store.entries.first?.name == "Recovered") + } +} diff --git a/docs/plans/1.2-rig-library.md b/docs/plans/1.2-rig-library.md new file mode 100644 index 0000000..c68b62e --- /dev/null +++ b/docs/plans/1.2-rig-library.md @@ -0,0 +1,69 @@ +# Rig Library (iCloud-synced rigs) + +Replaces the single hand-saved rig file with a managed **library of named rigs** persisted in app +storage and synced across devices and both apps via a shared iCloud container. A rig is a whole +session (`ShoeGazeState`) and may contain multiple boards. + +## What shipped + +**Core (`LyrebirdShoeGaze/Presets/`)** +- `RigEntry` — a named, timestamped `ShoeGazeState` (rig-level analogue of `BoardVersion`). +- `RigArchive` — a portable bundle of many `RigEntry` in one JSON file (Export/Import Archive). A + legacy single-rig file (bare `ShoeGazeState`) imports as a one-rig archive. +- `RigLibraryLocation` — resolves the library directory: shared iCloud container `Documents/Rigs/` + when available, else local Application Support (`LyrebirdShoeGaze/Rigs/`). +- `RigLibraryStore` (`@MainActor @Observable`) — one JSON file per rig + (`-.json`); save/delete/duplicate/rename/eraseAll/import/export. iCloud + reads/writes are coordinated via `NSFileCoordinator`; remote changes are watched with + `NSMetadataQuery` so a rig saved on one device appears on another live. +- `ShoeGaze.loadRig(from: ShoeGazeState)` overload + `ShoeGaze.captureEntry(name:id:)`. +- `sanitizePresetFilename` factored out of `BoardVersionStore` and shared. + +**UI (`LyrebirdShoeGazeUI/`)** +- `RigLibrarySidebarView` — persistent left listing; rows show name + timestamp, context menu + (Rename / Duplicate / Delete), bottom bar (New / Save / Save As / ⋯ → Import / Export / Erase + All), and an iCloud status glyph. +- `RigNamePrompt` — shared name-entry alert (New / Save As / Rename / Duplicate). +- `RigLibraryBootstrap` — one-call shell setup: resolve location, start the store, seed it from the + working rig on first run, resolve the launch highlight. +- `ShoeGazeBuilderView` gains the sidebar; selecting a rig **replaces** the current session + (engine stopped/restarted around the rebuild). The old single-rig Save/Load is gone; the File + menu / sidebar now do whole-library **Archive** import/export. + +**Shells / entitlements** +- macOS `AppDelegate` and iOS app model own + start the store and pass it to the view; macOS File + menu = Export/Import Archive. +- Both builder targets carry the iCloud entitlement for container + `iCloud.net.realizedsound.ShoeGazeData`; `NSUbiquitousContainers` exposes `Documents/Rigs` in the + Files app. + +## Manual provisioning (required before iCloud sync works) + +Code is in place but signing is not provisionable from here. In Xcode, for **both** builder targets +(`ShoeGazeBuilder`, `ShoeGazeBuilderiOS`), under Signing & Capabilities: +1. Confirm the **iCloud** capability is present with **iCloud Documents** checked and the container + `iCloud.net.realizedsound.ShoeGazeData` selected (entitlement files already declare it). +2. Register that container on **both** App IDs in the developer account (same Team `HE5VJFE9E4`). +3. Build signed to a device/Mac signed into iCloud to verify cross-device sync. + +If iCloud is unavailable the library transparently falls back to local storage (no sync) — the app +still works; the sidebar shows the `icloud.slash` glyph. + +## Notes / follow-ups + +- Editing a loaded rig does not auto-save to its library entry — Save is explicit. `RigStore` + autosave still preserves unsaved working state across restarts. + +### Known limitations / deferred (from pre-PR review) + +- **Main-thread iCloud I/O.** `RigLibraryLocation.resolve()` does a blocking ubiquity lookup, and + `RigLibraryStore`'s `NSFileCoordinator` reads/writes run on the main actor. Mitigated for the + common case: `resolve()` short-circuits to local (no blocking call) when no iCloud account is + signed in, and coordinated writes only happen on explicit, occasional user saves. A full fix + needs an async resolve + a loading state in the builder, and must move seeding *after* the iCloud + state is known — otherwise a first-launch seed races the synced library and creates a spurious + "Default" rig on every device. Deferred deliberately. +- **`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. +- Possible later work: conflict UI for simultaneous multi-device edits; the async-resolve redesign + above.