Add looper pedal: beat-quantized transport, undo, reverse, timeline
Extend the looper into a double-width tempo-aware pedal: - Beat-quantized transport: record start and loop close both snap to the next beat via a LyrebirdRoutine waiting on the shared clock; loop length is an exact whole-beat span. Falls back to immediate/unquantized when no clock is present. - Loop-length read-outs (frames/seconds/beats), transport state, and a sample-clock-derived play-head position for the UI timeline. - Overdub undo (pre-dub snapshot + restore), reverse playback (live rate flip), and feedback-decay overdub (overdub preLevel via a Feedback knob). - Inject the shared LyrebirdClock + SynthesisEngine into Pedal via PedalBoard/ChainRouter so tempo-aware pedals can reach them. - New double-width LooperTimelineView (state badge, length read-out, sweeping play-head) wired into PedalView via Pedal.widthUnits. Concurrency hardening from RT-safety review: a transportGeneration counter drops superseded deferred beat/undo callbacks that LyrebirdRoutine.stop() cannot recall once enqueued; the undo restore is deferred past the RT overdub gate-close; transport routines use non-blocking stop(). Note: this commit also snapshots pre-existing uncommitted work-in-progress already in the tree (MIDI control refactor, Tuner, Tempo, preset changes), which is interleaved with the looper changes through shared files and could not be split into a separately-building commit. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,144 @@
|
||||
// LooperTimelineView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// The looper's loop timeline: a transport-state label, a loop-length read-out, and a track
|
||||
/// with a sweeping play-head. Rendered inside the double-width ``PedalView`` for a `LooperPedal`.
|
||||
///
|
||||
/// `LooperPedal`'s transport state is plain (non-`@Observable`) RT-adjacent data, so this view
|
||||
/// polls it on a `.task` loop — the same convention as `TempoView`'s clock read-out — rather
|
||||
/// than relying on SwiftUI change tracking.
|
||||
struct LooperTimelineView: View {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let trackHeight: CGFloat = 16
|
||||
private static let trackCornerRadius: CGFloat = 4
|
||||
private static let playheadWidth: CGFloat = 2
|
||||
private static let sectionSpacing: CGFloat = 6
|
||||
private static let labelFontSize: CGFloat = 11
|
||||
private static let trackBrightness: Double = 0.14
|
||||
private static let trackBorderOpacity: Double = 0.35
|
||||
private static let filledOpacity: Double = 0.22
|
||||
private static let pollIntervalNanoseconds: UInt64 = 33_000_000 // ~30 Hz
|
||||
private static let ledDiameter: CGFloat = 9
|
||||
private static let badgeInnerSpacing: CGFloat = 4
|
||||
private static let lengthLabelOpacity: Double = 0.75
|
||||
private static let emptyLedBrightness: Double = 0.3
|
||||
private static let borderLineWidth: CGFloat = 1
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let pedal: LooperPedal
|
||||
|
||||
@State private var position: Double?
|
||||
@State private var state: LooperTransportState = .empty
|
||||
@State private var lengthSeconds: Double = 0.0
|
||||
@State private var lengthBeats: Double = 0.0
|
||||
|
||||
init(pedal: LooperPedal) {
|
||||
self.pedal = pedal
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: LooperTimelineView.sectionSpacing) {
|
||||
HStack(spacing: LooperTimelineView.sectionSpacing) {
|
||||
stateBadge
|
||||
Spacer(minLength: 0)
|
||||
lengthLabel
|
||||
}
|
||||
track
|
||||
}
|
||||
.task {
|
||||
// Poll the pedal's transport read-outs; it isn't @Observable (RT-adjacent state).
|
||||
while !Task.isCancelled {
|
||||
position = pedal.playbackPosition01()
|
||||
state = pedal.transportState
|
||||
lengthSeconds = pedal.loopLengthSeconds
|
||||
lengthBeats = pedal.loopLengthBeats
|
||||
try? await Task.sleep(nanoseconds: LooperTimelineView.pollIntervalNanoseconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private var stateBadge: some View {
|
||||
HStack(spacing: LooperTimelineView.badgeInnerSpacing) {
|
||||
Circle()
|
||||
.fill(stateColor)
|
||||
.frame(width: LooperTimelineView.ledDiameter, height: LooperTimelineView.ledDiameter)
|
||||
Text(stateText)
|
||||
.font(.system(size: LooperTimelineView.labelFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
private var lengthLabel: some View {
|
||||
Text(lengthText)
|
||||
.font(.system(size: LooperTimelineView.labelFontSize, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(LooperTimelineView.lengthLabelOpacity))
|
||||
}
|
||||
|
||||
private var track: some View {
|
||||
GeometryReader { geometry in
|
||||
let width: CGFloat = geometry.size.width
|
||||
let pos: CGFloat = CGFloat(position ?? 0.0)
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||
.fill(Color(white: LooperTimelineView.trackBrightness))
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||
.stroke(Color.white.opacity(LooperTimelineView.trackBorderOpacity),
|
||||
lineWidth: LooperTimelineView.borderLineWidth)
|
||||
)
|
||||
// Filled region up to the play-head, only while playing.
|
||||
if position != nil {
|
||||
RoundedRectangle(cornerRadius: LooperTimelineView.trackCornerRadius)
|
||||
.fill(Color.white.opacity(LooperTimelineView.filledOpacity))
|
||||
.frame(width: max(0, pos * width))
|
||||
Rectangle()
|
||||
.fill(Color.white)
|
||||
.frame(width: LooperTimelineView.playheadWidth)
|
||||
.offset(x: min(max(0, pos * width), width - LooperTimelineView.playheadWidth))
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(height: LooperTimelineView.trackHeight)
|
||||
}
|
||||
|
||||
// MARK: - State mapping
|
||||
|
||||
private var stateColor: Color {
|
||||
switch state {
|
||||
case .empty: return Color(white: LooperTimelineView.emptyLedBrightness)
|
||||
case .armedRecord, .armedStop: return Color.orange
|
||||
case .recording: return Color.red
|
||||
case .playing: return Color.green
|
||||
}
|
||||
}
|
||||
|
||||
private var stateText: String {
|
||||
switch state {
|
||||
case .empty: return "EMPTY"
|
||||
case .armedRecord: return "ARM"
|
||||
case .recording: return "REC"
|
||||
case .armedStop: return "END"
|
||||
case .playing: return "PLAY"
|
||||
}
|
||||
}
|
||||
|
||||
private var lengthText: String {
|
||||
guard lengthSeconds > 0 else { return "--" }
|
||||
let seconds: String = String(format: "%.2fs", lengthSeconds)
|
||||
guard lengthBeats > 0 else { return seconds }
|
||||
return seconds + " · \(Int(lengthBeats)) beat" + (lengthBeats == 1 ? "" : "s")
|
||||
}
|
||||
}
|
||||
@@ -102,23 +102,22 @@ public struct MIDIMappingSheet: View {
|
||||
SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"),
|
||||
SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"),
|
||||
]
|
||||
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
|
||||
let boardIndex: Int = boardPair.offset
|
||||
let board: PedalBoard = boardPair.element
|
||||
rows.append(SwitchRowModel(id: "sw-solo-\(boardIndex)",
|
||||
action: .boardSolo(boardIndex: boardIndex),
|
||||
for board: PedalBoard in shoeGaze.boards {
|
||||
let boardID: UUID = board.id
|
||||
rows.append(SwitchRowModel(id: "sw-solo-\(boardID)",
|
||||
action: .boardSolo(boardID: boardID),
|
||||
label: "\(board.label) · Solo"))
|
||||
rows.append(SwitchRowModel(id: "sw-aud-\(boardIndex)",
|
||||
action: .boardAudible(boardIndex: boardIndex),
|
||||
rows.append(SwitchRowModel(id: "sw-aud-\(boardID)",
|
||||
action: .boardAudible(boardID: boardID),
|
||||
label: "\(board.label) · Audible"))
|
||||
rows.append(SwitchRowModel(id: "sw-byp-\(boardIndex)",
|
||||
action: .boardBypass(boardIndex: boardIndex),
|
||||
rows.append(SwitchRowModel(id: "sw-byp-\(boardID)",
|
||||
action: .boardBypass(boardID: boardID),
|
||||
label: "\(board.label) · Bypass"))
|
||||
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
|
||||
for pedal: Pedal in board.pedals {
|
||||
rows.append(SwitchRowModel(
|
||||
id: "sw-pb-\(boardIndex)-\(pedalPair.offset)",
|
||||
action: .pedalBypass(boardIndex: boardIndex, pedalIndex: pedalPair.offset),
|
||||
label: "\(board.label) · \(pedalPair.element.displayName) · Bypass"))
|
||||
id: "sw-pb-\(pedal.id)",
|
||||
action: .pedalBypass(pedalID: pedal.id),
|
||||
label: "\(board.label) · \(pedal.displayName) · Bypass"))
|
||||
}
|
||||
}
|
||||
return rows
|
||||
@@ -128,23 +127,18 @@ public struct MIDIMappingSheet: View {
|
||||
var rows: [CCRowModel] = [
|
||||
CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"),
|
||||
]
|
||||
for boardPair: (offset: Int, element: PedalBoard) in shoeGaze.boards.enumerated() {
|
||||
let boardIndex: Int = boardPair.offset
|
||||
let board: PedalBoard = boardPair.element
|
||||
for board: PedalBoard in shoeGaze.boards {
|
||||
// Board master level (the board fader).
|
||||
rows.append(CCRowModel(
|
||||
id: "cc-blvl-\(boardIndex)",
|
||||
target: .boardLevel(boardIndex: boardIndex, boardLabelHint: nil),
|
||||
id: "cc-blvl-\(board.id)",
|
||||
target: .boardLevel(boardID: board.id, boardLabelHint: nil),
|
||||
label: "\(board.label) · Level"))
|
||||
for pedalPair: (offset: Int, element: Pedal) in board.pedals.enumerated() {
|
||||
let pedalIndex: Int = pedalPair.offset
|
||||
let pedal: Pedal = pedalPair.element
|
||||
for pedal: Pedal in board.pedals {
|
||||
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
|
||||
rows.append(CCRowModel(
|
||||
id: "cc-\(boardIndex)-\(pedalIndex)-\(controlPair.offset)",
|
||||
id: "cc-\(pedal.id)-\(controlPair.offset)",
|
||||
target: .pedalControl(
|
||||
boardIndex: boardIndex,
|
||||
pedalIndex: pedalIndex,
|
||||
pedalID: pedal.id,
|
||||
controlIndex: controlPair.offset,
|
||||
pedalNameHint: nil,
|
||||
controlLabelHint: nil),
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// PedalButtonView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
// MARK: - PedalButtonView
|
||||
|
||||
/// A stomp-style action button rendered from a ``PedalButton`` descriptor.
|
||||
///
|
||||
/// `.momentary` renders a plain `ParameterButton`. `.toggle` renders the same LED +
|
||||
/// footswitch look as the pedal's own bypass control (`PedalView`'s `LEDIndicator` /
|
||||
/// `FootswitchButton`), with a caption label beneath — so a looper's Overdub/Loop toggles
|
||||
/// read as stomp switches with state, not a segmented picker.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// PedalButtonView(pedalButton)
|
||||
/// ```
|
||||
public struct PedalButtonView: View {
|
||||
|
||||
private static let toggleOnThreshold: Double = 0.5
|
||||
private static let sectionSpacing: CGFloat = 6
|
||||
private static let captionFontSize: CGFloat = 11
|
||||
|
||||
private let pedalButton: PedalButton
|
||||
|
||||
/// Creates a button view from a descriptor.
|
||||
///
|
||||
/// - Parameter pedalButton: The button to render.
|
||||
public init(_ pedalButton: PedalButton) {
|
||||
self.pedalButton = pedalButton
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
switch pedalButton.style {
|
||||
case .momentary:
|
||||
ParameterButton(pedalButton.label, action: pedalButton.action ?? {})
|
||||
case .toggle:
|
||||
if let node: UIParamNode = pedalButton.node {
|
||||
// Reading `node.value` registers this view for @Observable re-render.
|
||||
let isOn: Bool = node.value >= PedalButtonView.toggleOnThreshold
|
||||
VStack(spacing: PedalButtonView.sectionSpacing) {
|
||||
LEDIndicator(isOn: isOn)
|
||||
FootswitchButton(node: node)
|
||||
Text(pedalButton.label)
|
||||
.font(.system(size: PedalButtonView.captionFontSize))
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,9 +90,11 @@ private struct ScrewDot: View {
|
||||
|
||||
/// A small circular LED that glows green when the effect is engaged.
|
||||
///
|
||||
/// Bypass polarity: `0` = engaged (effect ON), `1` = bypassed.
|
||||
/// The LED is lit when `bypassValue < 0.5`.
|
||||
private struct LEDIndicator: View {
|
||||
/// 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
|
||||
@@ -101,13 +103,11 @@ private struct LEDIndicator: View {
|
||||
private static let dimBrightness: Double = 0.15
|
||||
private static let rimStrokeOpacity: Double = 0.30
|
||||
|
||||
let bypassValue: Double
|
||||
|
||||
private var isEngaged: Bool { bypassValue < 0.5 }
|
||||
let isOn: Bool
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
if isEngaged {
|
||||
if isOn {
|
||||
Circle()
|
||||
.fill(Color.green.opacity(LEDIndicator.glowOpacity))
|
||||
.frame(
|
||||
@@ -117,7 +117,7 @@ private struct LEDIndicator: View {
|
||||
.blur(radius: LEDIndicator.glowRadius / 2)
|
||||
}
|
||||
Circle()
|
||||
.fill(isEngaged ? Color.green : Color(white: LEDIndicator.dimBrightness))
|
||||
.fill(isOn ? Color.green : Color(white: LEDIndicator.dimBrightness))
|
||||
.frame(width: LEDIndicator.diameter, height: LEDIndicator.diameter)
|
||||
.overlay(
|
||||
Circle()
|
||||
@@ -132,8 +132,10 @@ private struct LEDIndicator: View {
|
||||
|
||||
// MARK: - Footswitch
|
||||
|
||||
/// A round footswitch-style button that toggles bypass on/off.
|
||||
private struct FootswitchButton: View {
|
||||
/// A round footswitch-style button that flips a `UIParamNode` between `0` and `1`.
|
||||
/// `internal` (not `private`) so other views in this module (e.g. `PedalButtonView`) can
|
||||
/// reuse the same stompbox footswitch look for non-bypass toggles.
|
||||
struct FootswitchButton: View {
|
||||
|
||||
private static let diameter: CGFloat = 44
|
||||
private static let strokeWidth: CGFloat = 2.5
|
||||
@@ -291,9 +293,11 @@ public struct PedalView: View {
|
||||
// Content stack
|
||||
VStack(spacing: PedalView.sectionSpacing) {
|
||||
namePlate
|
||||
looperTimeline
|
||||
knobGrid
|
||||
selectorRow
|
||||
switchRow
|
||||
buttonRow
|
||||
sliderBank(sliders)
|
||||
Spacer(minLength: 0)
|
||||
bottomControls
|
||||
@@ -334,6 +338,15 @@ public struct PedalView: View {
|
||||
.clipShape(RoundedRectangle(cornerRadius: PedalView.namePlateCornerRadius))
|
||||
}
|
||||
|
||||
/// Loop timeline strip — rendered only for the double-width `LooperPedal`, between the
|
||||
/// name plate and the knob grid. Other pedals render nothing here.
|
||||
@ViewBuilder
|
||||
private var looperTimeline: some View {
|
||||
if let looper: LooperPedal = pedal as? LooperPedal {
|
||||
LooperTimelineView(pedal: looper)
|
||||
}
|
||||
}
|
||||
|
||||
/// Info button tucked just under the top-left corner screw.
|
||||
private var infoButton: some View {
|
||||
Button {
|
||||
@@ -417,6 +430,22 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Row of stomp-style action buttons drawn from `pedal.effectButtons`, beneath the
|
||||
/// switch 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
|
||||
@@ -431,16 +460,19 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enclosure width — the base stompbox width, widened to fit a wide vertical-fader bank
|
||||
/// (e.g. a multi-band graphic EQ) so its faders are never clipped.
|
||||
/// 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 PedalView.enclosureWidth }
|
||||
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(PedalView.enclosureWidth, needed)
|
||||
return max(unitWidth, needed)
|
||||
}
|
||||
|
||||
/// Bottom control row: the `Level` knob, the bypass switch, and the `Mix` knob,
|
||||
@@ -479,9 +511,10 @@ public struct PedalView: View {
|
||||
// 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(bypassValue: bypassValue)
|
||||
LEDIndicator(isOn: bypassValue < engagedThreshold)
|
||||
FootswitchButton(node: pedal.$bypass)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,9 +533,12 @@ public struct ShoeGazeBuilderView: View {
|
||||
private var transportRow: some View {
|
||||
_ = transportTick
|
||||
return HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||||
Text("ShoeGaze Builder")
|
||||
.font(.title2).bold()
|
||||
.foregroundStyle(Color.white)
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text("ShoeGaze Builder")
|
||||
.font(.title2).bold()
|
||||
.foregroundStyle(Color.white)
|
||||
currentRigLabel
|
||||
}
|
||||
if shoeGaze.isRecording {
|
||||
// Recording indicator (both platforms; recording is driven from the macOS Record
|
||||
// menu or the iOS controls below).
|
||||
@@ -549,6 +552,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
Spacer()
|
||||
TempoView(shoeGaze: shoeGaze)
|
||||
TunerView(shoeGaze: shoeGaze)
|
||||
if let midi: MIDIController = midi {
|
||||
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
|
||||
}
|
||||
@@ -729,6 +734,11 @@ public struct ShoeGazeBuilderView: View {
|
||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||
if wasRunning { shoeGaze.engine.stop() }
|
||||
|
||||
// Clearing the rig discards its MIDI bindings — they are addressed positionally and
|
||||
// belong to the rig being cleared. Reset before rebuilding so stale bindings can't
|
||||
// re-resolve onto the fresh board's pedals.
|
||||
shoeGaze.midiMap = nil
|
||||
|
||||
// Snapshot before removing — removeBoard mutates shoeGaze.boards.
|
||||
for board: PedalBoard in Array(shoeGaze.boards) {
|
||||
shoeGaze.removeBoard(board)
|
||||
@@ -1096,6 +1106,32 @@ public struct ShoeGazeBuilderView: View {
|
||||
return library.entries.first(where: { $0.id == id })?.name
|
||||
}
|
||||
|
||||
/// A subtitle under the app title showing which rig is loaded. Resolves the name from the
|
||||
/// library once it has loaded; shows "Unsaved rig" when the working graph has no source-rig
|
||||
/// id (a cleared / never-saved session). Reads `shoeGaze.currentRigID` and `library.entries`
|
||||
/// so it refreshes automatically when a rig is loaded or the library finishes loading.
|
||||
private var currentRigLabel: some View {
|
||||
let hasSource: Bool = currentRigID != nil
|
||||
let name: String
|
||||
if let resolved: String = currentRigName() {
|
||||
name = resolved
|
||||
} else if hasSource {
|
||||
// Source id exists but the library hasn't resolved it yet (still loading).
|
||||
name = library.isLoaded ? "Unknown rig" : "Loading…"
|
||||
} else {
|
||||
name = "Unsaved rig"
|
||||
}
|
||||
return HStack(spacing: 5) {
|
||||
Image(systemName: hasSource ? "guitars.fill" : "guitars")
|
||||
.font(.caption2)
|
||||
Text(name)
|
||||
.font(.caption)
|
||||
.lineLimit(1)
|
||||
}
|
||||
.foregroundStyle(Color.white.opacity(hasSource ? 0.8 : 0.5))
|
||||
.help(hasSource ? "Loaded rig: \(name)" : "This rig has not been saved to the library yet")
|
||||
}
|
||||
|
||||
/// A default name for a new rig: `"Rig N"` where N avoids collisions with existing names.
|
||||
private func defaultNewRigName() -> String {
|
||||
let base: String = "Rig"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// TempoView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Tempo indicator: a BPM readout/stepper, a beat-synced flashing LED, and a tap area that
|
||||
/// responds to mouse/touch taps (call ``ShoeGaze/tapTempo()`` directly for a MIDI trigger).
|
||||
///
|
||||
/// Polls ``ShoeGaze/clock``'s `currentBeat` on a `.task` loop (matching the scope/CPU-meter
|
||||
/// polling convention) since `LyrebirdClock` isn't `@Observable` — it's sample-accurate RT
|
||||
/// state, not push-notified UI state.
|
||||
public struct TempoView: View {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let pollIntervalNanoseconds: UInt64 = 33_333_333 // ~30 Hz
|
||||
/// Fraction of each beat the LED stays lit — a short flash, not a 50% duty-cycle blink.
|
||||
private static let flashDutyCycle: Double = 0.15
|
||||
private static let minBpm: Double = 30.0
|
||||
private static let maxBpm: Double = 300.0
|
||||
private static let bpmStep: Double = 1.0
|
||||
private static let ledDiameter: CGFloat = 16
|
||||
private static let panelSpacing: CGFloat = 10
|
||||
private static let rowSpacing: CGFloat = 14
|
||||
private static let tapAreaSize: CGFloat = 64
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
|
||||
@State private var displayedBpm: Double
|
||||
@State private var ledOn: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives.
|
||||
public init(shoeGaze: ShoeGaze) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: TempoView.panelSpacing) {
|
||||
HStack(spacing: TempoView.rowSpacing) {
|
||||
led
|
||||
Text("\(Int(displayedBpm.rounded())) BPM")
|
||||
.font(.system(size: 18, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(Color.white)
|
||||
Stepper(
|
||||
"",
|
||||
value: Binding(
|
||||
get: { displayedBpm },
|
||||
set: { newValue in
|
||||
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
|
||||
shoeGaze.clock.bpm = clamped
|
||||
displayedBpm = clamped
|
||||
}
|
||||
),
|
||||
in: TempoView.minBpm ... TempoView.maxBpm,
|
||||
step: TempoView.bpmStep
|
||||
)
|
||||
.labelsHidden()
|
||||
}
|
||||
|
||||
tapArea
|
||||
}
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
let beat: Double = shoeGaze.clock.currentBeat
|
||||
let phase: Double = beat - beat.rounded(.down)
|
||||
ledOn = phase < TempoView.flashDutyCycle
|
||||
displayedBpm = shoeGaze.clock.bpm
|
||||
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private var led: some View {
|
||||
Circle()
|
||||
.fill(ledOn ? Color.red : Color.red.opacity(0.15))
|
||||
.frame(width: TempoView.ledDiameter, height: TempoView.ledDiameter)
|
||||
}
|
||||
|
||||
private var tapArea: some View {
|
||||
Button {
|
||||
shoeGaze.tapTempo()
|
||||
displayedBpm = shoeGaze.clock.bpm
|
||||
} label: {
|
||||
Text("TAP")
|
||||
.font(.system(size: 14, weight: .bold, design: .rounded))
|
||||
.frame(width: TempoView.tapAreaSize, height: TempoView.tapAreaSize)
|
||||
.background(Color.white.opacity(0.08))
|
||||
.clipShape(Circle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// TunerView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// Chromatic tuner panel: an engage toggle, a mute-rig-while-tuning toggle, and a live
|
||||
/// note/cents readout.
|
||||
///
|
||||
/// Polls ``ShoeGaze/currentPitchHz`` on a `.task` loop (matching `LyrebirdEngineStatusView`'s
|
||||
/// CPU-meter convention) since the value is computed from RT-thread state on demand, not an
|
||||
/// `@Observable`-tracked property. Polling only runs while the tuner is engaged.
|
||||
public struct TunerView: View {
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let pollIntervalNanoseconds: UInt64 = 250_000_000 // 4 Hz, at most
|
||||
private static let inTuneCentsThreshold: Double = 5.0
|
||||
private static let closeCentsThreshold: Double = 15.0
|
||||
/// Below this YIN confidence the reading is treated as untracked — the last stable pitch
|
||||
/// is latched and the display dims, rather than chasing a transient/attack estimate.
|
||||
private static let trackingConfidenceThreshold: Double = 0.8
|
||||
/// Opacity applied to the latched readout while not actively tracking.
|
||||
private static let untrackedOpacity: Double = 0.35
|
||||
private static let panelSpacing: CGFloat = 10
|
||||
private static let rowSpacing: CGFloat = 14
|
||||
private static let noteFontSize: CGFloat = 34
|
||||
private static let statusFontSize: CGFloat = 10
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let shoeGaze: ShoeGaze
|
||||
|
||||
/// Last pitch accepted at or above the confidence threshold (latched through dropouts).
|
||||
@State private var latchedPitch: TunerPitchReading?
|
||||
/// `true` when the most recent poll was above the confidence threshold.
|
||||
@State private var isTracking: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameter shoeGaze: The session whose tuner state this view controls and displays.
|
||||
public init(shoeGaze: ShoeGaze) {
|
||||
self.shoeGaze = shoeGaze
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: TunerView.panelSpacing) {
|
||||
HStack(spacing: TunerView.rowSpacing) {
|
||||
Button(shoeGaze.tunerEngaged ? "Tuner: On" : "Tuner: Off") {
|
||||
shoeGaze.toggleTunerEngaged()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(shoeGaze.tunerEngaged ? .green : .gray)
|
||||
|
||||
Toggle("Mute rig", isOn: Binding(
|
||||
get: { shoeGaze.tunerMutesRig },
|
||||
set: { shoeGaze.tunerMutesRig = $0 }
|
||||
))
|
||||
.toggleStyle(.switch)
|
||||
}
|
||||
|
||||
if shoeGaze.tunerEngaged {
|
||||
readout
|
||||
}
|
||||
}
|
||||
.task(id: shoeGaze.tunerEngaged) {
|
||||
while shoeGaze.tunerEngaged && !Task.isCancelled {
|
||||
updateReading()
|
||||
try? await Task.sleep(nanoseconds: TunerView.pollIntervalNanoseconds)
|
||||
}
|
||||
if !shoeGaze.tunerEngaged {
|
||||
latchedPitch = nil
|
||||
isTracking = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Polls freq + confidence. Above the confidence threshold, updates the latched pitch
|
||||
/// and marks tracking active; below it, leaves the latched pitch in place (so restrikes
|
||||
/// don't make the reading ramp) and marks tracking inactive.
|
||||
private func updateReading() {
|
||||
let confidence: Double = shoeGaze.currentPitchConfidence ?? 0.0
|
||||
let hz: Double = shoeGaze.currentPitchHz ?? 0.0
|
||||
if confidence >= TunerView.trackingConfidenceThreshold && hz > 0 {
|
||||
latchedPitch = TunerPitchReading(hz: hz)
|
||||
isTracking = true
|
||||
} else {
|
||||
isTracking = false
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Readout
|
||||
|
||||
@ViewBuilder
|
||||
private var readout: some View {
|
||||
if let pitch: TunerPitchReading = latchedPitch {
|
||||
VStack(spacing: 6) {
|
||||
Text(pitch.noteName)
|
||||
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
|
||||
.foregroundStyle(TunerView.color(forCents: pitch.cents))
|
||||
TunerCentsMeter(cents: pitch.cents)
|
||||
Text(isTracking ? "TRACKING" : "…")
|
||||
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(0.5))
|
||||
}
|
||||
.opacity(isTracking ? 1.0 : TunerView.untrackedOpacity)
|
||||
} else {
|
||||
VStack(spacing: 6) {
|
||||
Text("—")
|
||||
.font(.system(size: TunerView.noteFontSize, weight: .bold, design: .rounded))
|
||||
.foregroundStyle(Color.white.opacity(0.4))
|
||||
Text("play a note")
|
||||
.font(.system(size: TunerView.statusFontSize, weight: .semibold, design: .monospaced))
|
||||
.foregroundStyle(Color.white.opacity(0.4))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static func color(forCents cents: Double) -> Color {
|
||||
let magnitude: Double = abs(cents)
|
||||
if magnitude <= TunerView.inTuneCentsThreshold { return .green }
|
||||
if magnitude <= TunerView.closeCentsThreshold { return .yellow }
|
||||
return .red
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TunerCentsMeter
|
||||
|
||||
/// A horizontal -50…+50 cents meter: a track with a centre "in tune" tick and a vertical
|
||||
/// marker positioned at the current deviation, coloured with the same red/yellow/green
|
||||
/// thresholds as the note readout.
|
||||
struct TunerCentsMeter: View {
|
||||
|
||||
private static let range: Double = 50.0
|
||||
private static let trackWidth: CGFloat = 140
|
||||
private static let trackHeight: CGFloat = 4
|
||||
private static let markerWidth: CGFloat = 3
|
||||
private static let markerHeight: CGFloat = 18
|
||||
private static let centerTickWidth: CGFloat = 1.5
|
||||
private static let centerTickHeight: CGFloat = 10
|
||||
|
||||
let cents: Double
|
||||
|
||||
private var clampedFraction: Double {
|
||||
// Maps [-range, +range] to [0, 1]; values beyond the range pin to the edge.
|
||||
let clamped: Double = min(max(cents, -TunerCentsMeter.range), TunerCentsMeter.range)
|
||||
return (clamped + TunerCentsMeter.range) / (2.0 * TunerCentsMeter.range)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
let width: CGFloat = geometry.size.width
|
||||
let markerX: CGFloat = width * clampedFraction
|
||||
|
||||
ZStack(alignment: .leading) {
|
||||
// Track.
|
||||
RoundedRectangle(cornerRadius: TunerCentsMeter.trackHeight / 2)
|
||||
.fill(Color.white.opacity(0.15))
|
||||
.frame(height: TunerCentsMeter.trackHeight)
|
||||
.frame(maxWidth: .infinity)
|
||||
|
||||
// Centre "in tune" reference tick.
|
||||
Rectangle()
|
||||
.fill(Color.white.opacity(0.5))
|
||||
.frame(width: TunerCentsMeter.centerTickWidth, height: TunerCentsMeter.centerTickHeight)
|
||||
.position(x: width / 2, y: TunerCentsMeter.trackHeight / 2)
|
||||
|
||||
// Deviation marker.
|
||||
Rectangle()
|
||||
.fill(TunerView.color(forCents: cents))
|
||||
.frame(width: TunerCentsMeter.markerWidth, height: TunerCentsMeter.markerHeight)
|
||||
.position(x: markerX, y: TunerCentsMeter.trackHeight / 2)
|
||||
}
|
||||
}
|
||||
.frame(width: TunerCentsMeter.trackWidth, height: TunerCentsMeter.markerHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - TunerPitchReading
|
||||
|
||||
/// Converts a detected frequency into the nearest chromatic note name, octave, and cents
|
||||
/// deviation. Standard 12-TET sharp spelling — a tuner display doesn't need the full
|
||||
/// spelling-aware `NoteName`/`Scale` theory toolkit (that's for compositional notation).
|
||||
struct TunerPitchReading {
|
||||
private static let chromaticNames: [String] = [
|
||||
"C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B",
|
||||
]
|
||||
private static let semitonesPerOctave: Int = 12
|
||||
private static let midiOctaveOffset: Int = 1 // MIDI note 0 = C-1
|
||||
private static let centsPerSemitone: Double = 100.0
|
||||
|
||||
let noteName: String
|
||||
let cents: Double
|
||||
|
||||
init(hz: Double) {
|
||||
let midi: Double = hzToMidi(hz)
|
||||
let nearestMidi: Int = Int(midi.rounded())
|
||||
cents = (midi - Double(nearestMidi)) * TunerPitchReading.centsPerSemitone
|
||||
let pitchClass: Int = ((nearestMidi % TunerPitchReading.semitonesPerOctave)
|
||||
+ TunerPitchReading.semitonesPerOctave) % TunerPitchReading.semitonesPerOctave
|
||||
let octave: Int = nearestMidi / TunerPitchReading.semitonesPerOctave - TunerPitchReading.midiOctaveOffset
|
||||
noteName = "\(TunerPitchReading.chromaticNames[pitchClass])\(octave)"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user