diff --git a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift index 22f044a..6cb4ecb 100644 --- a/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift +++ b/Demo/ShoeGazeBuilderiOS/ShoeGazeBuilderiOSAppModel.swift @@ -24,6 +24,11 @@ final class ShoeGazeBuilderiOSAppModel { private static let blockSize: Int = 512 private static let outputChannels: Int = 2 + // Kept at 0: with input channels the iOS driver switches the session to `.playAndRecord` + // and enables the RemoteIO input element, which makes iOS prompt for microphone access at + // engine start even in test-loop mode. iOS live input needs a permission-gated engine + // rebuild (request mic → reconstruct the engine with an input channel) before it can be + // enabled here without that surprise prompt. private static let numAudioBuses: Int = 256 private static let seedPedalType: String = "Overdrive" diff --git a/Sources/LyrebirdShoeGaze/ShoeGaze.swift b/Sources/LyrebirdShoeGaze/ShoeGaze.swift index 06868da..69720b2 100644 --- a/Sources/LyrebirdShoeGaze/ShoeGaze.swift +++ b/Sources/LyrebirdShoeGaze/ShoeGaze.swift @@ -385,14 +385,15 @@ public final class ShoeGaze { /// Moves `board` to `targetIndex` within `boards`, locating it by identity. /// /// This is an internal helper that mutates `boards` directly — valid only because - /// `ShoeGaze` is `@MainActor` (no concurrent access). The method is `internal` rather than - /// `public` so callers outside the ShoeGaze module cannot disrupt board ordering. + /// `ShoeGaze` is `@MainActor` (no concurrent access). Reordering only permutes the + /// `boards` array; it does not touch the engine graph, so it is safe to call while the + /// engine is running. /// /// - Parameters: /// - board: The `PedalBoard` to reposition. No-op if not found in `boards`. /// - index: The desired destination index. Clamped to `boards.count` after removal /// so it is always a valid insertion point. - internal func moveBoard(_ board: PedalBoard, to index: Int) { + public func moveBoard(_ board: PedalBoard, to index: Int) { guard let sourceIndex: Int = boards.firstIndex(where: { $0 === board }) else { return } let removed: PedalBoard = boards.remove(at: sourceIndex) let destination: Int = min(index, boards.count) diff --git a/Sources/LyrebirdShoeGazeUI/BoardsSheetView.swift b/Sources/LyrebirdShoeGazeUI/BoardsSheetView.swift new file mode 100644 index 0000000..4f8e99c --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/BoardsSheetView.swift @@ -0,0 +1,243 @@ +// BoardsSheetView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A full board manager presented as a sheet — the richer companion to the inline +/// ``BoardBarView``. +/// +/// Each board is a `List` row with an audible toggle, a Solo button, a master-gain fader, an +/// inline rename field, and an "Edit" action that selects it as the builder's edit target and +/// dismisses. Rows reorder by drag (`.onMove`) and delete by swipe (`.onDelete`). A header +/// pairs the **Solo / Blend** mode switch with the crossfade slider, mirroring the board bar. +/// +/// Primarily used on iOS/iPadOS (presented with `.presentationDetents`) where the inline bar +/// has no room for rename / reorder, but the view is platform-neutral. +public struct BoardsSheetView: View { + + // MARK: - Play mode + + private enum PlayMode: Hashable { + case solo + case blend + } + + // MARK: - Layout constants + + private static let rowSpacing: CGFloat = 12 + private static let faderWidth: CGFloat = 120 + private static let soloButtonSize: CGFloat = 28 + private static let ledDiameter: CGFloat = 14 + private static let ledDimBrightness: Double = 0.16 + private static let ledRimOpacity: Double = 0.30 + private static let maxCrossfadeSeconds: Double = 10.0 + private static let crossfadeStep: Double = 0.1 + private static let headerSpacing: CGFloat = 10 + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + @Binding private var editingBoardIndex: Int + @Binding private var crossfadeSeconds: Double + private let onAddBoard: () -> Void + + @Environment(\.dismiss) private var dismiss + @State private var mode: PlayMode = .solo + + // MARK: - Init + + /// Creates a board-manager sheet. + /// + /// - Parameters: + /// - shoeGaze: The manager whose `boards` are edited. + /// - editingBoardIndex: The builder's edit target; a row's "Edit" action sets this. + /// - crossfadeSeconds: Crossfade duration applied to switches / toggles. + /// - onAddBoard: Called when the **Add Board** button is tapped. + public init( + shoeGaze: ShoeGaze, + editingBoardIndex: Binding, + crossfadeSeconds: Binding, + onAddBoard: @escaping () -> Void + ) { + self.shoeGaze = shoeGaze + self._editingBoardIndex = editingBoardIndex + self._crossfadeSeconds = crossfadeSeconds + self.onAddBoard = onAddBoard + } + + // MARK: - Body + + public var body: some View { + NavigationStack { + VStack(spacing: BoardsSheetView.headerSpacing) { + header + List { + ForEach(Array(shoeGaze.boards.enumerated()), id: \.offset) { pair in + boardRow(index: pair.offset, board: pair.element) + } + .onMove(perform: moveBoards) + .onDelete(perform: deleteBoards) + } + } + .padding(.top, BoardsSheetView.headerSpacing) + .navigationTitle("Boards") + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + ToolbarItem(placement: .primaryAction) { + Button { + onAddBoard() + } label: { + Label("Add Board", systemImage: "plus") + } + } + } + } + } + + // MARK: - Header + + private var header: some View { + HStack(spacing: BoardsSheetView.headerSpacing) { + Picker("Mode", selection: $mode) { + Text("Solo").tag(PlayMode.solo) + Text("Blend").tag(PlayMode.blend) + } + .pickerStyle(.segmented) + .frame(maxWidth: 180) + + Button("All") { + shoeGaze.selectAllBoards(crossfadeSeconds: clampedCrossfade) + } + .buttonStyle(.bordered) + + Spacer() + + Text("XFade") + Slider( + value: $crossfadeSeconds, + in: 0 ... BoardsSheetView.maxCrossfadeSeconds, + step: BoardsSheetView.crossfadeStep + ) + .frame(width: BoardsSheetView.faderWidth) + Text(String(format: "%.1fs", clampedCrossfade)) + .monospacedDigit() + } + .padding(.horizontal) + } + + // MARK: - Board row + + @ViewBuilder + private func boardRow(index: Int, board: PedalBoard) -> some View { + let isAudible: Bool = shoeGaze.isBoardAudible(board) + let isSoloed: Bool = shoeGaze.activeBoardIndex == index + + HStack(spacing: BoardsSheetView.rowSpacing) { + ledButton(board: board, isAudible: isAudible) + soloButton(board: board, isSoloed: isSoloed) + + TextField( + "Board \(index + 1)", + text: Binding( + get: { board.label }, + set: { board.label = $0 } + ) + ) + .textFieldStyle(.roundedBorder) + + if let gainNode: UIParamNode = board.masterGainNode { + Slider( + value: Binding( + get: { gainNode.value }, + set: { gainNode.update($0) } + ), + in: 0.0 ... 1.0 + ) + .frame(width: BoardsSheetView.faderWidth) + } + + Button("Edit") { + editingBoardIndex = index + dismiss() + } + .buttonStyle(.borderless) + } + .padding(.vertical, 4) + } + + private func ledButton(board: PedalBoard, isAudible: Bool) -> some View { + Button { + switch mode { + case .solo: + shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade) + case .blend: + shoeGaze.setBoard(board, audible: !isAudible, crossfadeSeconds: clampedCrossfade) + } + } label: { + Circle() + .fill(isAudible ? Color.green : Color(white: BoardsSheetView.ledDimBrightness)) + .frame(width: BoardsSheetView.ledDiameter, height: BoardsSheetView.ledDiameter) + .overlay( + Circle().stroke(Color.white.opacity(BoardsSheetView.ledRimOpacity), lineWidth: 0.5) + ) + } + .buttonStyle(.plain) + } + + private func soloButton(board: PedalBoard, isSoloed: Bool) -> some View { + Button { + shoeGaze.soloBoard(board, crossfadeSeconds: clampedCrossfade) + } label: { + Text("S") + .font(.system(size: 13, weight: .bold)) + .foregroundStyle(isSoloed ? Color.black : Color.primary) + .frame(width: BoardsSheetView.soloButtonSize, height: BoardsSheetView.soloButtonSize) + .background( + RoundedRectangle(cornerRadius: 5) + .fill(isSoloed ? Color.yellow : Color.secondary.opacity(0.2)) + ) + } + .buttonStyle(.plain) + } + + // MARK: - Mutations + + /// Reorders boards, translating SwiftUI's `onMove` offsets to `ShoeGaze.moveBoard`. + private func moveBoards(from source: IndexSet, to destination: Int) { + // List drag delivers a single source row; ignore any multi-selection move so a + // dropped row can never desync `shoeGaze.boards` from the displayed order. + guard source.count == 1, let sourceIndex: Int = source.first else { return } + let board: PedalBoard = shoeGaze.boards[sourceIndex] + // SwiftUI's destination is the insertion point in the pre-move list; moveBoard + // removes first, so shift down by one when moving forward. + let target: Int = destination > sourceIndex ? destination - 1 : destination + shoeGaze.moveBoard(board, to: target) + clampEditingIndex() + } + + private func deleteBoards(_ offsets: IndexSet) { + for index: Int in offsets.sorted(by: >) where index < shoeGaze.boards.count { + shoeGaze.removeBoard(shoeGaze.boards[index]) + } + clampEditingIndex() + } + + // MARK: - Helpers + + private var clampedCrossfade: Double { + min(max(crossfadeSeconds, 0.0), BoardsSheetView.maxCrossfadeSeconds) + } + + private func clampEditingIndex() { + let count: Int = shoeGaze.boards.count + guard count > 0 else { editingBoardIndex = 0; return } + editingBoardIndex = min(editingBoardIndex, count - 1) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift index 1509606..aae545c 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -48,6 +48,12 @@ public struct ShoeGazeBuilderView: View { 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 @@ -69,6 +75,12 @@ public struct ShoeGazeBuilderView: View { /// 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 @@ -133,6 +145,17 @@ public struct ShoeGazeBuilderView: View { 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: { @@ -204,6 +227,10 @@ public struct ShoeGazeBuilderView: View { .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); @@ -331,6 +358,7 @@ public struct ShoeGazeBuilderView: View { if wasRunning { shoeGaze.engine.stop() } do { try shoeGaze.setInputSource(source) + persistInputSelection(source) } catch { print("[ShoeGazeBuilderView] setInputSource failed: \(error)") } @@ -340,6 +368,65 @@ public struct ShoeGazeBuilderView: View { 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 diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift index eed07c4..b4d5fc1 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeView.swift @@ -79,6 +79,10 @@ public struct ShoeGazeView: View { /// 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. @@ -108,7 +112,12 @@ public struct ShoeGazeView: View { recordingRow Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) - boardSelectRow + BoardBarView( + shoeGaze: shoeGaze, + editingBoardIndex: $selectedBoardIndex, + crossfadeSeconds: $crossfadeSeconds, + onAddBoard: { addBoard() } + ) Divider() .overlay(Color.white.opacity(ShoeGazeView.dividerOpacity)) boardList @@ -230,77 +239,6 @@ public struct ShoeGazeView: View { } } - /// A `Binding` that maps between the Picker's integer tag and `ShoeGaze` select API. - /// - /// Tag `-1` represents "All boards audible" (`activeBoardIndex == nil`). - /// Tags `0 ..< boards.count` represent the soloed board at that index. - /// Setting the binding calls `selectBoard(_:crossfadeSeconds:)` or - /// `selectAllBoards(crossfadeSeconds:)` with the current `crossfadeSeconds` value. - private var boardSelectBinding: Binding { - Binding( - get: { shoeGaze.activeBoardIndex ?? -1 }, - set: { newValue in - // Clamp here so a value typed into the crossfade text field (which has no - // built-in bounds) can never pass a negative or oversized lag time. - let seconds: Double = min(max(crossfadeSeconds, 0.0), ShoeGazeView.maxCrossfadeSeconds) - if newValue == -1 { - shoeGaze.selectAllBoards(crossfadeSeconds: seconds) - } else if newValue >= 0, newValue < shoeGaze.boards.count { - shoeGaze.selectBoard(shoeGaze.boards[newValue], crossfadeSeconds: seconds) - } - } - ) - } - - /// Board-select row: an "Active" Picker to solo a board (or hear all), a crossfade- - /// seconds text field, and a companion Stepper for convenient adjustment. - /// - /// The row is always visible. When `boards.count <= 1` the Picker has only one or two - /// options, which is still useful for the "All" / single-board toggle. - private var boardSelectRow: some View { - HStack(spacing: ShoeGazeView.boardSelectSpacing) { - Text("Active:") - .font(.subheadline) - .foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity)) - - Picker("Active", selection: boardSelectBinding) { - Text("All").tag(-1) - 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) - - Spacer() - - Text("Crossfade (s):") - .font(.subheadline) - .foregroundStyle(Color.white.opacity(ShoeGazeView.labelOpacity)) - - TextField( - "s", - value: $crossfadeSeconds, - format: .number.precision(.fractionLength(1)) - ) - .frame(width: ShoeGazeView.crossfadeFieldWidth) - #if os(macOS) - .textFieldStyle(.squareBorder) - #endif - - Stepper( - "", - value: $crossfadeSeconds, - in: 0...ShoeGazeView.maxCrossfadeSeconds, - step: ShoeGazeView.crossfadeStepIncrement - ) - .labelsHidden() - } - } - /// Vertically scrollable list of board strips. /// /// Keyed by `\.offset` on an enumerated snapshot; see the doc-comment on