// PedalView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT import SwiftUI import UniformTypeIdentifiers import LyrebirdUI import LyrebirdShoeGaze // MARK: - Accent-color mapping (UI-only, never in the core target) /// Returns a stompbox enclosure tint colour keyed on the pedal's display name. /// /// The core `Pedal` type cannot carry a SwiftUI `Color`, so the mapping lives /// here in the UI target. Unrecognised names fall through to `.gray`. private func enclosureColor(for displayName: String) -> Color { switch displayName { case "California": return Color(red: 0.20, green: 0.28, blue: 0.34) // West-Coast steel blue case "British": return Color(red: 0.30, green: 0.16, blue: 0.10) // oxblood tolex case "Chime": return Color(red: 0.16, green: 0.24, blue: 0.22) // vintage green case "Neural Amp": return Color(red: 0.22, green: 0.16, blue: 0.30) // deep neural violet case "Overdrive": return Color(red: 0.85, green: 0.42, blue: 0.08) // warm orange case "Distortion": return Color(red: 0.80, green: 0.26, blue: 0.12) // hot rust case "Delay": return Color(red: 0.10, green: 0.55, blue: 0.55) // teal case "Reverb": return Color(red: 0.30, green: 0.18, blue: 0.65) // indigo case "Shimmer Reverb": return Color(red: 0.46, green: 0.52, blue: 0.78) // icy periwinkle case "Plate Reverb": return Color(red: 0.26, green: 0.30, blue: 0.60) // deep slate blue case "Room Reverb": return Color(red: 0.24, green: 0.40, blue: 0.66) // ocean blue case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold case "Wah": return Color(red: 0.72, green: 0.50, blue: 0.06) // amber gold case "Volume": return Color(red: 0.30, green: 0.30, blue: 0.34) // graphite case "Feedback Delay": return Color(red: 0.48, green: 0.30, blue: 0.14) // tape sepia case "Multi-Tap Delay": return Color(red: 0.08, green: 0.48, blue: 0.68) // cyan case "Reverse Delay": return Color(red: 0.10, green: 0.44, blue: 0.60) // deep cyan-teal case "Limiter": return Color(red: 0.62, green: 0.16, blue: 0.20) // brick red case "Noise Gate": return Color(red: 0.24, green: 0.26, blue: 0.30) // gunmetal case "Graphic EQ": return Color(red: 0.14, green: 0.40, blue: 0.50) // deep teal case "Cabinet": return Color(red: 0.50, green: 0.36, blue: 0.18) // tweed / cabinet tan case "Chorus": return Color(red: 0.16, green: 0.50, blue: 0.64) // aqua case "Flanger": return Color(red: 0.28, green: 0.52, blue: 0.78) // steel blue case "Vibrato": return Color(red: 0.42, green: 0.30, blue: 0.70) // violet-blue case "Rotary": return Color(red: 0.45, green: 0.34, blue: 0.20) // Leslie cabinet walnut case "Sustainer": return Color(red: 0.22, green: 0.46, blue: 0.30) // pine green case "Ring Modulator": return Color(red: 0.64, green: 0.30, blue: 0.10) // burnt amber case "Diffuser": return Color(red: 0.34, green: 0.30, blue: 0.62) // periwinkle case "Harmonizer": return Color(red: 0.52, green: 0.20, blue: 0.40) // wine / mauve case "Bitcrusher": return Color(red: 0.30, green: 0.34, blue: 0.40) // slate / digital gray case "Granulator": return Color(red: 0.20, green: 0.55, blue: 0.50) // sea green case "Auto Granulator": return Color(red: 0.24, green: 0.50, blue: 0.56) // teal-aqua default: return Color(red: 0.36, green: 0.36, blue: 0.38) // steel gray } } // MARK: - Screw decoration /// A small circular "screw head" decoration placed in each corner of the enclosure. private struct ScrewDot: View { private static let size: CGFloat = 8 private static let strokeWidth: CGFloat = 1 private static let slotWidth: CGFloat = 1 private static let slotHeight: CGFloat = 4 private static let fillOpacity: Double = 0.25 private static let rimOpacity: Double = 0.18 private static let slotOpacity: Double = 0.50 var body: some View { ZStack { Circle() .fill(Color.black.opacity(ScrewDot.fillOpacity)) .frame(width: ScrewDot.size, height: ScrewDot.size) Circle() .stroke(Color.white.opacity(ScrewDot.rimOpacity), lineWidth: ScrewDot.strokeWidth) .frame(width: ScrewDot.size, height: ScrewDot.size) // Slot line — Phillips-style cross Rectangle() .fill(Color.black.opacity(ScrewDot.slotOpacity)) .frame(width: ScrewDot.slotWidth, height: ScrewDot.slotHeight) Rectangle() .fill(Color.black.opacity(ScrewDot.slotOpacity)) .frame(width: ScrewDot.slotHeight, height: ScrewDot.slotWidth) } } } // MARK: - LED /// A small circular LED that glows green when the effect is engaged. /// /// A small round LED, lit green when `isOn` and dark otherwise. Polarity-agnostic — the /// caller decides what `isOn` means for its own control (e.g. bypass's `value < 0.5`, or a /// plain toggle's `value >= 0.5`). `internal` (not `private`) so other views in this module /// (e.g. `PedalButtonView`) can reuse the same stompbox LED look. struct LEDIndicator: View { private static let diameter: CGFloat = 10 private static let glowRadius: CGFloat = 6 private static let glowOpacity: Double = 0.75 private static let rimLineWidth: CGFloat = 0.5 private static let dimBrightness: Double = 0.15 private static let rimStrokeOpacity: Double = 0.30 let isOn: Bool var body: some View { ZStack { if isOn { Circle() .fill(Color.green.opacity(LEDIndicator.glowOpacity)) .frame( width: LEDIndicator.diameter + LEDIndicator.glowRadius, height: LEDIndicator.diameter + LEDIndicator.glowRadius ) .blur(radius: LEDIndicator.glowRadius / 2) } Circle() .fill(isOn ? Color.green : Color(white: LEDIndicator.dimBrightness)) .frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter) .overlay( Circle() .stroke(Color.white.opacity(LEDIndicator.rimStrokeOpacity), lineWidth: LEDIndicator.rimLineWidth) .frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter) ) } .frame(width: LEDIndicator.diameter + LEDIndicator.glowRadius, height: LEDIndicator.diameter + LEDIndicator.glowRadius) } } // MARK: - Footswitch /// A round footswitch-style button. Either flips a bound `UIParamNode` between `0` and `1` /// (toggle) or runs an arbitrary action (momentary) — both render the identical stompbox look. /// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can reuse /// it for non-bypass toggles and momentary stomp actions. struct FootswitchButton: View { private static let diameter: CGFloat = 44 private static let strokeWidth: CGFloat = 2.5 private static let innerDiameter: CGFloat = 36 private static let outerFillBrightness: Double = 0.18 private static let ringBrightness: Double = 0.50 private static let innerFillBrightness: Double = 0.25 private let action: () -> Void /// Flips `node` between `0` and `1` on each press. init(node: UIParamNode) { self.action = { let engaged: Bool = node.value < 0.5 node.update(engaged ? 1.0 : 0.0) } } /// Runs `action` on each press (momentary). init(action: @escaping () -> Void) { self.action = action } var body: some View { Button(action: action) { ZStack { Circle() .fill(Color(white: FootswitchButton.outerFillBrightness)) .frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter) Circle() .stroke(Color(white: FootswitchButton.ringBrightness), lineWidth: FootswitchButton.strokeWidth) .frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter) Circle() .fill(Color(white: FootswitchButton.innerFillBrightness)) .frame(width: FootswitchButton.innerDiameter, height: FootswitchButton.innerDiameter) } } .buttonStyle(.plain) .frame(width: FootswitchButton.diameter, height: FootswitchButton.diameter) } } // MARK: - Tempo-sync knob /// A knob that can be locked to a note division of the live tempo. /// /// When free, it is an ordinary ``ParameterKnob``. A compact menu below the dial lets the user /// pick `Free` or a ``NoteDivision``; once a division is chosen the knob is driven by the tempo /// (its dial shows the derived value but is disabled, since the number is computed). The menu is /// shown only while tempo is enabled — the enclosing view gates on `shoeGazeTempoEnabled`. struct TempoSyncKnobView: View { private static let cellSpacing: CGFloat = 4 private static let syncedDialOpacity: Double = 0.55 private static let menuFontSize: CGFloat = 10 private static let labelGlyphSpacing: CGFloat = 3 private static let warningIconSize: CGFloat = 8 /// Height of the glyph in the collapsed menu button, and of the whole menu row, so the row is the /// same height whether it shows the "Free" text or a note glyph — the pedal card never grows. private static let labelGlyphHeight: CGFloat = 18 private static let menuRowHeight: CGFloat = 20 private static let freeKey: String = "free" // Division-picker popover: a height-capped scroll list the system keeps on-screen (it flips // above the button near the bottom edge) rather than a native menu that can run off-screen. private static let pickerMaxHeight: CGFloat = 260 private static let pickerGlyphHeight: CGFloat = 22 private static let pickerRowSpacing: CGFloat = 2 private static let pickerPadding: CGFloat = 8 private static let pickerRowMinWidth: CGFloat = 84 private static let checkmarkFontSize: CGFloat = 11 let pedal: Pedal let knob: PedalKnob let param: TempoSyncableParam /// Presentation flag for the division-picker popover. @State private var showDivisionPicker: Bool = false var body: some View { // Observe the pedal's sync-revision so the badge refreshes when `tempoSync` changes through // any path — this view's picker, a preset load, or a lightweight recall. let _ = pedal.tempoSyncRevision.value let currentKey: String = keyForCurrentSync() let isSynced: Bool = currentKey != TempoSyncKnobView.freeKey let currentBpm: Double? = pedal.clock?.bpm // Reading the live parameter value subscribes this view to Observation, so a tempo change // (which rewrites the node via `applyTempoSync`) re-renders the clamp warning without polling. let liveValue: Double = param.node.value let activeDivision: NoteDivision? = NoteDivision(rawValue: currentKey) let activeClamped: Bool = { _ = liveValue guard isSynced, let bpm: Double = currentBpm, let division: NoteDivision = activeDivision else { return false } return param.value(for: division, bpm: bpm).clamped }() VStack(spacing: TempoSyncKnobView.cellSpacing) { ParameterKnob(knob.label, node: knob.node, range: knob.range) .foregroundStyle(Color.white) .disabled(isSynced) .opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0) Button { showDivisionPicker = true } label: { HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) { if isSynced, let division: NoteDivision = activeDivision { NoteGlyphImageCache.image(for: division) .resizable() .scaledToFit() .frame(height: TempoSyncKnobView.labelGlyphHeight) .accessibilityLabel(Text(labelForKey(currentKey))) } else { Text("Free") .font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded)) } if activeClamped { Image(systemName: "exclamationmark.triangle.fill") .font(.system(size: TempoSyncKnobView.warningIconSize)) } Image(systemName: "chevron.down") .font(.system(size: TempoSyncKnobView.warningIconSize)) .opacity(0.6) } .frame(height: TempoSyncKnobView.menuRowHeight) .foregroundStyle(activeClamped ? Color.orange : Color.white.opacity(isSynced ? 1.0 : 0.65)) } .buttonStyle(.plain) .fixedSize() .help(activeClamped ? "This note can't be represented at the current tempo — \(knob.label) is clamped to its limit." : "Sync \(knob.label) to the tempo, or set it freely") .popover(isPresented: $showDivisionPicker) { divisionPicker .presentationCompactAdaptation(.popover) } } } /// Height-capped, scrollable list of `Free` + every note division. Presented as a popover so the /// system keeps it on-screen (flipping above the button near the bottom edge) and it scrolls when /// taller than ``pickerMaxHeight`` — unlike a native menu, which ran off the bottom on iOS. private var divisionPicker: some View { let currentBpm: Double? = pedal.clock?.bpm let currentKey: String = keyForCurrentSync() return ScrollView { VStack(alignment: .leading, spacing: TempoSyncKnobView.pickerRowSpacing) { pickerRow( key: TempoSyncKnobView.freeKey, glyph: nil, disabled: false, selected: currentKey == TempoSyncKnobView.freeKey ) ForEach(NoteDivision.allCases, id: \.self) { division in // A division whose value clamps at the current tempo (e.g. a note longer than the // maximum delay time) can't be represented accurately, so it is shown but disabled. let unavailable: Bool = currentBpm.map { param.value(for: division, bpm: $0).clamped } ?? false pickerRow( key: division.rawValue, glyph: division, disabled: unavailable, selected: currentKey == division.rawValue ) } } .padding(TempoSyncKnobView.pickerPadding) } .frame(maxHeight: TempoSyncKnobView.pickerMaxHeight) } /// One selectable row in ``divisionPicker`` — a note glyph (or "Free" text), a trailing checkmark /// when it is the current selection, and a disabled state for divisions that clamp at this tempo. @ViewBuilder private func pickerRow(key: String, glyph: NoteDivision?, disabled: Bool, selected: Bool) -> some View { Button { select(key) showDivisionPicker = false } label: { HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) { if let glyph: NoteDivision = glyph { NoteGlyphImageCache.image(for: glyph) .resizable() .scaledToFit() .frame(height: TempoSyncKnobView.pickerGlyphHeight) } else { Text("Free") .font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded)) } Spacer(minLength: TempoSyncKnobView.labelGlyphSpacing) if selected { Image(systemName: "checkmark") .font(.system(size: TempoSyncKnobView.checkmarkFontSize, weight: .semibold)) } } .frame(minWidth: TempoSyncKnobView.pickerRowMinWidth, alignment: .leading) .contentShape(Rectangle()) } .buttonStyle(.plain) .disabled(disabled) .accessibilityLabel(Text(glyph?.label ?? "Free")) } private func keyForCurrentSync() -> String { if case .division(let division) = pedal.tempoSync[param.key] ?? .free { return division.rawValue } return TempoSyncKnobView.freeKey } private func labelForKey(_ key: String) -> String { key == TempoSyncKnobView.freeKey ? "Free" : (NoteDivision(rawValue: key)?.label ?? key) } private func select(_ key: String) { // `setSync` bumps `pedal.tempoSyncRevision`, which this view observes — no local flag needed. if key == TempoSyncKnobView.freeKey { pedal.setSync(.free, for: param.key) } else if let division: NoteDivision = NoteDivision(rawValue: key) { pedal.setSync(.division(division), for: param.key) } } } // MARK: - PedalView /// A stompbox-style enclosure view that renders all controls for a single `Pedal`. /// /// The enclosure shows: /// - Corner screw decorations. /// - A contrasting name-plate capsule near the top with `displayName`. /// - A grid of ``ParameterKnob`` controls (up to ``knobColumnCount`` per row) drawn from /// the effect + `Mix` knobs of ``Pedal/knobs``. /// - A centred bottom row pairing the `Level` knob with the bypass switch (LED + footswitch). /// /// ## Bypass LED polarity /// /// `Pedal.bypass` is `0` = engaged (effect active), `1` = bypassed. /// The LED is **green/lit** when `bypass < 0.5` (effect is on) and dark when bypassed. /// /// ## Accent color /// /// The enclosure tint is assigned by `enclosureColor(for:)` — a private helper in /// this file keyed on `displayName`. Core `Pedal` never imports SwiftUI. /// /// ## Usage /// /// ```swift /// PedalView(pedal: overdrivePedal) /// ``` public struct PedalView: View { // MARK: - Layout constants /// Wide enough for three ~55 pt knobs (dial + label + value) plus padding in a /// single row, so the effect controls never overlap. private static let enclosureWidth: CGFloat = 220 private static let enclosureCornerRadius: CGFloat = 12 private static let enclosurePadding: CGFloat = 14 private static let screwInset: CGFloat = 6 private static let knobColumnCount: Int = 3 /// Knob columns for a double-width pedal card (fits a four-knob effect bank on one row). private static let wideKnobColumnCount: Int = 4 private static let knobSpacing: CGFloat = 10 /// Horizontal gap between knobs within a row. Wider than `knobSpacing` so centred /// rows keep a comfortable, touch-friendly gap between adjacent knobs. private static let knobRowItemSpacing: CGFloat = 24 /// Horizontal gap between adjacent vertical faders in the slider bank. private static let sliderBankSpacing: CGFloat = 4 /// Approximate per-fader footprint (matches `VerticalParameterSlider.controlWidth`), /// used to widen the enclosure so a wide bank (e.g. a 6-band EQ) is never clipped. private static let sliderBankItemWidth: CGFloat = 28 /// Horizontal gap between the Level knob and the bypass control in the bottom row. private static let bottomControlsSpacing: CGFloat = 18 private static let sectionSpacing: CGFloat = 14 /// Neural Amp model row: label/button spacing, caption size, and caption opacity. private static let neuralRowSpacing: CGFloat = 6 private static let neuralRowFontSize: CGFloat = 11 private static let neuralRowLabelOpacity: Double = 0.85 private static let namePlateCornerRadius: CGFloat = 8 private static let namePlatePaddingH: CGFloat = 10 private static let namePlatePaddingV: CGFloat = 4 private static let outerBorderOpacity: Double = 0.60 private static let innerHighlightOpacity: Double = 0.22 private static let shadowRadius: CGFloat = 8 private static let shadowYOffset: CGFloat = 4 private static let shadowOpacity: Double = 0.60 private static let enclosureGradientDarkFraction: Double = 0.30 private static let bypassSectionSpacing: CGFloat = 6 /// Gap between the looper's three content columns. private static let looperColumnSpacing: CGFloat = 18 /// Fixed width of the looper's left (timeline) column. private static let looperTimelineColumnWidth: CGFloat = 200 /// Half the screw-dot size — used to centre screws on the corner position. private static let screwHalfSize: CGFloat = 4 private static let namePlateBackgroundOpacity: Double = 0.35 private static let fontSizeNamePlate: CGFloat = 13 /// Opacity of the ⓘ info button. private static let infoButtonOpacity: Double = 0.7 /// Insets placing the ⓘ info button just under the top-left corner screw. private static let infoButtonLeading: CGFloat = 5 private static let infoButtonTop: CGFloat = 20 private static let outerBorderLineWidth: CGFloat = 1.5 private static let innerHighlightLineWidth: CGFloat = 1 private static let innerHighlightPadding: CGFloat = 1 private static let shadowXOffset: CGFloat = 0 // MARK: - Properties private let pedal: Pedal /// Presentation flag for the pedal info panel (description + control ranges). @State private var showInfo: Bool = false /// Presentation flag for the Neural Amp model-file importer. @State private var showModelImporter: Bool = false /// Rebuilds this pedal's board after a non-`@UIParam` change (Neural Amp model file). Injected /// by the builder; no-op elsewhere. @Environment(\.pedalRebuildAction) private var pedalRebuildAction: @MainActor @Sendable (Pedal) -> Void /// The rig's control map, injected by the builder so the pedal can draw a mapping strip. `nil` /// when the rig has no bindings (or in contexts that don't set it) — the strip renders nothing. @Environment(\.controlMappingMap) private var controlMappingMap: MIDIMap? /// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off. @Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool // MARK: - Init /// Creates a stompbox pedal view for the given pedal. /// /// - Parameter pedal: The `Pedal` whose parameters will be displayed. public init(pedal: Pedal) { self.pedal = pedal } // MARK: - Body public var body: some View { let accent: Color = enclosureColor(for: pedal.displayName) let darkAccent: Color = accent.opacity(PedalView.enclosureGradientDarkFraction) // Evaluate the (computed) slider descriptors once per render — both the bank and // the enclosure-width calculation consume the same array. let sliders: [PedalSlider] = pedal.effectSliders // Content is the sizing layer so the enclosure hugs it vertically — a short pedal stays // short. The gradient fill and border/screw strokes are attached as background/overlay so // they conform to the content height instead of a greedy `RoundedRectangle` in a ZStack // dictating (and stretching) the height to fill the row. Group { if let looper: LooperPedal = pedal as? LooperPedal { looperColumnarContent(looper) } else { defaultContent(sliders: sliders) } } .padding(PedalView.enclosurePadding) .frame(width: enclosureWidth(for: sliders)) .background( // Enclosure fill with top-to-bottom gradient RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius) .fill( LinearGradient( gradient: Gradient(colors: [accent, darkAccent]), startPoint: .top, endPoint: .bottom ) ) ) .overlay( // Inner highlight rim (subtle bevel) RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius - PedalView.innerHighlightPadding) .stroke(Color.white.opacity(PedalView.innerHighlightOpacity), lineWidth: PedalView.innerHighlightLineWidth) .padding(PedalView.innerHighlightPadding) ) .overlay( // Outer border RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius) .stroke(Color.black.opacity(PedalView.outerBorderOpacity), lineWidth: PedalView.outerBorderLineWidth) ) // Corner screws — overlaid at the four corners. .overlay { screwCorners } // Info button, tucked just under the top-left corner screw. .overlay(alignment: .topLeading) { infoButton .padding(.leading, PedalView.infoButtonLeading) .padding(.top, PedalView.infoButtonTop) } .shadow( color: Color.black.opacity(PedalView.shadowOpacity), radius: PedalView.shadowRadius, x: PedalView.shadowXOffset, y: PedalView.shadowYOffset ) .sheet(isPresented: $showInfo) { PedalInfoView(pedal: pedal) .presentationDetents([.medium, .large]) } } // MARK: - Content layouts /// The default single-column section stack used by every pedal except the looper. private func defaultContent(sliders: [PedalSlider]) -> some View { VStack(spacing: PedalView.sectionSpacing) { namePlate knobGrid neuralModelRow selectorRow switchRow // Keyed on the pedal instance so the buttons' live captions (which poll the pedal // via `.task`) re-subscribe when a rig load / rebuild swaps in a new pedal instance. transportButtonRow .id(ObjectIdentifier(pedal)) buttonRow sliderBank(sliders) bottomControls PedalMappingStrip(pedal: pedal, map: controlMappingMap) } } /// Wide, three-column layout for the looper: the loop timeline on the left, the effect knobs /// over the Free/Sync switch in the centre, and the transport footswitch grid (with bypass) on /// the right. Laying the sections side-by-side keeps the tall pedal short enough to fit the /// canvas without scrolling. Requires the looper's `widthUnits` to be wide enough (3×). private func looperColumnarContent(_ looper: LooperPedal) -> some View { VStack(spacing: PedalView.sectionSpacing) { namePlate HStack(alignment: .top, spacing: PedalView.looperColumnSpacing) { // Left column: timeline, then the Free/Sync switch, then the Reset footswitch. // No trailing Spacer — the flow canvas offers the row its full viewport height, // and a greedy Spacer here would stretch the whole card to fill it (leaving a // large empty gap). Each column sizes to its content, like every other pedal. VStack(spacing: PedalView.sectionSpacing) { LooperTimelineView(pedal: looper) switchRow looperResetCell } .frame(width: PedalView.looperTimelineColumnWidth) // Centre column: the four effect knobs (2×2), with the Level + Bypass footer // directly beneath (no greedy Spacer — see the left column note). VStack(spacing: PedalView.sectionSpacing) { looperEffectKnobs(columns: 2) looperFooter } // Right column: the transport footswitches (minus Reset) in a 2×2 grid. looperTransportGrid(columns: 2) .id(ObjectIdentifier(pedal)) } PedalMappingStrip(pedal: pedal, map: controlMappingMap) } // Pin to intrinsic height so the enclosure hugs its content even though the flow // canvas offers the row its full viewport height. .fixedSize(horizontal: false, vertical: true) } /// The looper's effect knobs (everything except the trailing `Mix` / `Level`) laid out in /// rows of `columns`. private func looperEffectKnobs(columns: Int) -> some View { let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2)) let rows: [[PedalKnob]] = stride(from: 0, to: knobs.count, by: columns).map { start in Array(knobs[start ..< min(start + columns, knobs.count)]) } return VStack(spacing: PedalView.knobSpacing) { ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in HStack(spacing: PedalView.knobRowItemSpacing) { Spacer(minLength: 0) ForEach(Array(rowPair.element.enumerated()), id: \.offset) { knobPair in let knob: PedalKnob = knobPair.element ParameterKnob(knob.label, node: knob.node, range: knob.range) .foregroundStyle(Color.white) } Spacer(minLength: 0) } } } } /// Preferred grid order for the looper's transport footswitches (row-major), so the 2×2 grid /// reads Record / Reverse over Stop / Cue Stop. Buttons not listed keep their original order /// and follow. Matched by label to stay robust if the descriptor order changes. private static let looperTransportOrder: [String] = ["Loop", "Reverse", "Stop", "Cue Stop"] /// The looper's transport footswitches — everything except the trailing Reset (which sits in /// the left column) — laid out in rows of `columns` in ``looperTransportOrder``. private func looperTransportGrid(columns: Int) -> some View { let buttons: [PedalButton] = Array(pedal.effectTransportButtons.dropLast()) let ordered: [PedalButton] = PedalView.looperTransportOrder.compactMap { label in buttons.first { $0.label == label } } + buttons.filter { !PedalView.looperTransportOrder.contains($0.label) } let rows: [[PedalButton]] = stride(from: 0, to: ordered.count, by: columns).map { start in Array(ordered[start ..< min(start + columns, ordered.count)]) } return VStack(spacing: PedalView.knobSpacing) { ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) { Spacer(minLength: 0) ForEach(Array(rowPair.element.enumerated()), id: \.offset) { pair in PedalButtonView(pair.element) } Spacer(minLength: 0) } } } } /// The looper's footer: Level on the left, Bypass in the centre, and an empty third where a /// normal pedal's Mix knob would sit — so Bypass stays horizontally centred in the column. private var looperFooter: some View { HStack(spacing: 0) { levelControl .frame(maxWidth: .infinity) bypassControl .frame(maxWidth: .infinity) Color.clear .frame(maxWidth: .infinity, maxHeight: 0) // reserved Mix slot } } /// The Reset footswitch (the trailing transport button), centred — sits at the bottom of the /// looper's left (timeline) column. @ViewBuilder private var looperResetCell: some View { if let reset: PedalButton = pedal.effectTransportButtons.last { HStack(spacing: 0) { Spacer(minLength: 0) PedalButtonView(reset) Spacer(minLength: 0) } } } // MARK: - Subviews /// Capsule name plate near the top of the enclosure. private var namePlate: some View { Text(pedal.displayName) .font(.system(size: PedalView.fontSizeNamePlate, weight: .bold, design: .rounded)) .foregroundStyle(Color.white) .padding(.horizontal, PedalView.namePlatePaddingH) .padding(.vertical, PedalView.namePlatePaddingV) .background(Color.black.opacity(PedalView.namePlateBackgroundOpacity)) .clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius)) } /// Info button tucked just under the top-left corner screw. private var infoButton: some View { Button { showInfo = true } label: { Image(systemName: "info.circle") .font(.system(size: PedalView.fontSizeNamePlate)) .foregroundStyle(Color.white.opacity(PedalView.infoButtonOpacity)) } .buttonStyle(.plain) .help("About this pedal") } /// Grid of the effect knobs, in rows of up to `knobColumnCount`. /// /// The trailing `Mix` and `Level` knobs (the last two entries of `pedal.knobs`) are /// dropped here and rendered in the bottom control row flanking the bypass switch — /// `Level` on the left, `Mix` on the right — leaving more room for the effect controls /// at the top and giving every pedal a symmetric footer. private var knobGrid: some View { // Wide (double-width) pedals fit four knobs across, so a four-knob effect bank (e.g. // the looper's Crossfade / Playback / Overdub / Feedback) sits on one row. let columns: Int = pedal.widthUnits >= 2 ? PedalView.wideKnobColumnCount : PedalView.knobColumnCount let knobs: [PedalKnob] = Array(pedal.knobs.dropLast(2)) let rows: [[PedalKnob]] = stride( from: 0, to: knobs.count, by: columns ).map { startIndex in Array(knobs[startIndex ..< min(startIndex + columns, knobs.count)]) } return VStack(spacing: PedalView.knobSpacing) { ForEach(Array(rows.enumerated()), id: \.offset) { rowPair in let row: [PedalKnob] = rowPair.element // Centre each row: a short row sits centred in the enclosure rather than // left-aligned. A full row keeps the tight spacing so it fits the enclosure; // shorter centred rows use a wider, touch-friendly gap. let rowItemSpacing: CGFloat = row.count >= columns ? PedalView.knobSpacing : PedalView.knobRowItemSpacing // Top-align so every dial pins to the row's top edge — a tempo-sync cell grows taller // below the dial (glyph menu, warning) without dragging its neighbours' dials down. HStack(alignment: .top, spacing: rowItemSpacing) { Spacer(minLength: 0) ForEach(Array(row.enumerated()), id: \.offset) { knobPair in knobCell(knobPair.element) } Spacer(minLength: 0) } } } } /// Renders one effect knob — a tempo-sync knob when the parameter is syncable and tempo is /// enabled, otherwise a plain ``ParameterKnob``. Syncable knobs are matched by node identity /// against `pedal.tempoSyncableParams`. @ViewBuilder private func knobCell(_ knob: PedalKnob) -> some View { if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) { TempoSyncKnobView(pedal: pedal, knob: knob, param: param) } else { ParameterKnob(knob.label, node: knob.node, range: knob.range) .foregroundStyle(Color.white) } } /// The tempo-syncable descriptor whose parameter node backs `knob`, or `nil` if the knob is /// not syncable. Matched by `UIParamNode` identity so it is robust to label changes. private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? { pedal.tempoSyncableParams.first { $0.node === knob.node } } /// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid. /// Renders nothing when the pedal publishes no selectors. @ViewBuilder private var selectorRow: some View { let selectors: [PedalSelectorKnob] = pedal.effectSelectors if !selectors.isEmpty { HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) { Spacer(minLength: 0) ForEach(Array(selectors.enumerated()), id: \.offset) { pair in PedalSelectorKnobView( pair.element, onCommit: pair.element.rebuildsOnChange ? { [pedal, pedalRebuildAction] in pedalRebuildAction(pedal) } : nil ) } Spacer(minLength: 0) } } } /// Row of segmented switches drawn from `pedal.effectSwitches`, one per row, beneath /// the knob grid. Renders nothing when the pedal publishes no switches. @ViewBuilder private var switchRow: some View { let switches: [PedalSwitch] = pedal.effectSwitches if !switches.isEmpty { VStack(spacing: PedalView.knobSpacing) { ForEach(Array(switches.enumerated()), id: \.offset) { pair in PedalSwitchView(pair.element) } } } } /// Transport-control row drawn from `pedal.effectTransportButtons`, placed directly below /// the knobs so persistent state toggles and transport stops (e.g. the looper's Loop / /// Stop / Cue Stop / Reverse) sit apart from the momentary actions. Renders nothing when /// the pedal publishes no transport buttons. @ViewBuilder private var transportButtonRow: some View { let buttons: [PedalButton] = pedal.effectTransportButtons if !buttons.isEmpty { HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) { Spacer(minLength: 0) ForEach(Array(buttons.enumerated()), id: \.offset) { pair in PedalButtonView(pair.element) } Spacer(minLength: 0) } } } /// Row of momentary stomp-style action buttons drawn from `pedal.effectButtons`, beneath /// the transport row. Renders nothing when the pedal publishes no buttons. @ViewBuilder private var buttonRow: some View { let buttons: [PedalButton] = pedal.effectButtons if !buttons.isEmpty { HStack(spacing: PedalView.knobRowItemSpacing) { Spacer(minLength: 0) ForEach(Array(buttons.enumerated()), id: \.offset) { pair in PedalButtonView(pair.element) } Spacer(minLength: 0) } } } /// Row of vertical faders drawn from `pedal.effectSliders`, beneath the switch row. /// Renders nothing when the pedal publishes no sliders. @ViewBuilder private func sliderBank(_ sliders: [PedalSlider]) -> some View { if !sliders.isEmpty { HStack(alignment: .top, spacing: PedalView.sliderBankSpacing) { ForEach(Array(sliders.enumerated()), id: \.offset) { pair in let slider: PedalSlider = pair.element VerticalParameterSlider(slider.label, node: slider.node, range: slider.range) } } } } /// Enclosure width — the base stompbox width scaled by the pedal's `widthUnits` /// (a control-dense pedal such as the looper asks for a double-width card), widened /// further to fit a wide vertical-fader bank (e.g. a multi-band graphic EQ) so its /// faders are never clipped. private func enclosureWidth(for sliders: [PedalSlider]) -> CGFloat { let unitWidth: CGFloat = PedalView.enclosureWidth * CGFloat(max(1, pedal.widthUnits)) let sliderCount: Int = sliders.count guard sliderCount > 0 else { return unitWidth } let bankContentWidth: CGFloat = CGFloat(sliderCount) * PedalView.sliderBankItemWidth + CGFloat(max(0, sliderCount - 1)) * PedalView.sliderBankSpacing let needed: CGFloat = bankContentWidth + 2 * PedalView.enclosurePadding return max(unitWidth, needed) } /// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob, /// side-by-side and centred — a symmetric knob-switch-knob footer shared by all pedals. /// Neural Amp only: shows the loaded model file name and a picker to load a `.json` capture. /// Setting the model changes the graph, so after a pick it asks the host to rebuild the board. @ViewBuilder private var neuralModelRow: some View { if let neural: NeuralAmpPedal = pedal as? NeuralAmpPedal { VStack(spacing: PedalView.neuralRowSpacing) { Text(neuralModelLabel(neural)) .font(.system(size: PedalView.neuralRowFontSize, weight: .medium)) .foregroundStyle(Color.white.opacity(PedalView.neuralRowLabelOpacity)) .lineLimit(1) .truncationMode(.middle) Button("Load Model…") { showModelImporter = true } .buttonStyle(.bordered) .controlSize(.small) } .frame(maxWidth: .infinity) .fileImporter( isPresented: $showModelImporter, allowedContentTypes: [.json] ) { (result: Result) in guard case .success(let url) = result else { return } // The app is unsandboxed, so a plain path read works; still bracket access defensively. let accessed: Bool = url.startAccessingSecurityScopedResource() neural.resourcePath = url.path if accessed { url.stopAccessingSecurityScopedResource() } pedalRebuildAction(neural) } } } /// Loaded-model caption for the Neural Amp row — the model file's base name, or a prompt. private func neuralModelLabel(_ neural: NeuralAmpPedal) -> String { guard let path: String = neural.resourcePath, !path.isEmpty else { return "No model loaded" } return (path as NSString).lastPathComponent } private var bottomControls: some View { HStack(alignment: .center, spacing: PedalView.bottomControlsSpacing) { levelControl bypassControl mixControl } .frame(maxWidth: .infinity) } /// The `Level` knob — the last entry of `pedal.knobs` — placed left of the bypass switch. @ViewBuilder private var levelControl: some View { if let level: PedalKnob = pedal.knobs.last { ParameterKnob(level.label, node: level.node, range: level.range) .foregroundStyle(Color.white) } } /// The `Mix` knob — the second-to-last entry of `pedal.knobs` — placed right of the /// bypass switch to mirror `Level`. Hidden for pedals that manage their own dry/wet balance /// (``Pedal/showsMixControl``), e.g. the looper. @ViewBuilder private var mixControl: some View { if pedal.showsMixControl, let mix: PedalKnob = pedal.knobs.dropLast().last { ParameterKnob(mix.label, node: mix.node, range: mix.range) .foregroundStyle(Color.white) } } /// LED + footswitch bypass control, paired beside the Level knob. private var bypassControl: some View { // Reading `pedal.$bypass.value` here registers this view for automatic // re-renders whenever the bypass parameter changes on the main thread // (UIParamNode is @Observable). let bypassValue: Double = pedal.$bypass.value let engagedThreshold: Double = 0.5 return VStack(spacing: PedalView.bypassSectionSpacing) { LEDIndicator(isOn: bypassValue < engagedThreshold) FootswitchButton(node: pedal.$bypass) } } /// Four screw dots overlaid at the enclosure corners. private var screwCorners: some View { GeometryReader { geometry in let w: CGFloat = geometry.size.width let h: CGFloat = geometry.size.height let inset: CGFloat = PedalView.screwInset let half: CGFloat = PedalView.screwHalfSize ZStack(alignment: .topLeading) { // Top-left ScrewDot() .position(x: inset + half, y: inset + half) // Top-right ScrewDot() .position(x: w - inset - half, y: inset + half) // Bottom-left ScrewDot() .position(x: inset + half, y: h - inset - half) // Bottom-right ScrewDot() .position(x: w - inset - half, y: h - inset - half) } } } }