Files
ShoeGaze/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift
T
josh 46e075fb8c Add live-input mic permission, audio-input entitlement, and engine-config review fixes
Live input was silent on macOS because the apps ran under hardened runtime
without the microphone entitlement, so AUHAL input received silent zeros and
the OS never prompted. Fixes:

- Add com.apple.security.device.audio-input entitlement to the macOS Builder
  and Demo apps (CODE_SIGN_ENTITLEMENTS wired in both targets).
- Add MicrophonePermission helper (AVCaptureDevice.requestAccess) and gate
  live-input selection through it in the Builder view and Demo controller;
  deny falls back to the test loop with an explanatory alert.
- Fix ShoeGazeDemo inputChannels 6 -> 1 (built-in mics are mono; 6 made
  CoreAudio deliver silence).

Engine-config review fixes:
- installScopeTap now requires the engine stopped (precondition) and
  reconfigureEngine reinstalls the tap on every exit path via defer, so
  engine.scopeTap never points at a stale channel layout.
- EngineConfigView stops the engine on a post-start (iOS) sample-rate
  mismatch instead of running pitch-shifted, and surfaces non-mismatch
  start errors through the alert.
- Remove redundant installScopeTap call in the demo controller (ShoeGaze.init
  already installs it).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 09:36:35 -07:00

438 lines
17 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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
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
/// 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
#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))
HStack(alignment: .top, spacing: ShoeGazeBuilderView.columnSpacing) {
paletteSidebar
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
boardArea
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
ShoeGazeScopeView(shoeGaze: shoeGaze)
LyrebirdStatusView(engine: shoeGaze.engine)
}
.padding(ShoeGazeBuilderView.outerPadding)
.frame(minWidth: ShoeGazeBuilderView.minWidth, minHeight: ShoeGazeBuilderView.minHeight)
.background(
Color(
red: ShoeGazeBuilderView.backgroundRed,
green: ShoeGazeBuilderView.backgroundGreen,
blue: ShoeGazeBuilderView.backgroundBlue
)
)
.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)
Text("Board:")
.font(.subheadline)
.foregroundStyle(Color.white.opacity(ShoeGazeBuilderView.labelOpacity))
Picker("Board", selection: $selectedBoardIndex) {
ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in
let label: String = pair.element.label.isEmpty
? "Board \(pair.offset + 1)"
: pair.element.label
Text(label).tag(pair.offset)
}
}
.pickerStyle(.menu)
.foregroundStyle(Color.white)
Button("Add Board") { addBoard() }
.buttonStyle(.bordered).tint(.orange)
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)
} catch {
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
}
if wasRunning {
try? shoeGaze.engine.start()
}
transportTick.toggle()
}
// 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
}