From dc42db0c594395781bce3b047c7e37240bb34fb2 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 17:56:10 -0700 Subject: [PATCH 1/5] 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. From e8e134499da2fcd3e2093a04d40b4c2243c560e4 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 18:04:55 -0700 Subject: [PATCH 2/5] Add macOS New/Save Rig menu items and save-on-switch prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - macOS File menu gains New Rig (⌘N) and Save Rig (⌘S), which forward to the in-window builder via shoeGazeNewRig / shoeGazeSaveRig notifications so the naming prompt and current-rig highlight update correctly. - Selecting a different rig while the current one has unsaved changes now prompts Save / Don't Save / Cancel (both platforms). Dirtiness is captureState() != the loaded entry's state; a backing-less working rig with boards counts as dirty. - Generalize saveCurrentRig to take a completion (used by Save & Clear and by save-then-switch). Co-Authored-By: Claude Opus 4.8 --- Demo/ShoeGazeBuilder/AppDelegate.swift | 17 ++++- .../RigLibraryCommands.swift | 19 ++++++ .../ShoeGazeBuilderView.swift | 65 +++++++++++++++++-- docs/plans/1.2-rig-library.md | 10 ++- 4 files changed, 99 insertions(+), 12 deletions(-) create mode 100644 Sources/LyrebirdShoeGazeUI/RigLibraryCommands.swift diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index b8ec574..3cb2c2d 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -198,8 +198,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { mainMenu.addItem(fileMenuItem) let fileMenu: NSMenu = NSMenu(title: "File") fileMenuItem.submenu = fileMenu - // 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. + // Per-rig commands forward to the in-window builder (which owns the current-rig state and + // the naming prompts) via notifications. + addItem(to: fileMenu, title: "New Rig", action: #selector(newRigAction(_:)), key: "n") + addItem(to: fileMenu, title: "Save Rig", action: #selector(saveRigAction(_:)), key: "s") + fileMenu.addItem(NSMenuItem.separator()) + // 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") @@ -250,6 +254,15 @@ final class AppDelegate: NSObject, NSApplicationDelegate { // MARK: - Menu actions + @objc private func newRigAction(_ sender: Any?) { + // Forward to the builder view, which owns the current-rig state and naming prompt. + NotificationCenter.default.post(name: .shoeGazeNewRig, object: nil) + } + + @objc private func saveRigAction(_ sender: Any?) { + NotificationCenter.default.post(name: .shoeGazeSaveRig, object: nil) + } + @objc private func exportArchiveAction(_ sender: Any?) { let panel: NSSavePanel = NSSavePanel() panel.allowedContentTypes = [.json] diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryCommands.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryCommands.swift new file mode 100644 index 0000000..a8a7c7a --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryCommands.swift @@ -0,0 +1,19 @@ +// RigLibraryCommands.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Notifications the macOS app shell posts from its menu bar so the in-window +/// ``ShoeGazeBuilderView`` — which owns the current-rig state — performs the action with the +/// correct UI (naming prompts, highlight updates). iOS has no menu bar and simply never posts them. +public extension Notification.Name { + + /// Save the current rig to the library (overwrites the loaded entry, or prompts for a name). + static let shoeGazeSaveRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.saveRig") + + /// Create a new, named, empty rig and make it current. + static let shoeGazeNewRig: Notification.Name = Notification.Name("net.realizedsound.shoegaze.newRig") +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 47d2358..b699dbd 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -111,6 +111,11 @@ public struct ShoeGazeBuilderView: View { /// Confirmation dialog for the "Erase All Rigs" library action. @State private var showEraseAllDialog: Bool = false + /// Save-before-switch prompt: the rig the user asked to switch to while the current rig has + /// unsaved changes, and the flag presenting the dialog. + @State private var pendingSwitchEntry: RigEntry? + @State private var showSwitchSaveDialog: 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 @@ -197,13 +202,37 @@ public struct ShoeGazeBuilderView: View { Text("This permanently removes every saved rig from the library" + (library.isICloud ? " on all your devices." : ".")) } + .confirmationDialog( + "Save changes to the current rig?", + isPresented: $showSwitchSaveDialog, + titleVisibility: .visible, + presenting: pendingSwitchEntry + ) { target in + Button("Save") { + pendingSwitchEntry = nil + saveCurrentRig(then: { loadEntry(target) }) + } + Button("Don't Save", role: .destructive) { + pendingSwitchEntry = nil + loadEntry(target) + } + Button("Cancel", role: .cancel) { pendingSwitchEntry = nil } + } message: { target in + Text("Switching to \"\(target.name)\" will discard unsaved changes to the current rig.") + } + .onReceive(NotificationCenter.default.publisher(for: .shoeGazeSaveRig)) { _ in + saveCurrentRig() + } + .onReceive(NotificationCenter.default.publisher(for: .shoeGazeNewRig)) { _ in + promptNewRig() + } .confirmationDialog( "Clear all boards?", isPresented: $showClearDialog, titleVisibility: .visible ) { Button("Save & Clear") { - saveCurrentRig(thenClear: true) + saveCurrentRig(then: { performClear() }) } Button("Clear Without Saving", role: .destructive) { performClear() @@ -229,7 +258,7 @@ public struct ShoeGazeBuilderView: View { RigLibrarySidebarView( store: library, currentRigID: $currentRigID, - onSelect: { entry in loadEntry(entry) }, + onSelect: { entry in requestLoad(entry) }, onNew: { promptNewRig() }, onSave: { saveCurrentRig() }, onSaveAs: { promptSaveAs() }, @@ -700,16 +729,38 @@ public struct ShoeGazeBuilderView: View { transportTick.toggle() } + /// Switches to `entry`, prompting to save first when the current rig has unsaved changes. + /// No-op when `entry` is already the current rig. + private func requestLoad(_ entry: RigEntry) { + guard entry.id != currentRigID else { return } + if isCurrentRigDirty() { + pendingSwitchEntry = entry + showSwitchSaveDialog = true + } else { + loadEntry(entry) + } + } + + /// Whether the working rig differs from the library entry it was loaded from. A working rig with + /// no backing entry counts as dirty when it has any boards. + private func isCurrentRigDirty() -> Bool { + guard let id: UUID = currentRigID, + let entry: RigEntry = library.entries.first(where: { $0.id == id }) else { + return !shoeGaze.boards.isEmpty + } + return shoeGaze.captureState() != entry.state + } + /// 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() } : { } + /// - Parameter completion: Runs only after a successful save (e.g. clear the boards, or load the + /// rig the user was switching to). Cancelling the name prompt cancels it too — no save, no + /// follow-up. + private func saveCurrentRig(then completion: @escaping () -> Void = { }) { 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. + // No current entry — prompt for a name; the follow-up runs only on commit. namePrompt = RigNamePrompt( title: "Save Rig As", initialText: currentRigName() ?? defaultNewRigName(), diff --git a/docs/plans/1.2-rig-library.md b/docs/plans/1.2-rig-library.md index c68b62e..09cde92 100644 --- a/docs/plans/1.2-rig-library.md +++ b/docs/plans/1.2-rig-library.md @@ -27,12 +27,16 @@ session (`ShoeGazeState`) and may contain multiple boards. - `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. + (engine stopped/restarted around the rebuild). When the current rig has unsaved changes + (`captureState()` differs from its library entry), switching first prompts **Save / + Don't Save / Cancel** (both platforms). 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. + menu = New Rig (⌘N), Save Rig (⌘S), Export/Import Archive (⌘E/⌘I). The per-rig menu items forward + to the builder view via `Notification.Name` (`shoeGazeNewRig` / `shoeGazeSaveRig`) so naming + prompts and the current-rig highlight stay in the view that owns that state. - Both builder targets carry the iCloud entitlement for container `iCloud.net.realizedsound.ShoeGazeData`; `NSUbiquitousContainers` exposes `Documents/Rigs` in the Files app. From 849240e6e20d556283f44c64ae7e7208e3a9f9f1 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 19:40:02 -0700 Subject: [PATCH 3/5] Make rig saves non-blocking (background disk I/O) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Save/delete/eraseAll now update the in-memory entries on the main actor immediately and run the file write/delete — including NSFileCoordinator — on a serial background queue, removing the UI stall the synchronous coordinated write caused (especially on the iCloud path). - Encoding stays synchronous so encode errors still surface to the caller; only the disk write is deferred (logs on failure). - File-system helpers and coordinated I/O are now nonisolated static so the background queue can call them without touching actor state. - Add flushPendingWrites() to drain the queue; called by tests asserting on-disk state and by both app shells at termination / background. Co-Authored-By: Claude Opus 4.8 --- Demo/ShoeGazeBuilder/AppDelegate.swift | 2 + .../ShoeGazeBuilderiOSAppModel.swift | 3 + .../Presets/RigLibraryStore.swift | 166 +++++++++++------- .../RigLibraryStoreTests.swift | 10 ++ docs/plans/1.2-rig-library.md | 17 +- 5 files changed, 123 insertions(+), 75 deletions(-) diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index 3cb2c2d..664dcbe 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -156,6 +156,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { func applicationWillTerminate(_ notification: Notification) { RigStore.save(shoeGaze) + // Ensure any in-flight background rig-library writes finish before exit. + library.flushPendingWrites() engine.stop() } diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index 83fac10..bc7c830 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -91,6 +91,9 @@ final class ShoeGazeBuilderiOSAppModel { /// Persists the current rig. Call when the app moves to the background. func save() { RigStore.save(shoeGaze) + // Flush any in-flight background rig-library writes while we still have time in the + // background. + library.flushPendingWrites() } // MARK: - Audio session / engine construction diff --git a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift index bd782bc..2ca26c9 100644 --- a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift @@ -61,8 +61,15 @@ public final class RigLibraryStore { /// Retained NotificationCenter tokens for the metadata-query observers. @ObservationIgnored private var observerTokens: [NSObjectProtocol] = [] + /// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the + /// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the + /// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on + /// the same file — in submission order. + @ObservationIgnored private let ioQueue: DispatchQueue = + DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility) + /// File extension of a stored rig. - private static let fileExtension: String = "json" + private nonisolated static let fileExtension: String = "json" // MARK: - Init @@ -120,46 +127,73 @@ public final class RigLibraryStore { /// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`). /// /// - Parameter entry: The rig entry to persist. - /// - Throws: `JSONEncoder`, `NSFileCoordinator`, or write errors. + /// - Throws: `JSONEncoder` errors (encoding happens synchronously). The actual file write runs + /// asynchronously on a background queue and only logs on failure — call + /// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination). public func save(_ entry: RigEntry) throws { - // 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) - } + // Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then + // update the in-memory list immediately and push the disk write to the background queue. let data: Data = try encode(entry) - try writeData(data, to: fileURL(for: entry)) + let target: URL = fileURL(for: entry) + let directory: URL = self.directory + let id: UUID = entry.id + let coordinated: Bool = isICloud 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() { + ioQueue.async { + // Remove any prior file for this id first (a rename changes the name-prefixed filename). + if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory), + stale.standardizedFileURL != target.standardizedFileURL { + try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated) + } do { - try removeFile(at: url) + try RigLibraryStore.writeData(data, to: target, coordinated: coordinated) } catch { - if firstError == nil { firstError = error } + print("[RigLibraryStore] save write failed: \(error)") } } + } + + /// Deletes `entry` from memory immediately and removes its file on the background queue. + /// + /// - Parameter entry: The rig entry to remove. + /// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are + /// logged on the background queue. + public func delete(_ entry: RigEntry) throws { + entries.removeAll { $0.id == entry.id } + let directory: URL = self.directory + let id: UUID = entry.id + let coordinated: Bool = isICloud + ioQueue.async { + if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) { + do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) } + catch { print("[RigLibraryStore] delete failed: \(error)") } + } + } + } + + /// Clears the library in memory immediately and removes every rig file on the background queue. + /// + /// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are + /// logged on the background queue. + public func eraseAll() throws { entries.removeAll() - if let firstError: Error = firstError { throw firstError } + let directory: URL = self.directory + let coordinated: Bool = isICloud + ioQueue.async { + for url: URL in RigLibraryStore.rigFileURLs(in: directory) { + do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) } + catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") } + } + } + } + + /// Blocks until all queued background writes/deletes have completed. + /// + /// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure + /// the last save reaches disk before exit). Avoid calling on the main thread during normal use — + /// that would reintroduce the very stall this design removes. + public func flushPendingWrites() { + ioQueue.sync { } } /// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it, @@ -249,11 +283,12 @@ public final class RigLibraryStore { /// 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 { + let decoder: JSONDecoder = makeDecoder() + for url: URL in RigLibraryStore.rigFileURLs(in: directory) { + guard let data: Data = try? RigLibraryStore.readData(at: url, coordinated: isICloud) else { continue } + guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue } loaded.append(entry) } entries = RigLibraryStore.sorted(loaded) @@ -299,7 +334,7 @@ public final class RigLibraryStore { for index: Int in 0...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) } + /// change the name prefix) are still located. `nil` if no file is present. `static` so the + /// background I/O queue can call it without touching actor state. + private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? { + let suffix: String = "-\(id.uuidString).\(fileExtension)" + return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) } } - /// All `*.json` files currently in the directory (hidden iCloud placeholders excluded). - private func rigFileURLs() -> [URL] { + /// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded). + private nonisolated static func rigFileURLs(in directory: URL) -> [URL] { let contents: [URL] = (try? FileManager.default.contentsOfDirectory( at: directory, includingPropertiesForKeys: nil, options: .skipsHiddenFiles )) ?? [] - return contents.filter { $0.pathExtension == RigLibraryStore.fileExtension } + return contents.filter { $0.pathExtension == fileExtension } } - /// Whether `url` is a rig file inside this library's directory. - private func isInLibrary(_ url: URL) -> Bool { + /// Whether `url` is a rig file directly inside `directory`. + private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool { url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL - && url.pathExtension == RigLibraryStore.fileExtension + && url.pathExtension == fileExtension } - // MARK: - Coordinated I/O + // MARK: - Coordinated I/O (background-queue safe) /// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed. - private func writeData(_ data: Data, to url: URL) throws { - guard isICloud else { + private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws { + guard coordinated else { try data.write(to: url, options: .atomic) return } - try coordinate(url, options: .forReplacing) { target in + try coordinateWriting(url, options: .forReplacing) { target in try data.write(to: target, options: .atomic) } } /// Reads the contents of `url`, coordinating the read when iCloud-backed. - private func readData(at url: URL) throws -> Data { - guard isICloud else { + private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data { + guard coordinated else { return try Data(contentsOf: url) } var result: Data = Data() - try coordinate(url, options: .withoutChanges) { target in + try coordinateReading(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 { + private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws { + guard coordinated else { try FileManager.default.removeItem(at: url) return } - try coordinate(url, options: .forDeleting) { target in + try coordinateWriting(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( + /// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error + /// and any error thrown by `body`. + private nonisolated static func coordinateWriting( _ url: URL, options: NSFileCoordinator.WritingOptions, _ body: (URL) throws -> Void @@ -400,8 +430,8 @@ public final class RigLibraryStore { if let thrown: Error = thrown { throw thrown } } - /// Coordinated read overload (uses the reading coordinator path). - private func coordinate( + /// Runs `body` inside an `NSFileCoordinator` read block. + private nonisolated static func coordinateReading( _ url: URL, options: NSFileCoordinator.ReadingOptions, _ body: (URL) throws -> Void diff --git a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift index 2275a93..68ea1ee 100644 --- a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift +++ b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift @@ -40,6 +40,7 @@ struct RigLibraryStoreTests { // Sorted by name, case-insensitive. #expect(store.entries.map(\.name) == ["Ambient", "Crunch"]) + store.flushPendingWrites() // A fresh store over the same directory sees the persisted files. let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) reopened.start() @@ -59,6 +60,7 @@ struct RigLibraryStoreTests { #expect(store.entries.count == 1) #expect(store.entries.first?.name == "Renamed") + store.flushPendingWrites() let files: [URL] = try FileManager.default.contentsOfDirectory( at: dir, includingPropertiesForKeys: nil ).filter { $0.pathExtension == "json" } @@ -74,6 +76,7 @@ struct RigLibraryStoreTests { let renamed: RigEntry = try store.rename(entry, to: "After") #expect(renamed.id == entry.id) #expect(store.entries.map(\.name) == ["After"]) + store.flushPendingWrites() } @Test func duplicateCreatesIndependentEntry() throws { @@ -85,6 +88,7 @@ struct RigLibraryStoreTests { let copy: RigEntry = try store.duplicate(entry, newName: "Base 2") #expect(copy.id != entry.id) #expect(store.entries.count == 2) + store.flushPendingWrites() } @Test func deleteRemovesFileAndEntry() throws { @@ -96,6 +100,7 @@ struct RigLibraryStoreTests { try store.delete(entry) #expect(store.entries.isEmpty) + store.flushPendingWrites() let files: [URL] = try FileManager.default.contentsOfDirectory( at: dir, includingPropertiesForKeys: nil ).filter { $0.pathExtension == "json" } @@ -112,6 +117,7 @@ struct RigLibraryStoreTests { try store.eraseAll() #expect(store.entries.isEmpty) + store.flushPendingWrites() let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) reopened.start() #expect(reopened.entries.isEmpty) @@ -131,6 +137,8 @@ struct RigLibraryStoreTests { let added: Int = try other.importArchive(from: archiveData) #expect(added == 2) #expect(other.entries.map(\.name) == ["One", "Two"]) + store.flushPendingWrites() + other.flushPendingWrites() } @Test func importColludingIdGetsFreshId() throws { @@ -146,6 +154,7 @@ struct RigLibraryStoreTests { 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") + store.flushPendingWrites() } @Test func importLegacySingleRigFile() throws { @@ -158,5 +167,6 @@ struct RigLibraryStoreTests { let added: Int = try store.importArchive(from: data, legacyRigName: "Recovered") #expect(added == 1) #expect(store.entries.first?.name == "Recovered") + store.flushPendingWrites() } } diff --git a/docs/plans/1.2-rig-library.md b/docs/plans/1.2-rig-library.md index 09cde92..37f5ce7 100644 --- a/docs/plans/1.2-rig-library.md +++ b/docs/plans/1.2-rig-library.md @@ -60,13 +60,16 @@ still works; the sidebar shows the `icloud.slash` glyph. ### 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. +- **Background writes.** Save/delete/erase update the in-memory `entries` on the main actor + instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a + serial background queue (`ioQueue`). `flushPendingWrites()` drains it (used by tests and at app + termination / iOS background). This removed the save-time UI stall. +- **Remaining main-thread I/O.** `RigLibraryLocation.resolve()` still does a blocking ubiquity + lookup (short-circuited to local when no iCloud account is signed in), and the *reads* in + `reloadFromDirectory()` (launch + iCloud metadata updates) are still synchronous on the main + actor. 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 From 9a8e5461c05b4e70109a676a6df22bd97ab7892b Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 19:50:38 -0700 Subject: [PATCH 4/5] Make rig library loads/resolve fully off-main MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move the remaining synchronous main-thread I/O off the main actor: - RigLibraryStore now constructs instantly with a local placeholder and exposes an awaitable async start(): it resolves the iCloud-or-local location off-main (the blocking ubiquity lookup), loads entries off-main via the shared ioQueue (so a reload can't drop a just-saved rig), then sets isLoaded. reload() is async; iCloud metadata updates re-read via it. - Seeding moves into RigLibraryBootstrap.start(_:seedFrom:), which seeds a "Default" rig only AFTER the (possibly iCloud) library has loaded and is still empty — preventing a duplicate "Default" on every synced device on first launch. - Sidebar shows a Loading state until isLoaded; the builder restores the persisted current-rig highlight when isLoaded flips true (initialRigID param dropped). - Shells construct the store synchronously and start it asynchronously (macOS via Task in didFinishLaunching; iOS via .task). Codec + file helpers are nonisolated static so background work needs no actor hop. - Tests await store.start(). Full suite: 206 passing. Co-Authored-By: Claude Opus 4.8 --- Demo/ShoeGazeBuilder/AppDelegate.swift | 18 ++-- .../ShoeGazeBuilderiOSApp.swift | 2 +- .../ShoeGazeBuilderiOSAppModel.swift | 17 ++-- .../Presets/RigLibraryStore.swift | 98 ++++++++++++++----- .../RigLibraryBootstrap.swift | 73 ++++++-------- .../RigLibrarySidebarView.swift | 10 +- .../ShoeGazeBuilderView.swift | 23 +++-- .../RigLibraryStoreTests.swift | 46 ++++----- docs/plans/1.2-rig-library.md | 21 ++-- 9 files changed, 175 insertions(+), 133 deletions(-) diff --git a/Demo/ShoeGazeBuilder/AppDelegate.swift b/Demo/ShoeGazeBuilder/AppDelegate.swift index 664dcbe..d7be091 100644 --- a/Demo/ShoeGazeBuilder/AppDelegate.swift +++ b/Demo/ShoeGazeBuilder/AppDelegate.swift @@ -55,9 +55,8 @@ 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`. + /// The rig library; constructed in `init`, resolved + loaded asynchronously after launch. private let library: RigLibraryStore - private let initialRigID: UUID? /// Record toggle item, retained so `validateMenuItem(_:)` can flip its title + enabled state. private var recordMenuItem: NSMenuItem? @@ -88,14 +87,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate { ) // Stored `let`s must be set before `super.init()`. Restore the autosaved working rig (or - // 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`). + // seed a board) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super). if !RigStore.restore(into: shoeGaze) { AppDelegate.seedInitialBoard(into: shoeGaze) } - let bootstrap: RigLibraryBootstrap.Result = RigLibraryBootstrap.make(for: shoeGaze) - self.library = bootstrap.store - self.initialRigID = bootstrap.initialRigID + // The library constructs instantly; it resolves iCloud + loads asynchronously after launch. + self.library = RigLibraryBootstrap.makeStore() super.init() } @@ -120,16 +117,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let session: ShoeGaze = shoeGaze let driver: CoreAudioDriver = coreDriver let rigLibrary: RigLibraryStore = library - let startupRigID: UUID? = initialRigID window.open { ShoeGazeBuilderView( shoeGaze: session, library: rigLibrary, - initialRigID: startupRigID, hardwareSampleRate: { driver.deviceSampleRate } ) } anchorWindowLeft() + + // Resolve iCloud + load the library off the main thread, then seed from the working rig if + // it is still empty (first run). + let rigSession: ShoeGaze = shoeGaze + Task { await RigLibraryBootstrap.start(rigLibrary, seedFrom: rigSession) } } /// Anchors the window `leftMargin` points from the left of the visible screen and sizes it to diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift index 56d635f..e3b2479 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSApp.swift @@ -27,12 +27,12 @@ struct ShoeGazeBuilderiOSApp: App { ShoeGazeBuilderView( shoeGaze: model.shoeGaze, library: model.library, - initialRigID: model.initialRigID, hardwareSampleRate: { model.hardwareSampleRate }, onEnableLiveInput: { model.enableLiveInput() } ) .navigationTitle("ShoeGaze Builder") .navigationBarTitleDisplayMode(.inline) + .task { await model.startLibrary() } } .onDisappear { model.stop() } } diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index bc7c830..2899ef4 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -56,14 +56,10 @@ final class ShoeGazeBuilderiOSAppModel { /// 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 + /// Resolves iCloud + loads the library off the main thread, then seeds it from the working rig + /// on first run. Call once from the app's `.task`. Safe to call again (no-op once non-empty). + func startLibrary() async { + await RigLibraryBootstrap.start(library, seedFrom: shoeGaze) } // MARK: - Init @@ -84,8 +80,9 @@ final class ShoeGazeBuilderiOSAppModel { 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 + // Construct the library instantly; it resolves iCloud + loads asynchronously via + // startLibrary() from the app's .task. + self.library = RigLibraryBootstrap.makeStore() } /// Persists the current rig. Call when the app moves to the background. diff --git a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift index 2ca26c9..3a7b1a9 100644 --- a/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift +++ b/Sources/LyrebirdShoeGaze/Presets/RigLibraryStore.swift @@ -47,11 +47,17 @@ public final class RigLibraryStore { 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 + /// local-only fallback. Resolved during ``start()`` for an auto-resolving store. + public private(set) var isICloud: Bool - /// The directory holding the per-rig JSON files. - public let directory: URL + /// The directory holding the per-rig JSON files. May be repointed from local to iCloud during + /// ``start()`` for an auto-resolving store (before any writes, so no migration is needed). + public private(set) var directory: URL + + /// `false` until the first load completes. Views can show a loading state and callers should + /// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a + /// first-launch seed would race a not-yet-loaded iCloud library. + public private(set) var isLoaded: Bool = false // MARK: - Private @@ -71,10 +77,14 @@ public final class RigLibraryStore { /// File extension of a stored rig. private nonisolated static let fileExtension: String = "json" + /// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and + /// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer. + private let autoResolve: Bool + // MARK: - Init - /// Creates a store rooted at an explicit directory. Designated initializer; used directly by - /// tests with a temporary directory and `isICloud: false`. + /// Creates a store rooted at an explicit directory. Used directly by tests with a temporary + /// directory; `start()` will not re-resolve the location. /// /// - Parameters: /// - directory: The directory holding per-rig JSON files. Created if it does not exist. @@ -86,25 +96,60 @@ public final class RigLibraryStore { ) { self.directory = directory self.isICloud = isICloud + self.autoResolve = false 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) + /// Creates an auto-resolving store. Constructed instantly with a local placeholder directory; + /// ``start()`` resolves the real iCloud-or-local location off the main thread before loading. + public init() { + self.directory = RigLibraryLocation.localDirectory() + self.isICloud = false + self.autoResolve = true } // MARK: - Lifecycle - /// Loads the current library contents and, when iCloud-backed, begins watching for remote - /// changes. Safe to call once after construction. - public func start() { - reloadFromDirectory() + /// Resolves the location (off the main thread, for an auto-resolving store), loads the current + /// library contents (off the main thread), and — when iCloud-backed — begins watching for + /// remote changes. Awaitable so callers can seed/highlight only once the real library state is + /// known. Safe to call once after construction. + public func start() async { + if autoResolve { + let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain() + directory = resolved.directory + isICloud = resolved.isICloud + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } if isICloud { startMetadataQuery() } + await reload() + isLoaded = true + } + + /// Re-reads the library directory off the main thread and republishes `entries`. Ordered after + /// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops + /// the just-saved rig. + public func reload() async { + let dir: URL = directory + let coordinated: Bool = isICloud + let loaded: [RigEntry] = await withCheckedContinuation { continuation in + ioQueue.async { + continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated)) + } + } + entries = RigLibraryStore.sorted(loaded) + } + + /// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup + /// never runs on the main thread. + private static func resolveOffMain() async -> RigLibraryLocation.Resolved { + await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + continuation.resume(returning: RigLibraryLocation.resolve()) + } + } } /// Stops watching for remote changes and removes observers. Call when tearing the store down; @@ -239,7 +284,7 @@ public final class RigLibraryStore { /// - Throws: `JSONEncoder` errors. public func exportArchiveData() throws -> Data { let archive: RigArchive = RigArchive(rigs: entries) - return try makeEncoder().encode(archive) + return try RigLibraryStore.makeEncoder().encode(archive) } /// Imports rigs from archive `data`, saving each into the library, and returns how many were @@ -281,17 +326,15 @@ public final class RigLibraryStore { /// 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() { + private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] { var loaded: [RigEntry] = [] let decoder: JSONDecoder = makeDecoder() - for url: URL in RigLibraryStore.rigFileURLs(in: directory) { - guard let data: Data = try? RigLibraryStore.readData(at: url, coordinated: isICloud) else { - continue - } + for url: URL in rigFileURLs(in: directory) { + guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue } guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue } loaded.append(entry) } - entries = RigLibraryStore.sorted(loaded) + return loaded } // MARK: - iCloud metadata query @@ -341,7 +384,8 @@ public final class RigLibraryStore { try? fileManager.startDownloadingUbiquitousItem(at: url) } } - reloadFromDirectory() + // Re-read off the main thread; the in-memory list republishes when it completes. + Task { await self.reload() } } // MARK: - File helpers @@ -450,11 +494,11 @@ public final class RigLibraryStore { /// Encodes a single entry as a per-rig file would store it. private func encode(_ entry: RigEntry) throws -> Data { - try makeEncoder().encode(entry) + try RigLibraryStore.makeEncoder().encode(entry) } /// A JSON encoder configured for human-readable, round-trip-stable preset files. - private func makeEncoder() -> JSONEncoder { + private nonisolated static func makeEncoder() -> JSONEncoder { let encoder: JSONEncoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] encoder.dateEncodingStrategy = .secondsSince1970 @@ -462,7 +506,7 @@ public final class RigLibraryStore { } /// A JSON decoder matching ``makeEncoder()``. - private func makeDecoder() -> JSONDecoder { + private nonisolated static func makeDecoder() -> JSONDecoder { let decoder: JSONDecoder = JSONDecoder() decoder.dateDecodingStrategy = .secondsSince1970 return decoder @@ -474,7 +518,7 @@ public final class RigLibraryStore { _ data: Data, legacyRigName: String ) throws -> [RigEntry] { - let decoder: JSONDecoder = makeDecoder() + let decoder: JSONDecoder = RigLibraryStore.makeDecoder() if let archive: RigArchive = try? decoder.decode(RigArchive.self, from: data) { return archive.rigs } diff --git a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift index c367786..af88b34 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibraryBootstrap.swift @@ -7,61 +7,48 @@ import Foundation import LyrebirdShoeGaze -/// One-call setup of the rig library for an app shell. +/// Setup of the rig library for an app shell, split so nothing blocks the launch path. /// -/// Resolves the (iCloud-or-local) library location, constructs and starts a ``RigLibraryStore``, -/// 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. +/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous +/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work — +/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the +/// library from the current working rig **only after** the real (possibly iCloud) contents are +/// known, so a first launch can't create a duplicate "Default" rig on every synced device. @MainActor 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? + /// Creates an auto-resolving store. Construct this synchronously at launch; call + /// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`). + public static func makeStore() -> RigLibraryStore { + RigLibraryStore() } - /// 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. + /// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still + /// empty after loading (first run). Idempotent enough to call once at launch. /// /// - Parameters: + /// - store: The store from ``makeStore()``. /// - 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, + public static func start( + _ store: RigLibraryStore, + seedFrom shoeGaze: ShoeGaze, seedName: String = "Default" - ) -> Result { - let resolved: RigLibraryLocation.Resolved = RigLibraryLocation.resolve() - let store: RigLibraryStore = RigLibraryStore(resolved: resolved) - store.start() + ) async { + await 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)") - } + // Seed only after the (possibly iCloud) library has loaded: an empty library here means a + // genuine first run, not a not-yet-synced one. + guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return } + let entry: RigEntry = shoeGaze.captureEntry(name: seedName) + do { + try store.save(entry) + UserDefaults.standard.set( + entry.id.uuidString, + forKey: ShoeGazeBuilderView.currentRigDefaultsKey + ) + } 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 index 348cb9e..1485f68 100644 --- a/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift +++ b/Sources/LyrebirdShoeGazeUI/RigLibrarySidebarView.swift @@ -84,7 +84,15 @@ struct RigLibrarySidebarView: View { private var rigList: some View { ScrollView(.vertical, showsIndicators: true) { LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) { - if store.entries.isEmpty { + if !store.isLoaded { + HStack(spacing: 6) { + ProgressView().controlSize(.small) + Text("Loading…") + .font(.caption) + .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) + } + .padding(.vertical, RigLibrarySidebarView.rowPadding) + } else if store.entries.isEmpty { Text("No saved rigs yet.\nTap New or Save to add one.") .font(.caption) .foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity)) diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index b699dbd..abf475f 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -68,7 +68,6 @@ public struct ShoeGazeBuilderView: View { 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). @@ -143,20 +142,17 @@ 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`. + /// - library: The rig library store. The host should `start()` it (e.g. via + /// `RigLibraryBootstrap`); the view shows a loading state until then and highlights the + /// persisted current rig once the library has loaded. 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 } @@ -186,6 +182,7 @@ public struct ShoeGazeBuilderView: View { restoreInputSelection() restoreCurrentRig() } + .onChange(of: library.isLoaded) { restoreCurrentRig() } .onChange(of: currentRigID) { persistCurrentRigID() } .background(boardsSheetAnchor) .background(rigExportAnchor) @@ -695,11 +692,17 @@ public struct ShoeGazeBuilderView: View { // MARK: - Rig library - /// Seeds `currentRigID` from the entry the host restored at launch, once. + /// Highlights the persisted current rig once the library has loaded. Runs once; only sets the + /// highlight when nothing is selected yet and the saved id still exists in the library. private func restoreCurrentRig() { - guard !didRestoreRig else { return } + guard !didRestoreRig, library.isLoaded else { return } didRestoreRig = true - currentRigID = initialRigID + guard currentRigID == nil, + let stored: String = UserDefaults.standard.string( + forKey: ShoeGazeBuilderView.currentRigDefaultsKey), + let id: UUID = UUID(uuidString: stored), + library.entries.contains(where: { $0.id == id }) else { return } + currentRigID = id } /// Persists `currentRigID` so the same rig is highlighted on the next launch. diff --git a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift index 68ea1ee..3980316 100644 --- a/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift +++ b/Tests/LyrebirdShoeGazeTests/RigLibraryStoreTests.swift @@ -19,10 +19,10 @@ struct RigLibraryStoreTests { return url } - private func makeStore() -> (RigLibraryStore, URL) { + private func makeStore() async -> (RigLibraryStore, URL) { let dir: URL = makeTempDirectory() let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) - store.start() + await store.start() return (store, dir) } @@ -30,8 +30,8 @@ struct RigLibraryStoreTests { RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])])) } - @Test func saveAddsEntryAndReloadsAcrossInstances() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func saveAddsEntryAndReloadsAcrossInstances() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } try store.save(makeEntry("Ambient")) @@ -43,13 +43,13 @@ struct RigLibraryStoreTests { store.flushPendingWrites() // A fresh store over the same directory sees the persisted files. let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) - reopened.start() + await reopened.start() #expect(reopened.entries.count == 2) #expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"]) } - @Test func saveSameIdReplacesInPlace() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func saveSameIdReplacesInPlace() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } let entry: RigEntry = makeEntry("Original") @@ -67,8 +67,8 @@ struct RigLibraryStoreTests { #expect(files.count == 1, "rename must not leave the old-name file behind") } - @Test func renameKeepsIdChangesName() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func renameKeepsIdChangesName() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } let entry: RigEntry = makeEntry("Before") @@ -79,8 +79,8 @@ struct RigLibraryStoreTests { store.flushPendingWrites() } - @Test func duplicateCreatesIndependentEntry() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func duplicateCreatesIndependentEntry() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } let entry: RigEntry = makeEntry("Base") @@ -91,8 +91,8 @@ struct RigLibraryStoreTests { store.flushPendingWrites() } - @Test func deleteRemovesFileAndEntry() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func deleteRemovesFileAndEntry() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } let entry: RigEntry = makeEntry("Doomed") @@ -107,8 +107,8 @@ struct RigLibraryStoreTests { #expect(files.isEmpty) } - @Test func eraseAllClearsLibrary() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func eraseAllClearsLibrary() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } try store.save(makeEntry("A")) @@ -119,12 +119,12 @@ struct RigLibraryStoreTests { store.flushPendingWrites() let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false) - reopened.start() + await reopened.start() #expect(reopened.entries.isEmpty) } - @Test func exportThenImportRoundTrips() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func exportThenImportRoundTrips() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } try store.save(makeEntry("One")) @@ -132,7 +132,7 @@ struct RigLibraryStoreTests { let archiveData: Data = try store.exportArchiveData() // Import into a fresh, empty store. - let (other, otherDir): (RigLibraryStore, URL) = makeStore() + let (other, otherDir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: otherDir) } let added: Int = try other.importArchive(from: archiveData) #expect(added == 2) @@ -141,8 +141,8 @@ struct RigLibraryStoreTests { other.flushPendingWrites() } - @Test func importColludingIdGetsFreshId() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func importColludingIdGetsFreshId() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } let entry: RigEntry = makeEntry("Shared") @@ -157,8 +157,8 @@ struct RigLibraryStoreTests { store.flushPendingWrites() } - @Test func importLegacySingleRigFile() throws { - let (store, dir): (RigLibraryStore, URL) = makeStore() + @Test func importLegacySingleRigFile() async throws { + let (store, dir): (RigLibraryStore, URL) = await makeStore() defer { try? FileManager.default.removeItem(at: dir) } // A legacy file is a bare ShoeGazeState (no `rigs` array). diff --git a/docs/plans/1.2-rig-library.md b/docs/plans/1.2-rig-library.md index 37f5ce7..b5a85e8 100644 --- a/docs/plans/1.2-rig-library.md +++ b/docs/plans/1.2-rig-library.md @@ -60,16 +60,19 @@ still works; the sidebar shows the `icloud.slash` glyph. ### Known limitations / deferred (from pre-PR review) -- **Background writes.** Save/delete/erase update the in-memory `entries` on the main actor +- **Off-main I/O end to end.** Save/delete/erase update the in-memory `entries` on the main actor instantly (UI never blocks) and run the file write/delete — including `NSFileCoordinator` — on a - serial background queue (`ioQueue`). `flushPendingWrites()` drains it (used by tests and at app - termination / iOS background). This removed the save-time UI stall. -- **Remaining main-thread I/O.** `RigLibraryLocation.resolve()` still does a blocking ubiquity - lookup (short-circuited to local when no iCloud account is signed in), and the *reads* in - `reloadFromDirectory()` (launch + iCloud metadata updates) are still synchronous on the main - actor. 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. + serial background queue (`ioQueue`). Location resolution (`RigLibraryLocation.resolve()`, the + blocking ubiquity lookup) and the initial/refresh *reads* now also run off the main thread: + `RigLibraryStore` constructs instantly with a local placeholder, and `await start()` resolves the + real iCloud-or-local location, loads via `ioQueue`, then sets `isLoaded`. Reads share `ioQueue` + with writes, so a reload never drops a just-saved rig. `flushPendingWrites()` drains the queue + (tests, app termination / iOS background). +- **Loading + correct first-run seeding.** The sidebar shows a "Loading…" state until `isLoaded`. + `RigLibraryBootstrap.start(_:seedFrom:)` seeds the working rig as "Default" **only after** the + (possibly iCloud) library has loaded and is still empty — so a first launch on a device that + already has synced rigs does not create a duplicate "Default" everywhere. The builder restores the + persisted current-rig highlight once `isLoaded` flips true. - **`eraseAll()`** clears the in-memory list even if a file deletion fails (it still throws the 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 From 6e299b9d381443da71b913f8b8909100f5344f8c Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Sat, 27 Jun 2026 20:11:18 -0700 Subject: [PATCH 5/5] Rework builder layout: scope beside stacked mixer + horizontal pedal picker Reclaim vertical space in ShoeGazeBuilderView. The top section now places the scope + CPU meters on the left (width matched to the mixer's Solo/Blend/All control column) and a right column that stacks the board mixer over a horizontal pedal picker. The board canvas takes the full width below. - PedalPaletteView gains an `axis` parameter: `.vertical` keeps the full-width sidebar column; `.horizontal` lays the catalog out as a row of fixed-width cards for a horizontal scroller. - Remove the old left palette sidebar and the stacked-under-palette scope. Co-Authored-By: Claude Opus 4.8 --- .../LyrebirdShoeGazeUI/PedalPaletteView.swift | 51 +++++++++++- .../ShoeGazeBuilderView.swift | 79 +++++++++++-------- 2 files changed, 97 insertions(+), 33 deletions(-) diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift index 3335f24..04aead2 100644 --- a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -45,6 +45,8 @@ public struct PedalPaletteView: View { private static let rowSubtitleSpacing: CGFloat = 2 /// Opacity of the pedal-row description subtitle. private static let summaryOpacity: Double = 0.55 + /// Fixed card width when laid out horizontally (the vertical layout stretches to fill instead). + private static let horizontalCardWidth: CGFloat = 150 /// Preferred display order for the built-in pedals. Any registered pedal not listed here is /// appended afterwards (sorted) so the palette never silently drops a newly added pedal. @@ -74,19 +76,25 @@ public struct PedalPaletteView: View { private let onAdd: (String) -> Void private let onRouting: (RoutingAction) -> Void + private let axis: Axis // MARK: - Init /// Creates a pedal palette. /// /// - Parameters: + /// - axis: `.vertical` (default) lays the catalog out as a full-width column for a sidebar; + /// `.horizontal` lays it out as a fixed-width-card row for a horizontal scroller. The host + /// wraps the view in a `ScrollView` of the matching axis. /// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain). /// Rows are also `.draggable` carrying `"add:"` for drop-onto-lane targeting. /// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op. public init( + axis: Axis = .vertical, onAdd: @escaping (String) -> Void, onRouting: @escaping (RoutingAction) -> Void = { _ in } ) { + self.axis = axis self.onAdd = onAdd self.onRouting = onRouting } @@ -104,6 +112,14 @@ public struct PedalPaletteView: View { // MARK: - Body public var body: some View { + switch axis { + case .horizontal: horizontalBody + default: verticalBody + } + } + + /// Full-width column for a left sidebar. + private var verticalBody: some View { VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) { VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { sectionTitle("PEDALS") @@ -121,6 +137,22 @@ public struct PedalPaletteView: View { } } + /// Fixed-width-card row for a horizontal scroller: leading PEDALS group, a divider, then the + /// ROUTING group. + private var horizontalBody: some View { + HStack(alignment: .top, spacing: PedalPaletteView.rowSpacing) { + sectionTitle("PEDALS") + ForEach(orderedPedalNames, id: \.self) { name in + pedalRow(name) + } + Divider().overlay(Color.white.opacity(PedalPaletteView.cardBorderOpacity)) + sectionTitle("ROUTING") + ForEach(PedalPaletteView.routingOptions, id: \.title) { option in + routingCard(title: option.title, caption: option.caption, action: option.action) + } + } + } + // MARK: - Subviews private func sectionTitle(_ text: String) -> some View { @@ -158,7 +190,7 @@ public struct PedalPaletteView: View { } .padding(.horizontal, PedalPaletteView.cardPaddingH) .padding(.vertical, PedalPaletteView.cardPaddingV) - .frame(maxWidth: .infinity, alignment: .leading) + .modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth)) .background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness)) } .buttonStyle(.plain) @@ -180,12 +212,27 @@ public struct PedalPaletteView: View { } .padding(.horizontal, PedalPaletteView.cardPaddingH) .padding(.vertical, PedalPaletteView.cardPaddingV) - .frame(maxWidth: .infinity, alignment: .leading) + .modifier(CardFrame(axis: axis, width: PedalPaletteView.horizontalCardWidth)) .background(cardBackground(brightness: PedalPaletteView.routingCardBrightness)) } .buttonStyle(.plain) } + /// Stretches a card to fill width in a vertical column, or pins it to a fixed width in a + /// horizontal row. + private struct CardFrame: ViewModifier { + let axis: Axis + let width: CGFloat + func body(content: Content) -> some View { + switch axis { + case .horizontal: + content.frame(width: width, alignment: .leading) + default: + content.frame(maxWidth: .infinity, alignment: .leading) + } + } + } + private func cardBackground(brightness: Double) -> some View { RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius) .fill(Color(white: brightness)) diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index abf475f..48c58e0 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -43,6 +43,9 @@ public struct ShoeGazeBuilderView: View { private static let minWidth: CGFloat = 720 private static let minHeight: CGFloat = 460 private static let sidebarWidth: CGFloat = 168 + /// Width of the scope/CPU block in the bottom strip — matches `BoardBarView`'s Solo/Blend/All + /// control column so the scope aligns under it. + private static let scopeWidth: CGFloat = 188 private static let columnSpacing: CGFloat = 14 private static let backgroundRed: Double = 0.08 private static let backgroundGreen: Double = 0.07 @@ -268,7 +271,8 @@ public struct ShoeGazeBuilderView: View { ) } - /// The main builder column: transport, IO, boards, palette, board area, scope, and status. + /// The main builder column: transport, IO, the scope-plus-mixer/picker top section, then the + /// board canvas. private var builderColumn: some View { VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { transportRow @@ -277,28 +281,54 @@ public struct ShoeGazeBuilderView: View { recordingRow #endif Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) - BoardBarView( - shoeGaze: shoeGaze, - editingBoardIndex: $selectedBoardIndex, - crossfadeSeconds: $crossfadeSeconds, - onAddBoard: { addBoard() } - ) + topSection Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) - HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) { - paletteSidebar - Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) - boardArea - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - // Scope + CPU meters sit under the pedal palette, matching its width. - ShoeGazeScopeView(shoeGaze: shoeGaze) - .frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading) - LyrebirdStatusView(engine: shoeGaze.engine) - .frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading) + boardArea } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } + /// Top section: the scope + CPU meters on the left (sized to align with the mixer's + /// Solo/Blend/All control column), and a right column stacking the board mixer over the + /// horizontal pedal picker. + private var topSection: some View { + HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) { + VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) { + ShoeGazeScopeView(shoeGaze: shoeGaze) + LyrebirdStatusView(engine: shoeGaze.engine) + } + .frame(width: ShoeGazeBuilderView.scopeWidth, alignment: .leading) + + Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) + + VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { + BoardBarView( + shoeGaze: shoeGaze, + editingBoardIndex: $selectedBoardIndex, + crossfadeSeconds: $crossfadeSeconds, + onAddBoard: { addBoard() } + ) + Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)) + pedalPickerRow + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .fixedSize(horizontal: false, vertical: true) + } + + /// A compact horizontal pedal-picker strip (sits below the board mixer in the top section). + private var pedalPickerRow: some View { + ScrollView(.horizontal, showsIndicators: true) { + PedalPaletteView( + axis: .horizontal, + onAdd: { type in addPedal(type: type) }, + onRouting: { action in performRouting(action) } + ) + .padding(.bottom, 2) + } + .fixedSize(horizontal: false, vertical: true) + } + // MARK: - Presentation anchors /// Hosts the board-manager sheet on its own node so it does not collide with the file @@ -414,19 +444,6 @@ public struct ShoeGazeBuilderView: View { } } - // MARK: - Palette sidebar - - private var paletteSidebar: some View { - ScrollView(.vertical, showsIndicators: true) { - PedalPaletteView( - onAdd: { type in addPedal(type: type) }, - onRouting: { action in performRouting(action) } - ) - .padding(.trailing, 2) - } - .frame(width: ShoeGazeBuilderView.sidebarWidth) - } - // MARK: - Board area private var boardArea: some View {