// ShoeGazeView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT #if canImport(AppKit) import AppKit #endif import SwiftUI import LyrebirdSynth import LyrebirdUI import LyrebirdShoeGaze /// The top-level view for a `ShoeGaze` session. /// /// Displays a transport header (Start / Stop engine buttons and an Add Board button), /// a vertically scrollable list of ``PedalBoardView`` strips (one per board), and a /// ``LyrebirdStatusView`` CPU meter at the bottom, all on a dark backdrop that matches /// the stompbox enclosure aesthetic. /// /// ## Board identity keying /// /// The boards `ForEach` uses `id: \.offset` on an enumerated copy of `shoeGaze.boards`. /// `PedalBoard` is a `@MainActor` class and is neither `Identifiable` nor `Hashable` /// (adding conformance to the core type would violate the module-layering constraint). /// Index keying is stable for the simple append/remove-by-position pattern this demo /// uses and avoids any protocol requirements on the core `PedalBoard` type. /// /// ## Usage /// /// ```swift /// ShoeGazeView(shoeGaze: shoeGaze) /// ``` public struct ShoeGazeView: View { // MARK: - Layout constants private static let outerPadding: CGFloat = 20 private static let sectionSpacing: CGFloat = 16 private static let transportSpacing: CGFloat = 12 private static let boardSpacing: CGFloat = 20 private static let minWidth: CGFloat = 400 private static let dividerOpacity: Double = 0.12 /// Stage-floor dark background colour components (very dark warm black). private static let backgroundRed: Double = 0.08 private static let backgroundGreen: Double = 0.07 private static let backgroundBlue: Double = 0.06 /// Default crossfade duration in seconds for board-select transitions. private static let defaultCrossfadeSeconds: Double = 0.3 /// Maximum crossfade duration accepted by the crossfade seconds stepper. private static let maxCrossfadeSeconds: Double = 10.0 /// Stepper increment for the crossfade seconds control. private static let crossfadeStepIncrement: Double = 0.1 /// Width of the crossfade-seconds text field. private static let crossfadeFieldWidth: CGFloat = 60 /// Spacing inside the board-select row. private static let boardSelectSpacing: CGFloat = 8 /// Opacity for the board-select row labels. private static let labelOpacity: Double = 0.65 /// Diameter of the recording-in-progress indicator dot. private static let recordDotSize: CGFloat = 10 /// Opacity of the secondary folder-name label shown next to the folder picker button. private static let folderLabelOpacity: Double = 0.55 /// Spacing inside the recording controls sub-row. private static let recordingRowSpacing: CGFloat = 10 // MARK: - Properties private let shoeGaze: ShoeGaze private let hardwareSampleRate: () -> Double? /// Bumped on each transport button press to force a re-read of the engine's /// running state. The button labels/enabled-state read `shoeGaze.engine.isRunning` /// directly (the single source of truth) rather than a private mirror that could /// drift out of sync if the engine is started/stopped elsewhere. @State private var transportTick: Bool = false /// Crossfade duration used for the next board-select transition. @State private var crossfadeSeconds: Double = ShoeGazeView.defaultCrossfadeSeconds /// Highlighted board in the board bar (the bar's edit-target binding). The player shows /// every board strip, so this only drives the bar's selection outline. @State private var selectedBoardIndex: Int = 0 /// Controls presentation of the iOS `.fileImporter` directory picker. /// On macOS the picker is opened imperatively via `NSOpenPanel`; this flag is /// only meaningful on iOS / non-macOS targets. @State private var showFolderImporter: Bool = false // MARK: - Init /// Creates a top-level ShoeGaze view. /// /// - Parameters: /// - shoeGaze: The `ShoeGaze` manager whose boards and engine will be displayed. /// - 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: ShoeGazeView.sectionSpacing) { transportHeader recordingRow Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) BoardBarView( shoeGaze: shoeGaze, editingBoardIndex: $selectedBoardIndex, crossfadeSeconds: $crossfadeSeconds, onAddBoard: { addBoard() } ) Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) boardList Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) ShoeGazeScopeView(shoeGaze: shoeGaze) Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) LyrebirdStatusView(engine: shoeGaze.engine) } .padding(ShoeGazeView.outerPadding) .frame(minWidth: ShoeGazeView.minWidth) .background( Color( red: ShoeGazeView.backgroundRed, green: ShoeGazeView.backgroundGreen, blue: ShoeGazeView.backgroundBlue ) ) #if !os(macOS) .fileImporter( isPresented: $showFolderImporter, allowedContentTypes: [.folder] ) { result in switch result { case .success(let url): // A `.fileImporter` directory URL is security-scoped on iOS; access must // be started before `FileManager` can write into it. Kept open for the // session (released when the app exits). if url.startAccessingSecurityScopedResource() { shoeGaze.recordingFolder = url } else { print("[ShoeGazeView] could not access selected folder") } case .failure(let error): print("[ShoeGazeView] folder picker failed: \(error)") } } #endif } // MARK: - Subviews /// Transport bar: title, Start/Stop engine buttons, and Add Board button. /// /// The button state reads `shoeGaze.engine.isRunning` (the single source of truth) /// so it stays correct even when the engine is started/stopped by another control. /// Audio only flows once the user presses Start — adding boards does not auto-start /// the engine. private var transportHeader: some View { // Referencing `transportTick` makes a press (which toggles it) re-evaluate this // view so `engine.isRunning` is re-read; toggling any @State invalidates the view. _ = transportTick return HStack(spacing: ShoeGazeView.transportSpacing) { Text("ShoeGaze") .font(.title2) .bold() .foregroundStyle(Color.white) Spacer() Button("Add Board") { addBoard() } .buttonStyle(.bordered) .tint(.orange) EngineConfigView(shoeGaze: shoeGaze, hardwareSampleRate: hardwareSampleRate) } } /// Recording controls: folder picker, chosen-folder label, and record/stop button. /// /// The folder picker opens an `NSOpenPanel` on macOS or a `.fileImporter` sheet on iOS. /// The Record button is disabled until a folder has been chosen; it turns into a Stop /// button (red) while recording is in progress. private var recordingRow: some View { HStack(spacing: ShoeGazeView.recordingRowSpacing) { // --- Folder picker button --- Button("Choose Folder…") { chooseFolderAction() } .buttonStyle(.bordered) .tint(.blue) // --- Chosen folder label --- let folderName: String = shoeGaze.recordingFolder?.lastPathComponent ?? "No folder" Text(folderName) .font(.caption) .foregroundStyle(Color.white.opacity(ShoeGazeView.folderLabelOpacity)) .lineLimit(1) .truncationMode(.middle) Spacer() // --- Recording-in-progress indicator dot --- if shoeGaze.isRecording { Circle() .fill(Color.red) .frame( width: ShoeGazeView.recordDotSize, height: ShoeGazeView.recordDotSize ) } // --- Record / Stop button --- Button(shoeGaze.isRecording ? "Stop" : "Record") { if shoeGaze.isRecording { shoeGaze.stopRecording() } else { do { try shoeGaze.startRecording() } catch { print("[ShoeGazeView] startRecording() failed: \(error)") } } } .buttonStyle(.borderedProminent) .tint(shoeGaze.isRecording ? .red : .accentColor) .disabled(shoeGaze.recordingFolder == nil) } } /// Vertically scrollable list of board strips. /// /// Keyed by `\.offset` on an enumerated snapshot; see the doc-comment on /// `ShoeGazeView` for the rationale. private var boardList: some View { ScrollView(.vertical, showsIndicators: true) { VStack(alignment: .leading, spacing: ShoeGazeView.boardSpacing) { ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in let board: PedalBoard = pair.element PedalBoardView(board: board) { shoeGaze.removeBoard(board) } } } } } // MARK: - Recording /// Opens a directory picker so the user can choose the recording destination folder. /// /// On macOS an `NSOpenPanel` is presented imperatively (directories only, no file /// selection, no multiple selection). On iOS/non-macOS the `.fileImporter` modifier /// attached to the view hierarchy is toggled via `showFolderImporter`. private func chooseFolderAction() { #if os(macOS) let panel: NSOpenPanel = NSOpenPanel() panel.canChooseDirectories = true panel.canChooseFiles = false panel.allowsMultipleSelection = false panel.canCreateDirectories = true // show the "New Folder" button panel.prompt = "Choose" panel.message = "Select a folder for recording output" // `begin` is non-blocking (unlike `runModal`, which would freeze the SwiftUI // main-thread update loop while the panel is open). panel.begin { response in if response == .OK, let url: URL = panel.url { shoeGaze.recordingFolder = url } } #else showFolderImporter = true #endif } // MARK: - Board management /// Adds a new board with one `OverdrivePedal` as a default pedal so the board /// produces audible output immediately after being finalized. If any step after /// `shoeGaze.addBoard()` throws, the partially-built board is removed via /// `shoeGaze.removeBoard(_:)` before logging, leaving the rig in a consistent state. private func addBoard() { var createdBoard: PedalBoard? do { let board: PedalBoard = try shoeGaze.addBoard() createdBoard = board try board.add(OverdrivePedal()) try shoeGaze.finalizeBoard(board) } catch { if let board: PedalBoard = createdBoard { shoeGaze.removeBoard(board) } print("[ShoeGazeView] addBoard() failed: \(error)") } } }