3f05cfa416
The board canvas used to fill the remaining height and centre itself, pinning the pre-board strip above and the post-board strip below — so a tall pre/post chain clipped instead of scrolling, and the three sections never read as one signal path. Wrap pre-board → board → post-board in a single vertical ScrollView so the whole path scrolls top-to-bottom as one page, on macOS and iOS alike. The transport / palette / routing header stays fixed above it. BoardFlowView gains a `sizesToContent` mode: it sizes to its chain height and scrolls only horizontally, so it nests inside the outer vertical scroller with no competing vertical scroll (a tall parallel split simply grows the page). The default fill-and-centre behaviour is unchanged for any other caller. Verified on the iPad simulator: sections stack in signal-flow order and the board still scrolls horizontally through a long chain. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2189 lines
97 KiB
Swift
2189 lines
97 KiB
Swift
// ShoeGazeBuilderView.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
#if canImport(AppKit)
|
||
import AppKit
|
||
#endif
|
||
#if canImport(UIKit)
|
||
import UIKit
|
||
#endif
|
||
import SwiftUI
|
||
import UniformTypeIdentifiers
|
||
import LyrebirdSynth
|
||
import LyrebirdUI
|
||
import LyrebirdShoeGaze
|
||
|
||
/// A self-contained pedalboard builder: browse all pedals, build a board by adding / removing /
|
||
/// reordering pedals, tweak live controls, choose the input source, start the chain, and save or
|
||
/// load a board setup.
|
||
///
|
||
/// This view ties together ``PedalPaletteView`` (the catalog) and ``BoardBuilderView`` (the
|
||
/// editable chain) with a transport bar, an input-source picker, a board selector, and save/load.
|
||
/// It is the shared screen hosted by both the macOS and iOS builder app shells.
|
||
///
|
||
/// Save/load uses an `NSSavePanel`/`NSOpenPanel` on macOS and `.fileExporter`/`.fileImporter` on
|
||
/// iOS, both reading/writing the JSON produced by `ShoeGaze.rigData()` / consumed by
|
||
/// `loadRig(from:)`. Loading and input-source changes stop the engine first (they rebuild the
|
||
/// graph) and restart it if it was running.
|
||
///
|
||
/// ## Usage
|
||
///
|
||
/// ```swift
|
||
/// ShoeGazeBuilderView(shoeGaze: shoeGaze)
|
||
/// ```
|
||
public struct ShoeGazeBuilderView: View {
|
||
|
||
// MARK: - Layout constants
|
||
|
||
private static let outerPadding: CGFloat = 16
|
||
private static let sectionSpacing: CGFloat = 12
|
||
private static let rowSpacing: CGFloat = 10
|
||
private static let dividerOpacity: Double = 0.12
|
||
private static let labelOpacity: Double = 0.65
|
||
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
|
||
/// Narrow scope shown in the compact (iPad) header, tucked left of the transport buttons.
|
||
private static let compactHeaderScopeWidth: CGFloat = 340
|
||
private static let compactHeaderScopeHeight: CGFloat = 76
|
||
/// Stable height (fraction of the screen) for the Add-Pedal sheet — a single, non-resizable detent.
|
||
private static let paletteSheetHeightFraction: CGFloat = 0.82
|
||
private static let columnSpacing: CGFloat = 14
|
||
private static let backgroundRed: Double = 0.08
|
||
private static let backgroundGreen: Double = 0.07
|
||
private static let backgroundBlue: Double = 0.06
|
||
private static let testLoopTag: Int = -1
|
||
/// 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
|
||
|
||
/// The number of set-list rigs reachable by ⌘⇧1…⌘⇧0 (the top ten).
|
||
private static let maxRigShortcuts: Int = 10
|
||
/// 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?
|
||
|
||
/// The MIDI controller for foot-controller input, or `nil` when MIDI is unavailable/disabled.
|
||
/// When present, the transport row shows a connection indicator.
|
||
private let midi: MIDIController?
|
||
|
||
/// Host hook to enable live input when the current engine has no input channel (iOS).
|
||
/// The host requests microphone access and rebuilds the engine with one input channel,
|
||
/// preserving the rig, then swaps in a new `ShoeGaze`. `nil` on platforms (macOS) whose
|
||
/// engine already exposes an input channel, where live input is selected directly.
|
||
private let onEnableLiveInput: (() -> Void)?
|
||
|
||
/// Multi-level undo / redo for structural edits (add / remove / move pedals, boards, routing).
|
||
/// Supplied by the host app so the same instance also backs the macOS Edit-menu items. `nil` in
|
||
/// lightweight hosts (previews): edits then run directly, without recording history.
|
||
private let undo: UndoCoordinator?
|
||
|
||
/// Index of the board currently being edited.
|
||
@State private var selectedBoardIndex: Int = 0
|
||
|
||
/// Crossfade duration (seconds) applied to board switches in the board bar.
|
||
@State private var crossfadeSeconds: Double = 0.3
|
||
|
||
/// Bumped on transport/edit actions to force a re-read of `engine.isRunning`.
|
||
@State private var transportTick: Bool = false
|
||
|
||
/// Shown when live input is selected but microphone access is denied/restricted.
|
||
@State private var showMicDeniedAlert: Bool = false
|
||
|
||
/// Presents the "iCloud unavailable" guidance alert (rigs saved locally only).
|
||
@State private var showICloudUnavailableAlert: Bool = false
|
||
|
||
/// Guards the automatic one-shot iCloud-unavailable alert so it fires at most once per launch
|
||
/// (the tappable status icon can still re-present it on demand).
|
||
@State private var didCheckICloudStatus: Bool = false
|
||
|
||
/// Guards the one-time input-source restore in `.onAppear`.
|
||
@State private var didRestoreInput: Bool = false
|
||
|
||
/// Presentation flag for the board-manager sheet (rename / reorder / delete).
|
||
@State private var showBoardsSheet: Bool = false
|
||
|
||
/// Confirmation dialog for the Clear action.
|
||
@State private var showClearDialog: Bool = false
|
||
|
||
/// 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.
|
||
///
|
||
/// Backed by ``ShoeGaze/currentRigID`` (the single source of truth), so it is persisted inside
|
||
/// the autosave envelope together with the graph and restored consistently — the highlight can
|
||
/// never drift from the loaded rig. `@Observable` drives sidebar updates when it changes.
|
||
private var currentRigID: UUID? {
|
||
get { shoeGaze.currentRigID }
|
||
nonmutating set { shoeGaze.currentRigID = newValue }
|
||
}
|
||
|
||
/// 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
|
||
|
||
/// A failed edit (add pedal / routing / board) to surface as an alert. `nil` = no alert.
|
||
@State private var actionError: ActionError?
|
||
|
||
/// A user-facing failure message for the action-error alert.
|
||
private struct ActionError: Identifiable {
|
||
let id: UUID = UUID()
|
||
let title: String
|
||
let message: String
|
||
}
|
||
|
||
/// A pending confirmation to overwrite a built-in factory rig. Non-`nil` shows the dialog;
|
||
/// carries the target entry and the follow-up to run once the user resolves the choice (so the
|
||
/// "Save & Clear" flow still clears after a confirmed overwrite).
|
||
private struct FactoryOverwriteRequest: Identifiable {
|
||
let id: UUID = UUID()
|
||
let entry: RigEntry
|
||
let completion: () -> Void
|
||
}
|
||
|
||
/// Drives the "overwrite a starter rig?" confirmation dialog. `nil` = not shown.
|
||
@State private var factoryOverwrite: FactoryOverwriteRequest?
|
||
|
||
/// 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())
|
||
|
||
/// Archive import state (cross-platform).
|
||
@State private var showImporter: Bool = false
|
||
|
||
/// MIDI mapping sheet presentation flag.
|
||
@State private var showMIDISheet: Bool = false
|
||
|
||
/// Help sheet presentation flag (iOS button; macOS uses the Help menu).
|
||
@State private var showHelpSheet: Bool = false
|
||
|
||
/// Compact-layout sheet flags — the composition panels docked in the regular layout become
|
||
/// bottom sheets so the board canvas gets the full screen.
|
||
@State private var showRigsSheet: Bool = false
|
||
@State private var showPaletteSheet: Bool = false
|
||
/// When `true`, the next palette pick is added to the pre-board chain rather than a board.
|
||
@State private var addToPreBoard: Bool = false
|
||
/// When `true`, the next palette pick is added to the post-board chain rather than a board.
|
||
@State private var addToPostBoard: Bool = false
|
||
@State private var showSettingsSheet: Bool = false
|
||
|
||
/// Type filter for the compact Add-Pedal sheet, hoisted so it sits in the sheet's fixed header.
|
||
@State private var pedalFilter: PedalCategory?
|
||
|
||
/// `true` when the window is taller than it is wide (portrait). iPad is `.regular` in both
|
||
/// orientations, so this is derived from the actual size, not the size class. In portrait the
|
||
/// header scope moves to a full-width strip below the controls (it would otherwise overlay /
|
||
/// clip the header on narrower iPads); landscape keeps it inline beside the transport.
|
||
@State private var isPortrait: Bool = false
|
||
|
||
#if !os(macOS)
|
||
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
|
||
@State private var showRecordingFolderImporter: Bool = false
|
||
#endif
|
||
|
||
#if os(macOS)
|
||
/// The AppKit local key-down monitor that routes bare letter/digit keys to `midi.ingestKey`,
|
||
/// or `nil` when not installed. Stored so it can be removed on disappear.
|
||
@State private var keyMonitor: Any?
|
||
#else
|
||
/// Whether the builder root holds keyboard focus, so `.onKeyPress` delivers hardware-keyboard
|
||
/// presses to the key bindings. Held `true` except while a text field is being edited.
|
||
@FocusState private var keyboardFocused: Bool
|
||
#endif
|
||
|
||
// MARK: - Init
|
||
|
||
/// Creates a builder view.
|
||
///
|
||
/// - Parameters:
|
||
/// - shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The caller should
|
||
/// create at least one board before presenting this view.
|
||
/// - hardwareSampleRate: Returns the actual hardware/session sample rate (or `nil`), used by
|
||
/// the engine-config Start to warn on a mismatch. Defaults to `nil`.
|
||
/// - onEnableLiveInput: Host hook invoked when the user requests live input but the engine
|
||
/// has no input channel (iOS). The host should request microphone access, rebuild the
|
||
/// 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.
|
||
/// - midi: The MIDI controller for foot-controller input. When non-`nil`, the transport row
|
||
/// shows a connection indicator. Defaults to `nil`.
|
||
public init(
|
||
shoeGaze: ShoeGaze,
|
||
library: RigLibraryStore,
|
||
hardwareSampleRate: @escaping () -> Double? = { nil },
|
||
onEnableLiveInput: (() -> Void)? = nil,
|
||
midi: MIDIController? = nil,
|
||
undo: UndoCoordinator? = nil
|
||
) {
|
||
self.shoeGaze = shoeGaze
|
||
self.library = library
|
||
self.hardwareSampleRate = hardwareSampleRate
|
||
self.onEnableLiveInput = onEnableLiveInput
|
||
self.midi = midi
|
||
self.undo = undo
|
||
}
|
||
|
||
// MARK: - Body
|
||
|
||
/// `true` on iPad (any size) — the canvas-first layout with composition panels in sheets. The
|
||
/// docked desktop layout is macOS-only; on iPad it overflowed and clipped even at iPad-Pro
|
||
/// width, so every iPad size uses the sheet-based layout. macOS always uses the docked layout.
|
||
private var isCompact: Bool {
|
||
#if os(iOS)
|
||
return true
|
||
#else
|
||
return false
|
||
#endif
|
||
}
|
||
|
||
|
||
// The builder body is split across `layoutChrome` → `presentationChrome` → `body` because the
|
||
// full modifier chain (layout + lifecycle + every sheet / dialog / alert + key capture) is too
|
||
// large for the Swift expression type-checker as a single expression.
|
||
private var layoutChrome: some View {
|
||
rootContent
|
||
.padding(ShoeGazeBuilderView.outerPadding)
|
||
// A large min width is a macOS window sizing hint; on iPad it would force content wider than
|
||
// the screen and clip it, so the sheet-based iPad layout imposes no minimum width. Fill the
|
||
// whole window and pin to the top-leading corner so portrait isn't vertically centered.
|
||
.frame(
|
||
minWidth: isCompact ? nil : ShoeGazeBuilderView.minWidth + ShoeGazeBuilderView.librarySidebarReserve,
|
||
maxWidth: isCompact ? .infinity : nil,
|
||
minHeight: isCompact ? nil : ShoeGazeBuilderView.minHeight,
|
||
maxHeight: isCompact ? .infinity : nil,
|
||
alignment: .topLeading
|
||
)
|
||
.background(
|
||
Color(
|
||
red: ShoeGazeBuilderView.backgroundRed,
|
||
green: ShoeGazeBuilderView.backgroundGreen,
|
||
blue: ShoeGazeBuilderView.backgroundBlue
|
||
)
|
||
)
|
||
// Track portrait vs landscape by actual size (iPad is `.regular` in both orientations).
|
||
.background(
|
||
GeometryReader { proxy in
|
||
Color.clear.task(id: proxy.size) {
|
||
isPortrait = proxy.size.height > proxy.size.width
|
||
}
|
||
}
|
||
)
|
||
// The builder is always dark-themed; force the dark scheme so system controls (nav title,
|
||
// steppers, the Record button) use light text instead of black-on-dark in light mode.
|
||
.preferredColorScheme(.dark)
|
||
.background(boardSwitchShortcuts)
|
||
.onAppear {
|
||
restoreInputSelection()
|
||
syncIdleTimer()
|
||
maybeWarnICloudUnavailable()
|
||
#if os(macOS)
|
||
installKeyMonitor()
|
||
#else
|
||
keyboardFocused = true
|
||
#endif
|
||
}
|
||
.onDisappear {
|
||
releaseIdleTimer()
|
||
#if os(macOS)
|
||
removeKeyMonitor()
|
||
#endif
|
||
}
|
||
.onChange(of: transportTick) { syncIdleTimer() }
|
||
.onChange(of: library.isLoaded) {
|
||
maybeWarnICloudUnavailable()
|
||
}
|
||
}
|
||
|
||
// Split off the first half of the presentation chain into its own computed property: the full
|
||
// modifier chain is long enough to blow the Swift expression type-checker's budget, so this
|
||
// boundary keeps each half small enough to type-check quickly.
|
||
private var chromeWithPrompts: some View {
|
||
layoutChrome
|
||
.background(boardsSheetAnchor)
|
||
.background(rigExportAnchor)
|
||
.background(rigImportAnchor)
|
||
.background(actionErrorAnchor)
|
||
.rigNamePrompt($namePrompt)
|
||
.confirmationDialog(
|
||
"Starter rig",
|
||
isPresented: Binding(
|
||
get: { factoryOverwrite != nil },
|
||
set: { presented in if !presented { factoryOverwrite = nil } }
|
||
),
|
||
titleVisibility: .visible,
|
||
presenting: factoryOverwrite
|
||
) { request in
|
||
// A starter rig is managed content: it is refreshed to the shipped version whenever the
|
||
// starter catalog updates, so it deliberately cannot be overwritten in place — that would
|
||
// silently revert on the next update. The player keeps their changes as a new rig instead.
|
||
Button("Save as New Rig…") {
|
||
// Defer one runloop hop: presenting the name-entry alert while the confirmation
|
||
// dialog is still dismissing can drop the new presentation on some SwiftUI versions.
|
||
let completion: () -> Void = request.completion
|
||
DispatchQueue.main.async { promptSaveAs(then: completion) }
|
||
}
|
||
Button("Cancel", role: .cancel) { }
|
||
} message: { request in
|
||
Text("“\(request.entry.name)” is a built-in starter rig and can't be changed in place. "
|
||
+ "Save your changes as a new rig to keep them.")
|
||
}
|
||
}
|
||
|
||
private var presentationChrome: some View {
|
||
chromeWithPrompts
|
||
.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()
|
||
}
|
||
.onReceive(NotificationCenter.default.publisher(for: .shoeGazeLoadRigSlot)) { note in
|
||
if let index: Int = note.object as? Int {
|
||
loadRigSlot(index)
|
||
}
|
||
}
|
||
.confirmationDialog(
|
||
"Clear all boards?",
|
||
isPresented: $showClearDialog,
|
||
titleVisibility: .visible
|
||
) {
|
||
Button("Save & Clear") {
|
||
saveCurrentRig(then: { performClear() })
|
||
}
|
||
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.")
|
||
}
|
||
.alert("iCloud Unavailable", isPresented: $showICloudUnavailableAlert) {
|
||
Button("OK", role: .cancel) { }
|
||
} message: {
|
||
Text("Your rigs are saved on this device only. To sync them across your devices, "
|
||
+ "sign in to iCloud and turn on iCloud Drive in "
|
||
+ ShoeGazeBuilderView.settingsAppName
|
||
+ ", then reopen ShoeGaze.")
|
||
}
|
||
#if !os(macOS)
|
||
.background(recordingFolderImportAnchor)
|
||
#endif
|
||
.sheet(isPresented: $showMIDISheet) {
|
||
if let midi: MIDIController = midi {
|
||
MIDIMappingSheet(controller: midi, shoeGaze: shoeGaze)
|
||
}
|
||
}
|
||
.sheet(isPresented: $showHelpSheet) {
|
||
HelpView()
|
||
}
|
||
// Each compact composition sheet lives on its own anchor node — SwiftUI presents at most one
|
||
// sheet per node, so stacking them on the main node would silently swallow all but one.
|
||
.background(rigsSheetAnchor)
|
||
.background(paletteSheetAnchor)
|
||
.background(settingsSheetAnchor)
|
||
.overlay(alignment: .top) { midiLearnBanner }
|
||
}
|
||
|
||
public var body: some View {
|
||
presentationChrome
|
||
// Letter/digit keys drive bound rig actions. macOS uses an AppKit key monitor (installed in
|
||
// onAppear) because SwiftUI's `.onKeyPress` only delivers to the focused view, and the builder
|
||
// root is rarely the focused view. iOS routes hardware-keyboard presses through `.onKeyPress`,
|
||
// which requires the root to be focusable AND focused — so the root claims focus on appear and
|
||
// reclaims it whenever a modal that stole focus (a text-field sheet) closes. A focused
|
||
// `TextField` still wins while open, so typing is never hijacked.
|
||
#if !os(macOS)
|
||
.modifier(KeyboardCaptureModifier(
|
||
keyboardFocused: $keyboardFocused,
|
||
modalOpen: anyFocusStealingModalOpen,
|
||
onKeyPress: handleKeyPress
|
||
))
|
||
#endif
|
||
}
|
||
|
||
#if !os(macOS)
|
||
/// Whether any modal that can take keyboard focus from the builder root is currently open. When
|
||
/// it closes, the root reclaims focus so hardware-keyboard bindings keep firing. Text-field-
|
||
/// bearing sheets (rig rename, board editor) are the ones that matter, but covering the main
|
||
/// content sheets keeps focus robust across all of them.
|
||
private var anyFocusStealingModalOpen: Bool {
|
||
showMIDISheet || showHelpSheet || showRigsSheet || showPaletteSheet
|
||
|| showSettingsSheet || showBoardsSheet || namePrompt != nil
|
||
}
|
||
#endif
|
||
|
||
#if !os(macOS)
|
||
/// Routes a bare key press to the MIDI controller's key bindings, ignoring modified presses so
|
||
/// `⌘`-shortcuts still work. Returns `.handled` when a binding consumed the key, else `.ignored`.
|
||
/// A focused text field consumes keys first via the responder chain, so this only fires when the
|
||
/// user is not typing.
|
||
private func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result {
|
||
guard let midi: MIDIController = midi else { return .ignored }
|
||
// Command chords belong to the menu shortcuts; shift / control / option qualify the binding.
|
||
guard keyPress.modifiers.contains(.command) == false else { return .ignored }
|
||
var modifiers: MIDIMap.KeyModifiers = []
|
||
if keyPress.modifiers.contains(.shift) { modifiers.insert(.shift) }
|
||
if keyPress.modifiers.contains(.control) { modifiers.insert(.control) }
|
||
if keyPress.modifiers.contains(.option) { modifiers.insert(.option) }
|
||
// `key.character` is the unshifted base key, so shift stays represented in `modifiers` only.
|
||
let base: String = String(keyPress.key.character)
|
||
return midi.ingestKey(base, modifiers: modifiers) ? .handled : .ignored
|
||
}
|
||
#endif
|
||
|
||
#if !os(macOS)
|
||
/// The iOS/iPadOS key-capture modifiers, factored into a `ViewModifier` so the (large) builder
|
||
/// body stays under the Swift expression type-checker's complexity limit. Makes the root
|
||
/// focusable and focused so `.onKeyPress` receives hardware-keyboard presses, and reclaims focus
|
||
/// whenever a focus-stealing modal closes.
|
||
private struct KeyboardCaptureModifier: ViewModifier {
|
||
|
||
@FocusState.Binding var keyboardFocused: Bool
|
||
let modalOpen: Bool
|
||
let onKeyPress: (KeyPress) -> KeyPress.Result
|
||
|
||
func body(content: Content) -> some View {
|
||
content
|
||
.focusable()
|
||
.focusEffectDisabled()
|
||
.focused($keyboardFocused)
|
||
.onKeyPress(phases: .down) { keyPress in onKeyPress(keyPress) }
|
||
.onChange(of: modalOpen) { _, isOpen in
|
||
if isOpen == false { keyboardFocused = true }
|
||
}
|
||
}
|
||
}
|
||
#endif
|
||
|
||
#if os(macOS)
|
||
/// Installs an AppKit local key-down monitor that routes bare letter/digit keys to the MIDI
|
||
/// controller's key bindings. Unlike SwiftUI `.onKeyPress`, a local monitor sees every key-down
|
||
/// regardless of which view holds SwiftUI focus, so mapped keys fire even when the board — not a
|
||
/// text field — is what the user is looking at. Keys are swallowed only when a binding consumes
|
||
/// them; text entry and menu shortcuts pass through untouched.
|
||
private func installKeyMonitor() {
|
||
guard keyMonitor == nil else { return }
|
||
keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
|
||
let flags: NSEvent.ModifierFlags = event.modifierFlags
|
||
// Command chords belong to the menu keyboard shortcuts; key-repeat would toggle
|
||
// repeatedly while a key is held. Filter both before touching any binding.
|
||
//
|
||
// Derive the base key with *no* modifiers applied, not `charactersIgnoringModifiers`
|
||
// (which still bakes in Shift — `⇧2` → `"@"` — and mangles Control into a C0 code). This
|
||
// matches the iOS path's `keyPress.key.character`, so the same physical chord stores the
|
||
// same base key on both platforms and a rig stays portable across an iCloud sync.
|
||
guard flags.contains(.command) == false,
|
||
event.isARepeat == false,
|
||
let characters: String = event.characters(byApplyingModifiers: []) else { return event }
|
||
let modifiers: MIDIMap.KeyModifiers = ShoeGazeBuilderView.keyModifiers(from: flags)
|
||
// Local monitors are delivered on the main thread; hop the actor with only Sendable
|
||
// values (NSEvent itself is not Sendable and must not cross the boundary).
|
||
let consumed: Bool = MainActor.assumeIsolated { routeMonitoredKey(characters, modifiers) }
|
||
return consumed ? nil : event
|
||
}
|
||
}
|
||
|
||
/// Maps AppKit modifier flags to the persisted ``MIDIMap/KeyModifiers`` set (shift / control /
|
||
/// option; command is reserved for menu shortcuts and never reaches here).
|
||
private static func keyModifiers(from flags: NSEvent.ModifierFlags) -> MIDIMap.KeyModifiers {
|
||
var modifiers: MIDIMap.KeyModifiers = []
|
||
if flags.contains(.shift) { modifiers.insert(.shift) }
|
||
if flags.contains(.control) { modifiers.insert(.control) }
|
||
if flags.contains(.option) { modifiers.insert(.option) }
|
||
return modifiers
|
||
}
|
||
|
||
/// Applies a monitored key press to the MIDI controller's key bindings, returning `true` when a
|
||
/// binding consumed it. A field editor holding first responder means the user is typing, so the
|
||
/// key is let through untouched — a rig-name or board-label edit is never hijacked into a toggle.
|
||
@MainActor
|
||
private func routeMonitoredKey(_ characters: String, _ modifiers: MIDIMap.KeyModifiers) -> Bool {
|
||
guard let midi: MIDIController = midi else { return false }
|
||
if let responder: NSResponder = NSApp.keyWindow?.firstResponder, responder is NSText {
|
||
return false
|
||
}
|
||
return midi.ingestKey(characters, modifiers: modifiers)
|
||
}
|
||
|
||
/// Removes the local key-down monitor installed by ``installKeyMonitor()``.
|
||
private func removeKeyMonitor() {
|
||
if let monitor: Any = keyMonitor {
|
||
NSEvent.removeMonitor(monitor)
|
||
keyMonitor = nil
|
||
}
|
||
}
|
||
#endif
|
||
|
||
/// Hosts the compact rig-library sheet on its own node.
|
||
private var rigsSheetAnchor: some View {
|
||
Color.clear
|
||
.sheet(isPresented: $showRigsSheet) {
|
||
rigSidebar
|
||
.padding(.top, ShoeGazeBuilderView.outerPadding)
|
||
.presentationDetents([.large])
|
||
.preferredColorScheme(.dark)
|
||
}
|
||
}
|
||
|
||
/// Hosts the compact Add-pedal palette sheet on its own node.
|
||
private var paletteSheetAnchor: some View {
|
||
Color.clear
|
||
// Reset the pre/post-board routing flags on any dismissal (incl. swipe-to-dismiss), so a
|
||
// later board-level "+" never misroutes its pick into a pre- or post-board chain.
|
||
.sheet(isPresented: $showPaletteSheet, onDismiss: { addToPreBoard = false; addToPostBoard = false }) {
|
||
paletteSheet
|
||
}
|
||
}
|
||
|
||
/// Hosts the compact engine-settings sheet on its own node.
|
||
private var settingsSheetAnchor: some View {
|
||
Color.clear
|
||
.sheet(isPresented: $showSettingsSheet) {
|
||
settingsSheet
|
||
.presentationDetents([.medium, .large])
|
||
}
|
||
}
|
||
|
||
/// The whole-view layout: docked desktop layout on regular widths, canvas-first on compact.
|
||
@ViewBuilder
|
||
private var rootContent: some View {
|
||
if isCompact {
|
||
// No docked sidebar — the rig library is a sheet reached from the header.
|
||
builderColumn
|
||
} else {
|
||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||
rigSidebar
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
builderColumn
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A banner shown while a control is armed for MIDI Learn, prompting the user to move it.
|
||
@ViewBuilder
|
||
private var midiLearnBanner: some View {
|
||
if let midi: MIDIController = midi, let target: MIDIController.LearnTarget = midi.learnTarget {
|
||
Text(midiLearnBannerText(for: target))
|
||
.font(.callout.weight(.semibold))
|
||
.foregroundStyle(Color.black)
|
||
.padding(.horizontal, 14)
|
||
.padding(.vertical, 8)
|
||
.background(Capsule().fill(Color.orange))
|
||
.padding(.top, 6)
|
||
}
|
||
}
|
||
|
||
/// Banner copy tailored to what the armed Learn target is waiting for.
|
||
private func midiLearnBannerText(for target: MIDIController.LearnTarget) -> String {
|
||
switch target {
|
||
case .key:
|
||
return "Learn — press a key to assign it"
|
||
case .action:
|
||
return "Learn — press a footswitch to assign it"
|
||
case .cc:
|
||
return "Learn — move an expression pedal to assign it"
|
||
}
|
||
}
|
||
|
||
/// 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: Binding(get: { shoeGaze.currentRigID }, set: { shoeGaze.currentRigID = $0 }),
|
||
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() },
|
||
onRestoreStarters: { restoreStarterRigs() },
|
||
onShowCloudStatus: { showICloudUnavailableAlert = true }
|
||
)
|
||
}
|
||
|
||
/// (Re-)installs any shipped starter rigs missing from the library. Non-destructive: user rigs
|
||
/// are untouched, and already-present starters are skipped (matched by stable id).
|
||
private func restoreStarterRigs() {
|
||
let added: Int = RigLibraryBootstrap.restoreStarterRigs(into: library)
|
||
print("[ShoeGazeBuilderView] restored \(added) starter rig(s)")
|
||
}
|
||
|
||
// MARK: - Sleep / iCloud status
|
||
|
||
/// Platform name for the settings app, used in the iCloud guidance alert.
|
||
private static let settingsAppName: String = {
|
||
#if os(macOS)
|
||
return "System Settings"
|
||
#else
|
||
return "Settings"
|
||
#endif
|
||
}()
|
||
|
||
/// Keeps the device awake while audio is running so a live pedalboard session isn't cut off by
|
||
/// auto-lock; the assertion is released as soon as the engine stops. iOS/iPadOS only.
|
||
private func syncIdleTimer() {
|
||
#if os(iOS)
|
||
UIApplication.shared.isIdleTimerDisabled = shoeGaze.engine.isRunning
|
||
#endif
|
||
}
|
||
|
||
/// Clears the keep-awake assertion (view left the screen / app backgrounded).
|
||
private func releaseIdleTimer() {
|
||
#if os(iOS)
|
||
UIApplication.shared.isIdleTimerDisabled = false
|
||
#endif
|
||
}
|
||
|
||
/// Once the library has resolved, warn the user a single time if it fell back to local-only
|
||
/// storage (iCloud Drive signed out or disabled). The status icon can re-present on demand.
|
||
private func maybeWarnICloudUnavailable() {
|
||
guard library.isLoaded, !library.isICloud, !didCheckICloudStatus else { return }
|
||
didCheckICloudStatus = true
|
||
showICloudUnavailableAlert = true
|
||
}
|
||
|
||
/// 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) {
|
||
if isCompact {
|
||
compactHeader
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
compactTopSection
|
||
} else {
|
||
headerSection
|
||
#if !os(macOS)
|
||
recordingRow
|
||
#endif
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
topSection
|
||
}
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
ControlMappingLegend()
|
||
// Pre-board, the board canvas and post-board share a single vertical scroller, so the whole
|
||
// signal path reads top-to-bottom as one page (on macOS and iOS alike) instead of pinning
|
||
// the board and clipping the pre/post strips.
|
||
ScrollView(.vertical, showsIndicators: true) {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||
preBoardStrip
|
||
boardArea
|
||
postBoardStrip
|
||
}
|
||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||
}
|
||
.frame(maxHeight: .infinity)
|
||
}
|
||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||
// Make the undo coordinator reachable to every board / palette subview so their structural
|
||
// edits record history. Optional-object injection: `nil` resolves `@Environment(...)` to nil.
|
||
.environment(undo)
|
||
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
|
||
// Feed the rig's control map into the board tree so each pedal can draw its mapping strip.
|
||
// Reading `shoeGaze.midiMap` here (observable) refreshes every strip when a binding changes.
|
||
.environment(\.controlMappingMap, shoeGaze.midiMap)
|
||
// Let a pedal (e.g. Neural Amp on a model-file change) request a rebuild of its board.
|
||
// Captures only `shoeGaze` (a @MainActor session); `rebuildBoard` is safe on a running
|
||
// engine (at most one block of glitch).
|
||
.environment(\.pedalRebuildAction, { @MainActor [shoeGaze] (pedal: Pedal) in
|
||
// Branch-aware lookup — the pedal may live inside a parallel / stereo-split section.
|
||
guard let board: PedalBoard = shoeGaze.board(containing: pedal) else { return }
|
||
do {
|
||
_ = try shoeGaze.rebuildBoard(board, from: board.captureState())
|
||
} catch {
|
||
print("[ShoeGaze] board rebuild after model change failed: \(error)")
|
||
}
|
||
})
|
||
}
|
||
|
||
// MARK: - Compact layout (iPhone / narrow iPad)
|
||
|
||
/// The compact header: a performance row (title, transport, mute) always visible, plus a
|
||
/// horizontally scrollable row of panel toggles that open the composition sheets.
|
||
private var compactHeader: some View {
|
||
_ = transportTick
|
||
// The three control rows stack tight on the left; the transport sits top-right. The scope
|
||
// is inline (right, spanning the rows) in landscape, but on narrower portrait widths it
|
||
// would overlay/clip the header — so there it drops to a full-width strip below the rows.
|
||
// Row 1: title · [Bypass · Mute · Help · MIDI] Row 2: Tempo · Tuner Row 3: Rigs/Pedals/Settings
|
||
return VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
headerControlRows
|
||
|
||
if !isPortrait {
|
||
// Inline: clamped to the compact header height (a short strip beside transport).
|
||
headerScope
|
||
.frame(
|
||
width: ShoeGazeBuilderView.compactHeaderScopeWidth,
|
||
height: ShoeGazeBuilderView.compactHeaderScopeHeight
|
||
)
|
||
}
|
||
|
||
headerTransport
|
||
}
|
||
|
||
if isPortrait {
|
||
// Full-width strip at the scope's natural height (legend + lanes), so the legend
|
||
// doesn't overflow up into the panel row.
|
||
headerScope
|
||
.frame(maxWidth: .infinity)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The three stacked control rows shared by both orientations.
|
||
private var headerControlRows: some View {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
VStack(alignment: .leading, spacing: 1) {
|
||
Text("ShoeGaze").font(.headline).bold()
|
||
.foregroundStyle(Color.white)
|
||
currentRigLabel
|
||
}
|
||
if shoeGaze.isRecording { recordingBadge }
|
||
compactRigControlsRow
|
||
}
|
||
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
TempoView(shoeGaze: shoeGaze)
|
||
TunerView(shoeGaze: shoeGaze)
|
||
}
|
||
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
|
||
|
||
compactPanelRow
|
||
}
|
||
.frame(maxWidth: .infinity, alignment: .leading)
|
||
}
|
||
|
||
/// The oscilloscope. The caller sizes it: a fixed short strip inline (landscape) or a
|
||
/// full-width strip at natural height (portrait).
|
||
private var headerScope: some View {
|
||
ShoeGazeScopeView(shoeGaze: shoeGaze)
|
||
}
|
||
|
||
/// The Start / Stop over Record transport cluster (top-right in both orientations).
|
||
private var headerTransport: some View {
|
||
VStack(alignment: .trailing, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
EngineConfigView(
|
||
shoeGaze: shoeGaze,
|
||
hardwareSampleRate: hardwareSampleRate,
|
||
onConfigApplied: { transportTick.toggle(); autosave() },
|
||
transportOnly: true
|
||
)
|
||
#if !os(macOS)
|
||
recordButton
|
||
#endif
|
||
}
|
||
}
|
||
|
||
/// The rig-wide controls shown inline on the title row: Bypass / Mute / Help / MIDI.
|
||
private var compactRigControlsRow: some View {
|
||
ScrollView(.horizontal, showsIndicators: false) {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
undoButton
|
||
redoButton
|
||
rigBypassButton
|
||
rigMuteButton
|
||
inputMuteButton
|
||
helpButton
|
||
if let midi: MIDIController = midi {
|
||
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Undo of the last structural edit. Shown on iOS (where there is no Edit menu); disabled when
|
||
/// the undo stack is empty. macOS drives undo from the Edit menu (⌘Z) instead.
|
||
private var undoButton: some View {
|
||
Button {
|
||
undo?.undo()
|
||
} label: {
|
||
Image(systemName: "arrow.uturn.backward")
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.disabled(!(undo?.canUndo ?? false))
|
||
.help("Undo the last edit")
|
||
}
|
||
|
||
/// Redo of the last undone structural edit. iOS counterpart to the Edit-menu ⇧⌘Z.
|
||
private var redoButton: some View {
|
||
Button {
|
||
undo?.redo()
|
||
} label: {
|
||
Image(systemName: "arrow.uturn.forward")
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.disabled(!(undo?.canRedo ?? false))
|
||
.help("Redo the last undone edit")
|
||
}
|
||
|
||
/// The composition-panel row: buttons that open the Rigs / Pedals / Settings sheets.
|
||
private var compactPanelRow: some View {
|
||
ScrollView(.horizontal, showsIndicators: false) {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
compactPanelButton("Rigs", systemImage: "tray.full") { showRigsSheet = true }
|
||
compactPanelButton("Pedals", systemImage: "plus.app") { showPaletteSheet = true }
|
||
compactPanelButton("Settings", systemImage: "gearshape") { showSettingsSheet = true }
|
||
}
|
||
}
|
||
}
|
||
|
||
/// The recording indicator badge (extracted so both header variants can show it).
|
||
private var recordingBadge: some View {
|
||
HStack(spacing: 4) {
|
||
Circle()
|
||
.fill(Color.red)
|
||
.frame(width: ShoeGazeBuilderView.recordDotSize, height: ShoeGazeBuilderView.recordDotSize)
|
||
Text("REC")
|
||
.font(.caption.monospaced())
|
||
.foregroundStyle(Color.red)
|
||
}
|
||
}
|
||
|
||
/// A labelled icon button that opens one of the compact composition sheets.
|
||
private func compactPanelButton(
|
||
_ title: String,
|
||
systemImage: String,
|
||
action: @escaping () -> Void
|
||
) -> some View {
|
||
Button(action: action) {
|
||
Label(title, systemImage: systemImage)
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
}
|
||
|
||
/// Compact top strip: performance monitoring kept on screen — the board switch/mixer bar, the
|
||
/// scope, and the CPU meters. Tempo / Tuner sit below so they don't crowd the transport row.
|
||
private var compactTopSection: some View {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
BoardBarView(
|
||
shoeGaze: shoeGaze,
|
||
editingBoardIndex: $selectedBoardIndex,
|
||
crossfadeSeconds: $crossfadeSeconds,
|
||
onAddBoard: { addBoard() },
|
||
onClearBoards: { showClearDialog = true }
|
||
)
|
||
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
|
||
// Scope + Tempo/Tuner moved to the header; the CPU meters stay here.
|
||
LyrebirdStatusView(engine: shoeGaze.engine)
|
||
}
|
||
}
|
||
|
||
/// The Add-a-pedal palette + routing options, presented as a compact sheet.
|
||
private var paletteSheet: some View {
|
||
// A fixed header (title, type filter, Done) over a scrolling list. Not a NavigationStack —
|
||
// its transparent bar let the list scroll under the title. The palette does not self-wrap in
|
||
// a ScrollView (the host must), so it is wrapped here.
|
||
VStack(spacing: 0) {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
Text("Add Pedal")
|
||
.font(.headline)
|
||
.foregroundStyle(Color.white)
|
||
Spacer()
|
||
pedalFilterMenu
|
||
Button("Done") { addToPreBoard = false; addToPostBoard = false; showPaletteSheet = false }
|
||
.fontWeight(.semibold)
|
||
}
|
||
.padding()
|
||
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
|
||
ScrollView {
|
||
PedalPaletteView(
|
||
axis: .vertical,
|
||
filter: $pedalFilter,
|
||
showsFilterMenu: false,
|
||
onAdd: { type in
|
||
if addToPreBoard {
|
||
addPrePedal(type: type)
|
||
} else if addToPostBoard {
|
||
addPostPedal(type: type)
|
||
} else {
|
||
addPedal(type: type)
|
||
}
|
||
addToPreBoard = false
|
||
addToPostBoard = false
|
||
showPaletteSheet = false
|
||
},
|
||
onRouting: { action in
|
||
// Routing regions belong to a board, never the linear pre- or post-board chain.
|
||
addToPreBoard = false
|
||
addToPostBoard = false
|
||
performRouting(action)
|
||
showPaletteSheet = false
|
||
}
|
||
)
|
||
.padding()
|
||
}
|
||
}
|
||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
|
||
.preferredColorScheme(.dark)
|
||
// One fixed detent (no resize-drag) and drags scroll the list instead of the sheet.
|
||
.presentationDetents([.fraction(ShoeGazeBuilderView.paletteSheetHeightFraction)])
|
||
.presentationContentInteraction(.scrolls)
|
||
}
|
||
|
||
/// The type-filter menu shown in the Add-Pedal sheet header, bound to `pedalFilter`.
|
||
private var pedalFilterMenu: some View {
|
||
Menu {
|
||
Button("All Types") { pedalFilter = nil }
|
||
Divider()
|
||
ForEach(PedalCategory.allCases) { category in
|
||
Button(category.rawValue) { pedalFilter = category }
|
||
}
|
||
} label: {
|
||
HStack(spacing: 3) {
|
||
Image(systemName: "line.3.horizontal.decrease.circle")
|
||
Text(pedalFilter?.rawValue ?? "All").lineLimit(1)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Engine configuration (sample rate, input/output channel counts, input source), presented as
|
||
/// a compact sheet — the set-and-forget composition controls.
|
||
private var settingsSheet: some View {
|
||
NavigationStack {
|
||
// A plain scroll (not a Form) so the engine controls' horizontal row has the full sheet
|
||
// width — a Form row compresses it and clips the Start button to "S…".
|
||
ScrollView {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||
Text("Engine")
|
||
.font(.headline)
|
||
.foregroundStyle(Color.white)
|
||
EngineConfigView(
|
||
shoeGaze: shoeGaze,
|
||
hardwareSampleRate: hardwareSampleRate,
|
||
onConfigApplied: { transportTick.toggle(); autosave() }
|
||
)
|
||
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
|
||
HStack {
|
||
Text("Input")
|
||
.font(.headline)
|
||
.foregroundStyle(Color.white)
|
||
Spacer()
|
||
Picker("Input", selection: inputBinding) {
|
||
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
|
||
if shoeGaze.engine.numInputChannels > 0 {
|
||
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
|
||
Text("In \(channel)").tag(channel)
|
||
}
|
||
} else if onEnableLiveInput != nil {
|
||
Text("Live Input").tag(0)
|
||
}
|
||
}
|
||
.labelsHidden()
|
||
.pickerStyle(.menu)
|
||
}
|
||
|
||
#if !os(macOS)
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
Text("Recording")
|
||
.font(.headline)
|
||
.foregroundStyle(Color.white)
|
||
recordingFolderPicker
|
||
#endif
|
||
|
||
Spacer(minLength: 0)
|
||
}
|
||
.padding()
|
||
.frame(maxWidth: .infinity, alignment: .leading)
|
||
}
|
||
.navigationTitle("Settings")
|
||
#if os(iOS)
|
||
.navigationBarTitleDisplayMode(.inline)
|
||
#endif
|
||
.toolbar {
|
||
ToolbarItem(placement: .confirmationAction) {
|
||
Button("Done") { showSettingsSheet = false }
|
||
}
|
||
}
|
||
}
|
||
.preferredColorScheme(.dark)
|
||
}
|
||
|
||
/// 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() },
|
||
onClearBoards: { showClearDialog = true }
|
||
)
|
||
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
|
||
/// importers / exporter (one presentation per view node).
|
||
private var boardsSheetAnchor: some View {
|
||
Color.clear
|
||
.sheet(isPresented: $showBoardsSheet) {
|
||
BoardsSheetView(
|
||
shoeGaze: shoeGaze,
|
||
editingBoardIndex: $selectedBoardIndex,
|
||
crossfadeSeconds: $crossfadeSeconds,
|
||
onAddBoard: { addBoard() }
|
||
)
|
||
// Sheet content gets a fresh environment, so re-inject the coordinator here.
|
||
.environment(undo)
|
||
.presentationDetents([.medium, .large])
|
||
}
|
||
}
|
||
|
||
/// Hosts the library-export (`.shoegaze`) exporter on its own node. Writes the whole library as
|
||
/// one ``ShoeGazeDocument`` file for backup or transfer.
|
||
private var rigExportAnchor: some View {
|
||
Color.clear
|
||
.fileExporter(
|
||
isPresented: $showExporter,
|
||
document: exportDocument,
|
||
contentType: .shoeGaze,
|
||
defaultFilename: ShoeGazeBuilderView.defaultArchiveFileName
|
||
) { result in
|
||
if case .failure(let error) = result {
|
||
print("[ShoeGazeBuilderView] library export failed: \(error)")
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Hosts the library-import (`.shoegaze`) importer on its own node (cross-platform). Accepts a
|
||
/// ``ShoeGazeDocument`` or a legacy archive / single-rig file; imported rigs are added to the
|
||
/// library.
|
||
private var rigImportAnchor: some View {
|
||
Color.clear
|
||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.shoeGaze, .json]) { result in
|
||
handleArchiveImport(result)
|
||
}
|
||
}
|
||
|
||
/// Hosts the action-failure alert on its own node (one presentation per node).
|
||
private var actionErrorAnchor: some View {
|
||
Color.clear
|
||
.alert(
|
||
actionError?.title ?? "",
|
||
isPresented: Binding(
|
||
get: { actionError != nil },
|
||
set: { presented in if !presented { actionError = nil } }
|
||
),
|
||
presenting: actionError
|
||
) { _ in
|
||
Button("OK", role: .cancel) { }
|
||
} message: { error in
|
||
Text(error.message)
|
||
}
|
||
}
|
||
|
||
/// Surfaces a failed edit as an alert (and logs it). Maps the common stereo-width / merge errors
|
||
/// to player-facing wording (no API names); otherwise uses the error's `LocalizedError` text.
|
||
private func reportError(_ title: String, _ error: Error) {
|
||
actionError = ActionError(title: title, message: friendlyMessage(for: error))
|
||
}
|
||
|
||
private func friendlyMessage(for error: Error) -> String {
|
||
switch error as? ShoeGazeError {
|
||
case .stereoWidthExceeded, .cannotSplitStereoChain:
|
||
return "This board is already in stereo. Add a “Merge to Mono” before another stereo "
|
||
+ "(widening) pedal such as Chorus, Rotary, or a Granulator."
|
||
case .cannotMergeMonoChain:
|
||
return "This board is already mono — there’s no stereo signal to merge."
|
||
case .cannotUnzipMonoChain:
|
||
return "This board is mono — there’s no stereo signal to split into left/right lanes."
|
||
default:
|
||
return (error as? LocalizedError)?.errorDescription ?? error.localizedDescription
|
||
}
|
||
}
|
||
|
||
#if !os(macOS)
|
||
/// Hosts the recording-folder importer on its own node.
|
||
private var recordingFolderImportAnchor: some View {
|
||
Color.clear
|
||
.fileImporter(isPresented: $showRecordingFolderImporter, allowedContentTypes: [.folder]) { result in
|
||
handleRecordingFolderImport(result)
|
||
}
|
||
}
|
||
#endif
|
||
|
||
// MARK: - Transport row
|
||
|
||
/// Two-row header. Left: the title with the Tempo / Tuner toggles stacked and left-aligned
|
||
/// beside it. Right: the engine options (row 1) over the input controls (row 2), trailing-
|
||
/// aligned so both right edges line up. Keeping it two rows tall frees canvas for the pedals.
|
||
private var headerSection: some View {
|
||
_ = transportTick
|
||
return HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
VStack(alignment: .leading, spacing: 1) {
|
||
Text("ShoeGaze")
|
||
.font(.title2).bold()
|
||
.foregroundStyle(Color.white)
|
||
currentRigLabel
|
||
}
|
||
if shoeGaze.isRecording {
|
||
// Recording indicator (both platforms; recording is driven from the macOS Record
|
||
// menu or the iOS controls below).
|
||
HStack(spacing: 4) {
|
||
Circle()
|
||
.fill(Color.red)
|
||
.frame(width: ShoeGazeBuilderView.recordDotSize, height: ShoeGazeBuilderView.recordDotSize)
|
||
Text("REC")
|
||
.font(.caption.monospaced())
|
||
.foregroundStyle(Color.red)
|
||
}
|
||
}
|
||
|
||
// Tempo over Tuner, left-aligned to each other.
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
TempoView(shoeGaze: shoeGaze)
|
||
TunerView(shoeGaze: shoeGaze)
|
||
}
|
||
|
||
Spacer()
|
||
|
||
// Right column: engine options over input controls, both right-aligned.
|
||
VStack(alignment: .trailing, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
if let midi: MIDIController = midi {
|
||
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
|
||
}
|
||
helpButton
|
||
// Icon-only in the docked desktop cluster so the four toggles + Rate picker +
|
||
// I/O steppers + Start never overrun the row and clip the pickers. Each button
|
||
// keeps its `.help` tooltip; the compact layout still shows the text labels.
|
||
Group {
|
||
rigBypassButton
|
||
rigMuteButton
|
||
inputMuteButton
|
||
}
|
||
.labelStyle(.iconOnly)
|
||
EngineConfigView(
|
||
shoeGaze: shoeGaze,
|
||
hardwareSampleRate: hardwareSampleRate,
|
||
onConfigApplied: { transportTick.toggle(); autosave() }
|
||
)
|
||
}
|
||
.frame(height: TempoView.enabledHeight)
|
||
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
// Whether engaging the tuner silences the rig; sits left of the input selector.
|
||
Toggle("Mute while tuning", isOn: Binding(
|
||
get: { shoeGaze.tunerMutesRig },
|
||
set: { shoeGaze.tunerMutesRig = $0 }
|
||
))
|
||
.toggleStyle(.switch)
|
||
.fixedSize()
|
||
|
||
Text("Input:")
|
||
.font(.subheadline)
|
||
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
|
||
Picker("Input", selection: inputBinding) {
|
||
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
|
||
if shoeGaze.engine.numInputChannels > 0 {
|
||
ForEach(Array(0..<shoeGaze.engine.numInputChannels), id: \.self) { channel in
|
||
Text("In \(channel)").tag(channel)
|
||
}
|
||
} else if onEnableLiveInput != nil {
|
||
// No input channel yet: offer live input; selecting it asks the host to
|
||
// request mic access and rebuild the engine with one (channel 0).
|
||
Text("Live Input").tag(0)
|
||
}
|
||
}
|
||
.labelsHidden()
|
||
.pickerStyle(.menu)
|
||
.foregroundStyle(Color.white)
|
||
}
|
||
.frame(height: TempoView.enabledHeight)
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Opens the in-app help. Shown on both platforms; macOS also has a Help menu item.
|
||
private var helpButton: some View {
|
||
Button {
|
||
showHelpSheet = true
|
||
} label: {
|
||
Image(systemName: "questionmark.circle")
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.help("Open ShoeGaze Help")
|
||
}
|
||
|
||
/// Global rig bypass — routes every board to its dry input at once (pedals skipped). Lit when
|
||
/// engaged. A live performance panic/compare control.
|
||
private var rigBypassButton: some View {
|
||
let bypassed: Bool = shoeGaze.rigBypassed
|
||
return Button {
|
||
shoeGaze.toggleRigBypassed()
|
||
} label: {
|
||
Label(bypassed ? "Rig Bypassed" : "Bypass Rig", systemImage: "power")
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(bypassed ? .orange : .gray)
|
||
.help("Bypass the entire rig — every board passes your dry input straight through")
|
||
}
|
||
|
||
/// Global rig mute — a hard gate to silence the whole output (distinct from Bypass, which
|
||
/// passes the dry signal through). Lit when engaged. A live performance panic/silence control.
|
||
private var rigMuteButton: some View {
|
||
let muted: Bool = shoeGaze.rigMuted
|
||
return Button {
|
||
shoeGaze.toggleRigMuted()
|
||
} label: {
|
||
Label(muted ? "Rig Muted" : "Mute Rig",
|
||
systemImage: muted ? "speaker.slash.fill" : "speaker.wave.2.fill")
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(muted ? .red : .gray)
|
||
.help("Mute the entire rig output — silences all sound")
|
||
}
|
||
|
||
/// Input-mute toggle, shown beside the Start/Stop transport. Silences the incoming guitar / mic
|
||
/// signal (distinct from the rig-output mute). Comes up muted on each engine start, with a
|
||
/// pulsing red glow while muted so new users spot why they hear nothing.
|
||
private var inputMuteButton: some View {
|
||
InputMuteButton(shoeGaze: shoeGaze)
|
||
}
|
||
|
||
/// The input-mute toggle with a pulsing red glow while active. Its own view so it can own the
|
||
/// repeating-animation state; the glow reads `pulse`, which oscillates under a `repeatForever`
|
||
/// animation only while the input is muted.
|
||
private struct InputMuteButton: View {
|
||
|
||
let shoeGaze: ShoeGaze
|
||
|
||
/// Oscillates 0↔1 under a repeating animation while muted, driving the glow's radius/opacity.
|
||
@State private var pulse: Bool = false
|
||
|
||
private static let glowCornerRadius: CGFloat = 6
|
||
private static let glowLineWidth: CGFloat = 1.5
|
||
private static let glowRadiusLow: CGFloat = 2
|
||
private static let glowRadiusHigh: CGFloat = 9
|
||
private static let glowOpacityLow: Double = 0.35
|
||
private static let glowOpacityHigh: Double = 0.95
|
||
private static let pulseDuration: Double = 0.85
|
||
private static let pulseSettleDuration: Double = 0.2
|
||
|
||
var body: some View {
|
||
let muted: Bool = shoeGaze.inputMuted
|
||
return Button {
|
||
shoeGaze.toggleInputMuted()
|
||
} label: {
|
||
Label(muted ? "Input Muted" : "Mute Input",
|
||
systemImage: muted ? "mic.slash.fill" : "mic.fill")
|
||
.font(.subheadline)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(muted ? .red : .gray)
|
||
.overlay(glow(muted: muted))
|
||
.help("Mute the input feeding the pedals — silences the incoming guitar / mic signal")
|
||
.onChange(of: muted) { _, nowMuted in startOrStopPulse(muted: nowMuted) }
|
||
.onAppear { startOrStopPulse(muted: muted) }
|
||
}
|
||
|
||
/// A red ring + shadow that pulses while muted, and is invisible otherwise. Non-interactive
|
||
/// so it never intercepts the button's taps.
|
||
private func glow(muted: Bool) -> some View {
|
||
RoundedRectangle(cornerRadius: InputMuteButton.glowCornerRadius, style: .continuous)
|
||
.strokeBorder(Color.red, lineWidth: InputMuteButton.glowLineWidth)
|
||
.shadow(
|
||
color: Color.red,
|
||
radius: pulse ? InputMuteButton.glowRadiusHigh : InputMuteButton.glowRadiusLow
|
||
)
|
||
.opacity(muted ? (pulse ? InputMuteButton.glowOpacityHigh : InputMuteButton.glowOpacityLow) : 0)
|
||
.allowsHitTesting(false)
|
||
}
|
||
|
||
/// Starts the forever-repeating pulse when muted, or settles it back to rest when not.
|
||
private func startOrStopPulse(muted: Bool) {
|
||
if muted {
|
||
pulse = false
|
||
withAnimation(.easeInOut(duration: InputMuteButton.pulseDuration).repeatForever(autoreverses: true)) {
|
||
pulse = true
|
||
}
|
||
} else {
|
||
withAnimation(.easeOut(duration: InputMuteButton.pulseSettleDuration)) { pulse = false }
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - Pre-board strip
|
||
|
||
/// The shared pre-board processing chain, shown above the boards. Hidden to a thin "+ Pre" button
|
||
/// when empty; otherwise a horizontal row of pre-pedals over a divider marking that it feeds all
|
||
/// boards. Pre-pedals carry their own undo (knob edits) via the injected coordinator.
|
||
@ViewBuilder
|
||
private var preBoardStrip: some View {
|
||
let prePedals: [Pedal] = shoeGaze.preBoardPedals
|
||
if prePedals.isEmpty {
|
||
HStack {
|
||
Button {
|
||
addToPreBoard = true
|
||
showPaletteSheet = true
|
||
} label: {
|
||
Label("Pre-board", systemImage: "plus").font(.caption)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.help("Add a pre-board pedal — processes the input once, feeding every board")
|
||
Spacer()
|
||
}
|
||
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
|
||
} else {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
HStack {
|
||
Text("Pre-board").font(.caption).bold().foregroundStyle(Color.white)
|
||
Spacer()
|
||
Button {
|
||
addToPreBoard = true
|
||
showPaletteSheet = true
|
||
} label: {
|
||
Image(systemName: "plus")
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.help("Add a pre-board pedal")
|
||
}
|
||
ScrollView(.horizontal, showsIndicators: false) {
|
||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
// Key by the pedal's stable id — a pre-board edit rebuilds the chain into new
|
||
// instances, so an offset key would bind a card to a torn-down pedal.
|
||
ForEach(Array(prePedals.enumerated()), id: \.element.id) { pair in
|
||
PedalView(pedal: pair.element)
|
||
.overlay(alignment: .topTrailing) {
|
||
Button(role: .destructive) {
|
||
removePreBoardPedal(at: pair.offset)
|
||
} label: {
|
||
Image(systemName: "xmark.circle.fill")
|
||
.font(.title3)
|
||
.foregroundStyle(Color.white, Color.black.opacity(0.55))
|
||
}
|
||
.buttonStyle(.plain)
|
||
.padding(4)
|
||
.help("Remove this pre-board pedal")
|
||
}
|
||
}
|
||
}
|
||
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
|
||
}
|
||
HStack(spacing: 6) {
|
||
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
|
||
Text("feeds all boards")
|
||
.font(.caption2)
|
||
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
|
||
.fixedSize()
|
||
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
|
||
}
|
||
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
|
||
}
|
||
.environment(undo)
|
||
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
|
||
}
|
||
}
|
||
|
||
private func addPrePedal(type: String) {
|
||
do {
|
||
try editing("Add \(type) (pre-board)") { try shoeGaze.appendPrePedal(PedalType(type)) }
|
||
autosave()
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] appendPrePedal failed: \(error)")
|
||
reportError("Couldn’t add \(type)", error)
|
||
}
|
||
}
|
||
|
||
private func removePreBoardPedal(at index: Int) {
|
||
do {
|
||
try editing("Remove pre-board pedal") { try shoeGaze.removePrePedal(at: index) }
|
||
autosave()
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] removePrePedal failed: \(error)")
|
||
reportError("Couldn’t remove pre-board pedal", error)
|
||
}
|
||
}
|
||
|
||
// MARK: - Post-board chain
|
||
|
||
/// The post-board chain strip, shown below the boards. Mirrors ``preBoardStrip``: hidden (just a
|
||
/// "+Post" button) when empty, a horizontal pedal strip otherwise. The post-chain processes the
|
||
/// summed board mix once before the hardware output — global reverb, a bus limiter, a final EQ.
|
||
@ViewBuilder
|
||
private var postBoardStrip: some View {
|
||
let postPedals: [Pedal] = shoeGaze.postBoardPedals
|
||
if postPedals.isEmpty {
|
||
HStack {
|
||
Button {
|
||
addToPostBoard = true
|
||
showPaletteSheet = true
|
||
} label: {
|
||
Label("Post-board", systemImage: "plus").font(.caption)
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.help("Add a post-board pedal — processes the summed board mix before the output")
|
||
Spacer()
|
||
}
|
||
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
|
||
} else {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
HStack(spacing: 6) {
|
||
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
|
||
Text("from board mix")
|
||
.font(.caption2)
|
||
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
|
||
.fixedSize()
|
||
Rectangle().fill(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity)).frame(height: 1)
|
||
}
|
||
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
|
||
HStack {
|
||
Text("Post-board").font(.caption).bold().foregroundStyle(Color.white)
|
||
Spacer()
|
||
Button {
|
||
addToPostBoard = true
|
||
showPaletteSheet = true
|
||
} label: {
|
||
Image(systemName: "plus")
|
||
}
|
||
.buttonStyle(.bordered)
|
||
.tint(.gray)
|
||
.help("Add a post-board pedal")
|
||
}
|
||
ScrollView(.horizontal, showsIndicators: false) {
|
||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
// Key by the pedal's stable id — a post-board edit rebuilds the chain into new
|
||
// instances, so an offset key would bind a card to a torn-down pedal.
|
||
ForEach(Array(postPedals.enumerated()), id: \.element.id) { pair in
|
||
PedalView(pedal: pair.element)
|
||
.overlay(alignment: .topTrailing) {
|
||
Button(role: .destructive) {
|
||
removePostBoardPedal(at: pair.offset)
|
||
} label: {
|
||
Image(systemName: "xmark.circle.fill")
|
||
.font(.title3)
|
||
.foregroundStyle(Color.white, Color.black.opacity(0.55))
|
||
}
|
||
.buttonStyle(.plain)
|
||
.padding(4)
|
||
.help("Remove this post-board pedal")
|
||
}
|
||
}
|
||
}
|
||
.padding(.horizontal, ShoeGazeBuilderView.outerPadding)
|
||
}
|
||
}
|
||
.environment(undo)
|
||
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
|
||
}
|
||
}
|
||
|
||
private func addPostPedal(type: String) {
|
||
do {
|
||
try editing("Add \(type) (post-board)") { try shoeGaze.appendPostPedal(PedalType(type)) }
|
||
autosave()
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] appendPostPedal failed: \(error)")
|
||
reportError("Couldn’t add \(type)", error)
|
||
}
|
||
}
|
||
|
||
private func removePostBoardPedal(at index: Int) {
|
||
do {
|
||
try editing("Remove post-board pedal") { try shoeGaze.removePostPedal(at: index) }
|
||
autosave()
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] removePostPedal failed: \(error)")
|
||
reportError("Couldn’t remove post-board pedal", error)
|
||
}
|
||
}
|
||
|
||
// MARK: - Board area
|
||
|
||
private var boardArea: some View {
|
||
// Content-sized so it flows inside the shared pre/board/post vertical scroller (scrolls
|
||
// horizontally for a long chain; a tall parallel split grows the page). No vertical centering —
|
||
// the board sits in signal-flow order between the pre-board and post-board strips.
|
||
BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex, sizesToContent: true)
|
||
.frame(maxWidth: .infinity, alignment: .leading)
|
||
}
|
||
|
||
/// Performs a routing action from the palette against the selected board.
|
||
private func performRouting(_ action: PedalPaletteView.RoutingAction) {
|
||
guard !shoeGaze.boards.isEmpty else { return }
|
||
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
|
||
do {
|
||
switch action {
|
||
case .stereoSplit: try editing("Add Stereo Split") { _ = try shoeGaze.appendStereoSplit(to: board) }
|
||
case .parallelSplit: try editing("Add Parallel Split") { _ = try shoeGaze.appendParallelSplit(to: board) }
|
||
case .mergeToMono: try editing("Add Merge to Mono") { _ = try shoeGaze.appendMergeToMono(to: board) }
|
||
case .chainRouter: break // multi-board routing; not handled in the single-board builder
|
||
}
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] routing \(action) failed: \(error)")
|
||
reportError("Couldn’t add routing", error)
|
||
}
|
||
}
|
||
|
||
/// `selectedBoardIndex` clamped to a valid board (or `0`); guards against deletes/loads that
|
||
/// change the board count out from under the picker.
|
||
private var clampedBoardIndex: Int {
|
||
guard !shoeGaze.boards.isEmpty else { return 0 }
|
||
return min(max(selectedBoardIndex, 0), shoeGaze.boards.count - 1)
|
||
}
|
||
|
||
// MARK: - Input binding
|
||
|
||
private var inputBinding: Binding<Int> {
|
||
Binding(
|
||
get: {
|
||
switch shoeGaze.inputSource {
|
||
case .testLoop: return ShoeGazeBuilderView.testLoopTag
|
||
case .liveInput(let channel): return channel
|
||
}
|
||
},
|
||
set: { newValue in
|
||
if newValue == ShoeGazeBuilderView.testLoopTag {
|
||
switchInput(to: .testLoop)
|
||
} else if newValue < shoeGaze.engine.numInputChannels {
|
||
switchInput(to: .liveInput(channel: newValue))
|
||
} else if let onEnableLiveInput {
|
||
// Requested a channel the current engine doesn't have (iOS, 0 channels):
|
||
// hand off to the host to grant mic + rebuild with an input channel.
|
||
onEnableLiveInput()
|
||
}
|
||
}
|
||
)
|
||
}
|
||
|
||
// MARK: - Actions
|
||
|
||
/// Runs a structural edit through the undo coordinator (recording a checkpoint when it changes
|
||
/// the rig), or directly when no coordinator is present. Keep the closure to the mutation itself
|
||
/// so the before/after snapshots bracket exactly the edit.
|
||
@discardableResult
|
||
private func editing<T>(_ label: String, _ action: () throws -> T) rethrows -> T {
|
||
if let undo: UndoCoordinator = undo {
|
||
return try undo.perform(label, action)
|
||
}
|
||
return try action()
|
||
}
|
||
|
||
private func addPedal(type: String) {
|
||
guard !shoeGaze.boards.isEmpty else { return }
|
||
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
|
||
do {
|
||
try editing("Add \(type)") { try shoeGaze.appendPedal(PedalType(type), to: board) }
|
||
autosave()
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
|
||
reportError("Couldn’t add \(type)", error)
|
||
}
|
||
}
|
||
|
||
private func addBoard() {
|
||
var created: PedalBoard?
|
||
do {
|
||
try editing("Add Board") {
|
||
let board: PedalBoard = try shoeGaze.addBoard()
|
||
created = board
|
||
try shoeGaze.finalizeBoard(board)
|
||
}
|
||
selectedBoardIndex = shoeGaze.boards.count - 1
|
||
autosave()
|
||
} catch {
|
||
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
|
||
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
|
||
reportError("Couldn’t add board", error)
|
||
}
|
||
}
|
||
|
||
/// Persists the current rig to the autosave file. Called after structural edits so state
|
||
/// survives a restart even without an explicit Save; the app shells also save on background.
|
||
private func autosave() {
|
||
// The autosave envelope records `shoeGaze.currentRigID` alongside the graph, so the highlight
|
||
// and the restored graph stay consistent without any separate bookkeeping.
|
||
RigStore.save(shoeGaze)
|
||
}
|
||
|
||
/// Removes every board, then seeds one fresh empty board so the builder is never boardless.
|
||
/// Resets the edit target and autosaves the cleared state.
|
||
private func performClear() {
|
||
// Stop around the rebuild so removing every board and immediately re-adding a fresh one
|
||
// can't reuse a bus a just-removed master is still draining (one-block glitch).
|
||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||
if wasRunning { shoeGaze.engine.stop() }
|
||
|
||
// Recorded as one undoable checkpoint: undo restores the whole pre-clear rig (boards +
|
||
// MIDI bindings). The snapshot is captured at the top of this block, before the mutations.
|
||
editing("Clear Board") {
|
||
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
|
||
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
|
||
// re-resolve onto the fresh board's pedals.
|
||
shoeGaze.midiMap = nil
|
||
|
||
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
|
||
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] clear failed to seed a fresh board: \(error)")
|
||
}
|
||
}
|
||
selectedBoardIndex = 0
|
||
|
||
if wasRunning { try? shoeGaze.engine.start() }
|
||
autosave()
|
||
transportTick.toggle()
|
||
}
|
||
|
||
/// Switches input source, stopping/restarting the engine around the graph rebuild.
|
||
///
|
||
/// Live input requires microphone authorisation first — without it macOS feeds the AUHAL
|
||
/// input silent zeros. The request is asynchronous, so when the source is `.liveInput` the
|
||
/// actual switch is deferred until the grant resolves; a denial falls back to the test loop.
|
||
private func switchInput(to source: InputSource) {
|
||
guard case .liveInput = source else {
|
||
applyInputSource(source)
|
||
return
|
||
}
|
||
MicrophonePermission.request { granted in
|
||
if !granted { showMicDeniedAlert = true }
|
||
applyInputSource(granted ? source : .testLoop)
|
||
}
|
||
}
|
||
|
||
/// Applies an input-source change, stopping/restarting the engine around the graph rebuild.
|
||
private func applyInputSource(_ source: InputSource) {
|
||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||
if wasRunning { shoeGaze.engine.stop() }
|
||
do {
|
||
try shoeGaze.setInputSource(source)
|
||
autosave() // the rig is the source of truth for the input selection; record it now
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
|
||
}
|
||
if wasRunning {
|
||
try? shoeGaze.engine.start()
|
||
}
|
||
transportTick.toggle()
|
||
}
|
||
|
||
// MARK: - Input restore
|
||
|
||
/// Reconciles the microphone permission with the input source the rig already restored.
|
||
///
|
||
/// The rig (autosave envelope / library entry) is the single source of truth for the input
|
||
/// selection — `RigStore.restore` / `loadRig` set `shoeGaze.inputSource` before this view
|
||
/// appears, and a fresh-launch seed defaults it to live In 0. This runs once on appear only to
|
||
/// make a restored live-input selection actually audible: it requests mic access (surfacing the
|
||
/// prompt at launch rather than at the first Start) and falls back to the test loop on denial.
|
||
/// A restored test-loop selection is honoured untouched.
|
||
private func restoreInputSelection() {
|
||
guard !didRestoreInput else { return }
|
||
didRestoreInput = true
|
||
|
||
guard case .liveInput = shoeGaze.inputSource else { return }
|
||
MicrophonePermission.request { granted in
|
||
if !granted {
|
||
showMicDeniedAlert = true
|
||
applyInputSource(.testLoop)
|
||
}
|
||
}
|
||
}
|
||
|
||
// MARK: - Board-switch shortcuts
|
||
|
||
/// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the
|
||
/// edit target, plus ⌘Z / ⇧⌘Z (undo / redo), ⌘M (rig mute), and ⌘⇧1…⌘⇧0 (set-list rigs) on
|
||
/// iOS/iPadOS. Kept at zero opacity so the shortcuts stay active without showing chrome.
|
||
private var boardSwitchShortcuts: some View {
|
||
ZStack {
|
||
ForEach(0 ..< min(ShoeGazeBuilderView.maxBoardShortcuts, shoeGaze.boards.count), id: \.self) { index in
|
||
// Titles are invisible (the ZStack is opacity 0) but feed the iPadOS ⌘-hold
|
||
// discoverability HUD, so the shortcut reads as a named command there.
|
||
Button("Switch to Board \(index + 1)") { switchToBoard(index) }
|
||
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
|
||
}
|
||
// ⌘Z / ⇧⌘Z are Undo / Redo on iOS/iPadOS hardware keyboards; rig mute moves to ⌘M so the
|
||
// standard undo chord is free. On macOS the Edit / Board menus own these equivalents, so
|
||
// they are not also bound here (a double-bound event is ambiguous).
|
||
#if !os(macOS)
|
||
Button("Undo") { undo?.undo() }
|
||
.keyboardShortcut("z", modifiers: .command)
|
||
.disabled(!(undo?.canUndo ?? false))
|
||
Button("Redo") { undo?.redo() }
|
||
.keyboardShortcut("z", modifiers: [.command, .shift])
|
||
.disabled(!(undo?.canRedo ?? false))
|
||
Button("Mute / Unmute Rig") { shoeGaze.toggleRigMuted() }
|
||
.keyboardShortcut("m", modifiers: .command)
|
||
// ⌘⇧1…⌘⇧9 + ⌘⇧0 load set-list rigs 1…10. macOS binds these via the Rigs ▸ Set List menu
|
||
// instead, so they are not also bound here.
|
||
ForEach(0 ..< ShoeGazeBuilderView.maxRigShortcuts, id: \.self) { slot in
|
||
Button("Load Set List Rig \(slot + 1)") { loadRigSlot(slot) }
|
||
.keyboardShortcut(ShoeGazeBuilderView.rigSlotKey(slot), modifiers: [.command, .shift])
|
||
}
|
||
#endif
|
||
}
|
||
.opacity(0)
|
||
.frame(width: 0, height: 0)
|
||
.accessibilityHidden(true)
|
||
}
|
||
|
||
/// The key equivalent for set-list slot `slot` (0-based): slots 0…8 map to `1`…`9`, slot 9 to
|
||
/// `0` — matching the ⌘⇧1…⌘⇧0 physical row.
|
||
private static func rigSlotKey(_ slot: Int) -> KeyEquivalent {
|
||
KeyEquivalent(Character(slot < 9 ? "\(slot + 1)" : "0"))
|
||
}
|
||
|
||
/// Solos board `index` (a live amp-channel-style switch) and makes it the edit target.
|
||
private func switchToBoard(_ index: Int) {
|
||
guard index < shoeGaze.boards.count else { return }
|
||
selectedBoardIndex = index
|
||
let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeBuilderView.maxCrossfadeSeconds)
|
||
shoeGaze.soloBoard(shoeGaze.boards[index], crossfadeSeconds: seconds)
|
||
}
|
||
|
||
// MARK: - Recording (iOS)
|
||
|
||
// 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 {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
recordingFolderPicker
|
||
Spacer()
|
||
recordButton
|
||
}
|
||
}
|
||
|
||
/// The Record / Stop-Recording button (performance control; lives in the compact header).
|
||
private var recordButton: some View {
|
||
Button(shoeGaze.isRecording ? "Stop Recording" : "Record") {
|
||
toggleRecording()
|
||
}
|
||
.buttonStyle(.borderedProminent)
|
||
.tint(shoeGaze.isRecording ? .red : .accentColor)
|
||
.disabled(shoeGaze.recordingFolder == nil && !shoeGaze.isRecording)
|
||
}
|
||
|
||
/// The recording-folder chooser + current folder name (a set-and-forget control; shown in the
|
||
/// compact Settings sheet).
|
||
private var recordingFolderPicker: some View {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
Button("Recording Folder…") { showRecordingFolderImporter = true }
|
||
.buttonStyle(.bordered).tint(.blue)
|
||
Text(shoeGaze.recordingFolder?.lastPathComponent ?? "No folder")
|
||
.font(.caption)
|
||
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.folderLabelOpacity))
|
||
.lineLimit(1)
|
||
.truncationMode(.middle)
|
||
}
|
||
}
|
||
|
||
private func toggleRecording() {
|
||
if shoeGaze.isRecording {
|
||
shoeGaze.stopRecording()
|
||
} else {
|
||
do { try shoeGaze.startRecording() }
|
||
catch { print("[ShoeGazeBuilderView] startRecording() failed: \(error)") }
|
||
}
|
||
}
|
||
|
||
private func handleRecordingFolderImport(_ result: Result<URL, Error>) {
|
||
switch result {
|
||
case .success(let url):
|
||
// A `.fileImporter` folder URL is security-scoped on iOS; keep access open for the
|
||
// session so the recorder can write into it.
|
||
if url.startAccessingSecurityScopedResource() {
|
||
shoeGaze.recordingFolder = url
|
||
} else {
|
||
print("[ShoeGazeBuilderView] could not access recording folder")
|
||
}
|
||
case .failure(let error):
|
||
print("[ShoeGazeBuilderView] recording folder pick failed: \(error)")
|
||
}
|
||
}
|
||
#endif
|
||
|
||
// MARK: - Rig library
|
||
|
||
/// 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 {
|
||
// Keep the player's currently-chosen input across the switch (e.g. a live guitar), rather
|
||
// than snapping to the input the selected rig was authored with.
|
||
try shoeGaze.loadRig(from: entry.state, keepingCurrentInput: true)
|
||
currentRigID = entry.id
|
||
selectedBoardIndex = 0
|
||
autosave()
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] loadEntry failed: \(error)")
|
||
}
|
||
// Switching to a different rig is not an undoable edit — discard the previous rig's history
|
||
// so an undo can't restore a different document's topology. Unconditional: `loadRig` tears
|
||
// the old rig down even when it throws, so the prior history is invalid either way.
|
||
undo?.clear()
|
||
if wasRunning { try? shoeGaze.engine.start() }
|
||
transportTick.toggle()
|
||
}
|
||
|
||
/// Loads the set-list rig at zero-based `index` (the library's manual order), if one exists.
|
||
/// Backs the ⌘⇧1…⌘⇧0 shortcuts and the macOS Rigs ▸ Set List menu. Routes through
|
||
/// ``requestLoad(_:)`` so the unsaved-changes prompt and no-op-if-current behaviour apply.
|
||
///
|
||
/// - Parameter index: Zero-based slot index (0…9).
|
||
private func loadRigSlot(_ index: Int) {
|
||
guard index >= 0, index < library.entries.count else { return }
|
||
requestLoad(library.entries[index])
|
||
}
|
||
|
||
/// Switches to `entry`, prompting to save first when the current rig has unsaved changes.
|
||
/// No-op when `entry` is already the current rig.
|
||
private func requestLoad(_ entry: RigEntry) {
|
||
guard entry.id != currentRigID else { return }
|
||
if isCurrentRigDirty() {
|
||
pendingSwitchEntry = entry
|
||
showSwitchSaveDialog = true
|
||
} else {
|
||
loadEntry(entry)
|
||
}
|
||
}
|
||
|
||
/// Whether the working rig differs from the library entry it was loaded from. A working rig with
|
||
/// no backing entry counts as dirty when it has any boards.
|
||
///
|
||
/// Compares rig content only (boards, routers, MIDI, tempo) — not the live input source or engine
|
||
/// channel counts, which are intentionally kept across a rig switch and so must not register as
|
||
/// unsaved changes (otherwise switching between rigs always prompts to save).
|
||
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().hasSameRigContent(as: 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
|
||
}
|
||
// Overwriting a built-in starter rig replaces it in the library. Confirm first, offering a
|
||
// non-destructive "Save as New Rig" so the shipped original can be kept.
|
||
if FactoryRigLibrary.isFactory(existing.id) {
|
||
factoryOverwrite = FactoryOverwriteRequest(entry: existing, completion: 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).
|
||
///
|
||
/// - Parameter completion: Follow-up run once the new entry is persisted (e.g. the "Save & Clear"
|
||
/// clear step, or the pending action from a factory-rig overwrite prompt).
|
||
private func promptSaveAs(then completion: @escaping () -> Void = { }) {
|
||
namePrompt = RigNamePrompt(
|
||
title: "Save Rig As",
|
||
initialText: currentRigName() ?? defaultNewRigName(),
|
||
confirmLabel: "Save"
|
||
) { name in
|
||
persist(shoeGaze.captureEntry(name: name), then: completion)
|
||
}
|
||
}
|
||
|
||
/// 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 whole library into the `.shoegaze` document exporter.
|
||
private func exportArchiveAction() {
|
||
do {
|
||
exportDocument = RigFileDocument(data: try library.exportDocumentData())
|
||
showExporter = true
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] exportDocumentData 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
|
||
// A brand-new rig is a fresh document — drop any prior undo history.
|
||
undo?.clear()
|
||
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 subtitle under the app title showing which rig is loaded. Resolves the name from the
|
||
/// library once it has loaded; shows "Unsaved rig" when the working graph has no source-rig
|
||
/// id (a cleared / never-saved session). Reads `shoeGaze.currentRigID` and `library.entries`
|
||
/// so it refreshes automatically when a rig is loaded or the library finishes loading.
|
||
private var currentRigLabel: some View {
|
||
let hasSource: Bool = currentRigID != nil
|
||
let name: String
|
||
if let resolved: String = currentRigName() {
|
||
name = resolved
|
||
} else if hasSource {
|
||
// Source id exists but the library hasn't resolved it yet (still loading).
|
||
name = library.isLoaded ? "Unknown rig" : "Loading…"
|
||
} else {
|
||
name = "Unsaved rig"
|
||
}
|
||
return HStack(spacing: 5) {
|
||
Image(systemName: hasSource ? "guitars.fill" : "guitars")
|
||
.font(.caption2)
|
||
Text(name)
|
||
.font(.caption)
|
||
.lineLimit(1)
|
||
}
|
||
.foregroundStyle(Color.white.opacity(hasSource ? 0.8 : 0.5))
|
||
.help(hasSource ? "Loaded rig: \(name)" : "This rig has not been saved to the library yet")
|
||
}
|
||
|
||
/// 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)"
|
||
}
|
||
}
|