Add iCloud-synced rig library
Replace the single hand-saved rig file with a managed library of named rigs persisted in app storage and synced across devices and both builder apps via a shared iCloud container (iCloud.net.realizedsound.ShoeGazeData), falling back to local storage when iCloud is unavailable. Core (LyrebirdShoeGaze/Presets): - RigEntry: named, timestamped ShoeGazeState (a whole multi-board rig). - RigArchive: portable multi-rig JSON bundle for backup/transfer; legacy single-rig files import as a one-rig archive. - RigLibraryStore (@MainActor @Observable): one JSON file per rig, with NSFileCoordinator writes and NSMetadataQuery live remote-change watching. - RigLibraryLocation: iCloud-or-local directory resolver (skips the slow ubiquity lookup when no iCloud account is signed in). - ShoeGaze.loadRig(from: ShoeGazeState) + captureEntry; shared filename sanitizer factored out of BoardVersionStore. UI (LyrebirdShoeGazeUI): - RigLibrarySidebarView: persistent left listing with new/save/save-as/ duplicate/rename/delete/erase-all and archive import/export. - RigNamePrompt; RigLibraryBootstrap one-call shell setup. - ShoeGazeBuilderView: sidebar wired in; selecting a rig replaces the session; File menu / sidebar do whole-library archive import/export. Shells/entitlements: both builder targets own+start the store and carry the iCloud Documents entitlement; NSUbiquitousContainers exposes the rigs in the Files app. (macOS pbxproj also carries a pre-existing 1.0->1.1.1 version bump.) Tests: RigEntry/RigArchive round-trip + RigLibraryStore CRUD/import/export (15 new; full suite 206 passing). Provisioning (manual, not done here): enable the iCloud container on both App IDs and select it in Signing & Capabilities for both targets. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -50,17 +50,25 @@ public struct ShoeGazeBuilderView: View {
|
||||
private static let testLoopTag: Int = -1
|
||||
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
|
||||
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
|
||||
/// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be
|
||||
/// highlighted on the next launch. Read by the app shells to seed `initialRigID`.
|
||||
public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID"
|
||||
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
|
||||
private static let maxCrossfadeSeconds: Double = 10.0
|
||||
/// Highest board reachable via a ⌘-number switch shortcut.
|
||||
private static let maxBoardShortcuts: Int = 9
|
||||
private static let defaultRigFileName: String = "ShoeGazeRig"
|
||||
/// Default filename offered when exporting the whole library as an archive.
|
||||
private static let defaultArchiveFileName: String = "ShoeGaze Library"
|
||||
/// Extra width reserved for the rig-library sidebar on top of the builder's minimum width.
|
||||
private static let librarySidebarReserve: CGFloat = 216
|
||||
private static let recordDotSize: CGFloat = 9
|
||||
private static let folderLabelOpacity: Double = 0.55
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
private let library: RigLibraryStore
|
||||
private let initialRigID: UUID?
|
||||
private let hardwareSampleRate: () -> Double?
|
||||
|
||||
/// Host hook to enable live input when the current engine has no input channel (iOS).
|
||||
@@ -87,18 +95,31 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
|
||||
@State private var showBoardsSheet: Bool = false
|
||||
|
||||
/// Confirmation dialog for the Clear action, and a flag to clear once a chosen save completes.
|
||||
/// Confirmation dialog for the Clear action.
|
||||
@State private var showClearDialog: Bool = false
|
||||
@State private var pendingClearAfterSave: Bool = false
|
||||
|
||||
/// Rig-save export state. Cross-platform: the in-view exporter backs both the Save action and
|
||||
/// the "Save & Clear" flow on macOS and iOS (macOS additionally has a File-menu Save).
|
||||
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives
|
||||
/// the sidebar highlight and decides whether Save overwrites or prompts for a name.
|
||||
@State private var currentRigID: UUID?
|
||||
|
||||
/// Guards the one-time `currentRigID` seed from `initialRigID` on appear.
|
||||
@State private var didRestoreRig: Bool = false
|
||||
|
||||
/// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate).
|
||||
@State private var namePrompt: RigNamePrompt?
|
||||
|
||||
/// Confirmation dialog for the "Erase All Rigs" library action.
|
||||
@State private var showEraseAllDialog: Bool = false
|
||||
|
||||
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
|
||||
/// "Save & Clear" flow is separate (it saves to the library, not a file).
|
||||
@State private var showExporter: Bool = false
|
||||
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
|
||||
|
||||
#if !os(macOS)
|
||||
/// iOS file-dialog presentation flags. (macOS uses the File menu for load + recording folder.)
|
||||
/// Archive import state (cross-platform).
|
||||
@State private var showImporter: Bool = false
|
||||
|
||||
#if !os(macOS)
|
||||
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
|
||||
@State private var showRecordingFolderImporter: Bool = false
|
||||
#endif
|
||||
@@ -117,12 +138,20 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// engine with one input channel (preserving the rig), and select live input. Defaults to
|
||||
/// `nil` — on macOS the engine already has an input channel, so live input is selected
|
||||
/// directly without a rebuild.
|
||||
/// - library: The rig library store, already `start()`ed by the host. Backs the left-hand
|
||||
/// rig listing and all save / load / archive actions.
|
||||
/// - initialRigID: The library entry the host restored into `shoeGaze` at launch, if any, so
|
||||
/// the sidebar can highlight it as the current rig. Defaults to `nil`.
|
||||
public init(
|
||||
shoeGaze: ShoeGaze,
|
||||
library: RigLibraryStore,
|
||||
initialRigID: UUID? = nil,
|
||||
hardwareSampleRate: @escaping () -> Double? = { nil },
|
||||
onEnableLiveInput: (() -> Void)? = nil
|
||||
) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.library = library
|
||||
self.initialRigID = initialRigID
|
||||
self.hardwareSampleRate = hardwareSampleRate
|
||||
self.onEnableLiveInput = onEnableLiveInput
|
||||
}
|
||||
@@ -130,6 +159,91 @@ public struct ShoeGazeBuilderView: View {
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||||
rigSidebar
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
builderColumn
|
||||
}
|
||||
.padding(ShoeGazeBuilderView.outerPadding)
|
||||
.frame(
|
||||
minWidth: ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
|
||||
minHeight: ShoeGazeBuilderView.minHeight
|
||||
)
|
||||
.background(
|
||||
Color(
|
||||
red: ShoeGazeBuilderView.backgroundRed,
|
||||
green: ShoeGazeBuilderView.backgroundGreen,
|
||||
blue: ShoeGazeBuilderView.backgroundBlue
|
||||
)
|
||||
)
|
||||
.background(boardSwitchShortcuts)
|
||||
.onAppear {
|
||||
restoreInputSelection()
|
||||
restoreCurrentRig()
|
||||
}
|
||||
.onChange(of: currentRigID) { persistCurrentRigID() }
|
||||
.background(boardsSheetAnchor)
|
||||
.background(rigExportAnchor)
|
||||
.background(rigImportAnchor)
|
||||
.rigNamePrompt($namePrompt)
|
||||
.confirmationDialog(
|
||||
"Erase all rigs?",
|
||||
isPresented: $showEraseAllDialog,
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Erase All Rigs", role: .destructive) { eraseAllRigs() }
|
||||
Button("Cancel", role: .cancel) { }
|
||||
} message: {
|
||||
Text("This permanently removes every saved rig from the library"
|
||||
+ (library.isICloud ? " on all your devices." : "."))
|
||||
}
|
||||
.confirmationDialog(
|
||||
"Clear all boards?",
|
||||
isPresented: $showClearDialog,
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Save & Clear") {
|
||||
saveCurrentRig(thenClear: true)
|
||||
}
|
||||
Button("Clear Without Saving", role: .destructive) {
|
||||
performClear()
|
||||
}
|
||||
Button("Cancel", role: .cancel) { }
|
||||
} message: {
|
||||
Text("This removes every pedal and board. Save your current setup first?")
|
||||
}
|
||||
.alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) {
|
||||
Button("OK", role: .cancel) { }
|
||||
} message: {
|
||||
Text("Live input needs microphone access. Enable it in System Settings › Privacy & "
|
||||
+ "Security › Microphone, then select the input again.")
|
||||
}
|
||||
#if !os(macOS)
|
||||
.background(recordingFolderImportAnchor)
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/
|
||||
/// delete/erase and archive import/export. Selecting a rig replaces the current session.
|
||||
private var rigSidebar: some View {
|
||||
RigLibrarySidebarView(
|
||||
store: library,
|
||||
currentRigID: $currentRigID,
|
||||
onSelect: { entry in loadEntry(entry) },
|
||||
onNew: { promptNewRig() },
|
||||
onSave: { saveCurrentRig() },
|
||||
onSaveAs: { promptSaveAs() },
|
||||
onDuplicate: { entry in promptDuplicate(entry) },
|
||||
onRename: { entry in promptRename(entry) },
|
||||
onDelete: { entry in deleteEntry(entry) },
|
||||
onEraseAll: { showEraseAllDialog = true },
|
||||
onImportArchive: { showImporter = true },
|
||||
onExportArchive: { exportArchiveAction() }
|
||||
)
|
||||
}
|
||||
|
||||
/// The main builder column: transport, IO, boards, palette, board area, scope, and status.
|
||||
private var builderColumn: some View {
|
||||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||||
transportRow
|
||||
ioRow
|
||||
@@ -156,50 +270,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
LyrebirdStatusView(engine: shoeGaze.engine)
|
||||
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
|
||||
}
|
||||
.padding(ShoeGazeBuilderView.outerPadding)
|
||||
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
|
||||
.background(
|
||||
Color(
|
||||
red: ShoeGazeBuilderView.backgroundRed,
|
||||
green: ShoeGazeBuilderView.backgroundGreen,
|
||||
blue: ShoeGazeBuilderView.backgroundBlue
|
||||
)
|
||||
)
|
||||
.background(boardSwitchShortcuts)
|
||||
.onAppear { restoreInputSelection() }
|
||||
// Each presentation (sheet / importers / exporter / alert) lives on its own anchor
|
||||
// node. SwiftUI reliably drives only one presentation per view node, so stacking them
|
||||
// all on the root view silently swallowed some (e.g. the iOS Load file importer).
|
||||
.background(boardsSheetAnchor)
|
||||
.background(rigExportAnchor)
|
||||
.confirmationDialog(
|
||||
"Clear all boards?",
|
||||
isPresented: $showClearDialog,
|
||||
titleVisibility: .visible
|
||||
) {
|
||||
Button("Save & Clear") {
|
||||
pendingClearAfterSave = true
|
||||
saveAction()
|
||||
}
|
||||
Button("Clear Without Saving", role: .destructive) {
|
||||
performClear()
|
||||
}
|
||||
Button("Cancel", role: .cancel) {
|
||||
pendingClearAfterSave = false
|
||||
}
|
||||
} message: {
|
||||
Text("This removes every pedal and board. Save your current setup first?")
|
||||
}
|
||||
.alert("Microphone Access Needed", isPresented: $showMicDeniedAlert) {
|
||||
Button("OK", role: .cancel) { }
|
||||
} message: {
|
||||
Text("Live input needs microphone access. Enable it in System Settings › Privacy & "
|
||||
+ "Security › Microphone, then select the input again.")
|
||||
}
|
||||
#if !os(macOS)
|
||||
.background(rigImportAnchor)
|
||||
.background(recordingFolderImportAnchor)
|
||||
#endif
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
}
|
||||
|
||||
// MARK: - Presentation anchors
|
||||
@@ -219,37 +290,32 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Hosts the rig-save (`.json`) exporter on its own node. Cross-platform: backs both the
|
||||
/// Save action and the "Save & Clear" flow. On a successful save during "Save & Clear", the
|
||||
/// pending clear runs; cancelling the save leaves the boards untouched.
|
||||
/// Hosts the archive-export (`.json`) exporter on its own node. Writes the whole library as one
|
||||
/// ``RigArchive`` file for backup or transfer.
|
||||
private var rigExportAnchor: some View {
|
||||
Color.clear
|
||||
.fileExporter(
|
||||
isPresented: $showExporter,
|
||||
document: exportDocument,
|
||||
contentType: .json,
|
||||
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
|
||||
defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName
|
||||
) { result in
|
||||
switch result {
|
||||
case .failure(let error):
|
||||
print("[ShoeGazeBuilderView] export failed: \(error)")
|
||||
pendingClearAfterSave = false
|
||||
case .success:
|
||||
if pendingClearAfterSave { performClear() }
|
||||
pendingClearAfterSave = false
|
||||
if case .failure(let error) = result {
|
||||
print("[ShoeGazeBuilderView] archive export failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
/// Hosts the rig-load (`.json`) importer on its own node.
|
||||
/// Hosts the archive-import (`.json`) importer on its own node (cross-platform). Accepts a
|
||||
/// ``RigArchive`` or a legacy single-rig file; imported rigs are added to the library.
|
||||
private var rigImportAnchor: some View {
|
||||
Color.clear
|
||||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
|
||||
handleImport(result)
|
||||
handleArchiveImport(result)
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
/// Hosts the recording-folder importer on its own node.
|
||||
private var recordingFolderImportAnchor: some View {
|
||||
Color.clear
|
||||
@@ -316,19 +382,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
|
||||
Button("Clear") { showClearDialog = true }
|
||||
.buttonStyle(.bordered).tint(.red)
|
||||
.help("Remove all boards (with the option to save first)")
|
||||
.help("Remove all boards in the current rig (with the option to save first)")
|
||||
|
||||
Spacer()
|
||||
|
||||
// On macOS, Load lives in the app's File menu (see the app shell's AppDelegate); on
|
||||
// iOS it stays in-view via fileImporter. Save is in-view on both (cross-platform
|
||||
// exporter) so the "Save & Clear" flow works everywhere.
|
||||
Button("Save…") { saveAction() }
|
||||
.buttonStyle(.bordered).tint(.blue)
|
||||
#if !os(macOS)
|
||||
Button("Load…") { loadAction() }
|
||||
.buttonStyle(.bordered).tint(.blue)
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -559,11 +615,9 @@ public struct ShoeGazeBuilderView: View {
|
||||
shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds)
|
||||
}
|
||||
|
||||
// MARK: - Save / Load (iOS)
|
||||
// MARK: - Recording (iOS)
|
||||
|
||||
// Save is in-view on both platforms (cross-platform fileExporter) so "Save & Clear" works
|
||||
// everywhere. Load is the macOS File menu / iOS fileImporter; recording controls are iOS
|
||||
// in-view (macOS uses the Record menu).
|
||||
// Recording controls are iOS in-view (macOS uses the Record menu).
|
||||
#if !os(macOS)
|
||||
/// iOS recording controls: choose an output folder, then start/stop recording.
|
||||
private var recordingRow: some View {
|
||||
@@ -610,47 +664,211 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Presents the cross-platform rig-save exporter (also used by the "Save & Clear" flow).
|
||||
private func saveAction() {
|
||||
do {
|
||||
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
|
||||
showExporter = true
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] rigData failed: \(error)")
|
||||
// MARK: - Rig library
|
||||
|
||||
/// Seeds `currentRigID` from the entry the host restored at launch, once.
|
||||
private func restoreCurrentRig() {
|
||||
guard !didRestoreRig else { return }
|
||||
didRestoreRig = true
|
||||
currentRigID = initialRigID
|
||||
}
|
||||
|
||||
/// Persists `currentRigID` so the same rig is highlighted on the next launch.
|
||||
private func persistCurrentRigID() {
|
||||
let defaults: UserDefaults = UserDefaults.standard
|
||||
if let id: UUID = currentRigID {
|
||||
defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
|
||||
} else {
|
||||
defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
private func loadAction() {
|
||||
showImporter = true
|
||||
}
|
||||
|
||||
/// Loads a rig from a URL, stopping/restarting the engine around the rebuild and resetting the
|
||||
/// board selection to a valid index (load replaces all boards).
|
||||
private func loadRig(from url: URL) {
|
||||
/// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine
|
||||
/// around the rebuild, resets the board selection, and records the entry as current.
|
||||
private func loadEntry(_ entry: RigEntry) {
|
||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||
if wasRunning { shoeGaze.engine.stop() }
|
||||
do {
|
||||
try shoeGaze.loadRig(from: url)
|
||||
try shoeGaze.loadRig(from: entry.state)
|
||||
currentRigID = entry.id
|
||||
selectedBoardIndex = 0
|
||||
autosave()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] loadRig failed: \(error)")
|
||||
print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
|
||||
}
|
||||
if wasRunning { try? shoeGaze.engine.start() }
|
||||
transportTick.toggle()
|
||||
}
|
||||
|
||||
private func handleImport(_ result: Result<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)")
|
||||
/// Saves the current session over the loaded library entry, or prompts for a name when no entry
|
||||
/// is loaded (a new, never-saved rig).
|
||||
///
|
||||
/// - Parameter thenClear: When `true`, clears the boards after a successful save (the
|
||||
/// "Save & Clear" flow). Cancelling the name prompt cancels the clear too — no save, no clear.
|
||||
private func saveCurrentRig(thenClear: Bool = false) {
|
||||
let completion: () -> Void = thenClear ? { performClear() } : { }
|
||||
guard let id: UUID = currentRigID,
|
||||
let existing: RigEntry = library.entries.first(where: { $0.id == id }) else {
|
||||
// No current entry — prompt for a name; the clear (if any) runs only on commit.
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Save Rig As",
|
||||
initialText: currentRigName() ?? defaultNewRigName(),
|
||||
confirmLabel: "Save"
|
||||
) { name in
|
||||
persist(shoeGaze.captureEntry(name: name), then: completion)
|
||||
}
|
||||
return
|
||||
}
|
||||
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
|
||||
}
|
||||
|
||||
/// Prompts for a name, then creates a brand-new empty rig (one empty board) and selects it.
|
||||
private func promptNewRig() {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "New Rig",
|
||||
initialText: defaultNewRigName(),
|
||||
confirmLabel: "Create"
|
||||
) { name in
|
||||
createNewRig(named: name)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Prompts for a name and saves the current session as a new library entry (new id).
|
||||
private func promptSaveAs() {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Save Rig As",
|
||||
initialText: currentRigName() ?? defaultNewRigName(),
|
||||
confirmLabel: "Save"
|
||||
) { name in
|
||||
persist(shoeGaze.captureEntry(name: name))
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts for a name and duplicates `entry`, loading the copy as the current rig.
|
||||
private func promptDuplicate(_ entry: RigEntry) {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Duplicate Rig",
|
||||
initialText: "\(entry.name) copy",
|
||||
confirmLabel: "Duplicate"
|
||||
) { name in
|
||||
do {
|
||||
let copy: RigEntry = try library.duplicate(entry, newName: name)
|
||||
loadEntry(copy)
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] duplicate failed: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts for a new name and renames `entry` in the library.
|
||||
private func promptRename(_ entry: RigEntry) {
|
||||
namePrompt = RigNamePrompt(
|
||||
title: "Rename Rig",
|
||||
initialText: entry.name,
|
||||
confirmLabel: "Rename"
|
||||
) { name in
|
||||
do { _ = try library.rename(entry, to: name) }
|
||||
catch { print("[ShoeGazeBuilderView] rename failed: \(error)") }
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes `entry` from the library. Clears the current-rig marker if it was the loaded rig.
|
||||
private func deleteEntry(_ entry: RigEntry) {
|
||||
do {
|
||||
try library.delete(entry)
|
||||
if currentRigID == entry.id { currentRigID = nil }
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] delete failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Erases the entire library and clears the current-rig marker.
|
||||
private func eraseAllRigs() {
|
||||
do {
|
||||
try library.eraseAll()
|
||||
currentRigID = nil
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] eraseAll failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Captures the current session into the whole-library archive exporter.
|
||||
private func exportArchiveAction() {
|
||||
do {
|
||||
exportDocument = RigFileDocument(data: try library.exportArchiveData())
|
||||
showExporter = true
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] exportArchiveData failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Imports an archive (or legacy single-rig file) into the library.
|
||||
private func handleArchiveImport(_ result: Result<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)"
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user