Merge rig-library: iCloud rig library + builder layout rework
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -55,11 +55,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let window: LyrebirdWindow
|
||||
|
||||
/// The rig library; constructed in `init`, resolved + loaded asynchronously after launch.
|
||||
private let library: RigLibraryStore
|
||||
|
||||
/// 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 +76,29 @@ 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) — operating on `shoeGaze`, not on `self` methods (unavailable pre-super).
|
||||
if !RigStore.restore(into: shoeGaze) {
|
||||
seedInitialBoard()
|
||||
AppDelegate.seedInitialBoard(into: shoeGaze)
|
||||
}
|
||||
// The library constructs instantly; it resolves iCloud + loads asynchronously after launch.
|
||||
self.library = RigLibraryBootstrap.makeStore()
|
||||
|
||||
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,10 +116,20 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
installMainMenu()
|
||||
let session: ShoeGaze = shoeGaze
|
||||
let driver: CoreAudioDriver = coreDriver
|
||||
let rigLibrary: RigLibraryStore = library
|
||||
window.open {
|
||||
ShoeGazeBuilderView(shoeGaze: session, hardwareSampleRate: { driver.deviceSampleRate })
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: session,
|
||||
library: rigLibrary,
|
||||
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
|
||||
@@ -138,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()
|
||||
}
|
||||
|
||||
@@ -180,8 +200,14 @@ 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")
|
||||
// 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")
|
||||
|
||||
// Board menu — add board + transport.
|
||||
let boardMenuItem: NSMenuItem = NSMenuItem()
|
||||
@@ -230,34 +256,42 @@ 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]
|
||||
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)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,5 +28,17 @@
|
||||
<string>ShoeGaze Builder can route a hardware input channel through your pedalboard. Enable microphone access to use Live Input mode.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSUbiquitousContainers</key>
|
||||
<dict>
|
||||
<key>iCloud.net.realizedsound.ShoeGazeData</key>
|
||||
<dict>
|
||||
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
|
||||
<true/>
|
||||
<key>NSUbiquitousContainerName</key>
|
||||
<string>ShoeGaze</string>
|
||||
<key>NSUbiquitousContainerSupportedFolderLevels</key>
|
||||
<string>Any</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -4,5 +4,17 @@
|
||||
<dict>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
<key>com.apple.developer.icloud-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
<key>com.apple.developer.icloud-services</key>
|
||||
<array>
|
||||
<string>CloudDocuments</string>
|
||||
</array>
|
||||
<key>com.apple.developer.ubiquity-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -41,5 +41,17 @@
|
||||
<string>UIInterfaceOrientationLandscapeLeft</string>
|
||||
<string>UIInterfaceOrientationLandscapeRight</string>
|
||||
</array>
|
||||
<key>NSUbiquitousContainers</key>
|
||||
<dict>
|
||||
<key>iCloud.net.realizedsound.ShoeGazeData</key>
|
||||
<dict>
|
||||
<key>NSUbiquitousContainerIsDocumentScopePublic</key>
|
||||
<true/>
|
||||
<key>NSUbiquitousContainerName</key>
|
||||
<string>ShoeGaze</string>
|
||||
<key>NSUbiquitousContainerSupportedFolderLevels</key>
|
||||
<string>Any</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.developer.icloud-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
<key>com.apple.developer.icloud-services</key>
|
||||
<array>
|
||||
<string>CloudDocuments</string>
|
||||
</array>
|
||||
<key>com.apple.developer.ubiquity-container-identifiers</key>
|
||||
<array>
|
||||
<string>iCloud.net.realizedsound.ShoeGazeData</string>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -26,11 +26,13 @@ struct ShoeGazeBuilderiOSApp: App {
|
||||
NavigationStack {
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: model.shoeGaze,
|
||||
library: model.library,
|
||||
hardwareSampleRate: { model.hardwareSampleRate },
|
||||
onEnableLiveInput: { model.enableLiveInput() }
|
||||
)
|
||||
.navigationTitle("ShoeGaze Builder")
|
||||
.navigationBarTitleDisplayMode(.inline)
|
||||
.task { await model.startLibrary() }
|
||||
}
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
@@ -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,28 +49,48 @@ 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 }
|
||||
|
||||
/// 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
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// 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.
|
||||
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
|
||||
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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 `-<uuid>.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
|
||||
/// (`<name>-<uuid>.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<Character> = ["/", "\\", ":", "\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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: `<sanitized-name>-<uuid>.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
|
||||
/// (`<name>-<uuid>.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<Character> = ["/", "\\", ":", "\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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,549 @@
|
||||
// RigLibraryStore.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import Observation
|
||||
|
||||
/// The user's library of saved rigs, persisted as one JSON file per rig and (when available)
|
||||
/// synced across devices and apps through a shared iCloud container.
|
||||
///
|
||||
/// `RigLibraryStore` is `@Observable`, so SwiftUI views refresh automatically as `entries`
|
||||
/// changes — whether the change came from a local edit or from a remote iCloud update. All
|
||||
/// mutations run on the main actor.
|
||||
///
|
||||
/// ## Storage model
|
||||
///
|
||||
/// Each ``RigEntry`` is written as a separate pretty-printed JSON file named
|
||||
/// `<sanitized-name>-<id>.json` (see ``sanitizePresetFilename(_:maxLength:)``) inside the
|
||||
/// directory resolved by ``RigLibraryLocation``. One file per rig keeps iCloud merges
|
||||
/// conflict-free at rig granularity: editing rig A never rewrites rig B's file.
|
||||
///
|
||||
/// When the directory is an iCloud ubiquity container, reads and writes are wrapped in
|
||||
/// `NSFileCoordinator`, and an `NSMetadataQuery` watches for remote changes so a rig saved on one
|
||||
/// device appears on another without relaunching. Call ``start()`` once after construction to load
|
||||
/// the current contents and begin watching.
|
||||
///
|
||||
/// ## Typical usage
|
||||
///
|
||||
/// ```swift
|
||||
/// // Off the main thread at launch (the ubiquity lookup blocks):
|
||||
/// let resolved = RigLibraryLocation.resolve()
|
||||
/// // Back on the main actor:
|
||||
/// let store = RigLibraryStore(resolved: resolved)
|
||||
/// store.start()
|
||||
/// // …
|
||||
/// try store.save(shoeGaze.captureEntry(name: "Ambient Wash"))
|
||||
/// ```
|
||||
@MainActor
|
||||
@Observable
|
||||
public final class RigLibraryStore {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// All known rigs, sorted by name (case-insensitive), then most-recently-saved first.
|
||||
public private(set) var entries: [RigEntry] = []
|
||||
|
||||
/// `true` when the library is backed by the iCloud container (changes sync); `false` for the
|
||||
/// local-only fallback. Resolved during ``start()`` for an auto-resolving store.
|
||||
public private(set) var isICloud: Bool
|
||||
|
||||
/// The directory holding the per-rig JSON files. May be repointed from local to iCloud during
|
||||
/// ``start()`` for an auto-resolving store (before any writes, so no migration is needed).
|
||||
public private(set) var directory: URL
|
||||
|
||||
/// `false` until the first load completes. Views can show a loading state and callers should
|
||||
/// wait for this (or `await start()`) before deciding whether the library is empty — otherwise a
|
||||
/// first-launch seed would race a not-yet-loaded iCloud library.
|
||||
public private(set) var isLoaded: Bool = false
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
/// Live query over the iCloud documents scope; `nil` when local-only or not yet started.
|
||||
@ObservationIgnored private var metadataQuery: NSMetadataQuery?
|
||||
|
||||
/// Retained NotificationCenter tokens for the metadata-query observers.
|
||||
@ObservationIgnored private var observerTokens: [NSObjectProtocol] = []
|
||||
|
||||
/// Serial queue for all disk writes/deletes. Mutations update the in-memory `entries` on the
|
||||
/// main actor immediately (so the UI never blocks on disk or iCloud coordination), then hand the
|
||||
/// file work here. Serial ordering keeps a rename's delete-then-write — and any save/delete on
|
||||
/// the same file — in submission order.
|
||||
@ObservationIgnored private let ioQueue: DispatchQueue =
|
||||
DispatchQueue(label: "net.realizedsound.shoegaze.riglibrary.io", qos: .utility)
|
||||
|
||||
/// File extension of a stored rig.
|
||||
private nonisolated static let fileExtension: String = "json"
|
||||
|
||||
/// When `true`, ``start()`` resolves the iCloud-or-local location off the main thread and
|
||||
/// repoints `directory`/`isICloud` before loading. `false` for the explicit test initializer.
|
||||
private let autoResolve: Bool
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a store rooted at an explicit directory. Used directly by tests with a temporary
|
||||
/// directory; `start()` will not re-resolve the location.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - directory: The directory holding per-rig JSON files. Created if it does not exist.
|
||||
/// - isICloud: Whether `directory` is an iCloud ubiquity container (enables coordination and
|
||||
/// remote-change watching).
|
||||
public init(
|
||||
directory: URL,
|
||||
isICloud: Bool
|
||||
) {
|
||||
self.directory = directory
|
||||
self.isICloud = isICloud
|
||||
self.autoResolve = false
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
/// Creates an auto-resolving store. Constructed instantly with a local placeholder directory;
|
||||
/// ``start()`` resolves the real iCloud-or-local location off the main thread before loading.
|
||||
public init() {
|
||||
self.directory = RigLibraryLocation.localDirectory()
|
||||
self.isICloud = false
|
||||
self.autoResolve = true
|
||||
}
|
||||
|
||||
// MARK: - Lifecycle
|
||||
|
||||
/// Resolves the location (off the main thread, for an auto-resolving store), loads the current
|
||||
/// library contents (off the main thread), and — when iCloud-backed — begins watching for
|
||||
/// remote changes. Awaitable so callers can seed/highlight only once the real library state is
|
||||
/// known. Safe to call once after construction.
|
||||
public func start() async {
|
||||
if autoResolve {
|
||||
let resolved: RigLibraryLocation.Resolved = await RigLibraryStore.resolveOffMain()
|
||||
directory = resolved.directory
|
||||
isICloud = resolved.isICloud
|
||||
try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
}
|
||||
if isICloud {
|
||||
startMetadataQuery()
|
||||
}
|
||||
await reload()
|
||||
isLoaded = true
|
||||
}
|
||||
|
||||
/// Re-reads the library directory off the main thread and republishes `entries`. Ordered after
|
||||
/// any queued background writes (shares `ioQueue`), so a save followed by a reload never drops
|
||||
/// the just-saved rig.
|
||||
public func reload() async {
|
||||
let dir: URL = directory
|
||||
let coordinated: Bool = isICloud
|
||||
let loaded: [RigEntry] = await withCheckedContinuation { continuation in
|
||||
ioQueue.async {
|
||||
continuation.resume(returning: RigLibraryStore.loadEntries(in: dir, coordinated: coordinated))
|
||||
}
|
||||
}
|
||||
entries = RigLibraryStore.sorted(loaded)
|
||||
}
|
||||
|
||||
/// Resolves the iCloud-or-local location on a background queue so the blocking ubiquity lookup
|
||||
/// never runs on the main thread.
|
||||
private static func resolveOffMain() async -> RigLibraryLocation.Resolved {
|
||||
await withCheckedContinuation { continuation in
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
continuation.resume(returning: RigLibraryLocation.resolve())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops watching for remote changes and removes observers. Call when tearing the store down;
|
||||
/// the store otherwise lives for the app's lifetime.
|
||||
public func stop() {
|
||||
metadataQuery?.stop()
|
||||
metadataQuery = nil
|
||||
for token: NSObjectProtocol in observerTokens {
|
||||
NotificationCenter.default.removeObserver(token)
|
||||
}
|
||||
observerTokens.removeAll()
|
||||
}
|
||||
|
||||
// MARK: - Mutations
|
||||
|
||||
/// Saves `entry`, writing its JSON file and updating `entries` in memory.
|
||||
///
|
||||
/// If an entry with the same `id` already exists, its file and in-memory record are replaced
|
||||
/// (the on-disk filename also updates if the name changed). Use this both to add a brand-new
|
||||
/// rig and to overwrite an existing one (`shoeGaze.captureEntry(name:id:)`).
|
||||
///
|
||||
/// - Parameter entry: The rig entry to persist.
|
||||
/// - Throws: `JSONEncoder` errors (encoding happens synchronously). The actual file write runs
|
||||
/// asynchronously on a background queue and only logs on failure — call
|
||||
/// ``flushPendingWrites()`` to wait for it (e.g. in tests or at app termination).
|
||||
public func save(_ entry: RigEntry) throws {
|
||||
// Encode synchronously (cheap, CPU) so an encoding failure is surfaced to the caller; then
|
||||
// update the in-memory list immediately and push the disk write to the background queue.
|
||||
let data: Data = try encode(entry)
|
||||
let target: URL = fileURL(for: entry)
|
||||
let directory: URL = self.directory
|
||||
let id: UUID = entry.id
|
||||
let coordinated: Bool = isICloud
|
||||
upsert(entry)
|
||||
ioQueue.async {
|
||||
// Remove any prior file for this id first (a rename changes the name-prefixed filename).
|
||||
if let stale: URL = RigLibraryStore.existingFileURL(for: id, in: directory),
|
||||
stale.standardizedFileURL != target.standardizedFileURL {
|
||||
try? RigLibraryStore.removeFile(at: stale, coordinated: coordinated)
|
||||
}
|
||||
do {
|
||||
try RigLibraryStore.writeData(data, to: target, coordinated: coordinated)
|
||||
} catch {
|
||||
print("[RigLibraryStore] save write failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes `entry` from memory immediately and removes its file on the background queue.
|
||||
///
|
||||
/// - Parameter entry: The rig entry to remove.
|
||||
/// - Throws: Never throws today; remains `throws` for API stability. File-removal errors are
|
||||
/// logged on the background queue.
|
||||
public func delete(_ entry: RigEntry) throws {
|
||||
entries.removeAll { $0.id == entry.id }
|
||||
let directory: URL = self.directory
|
||||
let id: UUID = entry.id
|
||||
let coordinated: Bool = isICloud
|
||||
ioQueue.async {
|
||||
if let url: URL = RigLibraryStore.existingFileURL(for: id, in: directory) {
|
||||
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
|
||||
catch { print("[RigLibraryStore] delete failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears the library in memory immediately and removes every rig file on the background queue.
|
||||
///
|
||||
/// - Throws: Never throws today; remains `throws` for API stability. Per-file removal errors are
|
||||
/// logged on the background queue.
|
||||
public func eraseAll() throws {
|
||||
entries.removeAll()
|
||||
let directory: URL = self.directory
|
||||
let coordinated: Bool = isICloud
|
||||
ioQueue.async {
|
||||
for url: URL in RigLibraryStore.rigFileURLs(in: directory) {
|
||||
do { try RigLibraryStore.removeFile(at: url, coordinated: coordinated) }
|
||||
catch { print("[RigLibraryStore] eraseAll: removing \(url.lastPathComponent) failed: \(error)") }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocks until all queued background writes/deletes have completed.
|
||||
///
|
||||
/// Primarily for tests (assert on-disk state right after a mutation) and app termination (ensure
|
||||
/// the last save reaches disk before exit). Avoid calling on the main thread during normal use —
|
||||
/// that would reintroduce the very stall this design removes.
|
||||
public func flushPendingWrites() {
|
||||
ioQueue.sync { }
|
||||
}
|
||||
|
||||
/// Duplicates `entry` under `newName` as an independent entry with a fresh `id`, persists it,
|
||||
/// and returns it.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - entry: The rig to copy.
|
||||
/// - newName: The copy's name.
|
||||
/// - Returns: The newly created entry.
|
||||
/// - Throws: Any error from ``save(_:)``.
|
||||
@discardableResult
|
||||
public func duplicate(
|
||||
_ entry: RigEntry,
|
||||
newName: String
|
||||
) throws -> RigEntry {
|
||||
let copy: RigEntry = entry.duplicated(name: newName)
|
||||
try save(copy)
|
||||
return copy
|
||||
}
|
||||
|
||||
/// Renames `entry` to `newName`, keeping its `id`, and returns the updated entry.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - entry: The rig to rename.
|
||||
/// - newName: The new name.
|
||||
/// - Returns: The renamed entry.
|
||||
/// - Throws: Any error from ``save(_:)``.
|
||||
@discardableResult
|
||||
public func rename(
|
||||
_ entry: RigEntry,
|
||||
to newName: String
|
||||
) throws -> RigEntry {
|
||||
let renamed: RigEntry = entry.renamed(to: newName)
|
||||
try save(renamed)
|
||||
return renamed
|
||||
}
|
||||
|
||||
// MARK: - Archive import / export
|
||||
|
||||
/// Encodes the entire library as a single ``RigArchive`` JSON document 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 RigLibraryStore.makeEncoder().encode(archive)
|
||||
}
|
||||
|
||||
/// Imports rigs from archive `data`, saving each into the library, and returns how many were
|
||||
/// added.
|
||||
///
|
||||
/// Accepts either a ``RigArchive`` (the multi-rig export format) or a legacy single-rig file
|
||||
/// (a bare ``ShoeGazeState``), which is imported as one entry named `legacyRigName`. Imported
|
||||
/// entries whose `id` already exists in the library are given a fresh `id` so an import never
|
||||
/// silently overwrites an existing rig.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - data: Archive or legacy-rig JSON bytes.
|
||||
/// - legacyRigName: Name to use when importing a legacy single-rig file. Defaults to
|
||||
/// `"Imported Rig"`.
|
||||
/// - Returns: The number of rigs added to the library.
|
||||
/// - Throws: `JSONDecoder` errors when `data` is neither an archive nor a legacy rig, or any
|
||||
/// error from ``save(_:)``.
|
||||
@discardableResult
|
||||
public func importArchive(
|
||||
from data: Data,
|
||||
legacyRigName: String = "Imported Rig"
|
||||
) throws -> Int {
|
||||
let imported: [RigEntry] = try decodeImportable(data, legacyRigName: legacyRigName)
|
||||
let existingIDs: Set<UUID> = Set(entries.map(\.id))
|
||||
var added: Int = 0
|
||||
for entry: RigEntry in imported {
|
||||
// Avoid clobbering an existing rig that happens to share this id.
|
||||
let toSave: RigEntry = existingIDs.contains(entry.id)
|
||||
? entry.duplicated(name: entry.name, date: entry.savedAt)
|
||||
: entry
|
||||
try save(toSave)
|
||||
added += 1
|
||||
}
|
||||
return added
|
||||
}
|
||||
|
||||
// MARK: - Loading from disk
|
||||
|
||||
/// Rescans the directory and rebuilds `entries`. Files that cannot be read or decoded are
|
||||
/// skipped so one bad file never blocks the rest. Not-yet-downloaded iCloud placeholders (which
|
||||
/// are hidden `*.icloud` files) are naturally ignored and picked up on a later metadata update.
|
||||
private nonisolated static func loadEntries(in directory: URL, coordinated: Bool) -> [RigEntry] {
|
||||
var loaded: [RigEntry] = []
|
||||
let decoder: JSONDecoder = makeDecoder()
|
||||
for url: URL in rigFileURLs(in: directory) {
|
||||
guard let data: Data = try? readData(at: url, coordinated: coordinated) else { continue }
|
||||
guard let entry: RigEntry = try? decoder.decode(RigEntry.self, from: data) else { continue }
|
||||
loaded.append(entry)
|
||||
}
|
||||
return loaded
|
||||
}
|
||||
|
||||
// MARK: - iCloud metadata query
|
||||
|
||||
/// Starts the live query over the iCloud documents scope and wires update handlers.
|
||||
private func startMetadataQuery() {
|
||||
guard metadataQuery == nil else { return }
|
||||
let query: NSMetadataQuery = NSMetadataQuery()
|
||||
query.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]
|
||||
query.predicate = NSPredicate(
|
||||
format: "%K LIKE %@",
|
||||
NSMetadataItemFSNameKey,
|
||||
"*.\(RigLibraryStore.fileExtension)"
|
||||
)
|
||||
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
let handler: @Sendable (Notification) -> Void = { [weak self] _ in
|
||||
// queue: .main delivers on the main thread; we are a main-actor type.
|
||||
MainActor.assumeIsolated { self?.handleMetadataUpdate() }
|
||||
}
|
||||
observerTokens.append(center.addObserver(
|
||||
forName: .NSMetadataQueryDidFinishGathering, object: query, queue: .main, using: handler
|
||||
))
|
||||
observerTokens.append(center.addObserver(
|
||||
forName: .NSMetadataQueryDidUpdate, object: query, queue: .main, using: handler
|
||||
))
|
||||
|
||||
metadataQuery = query
|
||||
query.start()
|
||||
}
|
||||
|
||||
/// Handles a metadata-query result: triggers downloads for any rig files not yet present
|
||||
/// locally, then rescans the directory for whatever is now readable.
|
||||
private func handleMetadataUpdate() {
|
||||
guard let query: NSMetadataQuery = metadataQuery else { return }
|
||||
query.disableUpdates()
|
||||
defer { query.enableUpdates() }
|
||||
|
||||
let fileManager: FileManager = FileManager.default
|
||||
for index: Int in 0..<query.resultCount {
|
||||
guard let item: NSMetadataItem = query.result(at: index) as? NSMetadataItem,
|
||||
let url: URL = item.value(forAttribute: NSMetadataItemURLKey) as? URL,
|
||||
RigLibraryStore.isInLibrary(url, directory: directory) else { continue }
|
||||
let status: String? =
|
||||
item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String
|
||||
if status != NSMetadataUbiquitousItemDownloadingStatusCurrent {
|
||||
try? fileManager.startDownloadingUbiquitousItem(at: url)
|
||||
}
|
||||
}
|
||||
// Re-read off the main thread; the in-memory list republishes when it completes.
|
||||
Task { await self.reload() }
|
||||
}
|
||||
|
||||
// MARK: - File helpers
|
||||
|
||||
/// The write URL for `entry`: `<sanitized-name>-<id>.json` inside the library directory.
|
||||
private func fileURL(for entry: RigEntry) -> URL {
|
||||
let sanitized: String = sanitizePresetFilename(entry.name)
|
||||
let filename: String = "\(sanitized)-\(entry.id.uuidString).\(RigLibraryStore.fileExtension)"
|
||||
return directory.appendingPathComponent(filename)
|
||||
}
|
||||
|
||||
/// Finds the existing file for `id` by matching the `-<uuid>.json` suffix, so renames (which
|
||||
/// change the name prefix) are still located. `nil` if no file is present. `static` so the
|
||||
/// background I/O queue can call it without touching actor state.
|
||||
private nonisolated static func existingFileURL(for id: UUID, in directory: URL) -> URL? {
|
||||
let suffix: String = "-\(id.uuidString).\(fileExtension)"
|
||||
return rigFileURLs(in: directory).first { $0.lastPathComponent.hasSuffix(suffix) }
|
||||
}
|
||||
|
||||
/// All `*.json` files currently in `directory` (hidden iCloud placeholders excluded).
|
||||
private nonisolated static func rigFileURLs(in directory: URL) -> [URL] {
|
||||
let contents: [URL] = (try? FileManager.default.contentsOfDirectory(
|
||||
at: directory,
|
||||
includingPropertiesForKeys: nil,
|
||||
options: .skipsHiddenFiles
|
||||
)) ?? []
|
||||
return contents.filter { $0.pathExtension == fileExtension }
|
||||
}
|
||||
|
||||
/// Whether `url` is a rig file directly inside `directory`.
|
||||
private nonisolated static func isInLibrary(_ url: URL, directory: URL) -> Bool {
|
||||
url.deletingLastPathComponent().standardizedFileURL == directory.standardizedFileURL
|
||||
&& url.pathExtension == fileExtension
|
||||
}
|
||||
|
||||
// MARK: - Coordinated I/O (background-queue safe)
|
||||
|
||||
/// Writes `data` to `url`, coordinating the write through `NSFileCoordinator` when iCloud-backed.
|
||||
private nonisolated static func writeData(_ data: Data, to url: URL, coordinated: Bool) throws {
|
||||
guard coordinated else {
|
||||
try data.write(to: url, options: .atomic)
|
||||
return
|
||||
}
|
||||
try coordinateWriting(url, options: .forReplacing) { target in
|
||||
try data.write(to: target, options: .atomic)
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the contents of `url`, coordinating the read when iCloud-backed.
|
||||
private nonisolated static func readData(at url: URL, coordinated: Bool) throws -> Data {
|
||||
guard coordinated else {
|
||||
return try Data(contentsOf: url)
|
||||
}
|
||||
var result: Data = Data()
|
||||
try coordinateReading(url, options: .withoutChanges) { target in
|
||||
result = try Data(contentsOf: target)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/// Removes `url`, coordinating the delete when iCloud-backed.
|
||||
private nonisolated static func removeFile(at url: URL, coordinated: Bool) throws {
|
||||
guard coordinated else {
|
||||
try FileManager.default.removeItem(at: url)
|
||||
return
|
||||
}
|
||||
try coordinateWriting(url, options: .forDeleting) { target in
|
||||
try FileManager.default.removeItem(at: target)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `body` inside an `NSFileCoordinator` write block, surfacing both the coordinator's error
|
||||
/// and any error thrown by `body`.
|
||||
private nonisolated static func coordinateWriting(
|
||||
_ url: URL,
|
||||
options: NSFileCoordinator.WritingOptions,
|
||||
_ body: (URL) throws -> Void
|
||||
) throws {
|
||||
let coordinator: NSFileCoordinator = NSFileCoordinator()
|
||||
var coordinatorError: NSError?
|
||||
var thrown: Error?
|
||||
coordinator.coordinate(writingItemAt: url, options: options, error: &coordinatorError) { target in
|
||||
do { try body(target) } catch { thrown = error }
|
||||
}
|
||||
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
|
||||
if let thrown: Error = thrown { throw thrown }
|
||||
}
|
||||
|
||||
/// Runs `body` inside an `NSFileCoordinator` read block.
|
||||
private nonisolated static func coordinateReading(
|
||||
_ url: URL,
|
||||
options: NSFileCoordinator.ReadingOptions,
|
||||
_ body: (URL) throws -> Void
|
||||
) throws {
|
||||
let coordinator: NSFileCoordinator = NSFileCoordinator()
|
||||
var coordinatorError: NSError?
|
||||
var thrown: Error?
|
||||
coordinator.coordinate(readingItemAt: url, options: options, error: &coordinatorError) { target in
|
||||
do { try body(target) } catch { thrown = error }
|
||||
}
|
||||
if let coordinatorError: NSError = coordinatorError { throw coordinatorError }
|
||||
if let thrown: Error = thrown { throw thrown }
|
||||
}
|
||||
|
||||
// MARK: - Codec
|
||||
|
||||
/// Encodes a single entry as a per-rig file would store it.
|
||||
private func encode(_ entry: RigEntry) throws -> Data {
|
||||
try RigLibraryStore.makeEncoder().encode(entry)
|
||||
}
|
||||
|
||||
/// A JSON encoder configured for human-readable, round-trip-stable preset files.
|
||||
private nonisolated static func makeEncoder() -> JSONEncoder {
|
||||
let encoder: JSONEncoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
encoder.dateEncodingStrategy = .secondsSince1970
|
||||
return encoder
|
||||
}
|
||||
|
||||
/// A JSON decoder matching ``makeEncoder()``.
|
||||
private nonisolated static func makeDecoder() -> JSONDecoder {
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
decoder.dateDecodingStrategy = .secondsSince1970
|
||||
return decoder
|
||||
}
|
||||
|
||||
/// Decodes import bytes as a ``RigArchive`` first, falling back to a legacy single-rig
|
||||
/// ``ShoeGazeState``.
|
||||
private func decodeImportable(
|
||||
_ data: Data,
|
||||
legacyRigName: String
|
||||
) throws -> [RigEntry] {
|
||||
let decoder: JSONDecoder = RigLibraryStore.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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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:<displayName>"` 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))
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// RigLibraryBootstrap.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
|
||||
///
|
||||
/// ``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 {
|
||||
|
||||
/// 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()
|
||||
}
|
||||
|
||||
/// 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"`.
|
||||
public static func start(
|
||||
_ store: RigLibraryStore,
|
||||
seedFrom shoeGaze: ShoeGaze,
|
||||
seedName: String = "Default"
|
||||
) async {
|
||||
await store.start()
|
||||
|
||||
// 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)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// 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.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))
|
||||
.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)
|
||||
}
|
||||
}
|
||||
@@ -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<Bool> {
|
||||
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<RigNamePrompt?>) -> some View {
|
||||
modifier(RigNamePromptModifier(prompt: prompt))
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -50,17 +53,24 @@ 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 hardwareSampleRate: () -> Double?
|
||||
|
||||
/// Host hook to enable live input when the current engine has no input channel (iOS).
|
||||
@@ -87,18 +97,36 @@ 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
|
||||
|
||||
/// 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
|
||||
@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 +145,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. 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,
|
||||
hardwareSampleRate: @escaping () -> Double? = { nil },
|
||||
onEnableLiveInput: (() -> Void)? = nil
|
||||
) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.library = library
|
||||
self.hardwareSampleRate = hardwareSampleRate
|
||||
self.onEnableLiveInput = onEnableLiveInput
|
||||
}
|
||||
@@ -130,34 +163,16 @@ public struct ShoeGazeBuilderView: View {
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
transportRow
|
||||
ioRow
|
||||
#if !os(macOS)
|
||||
recordingRow
|
||||
#endif
|
||||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||||
rigSidebar
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
BoardBarView(
|
||||
shoeGaze: shoeGaze,
|
||||
editingBoardIndex: $selectedBoardIndex,
|
||||
crossfadeSeconds: $crossfadeSeconds,
|
||||
onAddBoard: { addBoard() }
|
||||
)
|
||||
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)
|
||||
builderColumn
|
||||
}
|
||||
.padding(ShoeGazeBuilderView.outerPadding)
|
||||
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
|
||||
.frame(
|
||||
minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
|
||||
minHeight: ShoeGazeBuilderView.minHeight
|
||||
)
|
||||
.background(
|
||||
Color(
|
||||
red: ShoeGazeBuilderView.backgroundRed,
|
||||
@@ -166,27 +181,63 @@ public struct ShoeGazeBuilderView: View {
|
||||
)
|
||||
)
|
||||
.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).
|
||||
.onAppear {
|
||||
restoreInputSelection()
|
||||
restoreCurrentRig()
|
||||
}
|
||||
.onChange(of: library.isLoaded) { 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(
|
||||
"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") {
|
||||
pendingClearAfterSave = true
|
||||
saveAction()
|
||||
saveCurrentRig(then: { performClear() })
|
||||
}
|
||||
Button("Clear Without Saving", role: .destructive) {
|
||||
performClear()
|
||||
}
|
||||
Button("Cancel", role: .cancel) {
|
||||
pendingClearAfterSave = false
|
||||
}
|
||||
Button("Cancel", role: .cancel) { }
|
||||
} message: {
|
||||
Text("This removes every pedal and board. Save your current setup first?")
|
||||
}
|
||||
@@ -197,11 +248,87 @@ public struct ShoeGazeBuilderView: View {
|
||||
+ "Security › Microphone, then select the input again.")
|
||||
}
|
||||
#if !os(macOS)
|
||||
.background(rigImportAnchor)
|
||||
.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 requestLoad(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, the scope-plus-mixer/picker top section, then the
|
||||
/// board canvas.
|
||||
private var builderColumn: some View {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
transportRow
|
||||
ioRow
|
||||
#if !os(macOS)
|
||||
recordingRow
|
||||
#endif
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
topSection
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
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
|
||||
@@ -219,37 +346,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,35 +438,12 @@ 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
|
||||
}
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -559,11 +658,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 +707,239 @@ 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
|
||||
|
||||
/// 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, library.isLoaded else { return }
|
||||
didRestoreRig = true
|
||||
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.
|
||||
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<URL, Error>) {
|
||||
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)")
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// 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 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 follow-up 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<URL, Error>) {
|
||||
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<String> = Set(library.entries.map(\.name))
|
||||
var index: Int = library.entries.count + 1
|
||||
while existing.contains("\(base) \(index)") { index += 1 }
|
||||
return "\(base) \(index)"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
// 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() async -> (RigLibraryStore, URL) {
|
||||
let dir: URL = makeTempDirectory()
|
||||
let store: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||
await store.start()
|
||||
return (store, dir)
|
||||
}
|
||||
|
||||
private func makeEntry(_ name: String) -> RigEntry {
|
||||
RigEntry(name: name, state: ShoeGazeState(boards: [BoardState(label: name, segments: [])]))
|
||||
}
|
||||
|
||||
@Test func saveAddsEntryAndReloadsAcrossInstances() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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"])
|
||||
|
||||
store.flushPendingWrites()
|
||||
// A fresh store over the same directory sees the persisted files.
|
||||
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||
await reopened.start()
|
||||
#expect(reopened.entries.count == 2)
|
||||
#expect(reopened.entries.map(\.name) == ["Ambient", "Crunch"])
|
||||
}
|
||||
|
||||
@Test func saveSameIdReplacesInPlace() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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")
|
||||
|
||||
store.flushPendingWrites()
|
||||
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() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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"])
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func duplicateCreatesIndependentEntry() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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)
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func deleteRemovesFileAndEntry() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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)
|
||||
|
||||
store.flushPendingWrites()
|
||||
let files: [URL] = try FileManager.default.contentsOfDirectory(
|
||||
at: dir, includingPropertiesForKeys: nil
|
||||
).filter { $0.pathExtension == "json" }
|
||||
#expect(files.isEmpty)
|
||||
}
|
||||
|
||||
@Test func eraseAllClearsLibrary() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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)
|
||||
|
||||
store.flushPendingWrites()
|
||||
let reopened: RigLibraryStore = RigLibraryStore(directory: dir, isICloud: false)
|
||||
await reopened.start()
|
||||
#expect(reopened.entries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func exportThenImportRoundTrips() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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) = await 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"])
|
||||
store.flushPendingWrites()
|
||||
other.flushPendingWrites()
|
||||
}
|
||||
|
||||
@Test func importColludingIdGetsFreshId() async throws {
|
||||
let (store, dir): (RigLibraryStore, URL) = await 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")
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
|
||||
@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).
|
||||
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")
|
||||
store.flushPendingWrites()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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
|
||||
(`<sanitized-name>-<uuid>.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). 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 = 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.
|
||||
|
||||
## 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)
|
||||
|
||||
- **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`). 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
|
||||
above.
|
||||
Reference in New Issue
Block a user