4627b3b800
Boards sheet (BoardsSheetView): rename, drag-reorder, swipe-delete, plus per-board enable/solo/level and a Solo/Blend + crossfade header. Opened from a "Boards…" button in the builder; presented with medium/large detents on iOS. Makes ShoeGaze.moveBoard public to back the reorder. Keyboard switching: hidden ⌘1…⌘9 buttons in the builder solo (live-switch to) the matching board and select it as the edit target. Unified player: ShoeGazeView drops its bespoke Active picker + crossfade field and hosts the shared BoardBarView, matching the builder. Input persistence: the builder saves the input choice (test loop vs live channel) to UserDefaults and restores it on appear. With no saved choice it defaults to live input when the mic is already authorised and an input channel exists, else stays on the test loop. The iOS builder now opens one input channel so live input is actually available there. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
521 lines
21 KiB
Swift
521 lines
21 KiB
Swift
// ShoeGazeBuilderView.swift
|
||
// Lyrebird
|
||
//
|
||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||
// SPDX-License-Identifier: MIT
|
||
|
||
#if canImport(AppKit)
|
||
import AppKit
|
||
#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
|
||
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
|
||
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
|
||
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
|
||
/// 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"
|
||
private static let recordDotSize: CGFloat = 9
|
||
private static let folderLabelOpacity: Double = 0.55
|
||
|
||
// MARK: - Properties
|
||
|
||
private let shoeGaze: ShoeGaze
|
||
private let hardwareSampleRate: () -> Double?
|
||
|
||
/// 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
|
||
|
||
/// 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
|
||
|
||
#if !os(macOS)
|
||
/// iOS file-dialog presentation flags + the document to export. (macOS uses the File menu.)
|
||
@State private var showImporter: Bool = false
|
||
@State private var showExporter: Bool = false
|
||
@State private var exportDocument: RigFileDocument = RigFileDocument(data: Data())
|
||
/// iOS recording-folder picker presentation flag. (macOS uses the Record menu.)
|
||
@State private var showRecordingFolderImporter: Bool = false
|
||
#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`.
|
||
public init(
|
||
shoeGaze: ShoeGaze,
|
||
hardwareSampleRate: @escaping () -> Double? = { nil }
|
||
) {
|
||
self.shoeGaze = shoeGaze
|
||
self.hardwareSampleRate = hardwareSampleRate
|
||
}
|
||
|
||
// MARK: - Body
|
||
|
||
public var body: some View {
|
||
VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) {
|
||
transportRow
|
||
ioRow
|
||
#if !os(macOS)
|
||
recordingRow
|
||
#endif
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
BoardBarView(
|
||
shoeGaze: shoeGaze,
|
||
editingBoardIndex: $selectedBoardIndex,
|
||
crossfadeSeconds: $crossfadeSeconds,
|
||
onAddBoard: { addBoard() }
|
||
)
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
|
||
paletteSidebar
|
||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||
boardArea
|
||
}
|
||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||
// Scope + CPU meters sit under the pedal palette, matching its width.
|
||
ShoeGazeScopeView(shoeGaze: shoeGaze)
|
||
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
|
||
LyrebirdStatusView(engine: shoeGaze.engine)
|
||
.frame(width: ShoeGazeBuilderView.sidebarWidth, alignment: .leading)
|
||
}
|
||
.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() }
|
||
.sheet(isPresented: $showBoardsSheet) {
|
||
BoardsSheetView(
|
||
shoeGaze: shoeGaze,
|
||
editingBoardIndex: $selectedBoardIndex,
|
||
crossfadeSeconds: $crossfadeSeconds,
|
||
onAddBoard: { addBoard() }
|
||
)
|
||
.presentationDetents([.medium, .large])
|
||
}
|
||
.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)
|
||
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in
|
||
handleImport(result)
|
||
}
|
||
.fileImporter(isPresented: $showRecordingFolderImporter, allowedContentTypes: [.folder]) { result in
|
||
handleRecordingFolderImport(result)
|
||
}
|
||
.fileExporter(
|
||
isPresented: $showExporter,
|
||
document: exportDocument,
|
||
contentType: .json,
|
||
defaultFilename: ShoeGazeBuilderView.defaultRigFileName
|
||
) { result in
|
||
if case .failure(let error) = result {
|
||
print("[ShoeGazeBuilderView] export failed: \(error)")
|
||
}
|
||
}
|
||
#endif
|
||
}
|
||
|
||
// MARK: - Transport row
|
||
|
||
private var transportRow: some View {
|
||
_ = transportTick
|
||
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
Text("ShoeGaze Builder")
|
||
.font(.title2).bold()
|
||
.foregroundStyle(Color.white)
|
||
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)
|
||
}
|
||
}
|
||
Spacer()
|
||
EngineConfigView(
|
||
shoeGaze: shoeGaze,
|
||
hardwareSampleRate: hardwareSampleRate,
|
||
onConfigApplied: { transportTick.toggle() }
|
||
)
|
||
}
|
||
}
|
||
|
||
// MARK: - Input + board + save/load row
|
||
|
||
private var ioRow: some View {
|
||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||
Text("Input:")
|
||
.font(.subheadline)
|
||
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
|
||
Picker("Input", selection: inputBinding) {
|
||
Text("Test Loop").tag(ShoeGazeBuilderView.testLoopTag)
|
||
ForEach(Array(0..<max(0, shoeGaze.engine.numInputChannels)), id: \.self) { channel in
|
||
Text("In \(channel)").tag(channel)
|
||
}
|
||
}
|
||
.pickerStyle(.menu)
|
||
.foregroundStyle(Color.white)
|
||
|
||
Button("Boards…") { showBoardsSheet = true }
|
||
.buttonStyle(.bordered).tint(.orange)
|
||
.help("Rename, reorder, or delete boards")
|
||
|
||
Spacer()
|
||
|
||
// On macOS, Save/Load live in the app's File menu (see the app shell's AppDelegate);
|
||
// on iOS they stay in-view, driven by fileExporter/fileImporter.
|
||
#if !os(macOS)
|
||
Button("Save…") { saveAction() }
|
||
.buttonStyle(.bordered).tint(.blue)
|
||
Button("Load…") { loadAction() }
|
||
.buttonStyle(.bordered).tint(.blue)
|
||
#endif
|
||
}
|
||
}
|
||
|
||
// MARK: - Palette sidebar
|
||
|
||
private var paletteSidebar: some View {
|
||
ScrollView(.vertical, showsIndicators: true) {
|
||
PedalPaletteView(
|
||
onAdd: { type in addPedal(type: type) },
|
||
onRouting: { action in performRouting(action) }
|
||
)
|
||
.padding(.trailing, 2)
|
||
}
|
||
.frame(width: ShoeGazeBuilderView.sidebarWidth)
|
||
}
|
||
|
||
// MARK: - Board area
|
||
|
||
private var boardArea: some View {
|
||
// Vertically center the signal-flow board in the available space.
|
||
VStack(spacing: 0) {
|
||
Spacer(minLength: 0)
|
||
BoardFlowView(shoeGaze: shoeGaze, boardIndex: clampedBoardIndex)
|
||
Spacer(minLength: 0)
|
||
}
|
||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||
}
|
||
|
||
/// 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 shoeGaze.appendStereoSplit(to: board)
|
||
case .parallelSplit: _ = try shoeGaze.appendParallelSplit(to: board)
|
||
case .mergeToMono: _ = 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)")
|
||
}
|
||
}
|
||
|
||
/// `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
|
||
let source: InputSource = newValue == ShoeGazeBuilderView.testLoopTag
|
||
? .testLoop
|
||
: .liveInput(channel: newValue)
|
||
switchInput(to: source)
|
||
}
|
||
)
|
||
}
|
||
|
||
// MARK: - Actions
|
||
|
||
private func addPedal(type: String) {
|
||
guard !shoeGaze.boards.isEmpty else { return }
|
||
let board: PedalBoard = shoeGaze.boards[clampedBoardIndex]
|
||
do {
|
||
_ = try shoeGaze.appendPedal(type: type, to: board)
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] appendPedal failed: \(error)")
|
||
}
|
||
}
|
||
|
||
private func addBoard() {
|
||
var created: PedalBoard?
|
||
do {
|
||
let board: PedalBoard = try shoeGaze.addBoard()
|
||
created = board
|
||
try shoeGaze.finalizeBoard(board)
|
||
selectedBoardIndex = shoeGaze.boards.count - 1
|
||
} catch {
|
||
if let board: PedalBoard = created { shoeGaze.removeBoard(board) }
|
||
print("[ShoeGazeBuilderView] addBoard failed: \(error)")
|
||
}
|
||
}
|
||
|
||
/// 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)
|
||
persistInputSelection(source)
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
|
||
}
|
||
if wasRunning {
|
||
try? shoeGaze.engine.start()
|
||
}
|
||
transportTick.toggle()
|
||
}
|
||
|
||
// MARK: - Input persistence
|
||
|
||
/// Saves the current input choice so it is restored on the next launch.
|
||
private func persistInputSelection(_ source: InputSource) {
|
||
let value: Int
|
||
switch source {
|
||
case .testLoop:
|
||
value = ShoeGazeBuilderView.testLoopTag
|
||
case .liveInput(let channel):
|
||
value = channel
|
||
}
|
||
UserDefaults.standard.set(value, forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
|
||
}
|
||
|
||
/// Restores the saved input choice once on appear. With no saved choice, defaults to live
|
||
/// input when the microphone is already authorised and the engine has an input channel —
|
||
/// otherwise stays on the test loop. A saved live channel that no longer fits the engine, or
|
||
/// a since-revoked permission, falls back to the test loop via `switchInput(to:)`.
|
||
private func restoreInputSelection() {
|
||
guard !didRestoreInput else { return }
|
||
didRestoreInput = true
|
||
|
||
let defaults: UserDefaults = UserDefaults.standard
|
||
if defaults.object(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey) != nil {
|
||
let stored: Int = defaults.integer(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
|
||
if stored >= 0, stored < shoeGaze.engine.numInputChannels {
|
||
switchInput(to: .liveInput(channel: stored))
|
||
}
|
||
// A test-loop choice (or an out-of-range channel) leaves the default test loop.
|
||
} else if MicrophonePermission.isAuthorized, shoeGaze.engine.numInputChannels > 0 {
|
||
// First launch with no saved choice but mic already granted → default to live input.
|
||
switchInput(to: .liveInput(channel: 0))
|
||
}
|
||
}
|
||
|
||
// MARK: - Board-switch shortcuts
|
||
|
||
/// Hidden ⌘1…⌘9 buttons that solo (live-switch to) the matching board and select it as the
|
||
/// edit target. 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
|
||
Button("") { switchToBoard(index) }
|
||
.keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command)
|
||
}
|
||
}
|
||
.opacity(0)
|
||
.frame(width: 0, height: 0)
|
||
.accessibilityHidden(true)
|
||
}
|
||
|
||
/// 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: - Save / Load (iOS)
|
||
|
||
// On macOS, Save/Load are driven from the app's File menu (the app shell owns the
|
||
// NSSavePanel/NSOpenPanel and calls `shoeGaze.saveRig`/`loadRig` directly). On iOS they are
|
||
// in-view, presenting `fileExporter`/`fileImporter`.
|
||
#if !os(macOS)
|
||
/// iOS recording controls: choose an output folder, then start/stop recording.
|
||
private var recordingRow: 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)
|
||
Spacer()
|
||
Button(shoeGaze.isRecording ? "Stop Recording" : "Record") {
|
||
toggleRecording()
|
||
}
|
||
.buttonStyle(.borderedProminent)
|
||
.tint(shoeGaze.isRecording ? .red : .accentColor)
|
||
.disabled(shoeGaze.recordingFolder == nil && !shoeGaze.isRecording)
|
||
}
|
||
}
|
||
|
||
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)")
|
||
}
|
||
}
|
||
|
||
private func saveAction() {
|
||
do {
|
||
exportDocument = RigFileDocument(data: try shoeGaze.rigData())
|
||
showExporter = true
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] rigData failed: \(error)")
|
||
}
|
||
}
|
||
|
||
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) {
|
||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||
if wasRunning { shoeGaze.engine.stop() }
|
||
do {
|
||
try shoeGaze.loadRig(from: url)
|
||
selectedBoardIndex = 0
|
||
} catch {
|
||
print("[ShoeGazeBuilderView] loadRig 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)")
|
||
}
|
||
}
|
||
#endif
|
||
}
|