diff --git a/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift new file mode 100644 index 0000000..0a316b4 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/BoardFlowView.swift @@ -0,0 +1,434 @@ +// BoardFlowView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdUI +import LyrebirdShoeGaze + +/// A left→right signal-flow view of one `PedalBoard`: live pedal cards joined by connector lines, +/// with split regions shown as two stacked lanes you can fill independently. +/// +/// Binds to `ShoeGaze` (`@Observable`) and reads the live board via `shoeGaze.boards[boardIndex]`. +/// All edits go through the lane-addressed API (`appendPedal`/`removePedal`/`movePedal`, +/// `appendStereoSplit`/`appendParallelSplit`/`appendMergeToMono`/`removeSegment`), which rebuild +/// the board in place — so the index is the stable anchor and the `PedalBoard` reference is never +/// cached. Region segments are addressed by their index in `board.orderedSegments`. +/// +/// Interaction: +/// - Drag a palette pedal (`"add:"`) onto a lane to append it there; tap a palette pedal to +/// append to the main chain. +/// - Drag a card onto another card in the same lane to reorder; the corner trash removes it. +/// - Connector lines render mono (single) or stereo (double) based on the running channel width. +/// +/// - Parameters: +/// - shoeGaze: The `ShoeGaze` manager that owns the board. +/// - boardIndex: Index into `shoeGaze.boards`. Renders a placeholder when out of range. +public struct BoardFlowView: View { + + // MARK: - Constants + + private static let placeholderOpacity: Double = 0.55 + private static let stageSpacing: CGFloat = 0 + private static let connectorWidth: CGFloat = 26 + private static let connectorThickness: CGFloat = 2 + private static let stereoLineGap: CGFloat = 6 + private static let laneSpacing: CGFloat = 10 + private static let laneMinWidth: CGFloat = 240 + private static let laneLabelWidth: CGFloat = 22 + private static let regionPadding: CGFloat = 10 + private static let regionCornerRadius: CGFloat = 12 + private static let regionBrightness: Double = 0.09 + private static let regionBorderOpacity: Double = 0.35 + private static let trashPadding: CGFloat = 6 + private static let trashOpacity: Double = 0.8 + private static let badgeFontSize: CGFloat = 11 + private static let badgeOpacity: Double = 0.6 + private static let dropHighlightWidth: CGFloat = 2 + private static let emptyLaneOpacity: Double = 0.4 + + /// Signal-path accent (the pink/magenta connector colour). + private static let flowColor: Color = Color(red: 0.92, green: 0.32, blue: 0.70) + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + private let boardIndex: Int + + /// Identifier of the lane/card currently hovered as a drop target, for highlight. + @State private var dropTarget: String? + + public init(shoeGaze: ShoeGaze, boardIndex: Int) { + self.shoeGaze = shoeGaze + self.boardIndex = boardIndex + } + + // MARK: - Body + + public var body: some View { + if boardIndex < 0 || boardIndex >= shoeGaze.boards.count { + Text("No board at index \(boardIndex).") + .foregroundStyle(Color.secondary.opacity(BoardFlowView.placeholderOpacity)) + } else { + let board: PedalBoard = shoeGaze.boards[boardIndex] + flow(board: board) + } + } + + private func flow(board: PedalBoard) -> some View { + let stages: [StageModel] = stageModels(board: board) + return ScrollView([.horizontal, .vertical], showsIndicators: true) { + HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) { + endpoint("IN") + ForEach(stages) { stage in + connector(stereo: stage.stereoIn) + stageView(stage) + } + connector(stereo: board.width == 2) + endpoint(board.width == 2 ? "OUT ⇒" : "OUT") + } + .padding(.vertical, BoardFlowView.regionPadding) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + + // MARK: - Stage model + + /// View-model for one top-level segment: its index (the lane region index), the live segment, + /// the main-chain linear index for `.pedal`, and the channel width entering the stage. + private struct StageModel: Identifiable { + let id: Int + let segmentIndex: Int + let segment: BoardSegment + let linearIndex: Int? + let stereoIn: Bool + } + + /// Walks `board.orderedSegments`, tagging each with a linear pedal index and the running width. + private func stageModels(board: PedalBoard) -> [StageModel] { + var models: [StageModel] = [] + var linearCounter: Int = 0 + var stereo: Bool = false + for (index, segment) in board.orderedSegments.enumerated() { + let stereoIn: Bool = stereo + var linearIndex: Int? + switch segment { + case .pedal(let pedal): + linearIndex = linearCounter + linearCounter += 1 + if pedal.channelKind != .mono { stereo = true } + case .stereoSplit: + stereo = true + case .parallel: + break + case .mergeToMono: + stereo = false + } + models.append( + StageModel( + id: index, + segmentIndex: index, + segment: segment, + linearIndex: linearIndex, + stereoIn: stereoIn + ) + ) + } + return models + } + + // MARK: - Stage dispatch + + @ViewBuilder + private func stageView(_ stage: StageModel) -> some View { + switch stage.segment { + case .pedal(let pedal): + mainPedalCard(pedal: pedal, linearIndex: stage.linearIndex ?? 0) + case .stereoSplit(let section): + regionNode( + title: "STEREO SPLIT", + segmentIndex: stage.segmentIndex, + leftLabel: "L", + rightLabel: "R", + leftPedals: section.left.pedals, + rightPedals: section.right.pedals, + control: AnyView(StereoRouteControlView(section: section)) + ) + case .parallel(let section): + regionNode( + title: "PARALLEL", + segmentIndex: stage.segmentIndex, + leftLabel: "A", + rightLabel: "B", + leftPedals: section.branchA.pedals, + rightPedals: section.branchB.pedals, + control: AnyView(SplitterView(splitter: section.splitter)) + ) + case .mergeToMono: + mergeNode(segmentIndex: stage.segmentIndex) + } + } + + // MARK: - Connectors + + private func connector(stereo: Bool) -> some View { + ZStack { + if stereo { + VStack(spacing: BoardFlowView.stereoLineGap) { + line + line + } + } else { + line + } + } + .frame(width: BoardFlowView.connectorWidth) + } + + private var line: some View { + Capsule() + .fill(BoardFlowView.flowColor) + .frame(height: BoardFlowView.connectorThickness) + } + + private func endpoint(_ text: String) -> some View { + Text(text) + .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold).monospaced()) + .foregroundStyle(BoardFlowView.flowColor) + } + + // MARK: - Main pedal card + + private func mainPedalCard(pedal: Pedal, linearIndex: Int) -> some View { + let payload: String = "movemain:\(linearIndex)" + return PedalView(pedal: pedal) + .overlay(alignment: .topTrailing) { trashButton { deleteSegment(forLinear: linearIndex) } } + .overlay { dropOutline(active: dropTarget == payload) } + .draggable(payload) + .dropDestination(for: String.self) { items, _ in + handleMainDrop(items, ontoLinear: linearIndex) + } isTargeted: { hovering in + dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) + } + } + + // MARK: - Region node (stereo split / parallel) + + private func regionNode( + title: String, + segmentIndex: Int, + leftLabel: String, + rightLabel: String, + leftPedals: [Pedal], + rightPedals: [Pedal], + control: AnyView + ) -> some View { + VStack(alignment: .leading, spacing: BoardFlowView.laneSpacing) { + HStack(spacing: 8) { + Text(title) + .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold)) + .foregroundStyle(BoardFlowView.flowColor) + Spacer() + control + trashButton { removeSegment(at: segmentIndex) } + } + laneRow(label: leftLabel, pedals: leftPedals, lane: .left(region: segmentIndex)) + laneRow(label: rightLabel, pedals: rightPedals, lane: .right(region: segmentIndex)) + } + .padding(BoardFlowView.regionPadding) + .background( + RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) + .fill(Color(white: BoardFlowView.regionBrightness)) + .overlay( + RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) + .stroke(BoardFlowView.flowColor.opacity(BoardFlowView.regionBorderOpacity), lineWidth: 1) + ) + ) + } + + private func laneRow(label: String, pedals: [Pedal], lane: PedalLane) -> some View { + let laneID: String = "lane:\(lane.regionIndex ?? -1):\(lane.isLeftBranch ? "L" : "R")" + return HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) { + Text(label) + .font(.system(size: BoardFlowView.badgeFontSize, weight: .bold).monospaced()) + .foregroundStyle(Color.white.opacity(BoardFlowView.badgeOpacity)) + .frame(width: BoardFlowView.laneLabelWidth) + if pedals.isEmpty { + Text("drop a pedal here") + .font(.caption) + .foregroundStyle(Color.white.opacity(BoardFlowView.emptyLaneOpacity)) + .frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading) + .padding(.vertical, BoardFlowView.regionPadding) + } else { + ForEach(Array(pedals.enumerated()), id: \.offset) { pair in + connector(stereo: false) + branchPedalCard(pedal: pair.element, lane: lane, index: pair.offset) + } + } + } + .frame(minWidth: BoardFlowView.laneMinWidth, alignment: .leading) + .overlay { dropOutline(active: dropTarget == laneID) } + .dropDestination(for: String.self) { items, _ in + handleLaneDrop(items, lane: lane) + } isTargeted: { hovering in + dropTarget = hovering ? laneID : (dropTarget == laneID ? nil : dropTarget) + } + } + + private func branchPedalCard(pedal: Pedal, lane: PedalLane, index: Int) -> some View { + let payload: String = "movebranch:\(lane.regionIndex ?? -1):\(lane.isLeftBranch ? "L" : "R"):\(index)" + return PedalView(pedal: pedal) + .overlay(alignment: .topTrailing) { + trashButton { removePedal(at: index, lane: lane) } + } + .overlay { dropOutline(active: dropTarget == payload) } + .draggable(payload) + .dropDestination(for: String.self) { items, _ in + handleBranchCardDrop(items, lane: lane, ontoIndex: index) + } isTargeted: { hovering in + dropTarget = hovering ? payload : (dropTarget == payload ? nil : dropTarget) + } + } + + private func mergeNode(segmentIndex: Int) -> some View { + VStack(spacing: 4) { + Text("⇒ MONO") + .font(.system(size: BoardFlowView.badgeFontSize, weight: .semibold)) + .foregroundStyle(BoardFlowView.flowColor) + trashButton { removeSegment(at: segmentIndex) } + } + .padding(BoardFlowView.regionPadding) + .background( + RoundedRectangle(cornerRadius: BoardFlowView.regionCornerRadius) + .stroke(BoardFlowView.flowColor.opacity(BoardFlowView.regionBorderOpacity), lineWidth: 1) + ) + } + + // MARK: - Shared bits + + private func trashButton(_ action: @escaping () -> Void) -> some View { + Button(role: .destructive, action: action) { + Image(systemName: "trash.circle.fill") + .foregroundStyle(Color.white.opacity(BoardFlowView.trashOpacity)) + } + .buttonStyle(.plain) + .padding(BoardFlowView.trashPadding) + } + + @ViewBuilder + private func dropOutline(active: Bool) -> some View { + if active { + RoundedRectangle(cornerRadius: 8) + .stroke(BoardFlowView.flowColor, lineWidth: BoardFlowView.dropHighlightWidth) + } + } + + // MARK: - Drop handling + + private func parse(_ items: [String]) -> String? { items.first } + + private func handleMainDrop(_ items: [String], ontoLinear: Int) -> Bool { + dropTarget = nil + guard let payload: String = parse(items) else { return false } + if let type: String = payload.afterPrefix("add:") { + append(type: type, lane: .main) + return true + } + if let src: Int = payload.afterPrefix("movemain:").flatMap(Int.init) { + reorderMain(from: src, onto: ontoLinear) + return true + } + return false + } + + private func handleLaneDrop(_ items: [String], lane: PedalLane) -> Bool { + dropTarget = nil + guard let payload: String = parse(items), let type: String = payload.afterPrefix("add:") else { + return false + } + append(type: type, lane: lane) + return true + } + + private func handleBranchCardDrop(_ items: [String], lane: PedalLane, ontoIndex: Int) -> Bool { + dropTarget = nil + guard let payload: String = parse(items) else { return false } + // Guard against a payload minted before a rebuild changed the segment layout: the encoded + // region index must still point at a live region segment. + if let region: Int = lane.regionIndex, + let liveBoard: PedalBoard = board, + region >= liveBoard.orderedSegments.count { + return false + } + if let type: String = payload.afterPrefix("add:") { + append(type: type, lane: lane) + return true + } + // Reorder within the same lane only: "movebranch:::". + let parts: [Substring] = payload.split(separator: ":") + if parts.count == 4, parts[0] == "movebranch", + Int(parts[1]) == lane.regionIndex, + (parts[2] == "L") == lane.isLeftBranch, + let src: Int = Int(parts[3]) { + reorderBranch(from: src, onto: ontoIndex, lane: lane) + return true + } + return false + } + + // MARK: - Edit actions + + private var board: PedalBoard? { + guard boardIndex >= 0, boardIndex < shoeGaze.boards.count else { return nil } + return shoeGaze.boards[boardIndex] + } + + private func append(type: String, lane: PedalLane) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.appendPedal(type: type, to: board, lane: lane) } + catch { print("[BoardFlowView] appendPedal failed: \(error)") } + } + + private func reorderMain(from source: Int, onto target: Int) { + guard source != target, let board: PedalBoard = board else { return } + // Convert "dropped ONTO the card at `target`" into movePedal's insert-before `toOffset`: + // a forward move lands after the target (target + 1); a backward move lands before it. + let destination: Int = source < target ? target + 1 : target + do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: .main) } + catch { print("[BoardFlowView] movePedal(main) failed: \(error)") } + } + + private func reorderBranch(from source: Int, onto target: Int, lane: PedalLane) { + guard source != target, let board: PedalBoard = board else { return } + let destination: Int = source < target ? target + 1 : target + do { _ = try shoeGaze.movePedal(from: source, to: destination, in: board, lane: lane) } + catch { print("[BoardFlowView] movePedal(branch) failed: \(error)") } + } + + private func removePedal(at index: Int, lane: PedalLane) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.removePedal(at: index, from: board, lane: lane) } + catch { print("[BoardFlowView] removePedal failed: \(error)") } + } + + private func deleteSegment(forLinear linearIndex: Int) { + // A main-chain pedal: remove by its lane index (preserves regions). + removePedal(at: linearIndex, lane: .main) + } + + private func removeSegment(at segmentIndex: Int) { + guard let board: PedalBoard = board else { return } + do { _ = try shoeGaze.removeSegment(at: segmentIndex, from: board) } + catch { print("[BoardFlowView] removeSegment failed: \(error)") } + } +} + +private extension String { + /// Returns the remainder after `prefix`, or `nil` if the string doesn't start with it. + func afterPrefix(_ prefix: String) -> String? { + guard hasPrefix(prefix) else { return nil } + return String(dropFirst(prefix.count)) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift new file mode 100644 index 0000000..ede1782 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/PedalPaletteView.swift @@ -0,0 +1,184 @@ +// PedalPaletteView.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import LyrebirdShoeGaze + +/// A vertical catalog of every available pedal plus a reference list of the routing/branching +/// options, sized to sit in a narrow left sidebar. +/// +/// The pedal rows are tappable: selecting one invokes `onAdd(type)` with the pedal's +/// `displayName`, which the host wires to `ShoeGaze.appendPedal(type:to:)`. The routing cards +/// (Parallel split, Stereo split, Chain router, Merge to mono) are informational only — they +/// describe the topologies the engine supports, which are built programmatically rather than via +/// linear add (see ``BoardBuilderView`` for the read-only display of existing branches). +/// +/// ## Usage +/// +/// ```swift +/// PedalPaletteView { type in +/// try? shoeGaze.appendPedal(type: type, to: board) +/// } +/// ``` +public struct PedalPaletteView: View { + + // MARK: - Layout constants + + private static let sectionSpacing: CGFloat = 14 + private static let rowSpacing: CGFloat = 6 + private static let titleFontSize: CGFloat = 12 + private static let titleOpacity: Double = 0.7 + private static let cardCornerRadius: CGFloat = 7 + private static let cardPaddingH: CGFloat = 10 + private static let cardPaddingV: CGFloat = 7 + private static let cardBorderOpacity: Double = 0.4 + private static let cardBorderWidth: CGFloat = 1 + private static let pedalCardBrightness: Double = 0.18 + private static let routingCardBrightness: Double = 0.1 + private static let routingCaptionOpacity: Double = 0.5 + private static let routingCaptionFontSize: CGFloat = 10 + private static let addGlyphOpacity: Double = 0.4 + + /// Preferred display order for the built-in pedals. Any registered pedal not listed here is + /// appended afterwards (sorted) so the palette never silently drops a newly added pedal. + private static let preferredOrder: [String] = [ + "Overdrive", "Compressor", "Fuzz", "Tremolo", "Phaser", "Modulation", + "Auto-Wah", "Mu-Tron", "Bass Octaver", "Octave Splitter", + "Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverb", + ] + + /// Routing/branching topologies the user can insert into the board. + private static let routingOptions: [(title: String, caption: String, action: RoutingAction)] = [ + ("Stereo Split", "L/R independent lanes", .stereoSplit), + ("Parallel Split", "A/B branches, mixed", .parallelSplit), + ("Merge to Mono", "Collapse stereo → mono", .mergeToMono), + ] + + /// Routing actions a host can perform from the palette. + public enum RoutingAction: Equatable, Sendable { + case stereoSplit + case parallelSplit + case mergeToMono + case chainRouter + } + + // MARK: - Properties + + private let onAdd: (String) -> Void + private let onRouting: (RoutingAction) -> Void + + // MARK: - Init + + /// Creates a pedal palette. + /// + /// - Parameters: + /// - onAdd: Invoked with a pedal's `displayName` when its row is tapped (append to main chain). + /// Rows are also `.draggable` carrying `"add:"` for drop-onto-lane targeting. + /// - onRouting: Invoked when a routing row is tapped. Defaults to a no-op. + public init( + onAdd: @escaping (String) -> Void, + onRouting: @escaping (RoutingAction) -> Void = { _ in } + ) { + self.onAdd = onAdd + self.onRouting = onRouting + } + + /// Registered pedal names in preferred order, with any unlisted registered pedals appended. + private var orderedPedalNames: [String] { + let registered: Set = Set(PedalRegistry.builtIn.keys) + let ordered: [String] = PedalPaletteView.preferredOrder.filter { registered.contains($0) } + let extras: [String] = registered + .subtracting(ordered) + .sorted() + return ordered + extras + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: PedalPaletteView.sectionSpacing) { + VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { + sectionTitle("PEDALS") + ForEach(orderedPedalNames, id: \.self) { name in + pedalRow(name) + } + } + + VStack(alignment: .leading, spacing: PedalPaletteView.rowSpacing) { + sectionTitle("ROUTING") + ForEach(PedalPaletteView.routingOptions, id: \.title) { option in + routingCard(title: option.title, caption: option.caption, action: option.action) + } + } + } + } + + // MARK: - Subviews + + private func sectionTitle(_ text: String) -> some View { + Text(text) + .font(.system(size: PedalPaletteView.titleFontSize, weight: .semibold)) + .foregroundStyle(Color.white.opacity(PedalPaletteView.titleOpacity)) + } + + /// A full-width pedal row: tap appends to the main chain; drag carries `"add:"` so it can + /// be dropped onto a stereo/parallel lane. + private func pedalRow(_ name: String) -> some View { + Button { + onAdd(name) + } label: { + HStack(spacing: 4) { + Text(name) + .font(.callout) + .foregroundStyle(Color.white) + .lineLimit(1) + Spacer(minLength: 0) + Image(systemName: "plus") + .font(.caption2) + .foregroundStyle(Color.white.opacity(PedalPaletteView.addGlyphOpacity)) + } + .padding(.horizontal, PedalPaletteView.cardPaddingH) + .padding(.vertical, PedalPaletteView.cardPaddingV) + .frame(maxWidth: .infinity, alignment: .leading) + .background(cardBackground(brightness: PedalPaletteView.pedalCardBrightness)) + } + .buttonStyle(.plain) + .draggable("add:\(name)") + } + + /// A tappable routing row that inserts a region/node into the board. + private func routingCard(title: String, caption: String, action: RoutingAction) -> some View { + Button { + onRouting(action) + } label: { + VStack(alignment: .leading, spacing: 2) { + Text(title) + .font(.callout) + .foregroundStyle(Color.white) + Text(caption) + .font(.system(size: PedalPaletteView.routingCaptionFontSize)) + .foregroundStyle(Color.white.opacity(PedalPaletteView.routingCaptionOpacity)) + } + .padding(.horizontal, PedalPaletteView.cardPaddingH) + .padding(.vertical, PedalPaletteView.cardPaddingV) + .frame(maxWidth: .infinity, alignment: .leading) + .background(cardBackground(brightness: PedalPaletteView.routingCardBrightness)) + } + .buttonStyle(.plain) + } + + private func cardBackground(brightness: Double) -> some View { + RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius) + .fill(Color(white: brightness)) + .overlay( + RoundedRectangle(cornerRadius: PedalPaletteView.cardCornerRadius) + .stroke( + Color.white.opacity(PedalPaletteView.cardBorderOpacity), + lineWidth: PedalPaletteView.cardBorderWidth + ) + ) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift b/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift new file mode 100644 index 0000000..2f65de8 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/RigFileDocument.swift @@ -0,0 +1,37 @@ +// RigFileDocument.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import SwiftUI +import UniformTypeIdentifiers + +/// A minimal JSON `FileDocument` wrapping a ShoeGaze rig's encoded bytes. +/// +/// Used by ``ShoeGazeBuilderView``'s iOS `.fileExporter` to write the result of +/// `ShoeGaze.rigData()` to a user-chosen location. macOS uses an `NSSavePanel` directly and does +/// not need this type. +struct RigFileDocument: FileDocument { + + /// The rig presets are plain JSON. + static var readableContentTypes: [UTType] { [.json] } + + /// Encoded rig JSON. + let data: Data + + /// Creates a document from already-encoded rig JSON. + init(data: Data) { + self.data = data + } + + /// Decodes an existing document's bytes (required by `FileDocument`, unused by the exporter). + init(configuration: ReadConfiguration) throws { + self.data = configuration.file.regularFileContents ?? Data() + } + + /// Writes the rig JSON into a file wrapper for export. + func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { + FileWrapper(regularFileWithContents: data) + } +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift new file mode 100644 index 0000000..b8104a6 --- /dev/null +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift @@ -0,0 +1,359 @@ +// 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" + + // MARK: - Properties + + private let shoeGaze: ShoeGaze + + /// 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 + + /// iOS file-dialog presentation flags + the document to export. + @State private var showImporter: Bool = false + @State private var showExporter: Bool = false + @State private var exportDocument: RigFileDocument = RigFileDocument(data: Data()) + + // MARK: - Init + + /// Creates a builder view. + /// + /// - Parameter shoeGaze: The `ShoeGaze` manager whose boards and engine are edited. The + /// caller should create at least one board before presenting this view. + public init(shoeGaze: ShoeGaze) { + self.shoeGaze = shoeGaze + } + + // MARK: - Body + + public var body: some View { + VStack(alignment: .leading, spacing: ShoeGazeBuilderView.sectionSpacing) { + transportRow + ioRow + 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) + 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 + ) + ) + #if !os(macOS) + .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in + handleImport(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 + let isRunning: Bool = shoeGaze.engine.isRunning + return HStack(spacing: ShoeGazeBuilderView.rowSpacing) { + Text("ShoeGaze Builder") + .font(.title2).bold() + .foregroundStyle(Color.white) + Spacer() + Button("Start") { + do { try shoeGaze.engine.start() } + catch { print("[ShoeGazeBuilderView] engine.start() failed: \(error)") } + transportTick.toggle() + } + .buttonStyle(.borderedProminent).tint(.green).disabled(isRunning) + + Button("Stop") { + shoeGaze.engine.stop() + transportTick.toggle() + } + .buttonStyle(.bordered).tint(.red).disabled(!isRunning) + } + } + + // 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(0.. { + 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. + private func switchInput(to 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 + + private func saveAction() { + #if os(macOS) + let panel: NSSavePanel = NSSavePanel() + panel.allowedContentTypes = [.json] + panel.nameFieldStringValue = "\(ShoeGazeBuilderView.defaultRigFileName).json" + panel.canCreateDirectories = true + panel.begin { response in + guard response == .OK, let url: URL = panel.url else { return } + do { try shoeGaze.saveRig(to: url) } + catch { print("[ShoeGazeBuilderView] saveRig failed: \(error)") } + } + #else + do { + exportDocument = RigFileDocument(data: try shoeGaze.rigData()) + showExporter = true + } catch { + print("[ShoeGazeBuilderView] rigData failed: \(error)") + } + #endif + } + + private func loadAction() { + #if os(macOS) + let panel: NSOpenPanel = NSOpenPanel() + panel.allowedContentTypes = [.json] + panel.canChooseDirectories = false + panel.allowsMultipleSelection = false + panel.begin { response in + guard response == .OK, let url: URL = panel.url else { return } + loadRig(from: url) + } + #else + showImporter = true + #endif + } + + /// 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() + } + + #if !os(macOS) + private func handleImport(_ result: Result) { + 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 +} diff --git a/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift b/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift index 6d1ecbe..0181e0f 100644 --- a/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift +++ b/Sources/LyrebirdShoeGazeUI/ShoeGazeUI.swift @@ -10,3 +10,7 @@ // ShoeGazeView.swift — top-level session view with transport // FlowLayout.swift — wrap-to-fit Layout (left-to-right, row-wrapping) // BoardEditorView.swift — per-board editor with FlowLayout pedal area + version store +// PedalPaletteView.swift — vertical palette: all pedals (tap/drag) + routing actions +// BoardFlowView.swift — left→right signal-flow board: cards, connectors, stereo/parallel lanes +// ShoeGazeBuilderView.swift — top-level builder: sidebar palette + flow board + transport + save/load +// RigFileDocument.swift — JSON FileDocument for the iOS save (.fileExporter)