Files
ShoeGaze/Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift
T
josh 947dfe427a 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>
2026-07-03 09:22:20 -07:00

253 lines
9.6 KiB
Swift

// MIDIMappingSheet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import SwiftUI
import LyrebirdShoeGaze
import LyrebirdUI
/// The MIDI mapping panel: shows connected devices and lets the user bind expression-pedal CCs to
/// pedal knobs via MIDI Learn.
///
/// Presented from the transport-row ``MIDIIndicatorView``. Rows are generated by walking the live
/// `ShoeGaze.boards` / `board.pedals` and each pedal's controls, so bindings address controls
/// positionally. A Switches section binds Program Change to toggle actions; an Expression section
/// binds Control Change to continuous pedal controls.
public struct MIDIMappingSheet: View {
// MARK: - Constants
private static let sheetMinWidth: CGFloat = 460
private static let sheetMinHeight: CGFloat = 520
private static let rowVerticalPadding: CGFloat = 2
// MARK: - Inputs
private let controller: MIDIController
private let shoeGaze: ShoeGaze
@Environment(\.dismiss) private var dismiss
/// Creates a MIDI mapping sheet.
///
/// - Parameters:
/// - controller: The MIDI controller that owns the connection, learn state, and bindings.
/// - shoeGaze: The rig whose boards / pedals / knobs are enumerated as binding targets.
public init(controller: MIDIController, shoeGaze: ShoeGaze) {
self.controller = controller
self.shoeGaze = shoeGaze
}
// MARK: - Body
public var body: some View {
NavigationStack {
List {
devicesSection
switchesSection
expressionSection
}
.navigationTitle("MIDI Mapping")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Done") {
controller.cancelLearn()
dismiss()
}
}
}
}
.frame(minWidth: MIDIMappingSheet.sheetMinWidth, minHeight: MIDIMappingSheet.sheetMinHeight)
}
// MARK: - Devices
private var devicesSection: some View {
Section("Devices") {
if controller.isConnected {
ForEach(controller.connectedDeviceNames, id: \.self) { name in
Label(name, systemImage: "pianokeys")
.foregroundStyle(Color.green)
}
} else {
Label("No MIDI device detected", systemImage: "pianokeys.inverse")
.foregroundStyle(.secondary)
}
}
}
// MARK: - Row models
/// A Program-Change switch row: a toggle action + its display label. `id` is globally unique so
/// SwiftUI never reuses a row view across the two sections (which would leak the wrong Learn
/// action into a row).
private struct SwitchRowModel: Identifiable {
let id: String
let action: MIDIMap.Action
let label: String
}
/// A Control-Change row: a continuous target (address-only, hints `nil`) + its display label.
private struct CCRowModel: Identifiable {
let id: String
let target: MIDIMap.CCTarget
let label: String
}
private var switchRowModels: [SwitchRowModel] {
var rows: [SwitchRowModel] = [
SwitchRowModel(id: "sw-rig", action: .rigBypass, label: "Rig Bypass"),
SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"),
SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"),
]
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-\(boardID)",
action: .boardAudible(boardID: boardID),
label: "\(board.label) · Audible"))
rows.append(SwitchRowModel(id: "sw-byp-\(boardID)",
action: .boardBypass(boardID: boardID),
label: "\(board.label) · Bypass"))
for pedal: Pedal in board.pedals {
rows.append(SwitchRowModel(
id: "sw-pb-\(pedal.id)",
action: .pedalBypass(pedalID: pedal.id),
label: "\(board.label) · \(pedal.displayName) · Bypass"))
}
}
return rows
}
private var ccRowModels: [CCRowModel] {
var rows: [CCRowModel] = [
CCRowModel(id: "cc-rigvol", target: .rigVolume, label: "Rig · Volume"),
]
for board: PedalBoard in shoeGaze.boards {
// Board master level (the board fader).
rows.append(CCRowModel(
id: "cc-blvl-\(board.id)",
target: .boardLevel(boardID: board.id, boardLabelHint: nil),
label: "\(board.label) · Level"))
for pedal: Pedal in board.pedals {
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
rows.append(CCRowModel(
id: "cc-\(pedal.id)-\(controlPair.offset)",
target: .pedalControl(
pedalID: pedal.id,
controlIndex: controlPair.offset,
pedalNameHint: nil,
controlLabelHint: nil),
label: "\(pedal.displayName) · \(controlPair.element.label)"))
}
}
}
return rows
}
// MARK: - Switches (Program Change)
private var switchesSection: some View {
Section("Switches (Program Change)") {
ForEach(switchRowModels) { row in
switchRow(row)
}
}
}
private func switchRow(_ row: SwitchRowModel) -> some View {
let isArmed: Bool = controller.learnTarget == .action(row.action)
let binding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action)
return HStack {
VStack(alignment: .leading, spacing: 1) {
Text(row.label)
Text(switchBindingLabel(isArmed: isArmed, binding: binding))
.font(.caption)
.foregroundStyle(isArmed ? Color.orange : .secondary)
}
Spacer()
if binding != nil {
Button("Clear") { controller.clearSwitchBinding(for: row.action) }
.buttonStyle(.borderless)
}
Button(isArmed ? "Cancel" : "Learn") {
if isArmed {
controller.cancelLearn()
} else {
controller.armSwitchLearn(row.action)
}
}
.buttonStyle(.bordered)
.tint(.orange)
}
.padding(.vertical, MIDIMappingSheet.rowVerticalPadding)
}
private func switchBindingLabel(isArmed: Bool, binding: MIDIMap.SwitchBinding?) -> String {
if isArmed { return "Listening — press a footswitch…" }
guard let binding: MIDIMap.SwitchBinding = binding else { return "Unassigned" }
let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? ""
return "PC \(binding.program)\(channelText)"
}
// MARK: - Expression (CC)
private var expressionSection: some View {
Section("Expression (Control Change)") {
if shoeGaze.boards.isEmpty {
Text("Add a pedal to assign expression control.")
.foregroundStyle(.secondary)
}
ForEach(ccRowModels) { row in
ccRow(row)
}
}
}
private func ccRow(_ row: CCRowModel) -> some View {
let isArmed: Bool = controller.learnTarget == .cc(row.target)
let binding: MIDIMap.CCBinding? = controller.ccBinding(for: row.target)
return HStack {
VStack(alignment: .leading, spacing: 1) {
Text(row.label)
Text(ccBindingLabel(isArmed: isArmed, binding: binding))
.font(.caption)
.foregroundStyle(isArmed ? Color.orange : .secondary)
}
Spacer()
if binding != nil {
Toggle("Invert", isOn: Binding(
get: { controller.isCCInverted(for: row.target) },
set: { controller.setCCInverted(for: row.target, $0) }
))
.toggleStyle(.button)
.tint(.orange)
Button("Clear") { controller.clearCCBinding(for: row.target) }
.buttonStyle(.borderless)
}
Button(isArmed ? "Cancel" : "Learn") {
if isArmed {
controller.cancelLearn()
} else {
controller.armCCLearn(row.target)
}
}
.buttonStyle(.bordered)
.tint(.orange)
}
.padding(.vertical, MIDIMappingSheet.rowVerticalPadding)
}
private func ccBindingLabel(isArmed: Bool, binding: MIDIMap.CCBinding?) -> String {
if isArmed { return "Listening — move an expression pedal…" }
guard let binding: MIDIMap.CCBinding = binding else { return "Unassigned" }
let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? ""
let invertText: String = binding.inverted ? " · inverted" : ""
return "CC \(binding.controller)\(channelText)\(invertText)"
}
}