1.0.0 release
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
// MultiSlider.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A row of `count` adjacent vertical sliders bound to consecutive cells of a
|
||||
/// `LyrebirdBuffer`.
|
||||
///
|
||||
/// Designed for driving per-bin parameter buffers — for example the per-bin
|
||||
/// delay times and feedbacks read by `SpectralBinDelay`, or the magnitude
|
||||
/// transfer curve read by `SpectralMagnitudeMap`. Each bar represents one
|
||||
/// `LyrebirdBuffer` cell starting at `startIndex`; dragging vertically over a
|
||||
/// bar writes the new value via `LyrebirdBuffer.setValue(_:at:)` (lock-free on
|
||||
/// the RT side, see the Lyrebird module's `BufferGuide`).
|
||||
///
|
||||
/// ```swift
|
||||
/// let delays = LyrebirdBuffer(count: 1024)
|
||||
/// delays.fill { i, n in Double(i) / Double(n) * 0.5 }
|
||||
///
|
||||
/// MultiSlider(
|
||||
/// buffer: delays,
|
||||
/// count: 64,
|
||||
/// range: 0.0...0.5,
|
||||
/// height: 120
|
||||
/// )
|
||||
/// ```
|
||||
public struct MultiSlider: View {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
private let buffer: LyrebirdBuffer
|
||||
private let count: Int
|
||||
private let startIndex: Int
|
||||
private let range: ClosedRange<Double>
|
||||
private let height: CGFloat
|
||||
|
||||
// MARK: - State
|
||||
|
||||
@State private var values: [Double]
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - buffer: Backing `LyrebirdBuffer`. Mono only. Initial values shown by
|
||||
/// the sliders are read once from `buffer[startIndex + i]` at view
|
||||
/// construction; thereafter the buffer is treated as one-way (this
|
||||
/// view writes; external readers consume).
|
||||
/// - count: Number of sliders in the row. Must be ≥ 1 and
|
||||
/// `startIndex + count <= buffer.count`.
|
||||
/// - startIndex: First buffer index this view writes to. Defaults to `0`.
|
||||
/// - range: Value range. Drag-top of a bar maps to `range.upperBound`,
|
||||
/// drag-bottom to `range.lowerBound`.
|
||||
/// - height: View height in points. Default `100`.
|
||||
public init(
|
||||
buffer: LyrebirdBuffer,
|
||||
count: Int,
|
||||
startIndex: Int = 0,
|
||||
range: ClosedRange<Double>,
|
||||
height: CGFloat = 100
|
||||
) {
|
||||
precondition(buffer.channelCount == 1,
|
||||
"MultiSlider: buffer must be mono, got channelCount=\(buffer.channelCount)")
|
||||
precondition(count >= 1,
|
||||
"MultiSlider: count must be >= 1, got \(count)")
|
||||
precondition(startIndex >= 0 && startIndex + count <= buffer.count,
|
||||
"MultiSlider: startIndex \(startIndex) + count \(count) "
|
||||
+ "exceeds buffer.count \(buffer.count)")
|
||||
precondition(range.lowerBound < range.upperBound,
|
||||
"MultiSlider: range must be non-empty, got \(range)")
|
||||
|
||||
self.buffer = buffer
|
||||
self.count = count
|
||||
self.startIndex = startIndex
|
||||
self.range = range
|
||||
self.height = height
|
||||
|
||||
var initial: [Double] = [Double](repeating: range.lowerBound, count: count)
|
||||
for i: Int in 0..<count {
|
||||
let raw: Double = buffer[startIndex + i]
|
||||
initial[i] = min(max(raw, range.lowerBound), range.upperBound)
|
||||
}
|
||||
_values = State(initialValue: initial)
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
GeometryReader { geo in
|
||||
let columnWidth: CGFloat = geo.size.width / CGFloat(count)
|
||||
ZStack(alignment: .topLeading) {
|
||||
Color.lyrebirdControlBackground
|
||||
|
||||
Canvas { ctx, size in
|
||||
let h: CGFloat = size.height
|
||||
let w: CGFloat = columnWidth
|
||||
for i: Int in 0..<count {
|
||||
let v: Double = values[i]
|
||||
let norm: Double = (v - range.lowerBound) / (range.upperBound - range.lowerBound)
|
||||
let barH: CGFloat = h * CGFloat(norm)
|
||||
let x: CGFloat = CGFloat(i) * w
|
||||
let rect: CGRect = CGRect(x: x + 1, y: h - barH, width: max(1, w - 2), height: barH)
|
||||
ctx.fill(Path(rect), with: .color(.accentColor))
|
||||
}
|
||||
}
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.gesture(
|
||||
DragGesture(minimumDistance: 0)
|
||||
.onChanged { drag in
|
||||
let column: Int = Int(drag.location.x / columnWidth)
|
||||
guard column >= 0 && column < count else { return }
|
||||
let yClamped: CGFloat = min(max(drag.location.y, 0), geo.size.height)
|
||||
let norm: Double = 1 - Double(yClamped / geo.size.height)
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let value: Double = range.lowerBound + norm * span
|
||||
// Drag fires many ticks per second; the SwiftUI diff
|
||||
// and `setValue`'s NSLock both make repeated identical
|
||||
// values cheap, so we don't bother short-circuiting on
|
||||
// equality (Double-equality on continuous drag is
|
||||
// almost always false).
|
||||
values[column] = value
|
||||
buffer.setValue(value, at: startIndex + column)
|
||||
}
|
||||
)
|
||||
}
|
||||
.frame(height: height)
|
||||
.overlay(
|
||||
Rectangle().stroke(Color.lyrebirdSeparator, lineWidth: 1)
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
// ParameterButton.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A button control for triggering actions or toggling a `UIParamNode` between two values.
|
||||
///
|
||||
/// Two styles:
|
||||
/// - `.momentary` (default) — executes a closure on press; no node binding required.
|
||||
/// - `.toggle` — flips the bound node between `offValue` and `onValue` on each press.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Momentary action button
|
||||
/// ParameterButton("Trigger") { synth.trigger() }
|
||||
///
|
||||
/// // Toggle bound to a UIParamNode
|
||||
/// ParameterButton("Mute", node: synth.$muted, style: .toggle)
|
||||
/// ```
|
||||
public struct ParameterButton: View {
|
||||
|
||||
// MARK: - Style
|
||||
|
||||
public enum Style {
|
||||
/// Executes the action closure on each press.
|
||||
case momentary
|
||||
/// Flips the node between `offValue` (0) and `onValue` (1) on each press.
|
||||
case toggle
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let label: String
|
||||
private let node: UIParamNode?
|
||||
private let style: Style
|
||||
private let action: (() -> Void)?
|
||||
|
||||
/// Value representing the "off" state for `.toggle` style (default 0).
|
||||
public var offValue: Double = 0.0
|
||||
/// Value representing the "on" state for `.toggle` style (default 1).
|
||||
public var onValue: Double = 1.0
|
||||
|
||||
// MARK: - Inits
|
||||
|
||||
/// Creates a momentary button that runs `action` on press.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Button text.
|
||||
/// - action: Closure called each time the button is pressed.
|
||||
public init(
|
||||
_ label: String,
|
||||
action: @escaping (
|
||||
) -> Void) {
|
||||
self.label = label
|
||||
self.node = nil
|
||||
self.style = .momentary
|
||||
self.action = action
|
||||
}
|
||||
|
||||
/// Creates a toggle button bound to a `UIParamNode`.
|
||||
///
|
||||
/// The node's value is interpreted as a boolean: any value ≥ 0.5 is "on".
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Button text.
|
||||
/// - node: The `UIParamNode` to toggle (pass `synth.$paramName`).
|
||||
/// - style: Must be `.toggle`; `.momentary` is handled by the other initializer.
|
||||
public init(
|
||||
_ label: String,
|
||||
node: UIParamNode,
|
||||
style: Style = .toggle
|
||||
) {
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.style = style
|
||||
self.action = nil
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
switch style {
|
||||
case .momentary:
|
||||
Button(label) { action?() }
|
||||
.buttonStyle(.bordered)
|
||||
|
||||
case .toggle:
|
||||
let isOn: Bool = (node?.value ?? 0) >= 0.5
|
||||
Button(action: {
|
||||
node?.update(isOn ? offValue : onValue)
|
||||
}) {
|
||||
Text(label)
|
||||
.frame(minWidth: 60)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.background(isOn ? Color.accentColor.opacity(0.3) : Color.clear)
|
||||
.cornerRadius(6)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// ParameterFormatting.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Threshold above which a value renders with zero fractional digits.
|
||||
internal let parameterFormatLargeMagnitudeThreshold: Double = 1000
|
||||
|
||||
/// Threshold above which a value renders with one fractional digit.
|
||||
internal let parameterFormatMediumMagnitudeThreshold: Double = 10
|
||||
|
||||
/// Render a numeric parameter value with magnitude-adaptive precision.
|
||||
///
|
||||
/// - `|v| >= 1000`: no decimals.
|
||||
/// - `1000 > |v| >= 10`: one decimal.
|
||||
/// - `|v| < 10`: three decimals.
|
||||
///
|
||||
/// Shared by `ParameterKnob` and `ParameterXY` so the two controls agree on
|
||||
/// display formatting.
|
||||
internal func formattedParameterValue(_ v: Double) -> String {
|
||||
if abs(v) >= parameterFormatLargeMagnitudeThreshold { return String(format: "%.0f", v) }
|
||||
if abs(v) >= parameterFormatMediumMagnitudeThreshold { return String(format: "%.1f", v) }
|
||||
return String(format: "%.3f", v)
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// ParameterKnob.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A rotary knob control bound to a `UIParamNode`.
|
||||
///
|
||||
/// Drag vertically to change value: drag up increases, drag down decreases.
|
||||
/// Equivalent in behaviour to `ParameterSlider` — choose whichever fits the layout.
|
||||
///
|
||||
/// ```swift
|
||||
/// ParameterKnob("Resonance", node: synth.$resonance, range: 0...1)
|
||||
/// ```
|
||||
public struct ParameterKnob: View {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let label: String
|
||||
private let node: UIParamNode
|
||||
private let range: ClosedRange<Double>
|
||||
|
||||
/// Pixels of vertical drag that span the full parameter range. Default 200.
|
||||
public var dragSensitivity: CGFloat = 200
|
||||
|
||||
// MARK: - Private drag state
|
||||
|
||||
@State private var dragStartPosition: CGFloat = 0
|
||||
@State private var dragStartValue: Double = 0
|
||||
@State private var dragInProgress: Bool = false
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a knob bound to a `UIParamNode`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Text displayed below the knob.
|
||||
/// - node: The `UIParamNode` to bind to (pass `synth.$paramName`).
|
||||
/// - range: The minimum and maximum parameter values.
|
||||
public init(
|
||||
_ label: String,
|
||||
node: UIParamNode,
|
||||
range: ClosedRange<Double>
|
||||
) {
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.range = range
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: 4) {
|
||||
knobDial
|
||||
.frame(width: 50, height: 50) // matches dialSize constant inside knobDial
|
||||
.gesture(dragGesture)
|
||||
Text(label)
|
||||
.font(.caption)
|
||||
Text(formattedValue)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Knob dial drawing
|
||||
|
||||
private var knobDial: some View {
|
||||
let normalised: Double = normalise(node.value)
|
||||
// Rotation: -135° (fully CCW) to +135° (fully CW)
|
||||
let startAngle: Double = -135.0
|
||||
let totalArc: Double = 270.0
|
||||
let rotation: Double = startAngle + normalised * totalArc
|
||||
|
||||
// Layout constants
|
||||
let dialSize: CGFloat = 50
|
||||
let indicatorWidth: CGFloat = 2
|
||||
let indicatorHeight: CGFloat = 14
|
||||
// Centre the indicator tip near the dial edge: dial radius − indicator height/2 − small inset
|
||||
let indicatorInset: CGFloat = 3
|
||||
let indicatorOffset: CGFloat = -(dialSize / 2 - indicatorHeight / 2 - indicatorInset)
|
||||
|
||||
return ZStack {
|
||||
Circle()
|
||||
.fill(Color.lyrebirdControlBackground)
|
||||
.overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
|
||||
// Indicator line
|
||||
Rectangle()
|
||||
.fill(Color.accentColor)
|
||||
.frame(width: indicatorWidth, height: indicatorHeight)
|
||||
.offset(y: indicatorOffset)
|
||||
.rotationEffect(.degrees(rotation))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Drag gesture
|
||||
|
||||
private var dragGesture: some Gesture {
|
||||
DragGesture(minimumDistance: 1)
|
||||
.onChanged { gesture in
|
||||
if !dragInProgress {
|
||||
// Capture drag origin on the first event. Using an explicit
|
||||
// flag avoids a sentinel collision when the bound value is
|
||||
// genuinely zero.
|
||||
dragInProgress = true
|
||||
dragStartPosition = gesture.location.y
|
||||
dragStartValue = node.value
|
||||
}
|
||||
let delta: CGFloat = dragStartPosition - gesture.location.y // up = positive
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let change: Double = Double(delta / dragSensitivity) * span
|
||||
let clamped: Double = min(max(dragStartValue + change, range.lowerBound), range.upperBound)
|
||||
node.update(clamped)
|
||||
}
|
||||
.onEnded { _ in
|
||||
dragInProgress = false
|
||||
dragStartPosition = 0
|
||||
dragStartValue = 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func normalise(_ value: Double) -> Double {
|
||||
let lo: Double = range.lowerBound
|
||||
let hi: Double = range.upperBound
|
||||
guard hi > lo else { return 0 }
|
||||
return min(max((value - lo) / (hi - lo), 0), 1)
|
||||
}
|
||||
|
||||
private var formattedValue: String {
|
||||
formattedParameterValue(node.value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// ParameterLabel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A read-only display label that shows the current value of a `UIParamNode`.
|
||||
///
|
||||
/// Updates automatically via `@Observable` on the backing node — no polling.
|
||||
///
|
||||
/// ```swift
|
||||
/// ParameterLabel("Level", node: synth.$amplitude)
|
||||
/// ParameterLabel("Freq (Hz)", node: synth.$frequency, decimalPlaces: 1)
|
||||
/// ```
|
||||
public struct ParameterLabel: View {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let label: String
|
||||
private let node: UIParamNode
|
||||
private let decimalPlaces: Int
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a read-only parameter label.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Descriptive text displayed before the value.
|
||||
/// - node: The `UIParamNode` to monitor (pass `synth.$paramName`).
|
||||
/// - decimalPlaces: Number of decimal places shown. Default 3.
|
||||
public init(
|
||||
_ label: String,
|
||||
node: UIParamNode,
|
||||
decimalPlaces: Int = 3
|
||||
) {
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.decimalPlaces = decimalPlaces
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
HStack {
|
||||
Text(label)
|
||||
.frame(minWidth: 80, alignment: .leading)
|
||||
Text(formattedValue)
|
||||
.monospacedDigit()
|
||||
.frame(minWidth: 60, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Formatting
|
||||
|
||||
private var formattedValue: String {
|
||||
String(format: "%.\(decimalPlaces)f", node.value)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// ParameterSlider.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A labelled continuous slider bound to a `UIParamNode`.
|
||||
///
|
||||
/// Changes flow through the node's atomic update path — RT-safe with no special handling.
|
||||
///
|
||||
/// ```swift
|
||||
/// ParameterSlider("Amplitude", node: synth.$amplitude, range: 0.0...1.0)
|
||||
/// ParameterSlider("Cutoff", node: synth.$cutoff, range: 20.0...20000.0, taper: .exponential)
|
||||
/// ```
|
||||
public struct ParameterSlider: View {
|
||||
|
||||
// MARK: - Taper
|
||||
|
||||
/// Value mapping applied between the slider's linear position and the parameter value.
|
||||
public enum Taper {
|
||||
/// No mapping — slider position maps directly to parameter value.
|
||||
case linear
|
||||
/// Exponential mapping — equal visual steps produce equal ratios (good for frequency, time).
|
||||
case exponential
|
||||
}
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let label: String
|
||||
private let node: UIParamNode
|
||||
private let range: ClosedRange<Double>
|
||||
private let taper: Taper
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a slider bound to a `UIParamNode`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - label: Text displayed beside the slider.
|
||||
/// - node: The `UIParamNode` to bind to (pass `synth.$paramName`).
|
||||
/// - range: The minimum and maximum parameter values.
|
||||
/// - taper: Value mapping. Default `.linear`.
|
||||
public init(
|
||||
_ label: String,
|
||||
node: UIParamNode,
|
||||
range: ClosedRange<Double>,
|
||||
taper: Taper = .linear
|
||||
) {
|
||||
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.range = range
|
||||
self.taper = taper
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
HStack {
|
||||
Text(label)
|
||||
.frame(minWidth: 80, alignment: .leading)
|
||||
Slider(value: binding, in: linearRange) { _ in }
|
||||
Text(formattedValue)
|
||||
.frame(minWidth: 60, alignment: .trailing)
|
||||
.monospacedDigit()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
/// Linear range always 0...1; taper mapping happens inside the Binding.
|
||||
private var linearRange: ClosedRange<Double> { 0.0...1.0 }
|
||||
|
||||
private var binding: Binding<Double> {
|
||||
Binding(
|
||||
get: { toLinear(node.value) },
|
||||
set: { node.update(fromLinear($0)) }
|
||||
)
|
||||
}
|
||||
|
||||
private func toLinear(_ value: Double) -> Double {
|
||||
let lo: Double = range.lowerBound
|
||||
let hi: Double = range.upperBound
|
||||
switch taper {
|
||||
case .linear:
|
||||
return (value - lo) / (hi - lo)
|
||||
case .exponential:
|
||||
guard lo > 0, hi > lo else { return (value - lo) / (hi - lo) }
|
||||
return log(value / lo) / log(hi / lo)
|
||||
}
|
||||
}
|
||||
|
||||
private func fromLinear(_ position: Double) -> Double {
|
||||
let lo: Double = range.lowerBound
|
||||
let hi: Double = range.upperBound
|
||||
switch taper {
|
||||
case .linear:
|
||||
return lo + position * (hi - lo)
|
||||
case .exponential:
|
||||
guard lo > 0, hi > lo else { return lo + position * (hi - lo) }
|
||||
return lo * pow(hi / lo, position)
|
||||
}
|
||||
}
|
||||
|
||||
private var formattedValue: String {
|
||||
let v: Double = node.value
|
||||
if abs(v) >= 1000 {
|
||||
return String(format: "%.0f", v)
|
||||
} else if abs(v) >= 10 {
|
||||
return String(format: "%.1f", v)
|
||||
} else {
|
||||
return String(format: "%.3f", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// ParameterXY.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A two-dimensional control pad that simultaneously controls two `UIParamNode` values.
|
||||
///
|
||||
/// Drag within the pad to set X and Y parameter values independently.
|
||||
/// X increases left-to-right; Y increases bottom-to-top.
|
||||
///
|
||||
/// ```swift
|
||||
/// ParameterXY(
|
||||
/// xLabel: "Pan", xNode: synth.$pan, xRange: -1...1,
|
||||
/// yLabel: "Amplitude", yNode: synth.$amplitude, yRange: 0...1
|
||||
/// )
|
||||
/// ```
|
||||
public struct ParameterXY: View {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let xLabel: String
|
||||
private let xNode: UIParamNode
|
||||
private let xRange: ClosedRange<Double>
|
||||
|
||||
private let yLabel: String
|
||||
private let yNode: UIParamNode
|
||||
private let yRange: ClosedRange<Double>
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an XY pad bound to two `UIParamNode` values.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - xLabel: Label for the X axis.
|
||||
/// - xNode: The `UIParamNode` controlled by horizontal position.
|
||||
/// - xRange: Value range for the X axis.
|
||||
/// - yLabel: Label for the Y axis.
|
||||
/// - yNode: The `UIParamNode` controlled by vertical position.
|
||||
/// - yRange: Value range for the Y axis.
|
||||
public init(
|
||||
xLabel: String,
|
||||
xNode: UIParamNode,
|
||||
xRange: ClosedRange<Double>,
|
||||
yLabel: String,
|
||||
yNode: UIParamNode,
|
||||
yRange: ClosedRange<Double>
|
||||
) {
|
||||
|
||||
self.xLabel = xLabel
|
||||
self.xNode = xNode
|
||||
self.xRange = xRange
|
||||
self.yLabel = yLabel
|
||||
self.yNode = yNode
|
||||
self.yRange = yRange
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: 4) {
|
||||
GeometryReader { geometry in
|
||||
ZStack {
|
||||
// Background
|
||||
RoundedRectangle(cornerRadius: 6)
|
||||
.fill(Color.lyrebirdControlBackground)
|
||||
.overlay(
|
||||
RoundedRectangle(cornerRadius: 6)
|
||||
.stroke(Color.lyrebirdSeparator, lineWidth: 1)
|
||||
)
|
||||
// Grid lines
|
||||
gridLines
|
||||
// Cursor
|
||||
cursor(in: geometry.size)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.gesture(dragGesture(in: geometry.size))
|
||||
}
|
||||
// Axis labels
|
||||
HStack {
|
||||
Text(yLabel)
|
||||
.font(.caption)
|
||||
Spacer()
|
||||
Text(xLabel)
|
||||
.font(.caption)
|
||||
}
|
||||
HStack {
|
||||
Text(formattedValue(yNode.value))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
Spacer()
|
||||
Text(formattedValue(xNode.value))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cursor
|
||||
|
||||
private func cursor(in size: CGSize) -> some View {
|
||||
let nx: Double = normalise(xNode.value, range: xRange)
|
||||
let ny: Double = 1.0 - normalise(yNode.value, range: yRange) // flip: bottom = 0
|
||||
let cx: Double = nx * size.width
|
||||
let cy: Double = ny * size.height
|
||||
return Circle()
|
||||
.fill(Color.accentColor)
|
||||
.frame(width: 12, height: 12)
|
||||
.position(x: cx, y: cy)
|
||||
}
|
||||
|
||||
// MARK: - Grid
|
||||
|
||||
private var gridLines: some View {
|
||||
Canvas { context, size in
|
||||
let midX: CGFloat = size.width / 2
|
||||
let midY: CGFloat = size.height / 2
|
||||
var path: Path = Path()
|
||||
path.move(to: CGPoint(x: midX, y: 0))
|
||||
path.addLine(to: CGPoint(x: midX, y: size.height))
|
||||
path.move(to: CGPoint(x: 0, y: midY))
|
||||
path.addLine(to: CGPoint(x: size.width, y: midY))
|
||||
context.stroke(path, with: .color(Color.lyrebirdSeparator.opacity(0.4)),
|
||||
lineWidth: 0.5)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Drag
|
||||
|
||||
private func dragGesture(in size: CGSize) -> some Gesture {
|
||||
DragGesture(minimumDistance: 0)
|
||||
.onChanged { gesture in
|
||||
let nx: CGFloat = min(max(gesture.location.x / size.width, 0), 1)
|
||||
let ny: CGFloat = min(max(gesture.location.y / size.height, 0), 1)
|
||||
xNode.update(denormalise(nx, range: xRange))
|
||||
yNode.update(denormalise(1.0 - ny, range: yRange)) // flip Y
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func normalise(
|
||||
_ value: Double,
|
||||
range: ClosedRange<Double>
|
||||
) -> Double {
|
||||
let lo: Double = range.lowerBound
|
||||
let hi: Double = range.upperBound
|
||||
guard hi > lo else { return 0 }
|
||||
return min(max((value - lo) / (hi - lo), 0), 1)
|
||||
}
|
||||
|
||||
private func denormalise(
|
||||
_ position: Double,
|
||||
range: ClosedRange<Double>
|
||||
) -> Double {
|
||||
range.lowerBound + position * (range.upperBound - range.lowerBound)
|
||||
}
|
||||
|
||||
private func formattedValue(_ v: Double) -> String {
|
||||
formattedParameterValue(v)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// PlatformColors.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
#else
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
extension Color {
|
||||
#if os(macOS)
|
||||
public static let lyrebirdControlBackground: Color = Color(NSColor.controlBackgroundColor)
|
||||
public static let lyrebirdSeparator: Color = Color(NSColor.separatorColor)
|
||||
#else
|
||||
public static let lyrebirdControlBackground = Color(UIColor.secondarySystemBackground)
|
||||
public static let lyrebirdSeparator = Color(UIColor.separator)
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// DbSliderConversion.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared dB ↔ linear-amplitude helpers for amplitude sliders.
|
||||
///
|
||||
/// Both `LyrebirdEventListView` and `LyrebirdProcessView` use a `-90 … +12` dB slider that
|
||||
/// writes a linear amplitude back to the underlying engine value. The conversion logic is
|
||||
/// identical between the two views; this enum centralises it so changes only need one edit.
|
||||
internal enum DbSliderConversion {
|
||||
|
||||
/// Slider floor — at this value the source is treated as silenced.
|
||||
static let minDb: Double = -90.0
|
||||
|
||||
/// Default slider ceiling — `dbToAmp(12) ≈ 3.98×`. Per-process views may
|
||||
/// override via ``LyrebirdProcess/maxUIAmpDb`` when more headroom is needed.
|
||||
static let maxDb: Double = 12.0
|
||||
|
||||
/// Convert the slider's dB position to the linear amplitude written to the engine value.
|
||||
/// Floors at `minDb` (silence).
|
||||
static func ampFromDb(_ db: Double) -> Double {
|
||||
if db <= minDb { return 0.0 }
|
||||
return dbToAmp(db)
|
||||
}
|
||||
|
||||
/// Inverse — used to seed the slider position from a linear amplitude. Treats
|
||||
/// `amp == 0` (or anything below `minDb`'s amplitude) as the slider floor so the
|
||||
/// knob does not jump to `-inf`. Caller passes the active slider ceiling so
|
||||
/// per-process maxima above `+12` dB are respected.
|
||||
static func dbFromAmp(_ amp: Double, maxDb: Double = DbSliderConversion.maxDb) -> Double {
|
||||
guard amp > 0 else { return minDb }
|
||||
let db: Double = ampToDb(amp)
|
||||
return max(minDb, min(maxDb, db))
|
||||
}
|
||||
|
||||
/// Render the current dB value. Shows `-inf` at the slider floor so users see
|
||||
/// immediately that the source is silenced rather than `−90.0 dB`.
|
||||
static func dbDisplay(_ db: Double) -> String {
|
||||
if db <= minDb { return "-inf dB" }
|
||||
return String(format: "%+.1f dB", db)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
// LyrebirdEngineStatusView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A status panel showing the live state of a `SynthesisEngine`.
|
||||
///
|
||||
/// Displays:
|
||||
/// - Running state (idle / running) with a coloured indicator dot.
|
||||
/// - A start / stop button that toggles the engine.
|
||||
/// - The current synthesizer and group counts (from `engine.synthesizerCount` /
|
||||
/// `engine.groupCount`).
|
||||
/// - Average and peak CPU usage as percentages of one block, mirroring
|
||||
/// `LyrebirdStatusView`.
|
||||
/// - Pre-run configuration controls — sample rate picker, output- and input-channel
|
||||
/// steppers. Editable only while the engine is stopped; greyed out and disabled
|
||||
/// once `engine.start()` succeeds.
|
||||
/// - Master output volume slider (dB-tapered, `-90`…`+12 dB`) paired with a text
|
||||
/// field accepting the same range — the two controls share state and update each
|
||||
/// other so the user can type `0` to snap back to unity. UI clips entered values
|
||||
/// to the bounded range. The underlying `engine.masterGain` API accepts any
|
||||
/// finite scalar — programmatic callers can step outside the UI bounds when
|
||||
/// needed. A mute toggle drives `engine.isMuted`. Changes are click-free —
|
||||
/// the engine ramps gain across one block on each update.
|
||||
///
|
||||
/// All values are polled at 10 Hz (`pollIntervalNs`).
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdEngineStatusView(engine: engine)
|
||||
/// .padding()
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, when no parent view is provided the convenience initializer
|
||||
/// `presentInWindow(engine:title:width:height:)` opens a standalone
|
||||
/// `LyrebirdWindow` hosting the view:
|
||||
///
|
||||
/// ```swift
|
||||
/// let win = LyrebirdEngineStatusView.presentInWindow(engine: engine)
|
||||
/// // … later …
|
||||
/// win.close()
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// The view body runs on the main thread. `engine.start()` / `engine.stop()` are
|
||||
/// invoked from the SwiftUI button action; both are main-thread-safe per
|
||||
/// `SynthesisEngine`'s public contract.
|
||||
public struct LyrebirdEngineStatusView: View {
|
||||
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var isRunning: Bool = false
|
||||
@State private var synthesizerCount: Int = 0
|
||||
@State private var groupCount: Int = 0
|
||||
@State private var averageCPU: Double = 0.0
|
||||
@State private var peakCPU: Double = 0.0
|
||||
@State private var lastStartError: String?
|
||||
|
||||
@State private var sampleRate: Double = 48000
|
||||
@State private var numOutputChannels: Int = 2
|
||||
@State private var numInputChannels: Int = 0
|
||||
@State private var masterGainDb: Double = 0.0
|
||||
@State private var masterGainDbText: String = "+0.0"
|
||||
@FocusState private var gainTextFocused: Bool
|
||||
@State private var isMuted: Bool = false
|
||||
@State private var lastConfigError: String?
|
||||
|
||||
@State private var isMessagesExpanded: Bool = false
|
||||
@State private var isNodeTreeExpanded: Bool = false
|
||||
#if os(macOS)
|
||||
@State private var messageWindow: LyrebirdWindow?
|
||||
@State private var nodeTreeWindow: LyrebirdWindow?
|
||||
#endif
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 100_000_000
|
||||
|
||||
private static let sampleRateOptions: [Double] = [
|
||||
44100, 48000, 88200, 96000, 176400, 192000
|
||||
]
|
||||
private static let outputChannelRange: ClosedRange<Int> = 1...32
|
||||
private static let inputChannelRange: ClosedRange<Int> = 0...32
|
||||
private static let gainDbRange: ClosedRange<Double> = -90.0...12.0
|
||||
/// Persistent groups always present in the engine: rootGroup + mainGroup.
|
||||
/// Surfaced in the displayed Groups count so the user sees the persistent
|
||||
/// baseline (e.g. 2 after a `LyrebirdEventList.killAll()` rather than 0).
|
||||
private static let persistentGroupCount: Int = 2
|
||||
|
||||
/// Creates a status view bound to the given engine.
|
||||
///
|
||||
/// - Parameter engine: The `SynthesisEngine` instance to monitor.
|
||||
public init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
// Seed @State from the engine's live values so the first frame matches
|
||||
// the engine instead of generic defaults. Without this the Picker would
|
||||
// render blank when the engine's sample rate differs from the
|
||||
// hard-coded default, and the volume display would briefly read +0.0
|
||||
// when the caller had set a different master gain before mounting.
|
||||
_sampleRate = State(initialValue: engine.sampleRate)
|
||||
_numOutputChannels = State(initialValue: engine.numOutputChannels)
|
||||
_numInputChannels = State(initialValue: engine.numInputChannels)
|
||||
_isRunning = State(initialValue: engine.isRunning)
|
||||
_isMuted = State(initialValue: engine.isMuted)
|
||||
let initialDb: Double = LyrebirdEngineStatusView.linearToDb(engine.masterGain)
|
||||
_masterGainDb = State(initialValue: initialDb)
|
||||
_masterGainDbText = State(initialValue: String(format: "%+.1f", initialDb))
|
||||
}
|
||||
|
||||
/// Linear amplitude → dB, with a finite floor at the slider's lower bound so
|
||||
/// `masterGain == 0` (or near-zero) doesn't produce `-inf` in the text field.
|
||||
private static func linearToDb(_ linear: Double) -> Double {
|
||||
guard linear > 0, linear.isFinite else { return gainDbRange.lowerBound }
|
||||
let db: Double = 20.0 * log10(linear)
|
||||
return min(max(db, gainDbRange.lowerBound), gainDbRange.upperBound)
|
||||
}
|
||||
|
||||
/// Picker rates = standard list plus the current `sampleRate` if it isn't
|
||||
/// already represented. Keeps the menu sorted ascending so an odd
|
||||
/// device-reported rate (e.g. 22050) slots in next to the closest standard.
|
||||
private var sampleRatePickerOptions: [Double] {
|
||||
var rates: [Double] = LyrebirdEngineStatusView.sampleRateOptions
|
||||
if !rates.contains(sampleRate) {
|
||||
rates.append(sampleRate)
|
||||
rates.sort()
|
||||
}
|
||||
return rates
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(isRunning ? Color.green : Color.secondary.opacity(0.4))
|
||||
.frame(width: 10, height: 10)
|
||||
Text(isRunning ? "Running" : "Stopped")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Button(isRunning ? "Stop" : "Start") {
|
||||
toggleEngine()
|
||||
}
|
||||
}
|
||||
|
||||
if let err: String = lastStartError {
|
||||
Text(err)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
HStack(spacing: 16) {
|
||||
CountTile(label: "Synths", value: synthesizerCount)
|
||||
CountTile(
|
||||
label: "Groups",
|
||||
value: groupCount + LyrebirdEngineStatusView.persistentGroupCount,
|
||||
subtitle: "incl. rootGroup, mainGroup"
|
||||
)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
CPURow(label: "CPU Avg", value: averageCPU)
|
||||
CPURow(label: "CPU Peak", value: peakCPU)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
nodeTreeSection
|
||||
|
||||
Divider()
|
||||
|
||||
messagesSection
|
||||
|
||||
Divider()
|
||||
|
||||
configurationSection
|
||||
|
||||
Divider()
|
||||
|
||||
outputSection
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 260)
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
refresh()
|
||||
try? await Task.sleep(nanoseconds: LyrebirdEngineStatusView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var configurationSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Configuration")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
HStack {
|
||||
Text("Sample Rate")
|
||||
.frame(width: 110, alignment: .leading)
|
||||
Picker("", selection: $sampleRate) {
|
||||
ForEach(sampleRatePickerOptions, id: \.self) { rate in
|
||||
Text("\(Int(rate)) Hz").tag(rate)
|
||||
}
|
||||
}
|
||||
.labelsHidden()
|
||||
.pickerStyle(.menu)
|
||||
}
|
||||
|
||||
Stepper(
|
||||
"Output Channels: \(numOutputChannels)",
|
||||
value: $numOutputChannels,
|
||||
in: LyrebirdEngineStatusView.outputChannelRange
|
||||
)
|
||||
|
||||
Stepper(
|
||||
"Input Channels: \(numInputChannels)",
|
||||
value: $numInputChannels,
|
||||
in: LyrebirdEngineStatusView.inputChannelRange
|
||||
)
|
||||
|
||||
if let err: String = lastConfigError {
|
||||
Text(err)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
}
|
||||
.disabled(isRunning)
|
||||
.opacity(isRunning ? 0.5 : 1.0)
|
||||
.onChange(of: sampleRate) { _, newValue in
|
||||
pushConfigToEngine { try engine.setSampleRate(newValue) }
|
||||
}
|
||||
.onChange(of: numOutputChannels) { _, newValue in
|
||||
pushConfigToEngine { try engine.setNumOutputChannels(newValue) }
|
||||
}
|
||||
.onChange(of: numInputChannels) { _, newValue in
|
||||
pushConfigToEngine { try engine.setNumInputChannels(newValue) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap a setter call so `.onChange` handlers fired while the engine is
|
||||
/// running — e.g. the mirror assignment in `refresh()` triggered by an
|
||||
/// external engine state change — don't bubble a spurious
|
||||
/// `engineIsRunning` error into the UI. The user can never edit the
|
||||
/// controls while running (`.disabled(isRunning)`), so the only path
|
||||
/// through `.onChange` during a run is the mirror.
|
||||
private func pushConfigToEngine(_ apply: () throws -> Void) {
|
||||
guard !isRunning else { return }
|
||||
applyConfig(apply)
|
||||
}
|
||||
|
||||
private var outputSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Output")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Toggle("Mute", isOn: $isMuted)
|
||||
.onChange(of: isMuted) { _, newValue in
|
||||
engine.isMuted = newValue
|
||||
}
|
||||
|
||||
HStack(spacing: 8) {
|
||||
Text("Volume")
|
||||
.frame(width: 60, alignment: .leading)
|
||||
Slider(value: $masterGainDb, in: LyrebirdEngineStatusView.gainDbRange)
|
||||
.onChange(of: masterGainDb) { _, db in
|
||||
engine.masterGain = pow(10.0, db / 20.0)
|
||||
if !gainTextFocused {
|
||||
masterGainDbText = String(format: "%+.1f", db)
|
||||
}
|
||||
}
|
||||
TextField("dB", text: $masterGainDbText)
|
||||
.font(.caption.monospaced())
|
||||
.monospacedDigit()
|
||||
.multilineTextAlignment(.trailing)
|
||||
.focused($gainTextFocused)
|
||||
.frame(width: 70)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit(commitMasterGainText)
|
||||
.onChange(of: gainTextFocused) { _, focused in
|
||||
if !focused { commitMasterGainText() }
|
||||
}
|
||||
Text("dB")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func commitMasterGainText() {
|
||||
var trimmed: String = masterGainDbText.trimmingCharacters(in: .whitespaces)
|
||||
// Strip only a leading `+` — `replacingOccurrences` would also remove the
|
||||
// `+` inside scientific notation like `1e+2`.
|
||||
if trimmed.first == "+" { trimmed.removeFirst() }
|
||||
if let parsed: Double = Double(trimmed) {
|
||||
let range: ClosedRange<Double> = LyrebirdEngineStatusView.gainDbRange
|
||||
let clamped: Double = min(max(parsed, range.lowerBound), range.upperBound)
|
||||
masterGainDb = clamped // triggers slider .onChange → engine update
|
||||
masterGainDbText = String(format: "%+.1f", clamped)
|
||||
} else {
|
||||
// Bad input — revert text to the current model value.
|
||||
masterGainDbText = String(format: "%+.1f", masterGainDb)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyConfig(_ apply: () throws -> Void) {
|
||||
do {
|
||||
try apply()
|
||||
lastConfigError = nil
|
||||
} catch {
|
||||
lastConfigError = "Config: \(error)"
|
||||
}
|
||||
}
|
||||
|
||||
private var nodeTreeSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
isNodeTreeExpanded.toggle()
|
||||
} label: {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: isNodeTreeExpanded ? "chevron.down" : "chevron.right")
|
||||
.font(.caption2)
|
||||
Text("Node Tree")
|
||||
.font(.caption.monospaced())
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
Spacer()
|
||||
#if os(macOS)
|
||||
Button("Open Window") {
|
||||
openNodeTreeWindow()
|
||||
}
|
||||
.font(.caption)
|
||||
#endif
|
||||
}
|
||||
|
||||
// Persistent-groups strip — always visible (even when the full
|
||||
// tree view is collapsed) so the user can see at a glance that
|
||||
// `rootGroup` and `mainGroup` are alive.
|
||||
persistentGroupsStrip
|
||||
|
||||
if isNodeTreeExpanded {
|
||||
LyrebirdNodeTreeView(mirror: engine.nodeTreeMirror)
|
||||
.frame(minHeight: 180, maxHeight: 300)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Always-visible row showing the persistent groups (`rootGroup` /
|
||||
/// `mainGroup`) and their child counts from the live snapshot. Renders
|
||||
/// whether the Node Tree section is expanded or collapsed.
|
||||
private var persistentGroupsStrip: some View {
|
||||
let snap: NodeTreeSnapshot = engine.nodeTreeMirror.snapshot
|
||||
let root: NodeTreeSnapshot.Node = snap.root
|
||||
let mainNode: NodeTreeSnapshot.Node? = root.children.first
|
||||
let mainChildCount: Int = mainNode?.children.count ?? 0
|
||||
return HStack(spacing: 6) {
|
||||
Image(systemName: "chevron.down")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
Text("rootGroup")
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
Text("(\(root.children.count))")
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.tertiary)
|
||||
Text("▸")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
Text("mainGroup")
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
Text("(\(mainChildCount))")
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.tertiary)
|
||||
Spacer()
|
||||
}
|
||||
.padding(.leading, 6)
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
private func openNodeTreeWindow() {
|
||||
if let existing: LyrebirdWindow = nodeTreeWindow {
|
||||
existing.close()
|
||||
nodeTreeWindow = nil
|
||||
}
|
||||
nodeTreeWindow = LyrebirdNodeTreeView.presentInWindow(engine: engine)
|
||||
}
|
||||
#endif
|
||||
|
||||
private var messagesSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
isMessagesExpanded.toggle()
|
||||
} label: {
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: isMessagesExpanded ? "chevron.down" : "chevron.right")
|
||||
.font(.caption2)
|
||||
Text("Messages")
|
||||
.font(.caption.monospaced())
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
Spacer()
|
||||
#if os(macOS)
|
||||
Button("Open Window") {
|
||||
openMessageWindow()
|
||||
}
|
||||
.font(.caption)
|
||||
#endif
|
||||
}
|
||||
|
||||
if isMessagesExpanded {
|
||||
LyrebirdMessageView()
|
||||
.frame(minHeight: 160, maxHeight: 260)
|
||||
} else {
|
||||
LyrebirdMessageBanner(onOpenFull: {
|
||||
isMessagesExpanded = true
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
private func openMessageWindow() {
|
||||
if let existing: LyrebirdWindow = messageWindow {
|
||||
existing.close()
|
||||
messageWindow = nil
|
||||
}
|
||||
messageWindow = LyrebirdMessageView.presentInWindow()
|
||||
}
|
||||
#endif
|
||||
|
||||
private func refresh() {
|
||||
isRunning = engine.isRunning
|
||||
synthesizerCount = engine.synthesizerCount
|
||||
groupCount = engine.groupCount
|
||||
averageCPU = engine.averageCPU
|
||||
peakCPU = engine.peakCPU
|
||||
|
||||
// Mirror engine-side config into UI state. SwiftUI only fires `.onChange`
|
||||
// on a real value change, so the engine-as-source-of-truth assignments
|
||||
// converge after one tick without an infinite onChange loop.
|
||||
if sampleRate != engine.sampleRate {
|
||||
sampleRate = engine.sampleRate
|
||||
}
|
||||
if numOutputChannels != engine.numOutputChannels {
|
||||
numOutputChannels = engine.numOutputChannels
|
||||
}
|
||||
if numInputChannels != engine.numInputChannels {
|
||||
numInputChannels = engine.numInputChannels
|
||||
}
|
||||
}
|
||||
|
||||
private func toggleEngine() {
|
||||
if engine.isRunning {
|
||||
engine.stop()
|
||||
lastStartError = nil
|
||||
} else {
|
||||
do {
|
||||
try engine.start()
|
||||
lastStartError = nil
|
||||
} catch {
|
||||
lastStartError = "Start failed: \(error)"
|
||||
}
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-views
|
||||
|
||||
private struct CountTile: View {
|
||||
let label: String
|
||||
let value: Int
|
||||
let subtitle: String?
|
||||
|
||||
init(
|
||||
label: String,
|
||||
value: Int,
|
||||
subtitle: String? = nil
|
||||
) {
|
||||
self.label = label
|
||||
self.value = value
|
||||
self.subtitle = subtitle
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(label)
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
Text("\(value)")
|
||||
.font(.title3.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
if let sub: String = subtitle {
|
||||
Text(sub)
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.tertiary)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct CPURow: View {
|
||||
let label: String
|
||||
let value: Double
|
||||
|
||||
private static let maxDisplayPercent: Double = 999.9
|
||||
private static let warningThreshold: Double = 0.5
|
||||
private static let criticalThreshold: Double = 0.8
|
||||
|
||||
private var displayPercent: Double {
|
||||
min(value * 100.0, CPURow.maxDisplayPercent)
|
||||
}
|
||||
|
||||
private var barColor: Color {
|
||||
switch value {
|
||||
case ..<CPURow.warningThreshold: return .green
|
||||
case ..<CPURow.criticalThreshold: return .yellow
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(label)
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 60, alignment: .leading)
|
||||
GeometryReader { geo in
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(Color.secondary.opacity(0.15))
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(barColor)
|
||||
.frame(width: geo.size.width * min(CGFloat(value), 1.0))
|
||||
.animation(.linear(duration: 0.1), value: value)
|
||||
}
|
||||
}
|
||||
.frame(height: 6)
|
||||
Text(String(format: "%.1f%%", displayPercent))
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: 56, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdEngineStatusView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting an engine status view.
|
||||
///
|
||||
/// Use when no parent SwiftUI view is available — a script, REPL session, or
|
||||
/// command-line demo can call this to surface engine status in its own window.
|
||||
/// The returned `LyrebirdWindow` retains the AppKit window; close it with
|
||||
/// `.close()`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` to monitor.
|
||||
/// - title: Window title bar text. Defaults to `"Engine Status"`.
|
||||
/// - width: Initial window width in points. Defaults to `320`.
|
||||
/// - height: Initial window height in points. Defaults to `480`.
|
||||
/// - Returns: The `LyrebirdWindow` hosting the view. Caller retains it to keep
|
||||
/// the window alive.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
engine: SynthesisEngine,
|
||||
title: String = "Engine Status",
|
||||
width: CGFloat = 320,
|
||||
height: CGFloat = 480
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdEngineStatusView(engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,259 @@
|
||||
// LyrebirdEnvelopeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - Region
|
||||
|
||||
/// Render region for one envelope segment.
|
||||
enum _EnvelopeRegion {
|
||||
case preLoop
|
||||
case loop
|
||||
case release
|
||||
|
||||
var color: Color {
|
||||
switch self {
|
||||
case .preLoop: return .cyan
|
||||
case .loop: return .green
|
||||
case .release: return .orange
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pure helpers (internal for testability via @testable import LyrebirdUI)
|
||||
|
||||
/// Returns the render region for a single segment index given loopNode/releaseNode.
|
||||
///
|
||||
/// Loop-only semantics (loopNode set, releaseNode nil): only the segment *at* loopNode
|
||||
/// is colored `.loop`. Segments after it are the gate-off release path — they play once
|
||||
/// after gate drops and are correctly classified as `.preLoop`.
|
||||
func _regionForSegment(
|
||||
index: Int,
|
||||
loopNode: Int?,
|
||||
releaseNode: Int?,
|
||||
segmentCount: Int
|
||||
) -> _EnvelopeRegion {
|
||||
switch (loopNode, releaseNode) {
|
||||
case (let ln?, let rn?):
|
||||
if index < ln { return .preLoop }
|
||||
if index < rn { return .loop }
|
||||
return .release
|
||||
case (let ln?, nil):
|
||||
return index == ln ? .loop : .preLoop
|
||||
case (nil, let rn?):
|
||||
return index < rn ? .preLoop : .release
|
||||
case (nil, nil):
|
||||
return .preLoop
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns cumulative boundary times: `[0, d0, d0+d1, …, totalDuration]`.
|
||||
/// Length is `durations.count + 1`.
|
||||
func _segmentBoundaryTimes(durations: [Double]) -> [Double] {
|
||||
var times: [Double] = [0]
|
||||
var elapsed: Double = 0
|
||||
for d: Double in durations {
|
||||
elapsed += d
|
||||
times.append(elapsed)
|
||||
}
|
||||
return times
|
||||
}
|
||||
|
||||
/// Returns Y display bounds for `levels` with 10 % headroom on each side.
|
||||
/// Returns `(0, 1)` when `levels` is empty.
|
||||
func _envelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) {
|
||||
let minimumLevelRange: Double = 1e-6
|
||||
let headroomFactor: Double = 0.1
|
||||
guard let lo: Double = levels.min(), let hi: Double = levels.max() else { return (0, 1) }
|
||||
let range: Double = max(hi - lo, minimumLevelRange)
|
||||
let headroom: Double = range * headroomFactor
|
||||
return (lo - headroom, hi + headroom)
|
||||
}
|
||||
|
||||
// MARK: - LyrebirdEnvelopeView
|
||||
|
||||
/// A SwiftUI view that plots an `Envelope` as a color-coded shape.
|
||||
///
|
||||
/// Segments are drawn in distinct colors based on their role:
|
||||
/// - **Cyan** — normal segments before any loop or release point
|
||||
/// - **Green** — loop region `[loopNode, releaseNode)`
|
||||
/// - **Orange** — release region from `releaseNode` to the end
|
||||
///
|
||||
/// Vertical dashed markers indicate `loopNode` ("L") and `releaseNode` ("R") boundaries.
|
||||
/// Horizontal hairlines show the target level for each segment endpoint.
|
||||
///
|
||||
/// ```swift
|
||||
/// let env = Envelope(
|
||||
/// levels: [0, 1, 0.6, 0],
|
||||
/// durations: [0.01, 0.3, 0.2],
|
||||
/// curves: [.sine, .lin, .exponential],
|
||||
/// loopNode: 1,
|
||||
/// releaseNode: 2
|
||||
/// )
|
||||
/// LyrebirdEnvelopeView(env)
|
||||
/// .padding()
|
||||
/// ```
|
||||
public struct LyrebirdEnvelopeView: View {
|
||||
|
||||
private let envelope: Envelope
|
||||
private let width: CGFloat
|
||||
private let height: CGFloat
|
||||
|
||||
private static let backgroundBrightness: CGFloat = 0.08
|
||||
private static let backgroundColor: Color = Color(white: backgroundBrightness)
|
||||
/// 2 path points per canvas pixel — smooth enough for all curve shapes.
|
||||
private static let oversample: CGFloat = 2
|
||||
private static let markerOpacity: Double = 0.7
|
||||
private static let levelTickOpacity: Double = 0.2
|
||||
private static let markerDash: [CGFloat] = [4, 3]
|
||||
private static let labelFontSize: CGFloat = 9
|
||||
private static let labelFont: Font = .system(size: labelFontSize, weight: .semibold, design: .monospaced)
|
||||
private static let signalLineWidth: CGFloat = 1.5
|
||||
private static let guideLineWidth: CGFloat = 0.5
|
||||
private static let markerLineWidth: CGFloat = 1
|
||||
private static let markerLabelOffsetX: CGFloat = 4
|
||||
private static let markerLabelOffsetY: CGFloat = 6
|
||||
private static let cornerRadius: CGFloat = 4
|
||||
|
||||
public init(
|
||||
_ envelope: Envelope,
|
||||
width: CGFloat = 300,
|
||||
height: CGFloat = 120
|
||||
) {
|
||||
self.envelope = envelope
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
Canvas { ctx, size in
|
||||
_draw(ctx: ctx, size: size)
|
||||
}
|
||||
.frame(width: width, height: height)
|
||||
.background(LyrebirdEnvelopeView.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: LyrebirdEnvelopeView.cornerRadius))
|
||||
}
|
||||
|
||||
// MARK: - Drawing
|
||||
|
||||
private func _draw(
|
||||
ctx: GraphicsContext,
|
||||
size: CGSize
|
||||
) {
|
||||
let (yMin, yMax) = _envelopeYBounds(levels: envelope.levels)
|
||||
let segCount: Int = envelope.segmentCount
|
||||
|
||||
// Zero-segment or zero-duration: draw flat line at constant level.
|
||||
guard segCount > 0 && envelope.totalDuration > 0 else {
|
||||
let v: Double = envelope.levels.first ?? 0
|
||||
let y: CGFloat = _yFor(v, yMin: yMin, yMax: yMax, height: size.height)
|
||||
var path: Path = Path()
|
||||
path.move(to: CGPoint(x: 0, y: y))
|
||||
path.addLine(to: CGPoint(x: size.width, y: y))
|
||||
ctx.stroke(path, with: .color(.cyan), lineWidth: LyrebirdEnvelopeView.signalLineWidth)
|
||||
return
|
||||
}
|
||||
|
||||
let boundaryTimes: [Double] = _segmentBoundaryTimes(durations: envelope.durations)
|
||||
let totalSamples: Int = Int(ceil(size.width * LyrebirdEnvelopeView.oversample))
|
||||
|
||||
// Horizontal level hairlines
|
||||
for level: Double in envelope.levels {
|
||||
let y: CGFloat = _yFor(level, yMin: yMin, yMax: yMax, height: size.height)
|
||||
var tick: Path = Path()
|
||||
tick.move(to: CGPoint(x: 0, y: y))
|
||||
tick.addLine(to: CGPoint(x: size.width, y: y))
|
||||
ctx.stroke(tick,
|
||||
with: .color(.white.opacity(LyrebirdEnvelopeView.levelTickOpacity)),
|
||||
lineWidth: LyrebirdEnvelopeView.guideLineWidth)
|
||||
}
|
||||
|
||||
// One colored path per segment
|
||||
for seg: Int in 0..<segCount {
|
||||
let region: _EnvelopeRegion = _regionForSegment(
|
||||
index: seg,
|
||||
loopNode: envelope.loopNode,
|
||||
releaseNode: envelope.releaseNode,
|
||||
segmentCount: segCount
|
||||
)
|
||||
let tStart: Double = boundaryTimes[seg]
|
||||
let tEnd: Double = boundaryTimes[seg + 1]
|
||||
let segDur: Double = tEnd - tStart
|
||||
let frac: Double = segDur / envelope.totalDuration
|
||||
// nSamples is a step count; the loop runs 0...nSamples (nSamples+1 points),
|
||||
// so the final point lands exactly at tEnd, closing each segment cleanly.
|
||||
let nSamples: Int = max(2, Int(ceil(CGFloat(totalSamples) * CGFloat(frac))))
|
||||
|
||||
var path: Path = Path()
|
||||
for i: Int in 0...nSamples {
|
||||
let t: Double = tStart + segDur * Double(i) / Double(nSamples)
|
||||
let v: Double = envelope.valueAtTime(t)
|
||||
let x: CGFloat = _xFor(t, width: size.width)
|
||||
let y: CGFloat = _yFor(v, yMin: yMin, yMax: yMax, height: size.height)
|
||||
let pt: CGPoint = CGPoint(x: x, y: y)
|
||||
if i == 0 { path.move(to: pt) } else { path.addLine(to: pt) }
|
||||
}
|
||||
ctx.stroke(path, with: .color(region.color),
|
||||
lineWidth: LyrebirdEnvelopeView.signalLineWidth)
|
||||
}
|
||||
|
||||
// Vertical dashed markers — loopNode and releaseNode are pre-validated by Envelope.init
|
||||
// to be in [0, segmentCount), so boundaryTimes[ln/rn] is always in bounds.
|
||||
if let ln: Int = envelope.loopNode {
|
||||
_drawMarker(ctx: ctx, time: boundaryTimes[ln], label: "L",
|
||||
color: .green, size: size)
|
||||
}
|
||||
if let rn: Int = envelope.releaseNode {
|
||||
_drawMarker(ctx: ctx, time: boundaryTimes[rn], label: "R",
|
||||
color: .orange, size: size)
|
||||
}
|
||||
}
|
||||
|
||||
private func _drawMarker(
|
||||
ctx: GraphicsContext,
|
||||
time: Double,
|
||||
label: String,
|
||||
color: Color,
|
||||
size: CGSize
|
||||
) {
|
||||
let x: CGFloat = _xFor(time, width: size.width)
|
||||
var line: Path = Path()
|
||||
line.move(to: CGPoint(x: x, y: 0))
|
||||
line.addLine(to: CGPoint(x: x, y: size.height))
|
||||
ctx.stroke(line,
|
||||
with: .color(color.opacity(LyrebirdEnvelopeView.markerOpacity)),
|
||||
style: StrokeStyle(lineWidth: LyrebirdEnvelopeView.markerLineWidth,
|
||||
dash: LyrebirdEnvelopeView.markerDash))
|
||||
ctx.draw(
|
||||
Text(label)
|
||||
.font(LyrebirdEnvelopeView.labelFont)
|
||||
.foregroundStyle(color),
|
||||
at: CGPoint(x: x + LyrebirdEnvelopeView.markerLabelOffsetX,
|
||||
y: LyrebirdEnvelopeView.markerLabelOffsetY),
|
||||
anchor: .leading
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Coordinate helpers
|
||||
|
||||
private func _xFor(
|
||||
_ t: Double,
|
||||
width: CGFloat
|
||||
) -> CGFloat {
|
||||
CGFloat(t / envelope.totalDuration) * width
|
||||
}
|
||||
|
||||
private func _yFor(
|
||||
_ v: Double,
|
||||
yMin: Double,
|
||||
yMax: Double,
|
||||
height: CGFloat
|
||||
) -> CGFloat {
|
||||
let t: Double = (v - yMin) / (yMax - yMin)
|
||||
return height * (1.0 - CGFloat(t))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
// LyrebirdEventListPerformanceView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A composite performance view: ``LyrebirdEventListView`` on top, plus a
|
||||
/// dynamically-populated stack of ``LyrebirdProcessView`` strips for every
|
||||
/// process currently running in the list.
|
||||
///
|
||||
/// As the user fires events (or as an external timeline advances the list),
|
||||
/// processes start and stop. This view polls
|
||||
/// `LyrebirdEventList.allProcesses` at 10 Hz, filters by
|
||||
/// `LyrebirdProcess.isRunning`, and renders a control strip for each. When
|
||||
/// a process finishes (envelope reaches its natural end, `LyrebirdEventList`
|
||||
/// releases it, etc.) its strip disappears on the next poll.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdEventListPerformanceView(eventList: list, engine: engine)
|
||||
/// .padding()
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, `presentInWindow(eventList:engine:title:width:height:)` opens a
|
||||
/// standalone `LyrebirdWindow`:
|
||||
///
|
||||
/// ```swift
|
||||
/// let win = LyrebirdEventListPerformanceView.presentInWindow(
|
||||
/// eventList: list, engine: engine
|
||||
/// )
|
||||
/// // … later …
|
||||
/// win.close()
|
||||
/// ```
|
||||
public struct LyrebirdEventListPerformanceView: View {
|
||||
|
||||
public let eventList: LyrebirdEventList
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var runningProcesses: [LyrebirdProcess] = []
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 100_000_000
|
||||
|
||||
/// Creates a performance view bound to the given event list.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The `LyrebirdEventList` to drive.
|
||||
/// - engine: The `SynthesisEngine` that hosts both the list and any
|
||||
/// ad-hoc `Start` actions on individual process strips.
|
||||
public init(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine
|
||||
) {
|
||||
self.eventList = eventList
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
LyrebirdEventListView(eventList: eventList)
|
||||
|
||||
Divider()
|
||||
|
||||
if runningProcesses.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 8) {
|
||||
ForEach(runningProcesses, id: \.identityKey) { proc in
|
||||
LyrebirdProcessView(process: proc, engine: engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 360, minHeight: 320)
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
refresh()
|
||||
try? await Task.sleep(nanoseconds: LyrebirdEventListPerformanceView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text("No processes running")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Text("Press Next to fire the queued event.")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
private func refresh() {
|
||||
let snapshot: [LyrebirdProcess] = eventList.allProcesses.filter { $0.isRunning }
|
||||
// Avoid issuing identity-changes on every poll when the membership is
|
||||
// unchanged — cheaper for SwiftUI's diffing pass.
|
||||
if !snapshot.elementsEqualByIdentity(to: runningProcesses) {
|
||||
runningProcesses = snapshot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Stable identity for ForEach
|
||||
|
||||
private extension LyrebirdProcess {
|
||||
/// `ObjectIdentifier`-based key used for SwiftUI's `ForEach` so processes
|
||||
/// with duplicate user-supplied `id` strings still render distinct views.
|
||||
var identityKey: ObjectIdentifier { ObjectIdentifier(self) }
|
||||
}
|
||||
|
||||
private extension Array where Element == LyrebirdProcess {
|
||||
func elementsEqualByIdentity(to other: [LyrebirdProcess]) -> Bool {
|
||||
guard count == other.count else { return false }
|
||||
for (a, b) in zip(self, other) where a !== b { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdEventListPerformanceView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting an event-list performance view.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The `LyrebirdEventList` to drive.
|
||||
/// - engine: The `SynthesisEngine` for individual process Start actions.
|
||||
/// - title: Window title bar text. Defaults to the event list ID.
|
||||
/// - width: Initial window width in points. Defaults to `420`.
|
||||
/// - height: Initial window height in points. Defaults to `520`.
|
||||
/// - Returns: The `LyrebirdWindow` hosting the view. Caller retains it to
|
||||
/// keep the window alive.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine,
|
||||
title: String? = nil,
|
||||
width: CGFloat = 420,
|
||||
height: CGFloat = 520
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(
|
||||
title: title ?? eventList.id,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
win.open {
|
||||
LyrebirdEventListPerformanceView(eventList: eventList, engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,333 @@
|
||||
// LyrebirdEventListView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A control panel for driving a `LyrebirdEventList` from the GUI.
|
||||
///
|
||||
/// Displays the list ID, running state, the currently playing event and the
|
||||
/// queued next event (with their `starts` process IDs), a master amplitude
|
||||
/// slider, and transport controls:
|
||||
///
|
||||
/// - **Next** — fires the next event (`eventList.next()`).
|
||||
/// - **Back** — rewinds `index` by one without firing an event. Clamped at `0`.
|
||||
/// - **Skip** — advances `index` by one without firing an event.
|
||||
/// - **Release All** — gracefully releases every running process
|
||||
/// (`eventList.releaseAll()`).
|
||||
/// - **Kill All** — immediately kills every process and tears down the master
|
||||
/// synth (`eventList.killAll()`).
|
||||
/// - **Reset** — kills all and resets the playback index to `0`
|
||||
/// (`eventList.reset()`). Enabled only after Release All or Kill All has
|
||||
/// been pressed (or after the event list is otherwise stopped externally).
|
||||
/// - **Set Next** — types an absolute event index to queue up.
|
||||
///
|
||||
/// The view polls the event list at 10 Hz so external state changes
|
||||
/// (e.g. timeline playback advancing the index) stay reflected on screen.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdEventListView(eventList: list)
|
||||
/// .padding()
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, `presentInWindow(eventList:title:width:height:)` opens a
|
||||
/// standalone `LyrebirdWindow`:
|
||||
///
|
||||
/// ```swift
|
||||
/// let win = LyrebirdEventListView.presentInWindow(eventList: list)
|
||||
/// // … later …
|
||||
/// win.close()
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// The view body runs on the main thread. `LyrebirdEventList` is documented as
|
||||
/// main-thread-only for its public mutating API; all transport actions are
|
||||
/// dispatched from `@MainActor` SwiftUI contexts.
|
||||
public struct LyrebirdEventListView: View {
|
||||
|
||||
public let eventList: LyrebirdEventList
|
||||
|
||||
@State private var isRunning: Bool = false
|
||||
@State private var currentEvent: Int? = nil
|
||||
@State private var nextEvent: Int? = nil
|
||||
@State private var playIndex: Int = 0
|
||||
@State private var amp: Double = 1.0
|
||||
@State private var setNextField: String = ""
|
||||
@State private var hasBeenStopped: Bool = false
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 100_000_000
|
||||
|
||||
/// Creates an event-list control view bound to the given list.
|
||||
///
|
||||
/// - Parameter eventList: The `LyrebirdEventList` to control.
|
||||
public init(eventList: LyrebirdEventList) {
|
||||
self.eventList = eventList
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
header
|
||||
Divider()
|
||||
currentNextRows
|
||||
Divider()
|
||||
ampRow
|
||||
Divider()
|
||||
transportRow
|
||||
setNextRow
|
||||
stopRow
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 320)
|
||||
.task {
|
||||
// Seed amplitude from the list before the first poll so the slider
|
||||
// does not snap to a stale default while the engine is silent.
|
||||
amp = eventList.amp
|
||||
while !Task.isCancelled {
|
||||
refresh()
|
||||
try? await Task.sleep(nanoseconds: LyrebirdEventListView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(isRunning ? Color.green : Color.secondary.opacity(0.4))
|
||||
.frame(width: 10, height: 10)
|
||||
Text(eventList.id)
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(eventList.eventCount) events")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var currentNextRows: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
EventRow(
|
||||
label: "Now",
|
||||
index: currentEvent,
|
||||
description: descriptionForEvent(at: currentEvent)
|
||||
)
|
||||
EventRow(
|
||||
label: "Next",
|
||||
index: nextEvent,
|
||||
description: descriptionForEvent(at: nextEvent)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private var ampRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Amp")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 36, alignment: .leading)
|
||||
Slider(value: Binding(
|
||||
get: { dbFromAmp(amp) },
|
||||
set: { newDb in
|
||||
let newAmp: Double = ampFromDb(newDb)
|
||||
amp = newAmp
|
||||
eventList.amp = newAmp
|
||||
}
|
||||
), in: LyrebirdEventListView.minDb ... LyrebirdEventListView.maxDb)
|
||||
Text(dbDisplay(dbFromAmp(amp)))
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: 56, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - dB <-> linear amplitude (shared with `LyrebirdProcessView` via `DbSliderConversion`)
|
||||
|
||||
private static let minDb: Double = DbSliderConversion.minDb
|
||||
private static let maxDb: Double = DbSliderConversion.maxDb
|
||||
|
||||
private func ampFromDb(_ db: Double) -> Double { DbSliderConversion.ampFromDb(db) }
|
||||
private func dbFromAmp(_ amp: Double) -> Double { DbSliderConversion.dbFromAmp(amp) }
|
||||
private func dbDisplay(_ db: Double) -> String { DbSliderConversion.dbDisplay(db) }
|
||||
|
||||
private var transportRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Button("Next") { eventList.next() }
|
||||
.disabled(nextEvent == nil)
|
||||
|
||||
Spacer()
|
||||
|
||||
Button("Back") {
|
||||
let cur: Int = eventList.index
|
||||
guard cur > 0 else { return }
|
||||
eventList.index = cur - 1
|
||||
refresh()
|
||||
}
|
||||
.disabled(playIndex <= 0)
|
||||
Button("Skip") {
|
||||
let cur: Int = eventList.index
|
||||
guard cur < eventList.eventCount else { return }
|
||||
eventList.index = cur + 1
|
||||
refresh()
|
||||
}
|
||||
.disabled(nextEvent == nil)
|
||||
}
|
||||
}
|
||||
|
||||
private var setNextRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Set Next")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
TextField("index", text: $setNextField)
|
||||
.frame(maxWidth: 80)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
Button("Apply") {
|
||||
applySetNext()
|
||||
}
|
||||
.disabled(parsedSetNext() == nil)
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
private var stopRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Button("Reset") {
|
||||
eventList.reset()
|
||||
hasBeenStopped = false
|
||||
refresh()
|
||||
}
|
||||
.disabled(!hasBeenStopped)
|
||||
|
||||
Spacer()
|
||||
|
||||
Button("Release All") {
|
||||
eventList.releaseAll()
|
||||
hasBeenStopped = true
|
||||
refresh()
|
||||
}
|
||||
.disabled(!isRunning || hasBeenStopped)
|
||||
|
||||
Button("Kill All") {
|
||||
eventList.killAll()
|
||||
hasBeenStopped = true
|
||||
refresh()
|
||||
}
|
||||
.disabled(!isRunning || hasBeenStopped)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func refresh() {
|
||||
isRunning = eventList.isRunning
|
||||
currentEvent = eventList.currentEvent
|
||||
nextEvent = eventList.nextEvent
|
||||
playIndex = eventList.index
|
||||
amp = eventList.amp
|
||||
if !isRunning && currentEvent != nil {
|
||||
hasBeenStopped = true
|
||||
}
|
||||
}
|
||||
|
||||
private func descriptionForEvent(at index: Int?) -> String {
|
||||
guard let i: Int = index, i >= 0, i < eventList.eventCount else { return "—" }
|
||||
let event: LyrebirdEvent = eventList.events[i]
|
||||
let startIDs: [String] = event.starts.map(\.id)
|
||||
let releaseIDs: [String] = event.releases.map(\.id)
|
||||
|
||||
var parts: [String] = []
|
||||
if !startIDs.isEmpty { parts.append("▶ " + startIDs.joined(separator: ", ")) }
|
||||
if !releaseIDs.isEmpty { parts.append("⏹ " + releaseIDs.joined(separator: ", ")) }
|
||||
return parts.isEmpty ? "(empty event)" : parts.joined(separator: " ")
|
||||
}
|
||||
|
||||
private func parsedSetNext() -> Int? {
|
||||
guard let i: Int = Int(setNextField.trimmingCharacters(in: .whitespaces)) else { return nil }
|
||||
guard i >= 0, i < eventList.eventCount else { return nil }
|
||||
return i
|
||||
}
|
||||
|
||||
private func applySetNext() {
|
||||
guard let i: Int = parsedSetNext() else { return }
|
||||
eventList.index = i
|
||||
setNextField = ""
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-views
|
||||
|
||||
private struct EventRow: View {
|
||||
let label: String
|
||||
let index: Int?
|
||||
let description: String
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 8) {
|
||||
Text(label)
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 36, alignment: .leading)
|
||||
Text(indexText)
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: 32, alignment: .leading)
|
||||
Text(description)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.primary)
|
||||
.lineLimit(2)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private var indexText: String {
|
||||
if let i: Int = index { return "#\(i)" }
|
||||
return "—"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdEventListView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting an event-list control view.
|
||||
///
|
||||
/// Use when no parent SwiftUI view is available — a script, REPL, or CLI
|
||||
/// demo can call this to surface event-list transport in its own window.
|
||||
/// The returned `LyrebirdWindow` retains the AppKit window; close it with
|
||||
/// `.close()`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The `LyrebirdEventList` to control.
|
||||
/// - title: Window title bar text. Defaults to `"Event List"`.
|
||||
/// - width: Initial window width in points. Defaults to `360`.
|
||||
/// - height: Initial window height in points. Defaults to `260`.
|
||||
/// - Returns: The `LyrebirdWindow` hosting the view. Caller retains it to
|
||||
/// keep the window alive.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
eventList: LyrebirdEventList,
|
||||
title: String = "Event List",
|
||||
width: CGFloat = 360,
|
||||
height: CGFloat = 260
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdEventListView(eventList: eventList)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,126 @@
|
||||
// LyrebirdMessageBanner.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Compact banner showing the most recent few messages from a
|
||||
/// `LyrebirdMessageCenter`.
|
||||
///
|
||||
/// Designed for embedding inside larger control panels (e.g.
|
||||
/// ``LyrebirdEngineStatusView``). Renders up to ``lineCount`` most-recent
|
||||
/// messages with a tier-coloured left edge stripe. Tapping the banner
|
||||
/// invokes the optional ``onOpenFull`` callback so the host can open the
|
||||
/// full ``LyrebirdMessageView`` in a window or sheet.
|
||||
public struct LyrebirdMessageBanner: View {
|
||||
|
||||
@Bindable private var center: LyrebirdMessageCenter
|
||||
|
||||
/// Number of recent messages shown when present. Defaults to `3`.
|
||||
public let lineCount: Int
|
||||
|
||||
/// Callback invoked when the user taps the banner. Typically opens the
|
||||
/// full message view in a window. `nil` makes the banner non-interactive.
|
||||
public let onOpenFull: (() -> Void)?
|
||||
|
||||
/// Creates a banner bound to `LyrebirdMessageCenter.shared`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - lineCount: How many recent messages to show. Defaults to `3`.
|
||||
/// - onOpenFull: Tap action. Defaults to `nil`.
|
||||
@MainActor
|
||||
public init(
|
||||
lineCount: Int = 3,
|
||||
onOpenFull: (() -> Void)? = nil
|
||||
) {
|
||||
self.center = LyrebirdMessageCenter.shared
|
||||
self.lineCount = lineCount
|
||||
self.onOpenFull = onOpenFull
|
||||
}
|
||||
|
||||
/// Creates a banner bound to the given center.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - center: Center to observe.
|
||||
/// - lineCount: How many recent messages to show. Defaults to `3`.
|
||||
/// - onOpenFull: Tap action. Defaults to `nil`.
|
||||
public init(
|
||||
center: LyrebirdMessageCenter,
|
||||
lineCount: Int = 3,
|
||||
onOpenFull: (() -> Void)? = nil
|
||||
) {
|
||||
self.center = center
|
||||
self.lineCount = lineCount
|
||||
self.onOpenFull = onOpenFull
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
let recent: [LyrebirdMessage] = recentMessages
|
||||
return Group {
|
||||
if recent.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
content(recent: recent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyState: some View {
|
||||
HStack(spacing: 6) {
|
||||
Image(systemName: "tray")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Text("No messages")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
}
|
||||
.padding(6)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(Color.secondary.opacity(0.05))
|
||||
)
|
||||
}
|
||||
|
||||
private func content(recent: [LyrebirdMessage]) -> some View {
|
||||
Button(action: { onOpenFull?() }) {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
ForEach(recent) { msg in
|
||||
bannerRow(msg)
|
||||
}
|
||||
}
|
||||
.padding(6)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(Color.secondary.opacity(0.05))
|
||||
)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(onOpenFull == nil)
|
||||
}
|
||||
|
||||
private func bannerRow(_ msg: LyrebirdMessage) -> some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Capsule()
|
||||
.fill(LyrebirdMessageTierStyle.color(for: msg.tier))
|
||||
.frame(width: 3, height: 11)
|
||||
Text(msg.text)
|
||||
.font(.caption)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.foregroundStyle(.primary)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private var recentMessages: [LyrebirdMessage] {
|
||||
let all: [LyrebirdMessage] = center.messages
|
||||
guard all.count > lineCount else { return all }
|
||||
let start: Int = all.count - lineCount
|
||||
return Array(all[start..<all.count])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// LyrebirdMessageHelpers.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Module-internal styling helpers shared between ``LyrebirdMessageView``
|
||||
/// and ``LyrebirdMessageBanner``.
|
||||
///
|
||||
/// Lives in a `*Helpers.swift` per the project rule for shared file-scope
|
||||
/// helpers used across more than one source file.
|
||||
enum LyrebirdMessageTierStyle {
|
||||
static func color(for tier: LyrebirdMessageTier) -> Color {
|
||||
switch tier {
|
||||
case .info: return .blue
|
||||
case .warning: return .orange
|
||||
case .error: return .red
|
||||
}
|
||||
}
|
||||
|
||||
static func shortLabel(for tier: LyrebirdMessageTier) -> String {
|
||||
switch tier {
|
||||
case .info: return "INFO"
|
||||
case .warning: return "WARN"
|
||||
case .error: return "ERR"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// LyrebirdMessageView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Full scrollable view over a `LyrebirdMessageCenter` ring.
|
||||
///
|
||||
/// Top bar: per-tier filter toggles (with live counts), Clear button, total
|
||||
/// count badge. Body: a scrolling list of rows showing timestamp, tier chip,
|
||||
/// optional source caption, and message text.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdMessageView()
|
||||
/// .padding()
|
||||
/// ```
|
||||
///
|
||||
/// Or bind to a non-shared center:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdMessageView(center: myCenter)
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, `presentInWindow(...)` opens a standalone `LyrebirdWindow`.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// `LyrebirdMessageCenter` is `@MainActor`; SwiftUI view bodies run on the
|
||||
/// main actor too, so all reads are safe.
|
||||
public struct LyrebirdMessageView: View {
|
||||
|
||||
@Bindable private var center: LyrebirdMessageCenter
|
||||
|
||||
@State private var enabledTiers: Set<LyrebirdMessageTier> =
|
||||
Set(LyrebirdMessageTier.allCases)
|
||||
|
||||
/// Creates a message view bound to `LyrebirdMessageCenter.shared`.
|
||||
@MainActor
|
||||
public init() {
|
||||
self.center = LyrebirdMessageCenter.shared
|
||||
}
|
||||
|
||||
/// Creates a message view bound to the given center.
|
||||
///
|
||||
/// - Parameter center: The center to observe.
|
||||
public init(center: LyrebirdMessageCenter) {
|
||||
self.center = center
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
headerRow
|
||||
filterRow
|
||||
Divider()
|
||||
listBody
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 360, minHeight: 200)
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var headerRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Messages")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(center.messages.count)")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
Button("Clear") { center.clear() }
|
||||
.disabled(center.messages.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
private var filterRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
ForEach(LyrebirdMessageTier.allCases, id: \.self) { tier in
|
||||
TierFilterChip(
|
||||
tier: tier,
|
||||
count: count(of: tier),
|
||||
isEnabled: enabledTiers.contains(tier),
|
||||
toggle: { toggle(tier) }
|
||||
)
|
||||
}
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
private var listBody: some View {
|
||||
let visible: [LyrebirdMessage] = filteredMessages
|
||||
return Group {
|
||||
if visible.isEmpty {
|
||||
Text(emptyStateText)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
|
||||
} else {
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 4) {
|
||||
ForEach(visible) { msg in
|
||||
MessageRow(message: msg)
|
||||
.id(msg.id)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
.onChange(of: visible.last?.id) { _, newest in
|
||||
if let newest: UUID = newest {
|
||||
withAnimation(.linear(duration: 0.12)) {
|
||||
proxy.scrollTo(newest, anchor: .bottom)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private var filteredMessages: [LyrebirdMessage] {
|
||||
center.messages.filter { enabledTiers.contains($0.tier) }
|
||||
}
|
||||
|
||||
private var emptyStateText: String {
|
||||
if center.messages.isEmpty { return "No messages." }
|
||||
return "No messages match the current filter."
|
||||
}
|
||||
|
||||
private func count(of tier: LyrebirdMessageTier) -> Int {
|
||||
var n: Int = 0
|
||||
for msg: LyrebirdMessage in center.messages where msg.tier == tier {
|
||||
n += 1
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
private func toggle(_ tier: LyrebirdMessageTier) {
|
||||
if enabledTiers.contains(tier) {
|
||||
enabledTiers.remove(tier)
|
||||
} else {
|
||||
enabledTiers.insert(tier)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-views
|
||||
|
||||
private struct TierFilterChip: View {
|
||||
let tier: LyrebirdMessageTier
|
||||
let count: Int
|
||||
let isEnabled: Bool
|
||||
let toggle: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Button(action: toggle) {
|
||||
HStack(spacing: 4) {
|
||||
Circle()
|
||||
.fill(LyrebirdMessageTierStyle.color(for: tier))
|
||||
.frame(width: 8, height: 8)
|
||||
.opacity(isEnabled ? 1.0 : 0.35)
|
||||
Text(LyrebirdMessageTierStyle.shortLabel(for: tier))
|
||||
.font(.caption.monospaced())
|
||||
Text("\(count)")
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 3)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 4)
|
||||
.fill(isEnabled
|
||||
? LyrebirdMessageTierStyle.color(for: tier).opacity(0.15)
|
||||
: Color.secondary.opacity(0.08))
|
||||
)
|
||||
.opacity(isEnabled ? 1.0 : 0.55)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MessageRow: View {
|
||||
let message: LyrebirdMessage
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 8) {
|
||||
Text(MessageRow.formatTime(message.timestamp))
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 80, alignment: .leading)
|
||||
Capsule()
|
||||
.fill(LyrebirdMessageTierStyle.color(for: message.tier))
|
||||
.frame(width: 3, height: 14)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
if let src: String = message.source, !src.isEmpty {
|
||||
Text(src)
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Text(message.text)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.primary)
|
||||
.textSelection(.enabled)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
|
||||
private static let timeFormatter: DateFormatter = {
|
||||
let f: DateFormatter = DateFormatter()
|
||||
f.dateFormat = "HH:mm:ss.SSS"
|
||||
return f
|
||||
}()
|
||||
|
||||
private static func formatTime(_ date: Date) -> String {
|
||||
timeFormatter.string(from: date)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdMessageView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a message view bound to the shared
|
||||
/// `LyrebirdMessageCenter`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - title: Window title bar text. Defaults to `"Messages"`.
|
||||
/// - width: Initial width in points. Defaults to `460`.
|
||||
/// - height: Initial height in points. Defaults to `360`.
|
||||
/// - Returns: The `LyrebirdWindow` hosting the view. Caller retains it to
|
||||
/// keep the window alive.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
title: String = "Messages",
|
||||
width: CGFloat = 460,
|
||||
height: CGFloat = 360
|
||||
) -> LyrebirdWindow {
|
||||
presentInWindow(
|
||||
center: LyrebirdMessageCenter.shared,
|
||||
title: title,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
center: LyrebirdMessageCenter,
|
||||
title: String = "Messages",
|
||||
width: CGFloat = 460,
|
||||
height: CGFloat = 360
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdMessageView(center: center)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,264 @@
|
||||
// LyrebirdNodeTreeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Live tree view of the engine's `NodeTreeMirror`.
|
||||
///
|
||||
/// Renders rows head→tail (top-to-bottom reading order matches RT signal
|
||||
/// flow). Groups expand / collapse via `DisclosureGroup`. Each row shows
|
||||
/// a kind glyph, a class name, an optional 4-hex identity suffix, and a
|
||||
/// child-count badge for groups.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdNodeTreeView(engine: engine)
|
||||
/// .padding()
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, `presentInWindow(...)` opens a detached `LyrebirdWindow`.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// `NodeTreeMirror` and its `snapshot` are read on the main thread. SwiftUI
|
||||
/// view bodies run on the main thread; reads are safe.
|
||||
public struct LyrebirdNodeTreeView: View {
|
||||
|
||||
/// `@Observable` reference; SwiftUI tracks `snapshot` reads via the
|
||||
/// macro-synthesized observation registrar.
|
||||
private let mirror: NodeTreeMirror
|
||||
|
||||
@State private var expanded: Set<ObjectIdentifier> = []
|
||||
|
||||
/// Creates a node-tree view bound to the given engine's mirror.
|
||||
public init(engine: SynthesisEngine) {
|
||||
self.mirror = engine.nodeTreeMirror
|
||||
}
|
||||
|
||||
/// Creates a node-tree view bound to the given mirror.
|
||||
public init(mirror: NodeTreeMirror) {
|
||||
self.mirror = mirror
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
headerRow
|
||||
Divider()
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
NodeRowList(
|
||||
node: mirror.snapshot.root,
|
||||
depth: 0,
|
||||
expanded: $expanded
|
||||
)
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 320, minHeight: 220)
|
||||
.onAppear { _seedDefaultExpansion() }
|
||||
}
|
||||
|
||||
private var headerRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Node Tree")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Button("Expand All") { _expandAll() }
|
||||
.font(.caption)
|
||||
Button("Collapse All") { expanded.removeAll() }
|
||||
.font(.caption)
|
||||
}
|
||||
}
|
||||
|
||||
/// Default expansion: root + mainGroup open, deeper nodes collapsed.
|
||||
private func _seedDefaultExpansion() {
|
||||
guard expanded.isEmpty else { return }
|
||||
let root: NodeTreeSnapshot.Node = mirror.snapshot.root
|
||||
expanded.insert(root.id)
|
||||
for child: NodeTreeSnapshot.Node in root.children where _isContainer(child.kind) {
|
||||
expanded.insert(child.id)
|
||||
}
|
||||
}
|
||||
|
||||
private func _expandAll() {
|
||||
var ids: Set<ObjectIdentifier> = []
|
||||
_collectContainerIds(mirror.snapshot.root, into: &ids)
|
||||
expanded = ids
|
||||
}
|
||||
|
||||
private func _collectContainerIds(
|
||||
_ node: NodeTreeSnapshot.Node,
|
||||
into ids: inout Set<ObjectIdentifier>
|
||||
) {
|
||||
if _isContainer(node.kind) {
|
||||
ids.insert(node.id)
|
||||
}
|
||||
for child: NodeTreeSnapshot.Node in node.children {
|
||||
_collectContainerIds(child, into: &ids)
|
||||
}
|
||||
}
|
||||
|
||||
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
|
||||
switch kind {
|
||||
case .group, .parallelGroup: return true
|
||||
case .synth: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Recursive row list
|
||||
|
||||
private struct NodeRowList: View {
|
||||
let node: NodeTreeSnapshot.Node
|
||||
let depth: Int
|
||||
@Binding var expanded: Set<ObjectIdentifier>
|
||||
|
||||
var body: some View {
|
||||
let isContainer: Bool = _isContainer(node.kind)
|
||||
let isExpanded: Bool = expanded.contains(node.id)
|
||||
NodeRow(
|
||||
node: node,
|
||||
depth: depth,
|
||||
isContainer: isContainer,
|
||||
isExpanded: isExpanded,
|
||||
toggle: {
|
||||
if isExpanded { expanded.remove(node.id) }
|
||||
else { expanded.insert(node.id) }
|
||||
}
|
||||
)
|
||||
if isContainer && isExpanded {
|
||||
ForEach(node.children) { child in
|
||||
NodeRowList(
|
||||
node: child,
|
||||
depth: depth + 1,
|
||||
expanded: $expanded
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func _isContainer(_ kind: NodeTreeSnapshot.Node.Kind) -> Bool {
|
||||
switch kind {
|
||||
case .group, .parallelGroup: return true
|
||||
case .synth: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Single row
|
||||
|
||||
private struct NodeRow: View {
|
||||
let node: NodeTreeSnapshot.Node
|
||||
let depth: Int
|
||||
let isContainer: Bool
|
||||
let isExpanded: Bool
|
||||
let toggle: () -> Void
|
||||
|
||||
private static let indentPoints: CGFloat = 14
|
||||
private static let dotIconSize: CGFloat = 6
|
||||
private static let chevronWidth: CGFloat = 12
|
||||
private static let identityHexSuffixLen: Int = 4
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Spacer()
|
||||
.frame(width: CGFloat(depth) * NodeRow.indentPoints)
|
||||
|
||||
if isContainer {
|
||||
Button(action: toggle) {
|
||||
Image(systemName: isExpanded ? "chevron.down" : "chevron.right")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: NodeRow.chevronWidth, alignment: .center)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
} else {
|
||||
Image(systemName: "circle.fill")
|
||||
.font(.system(size: NodeRow.dotIconSize))
|
||||
.foregroundStyle(.tertiary)
|
||||
.frame(width: NodeRow.chevronWidth, alignment: .center)
|
||||
}
|
||||
|
||||
Text(node.displayName)
|
||||
.font(.callout.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
|
||||
if let badge: String = childCountBadge {
|
||||
Text(badge)
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
Text(_identityShort(node.id))
|
||||
.font(.caption2.monospaced())
|
||||
.foregroundStyle(.tertiary)
|
||||
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { if isContainer { toggle() } }
|
||||
}
|
||||
|
||||
private var childCountBadge: String? {
|
||||
guard isContainer else { return nil }
|
||||
return "(\(node.children.count))"
|
||||
}
|
||||
|
||||
private func _identityShort(_ id: ObjectIdentifier) -> String {
|
||||
// Use `hashValue` rather than parsing `String(describing:)`. The
|
||||
// textual form of `ObjectIdentifier` is a stdlib implementation
|
||||
// detail with no API guarantee; `hashValue` is process-stable for
|
||||
// a given object identity (Hashable conformance) and yields a
|
||||
// deterministic short hex disambiguator.
|
||||
let mask: Int = (1 << (NodeRow.identityHexSuffixLen * 4)) - 1
|
||||
let masked: Int = id.hashValue & mask
|
||||
let raw: String = String(masked, radix: 16, uppercase: false)
|
||||
let padded: String
|
||||
if raw.count < NodeRow.identityHexSuffixLen {
|
||||
padded = String(repeating: "0", count: NodeRow.identityHexSuffixLen - raw.count) + raw
|
||||
} else {
|
||||
padded = raw
|
||||
}
|
||||
return "#" + padded
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdNodeTreeView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a node-tree view.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The engine to mirror.
|
||||
/// - title: Window title bar text. Defaults to `"Node Tree"`.
|
||||
/// - width: Initial width in points. Defaults to `420`.
|
||||
/// - height: Initial height in points. Defaults to `420`.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
engine: SynthesisEngine,
|
||||
title: String = "Node Tree",
|
||||
width: CGFloat = 420,
|
||||
height: CGFloat = 420
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdNodeTreeView(engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,222 @@
|
||||
// LyrebirdProcessView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A control panel for driving a single `LyrebirdProcess`.
|
||||
///
|
||||
/// Displays the process ID, a running indicator (idle / running / releasing),
|
||||
/// a master amplitude slider, and Start / Release buttons:
|
||||
///
|
||||
/// - **Start** — calls `LyrebirdProcess.play(engine:)`. Disabled while the
|
||||
/// process is already running.
|
||||
/// - **Release** — calls `LyrebirdProcess.release(reltime:)` with `nil`
|
||||
/// (envelope-defined release tail). Disabled when the process is idle or
|
||||
/// already releasing.
|
||||
///
|
||||
/// The view polls the process at 10 Hz so external lifecycle changes (a
|
||||
/// `LyrebirdEventList` releasing the process, the envelope reaching its
|
||||
/// natural end, etc.) stay reflected on screen.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent:
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdProcessView(process: proc, engine: engine)
|
||||
/// .padding()
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, `presentInWindow(process:engine:title:width:height:)` opens a
|
||||
/// standalone `LyrebirdWindow`:
|
||||
///
|
||||
/// ```swift
|
||||
/// let win = LyrebirdProcessView.presentInWindow(process: proc, engine: engine)
|
||||
/// // … later …
|
||||
/// win.close()
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// The view body runs on the main thread. `LyrebirdProcess.play(engine:)` /
|
||||
/// `release(reltime:)` are documented as main-thread-safe; both transport
|
||||
/// actions are dispatched from `@MainActor` SwiftUI contexts.
|
||||
public struct LyrebirdProcessView: View {
|
||||
|
||||
public let process: LyrebirdProcess
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var isRunning: Bool = false
|
||||
@State private var isReleasing: Bool = false
|
||||
@State private var amp: Double = 1.0
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 100_000_000
|
||||
|
||||
/// Creates a process control view bound to the given process.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - process: The `LyrebirdProcess` to control.
|
||||
/// - engine: The `SynthesisEngine` used by the **Start** button.
|
||||
public init(
|
||||
process: LyrebirdProcess,
|
||||
engine: SynthesisEngine
|
||||
) {
|
||||
self.process = process
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
header
|
||||
Divider()
|
||||
ampRow
|
||||
Divider()
|
||||
transportRow
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 280)
|
||||
.task {
|
||||
// Seed amp from the process before the first poll so the slider does
|
||||
// not snap from a stale default while the process is still idle.
|
||||
amp = process.amp
|
||||
while !Task.isCancelled {
|
||||
refresh()
|
||||
try? await Task.sleep(nanoseconds: LyrebirdProcessView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(stateColor)
|
||||
.frame(width: 10, height: 10)
|
||||
Text(process.id)
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text(stateLabel)
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var ampRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Amp")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 36, alignment: .leading)
|
||||
Slider(value: Binding(
|
||||
get: { dbFromAmp(amp) },
|
||||
set: { newDb in
|
||||
let newAmp: Double = ampFromDb(newDb)
|
||||
amp = newAmp
|
||||
process.amp = newAmp
|
||||
}
|
||||
), in: LyrebirdProcessView.minDb ... maxDb)
|
||||
Text(dbDisplay(dbFromAmp(amp)))
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: 56, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - dB <-> linear amplitude (shared with `LyrebirdEventListView` via `DbSliderConversion`)
|
||||
|
||||
private static let minDb: Double = DbSliderConversion.minDb
|
||||
|
||||
/// Per-process slider ceiling, sourced from ``LyrebirdProcess/maxUIAmpDb``.
|
||||
/// Defaults to `+12` dB; raised when the process opts in to extra headroom.
|
||||
private var maxDb: Double { process.maxUIAmpDb }
|
||||
|
||||
private func ampFromDb(_ db: Double) -> Double { DbSliderConversion.ampFromDb(db) }
|
||||
private func dbFromAmp(_ amp: Double) -> Double { DbSliderConversion.dbFromAmp(amp, maxDb: maxDb) }
|
||||
private func dbDisplay(_ db: Double) -> String { DbSliderConversion.dbDisplay(db) }
|
||||
|
||||
private var transportRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Button("Start") {
|
||||
process.play(engine: engine)
|
||||
refresh()
|
||||
}
|
||||
.disabled(isRunning)
|
||||
|
||||
Button("Release") {
|
||||
process.release()
|
||||
refresh()
|
||||
}
|
||||
.disabled(!isRunning || isReleasing)
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func refresh() {
|
||||
isRunning = process.isRunning
|
||||
isReleasing = process.isReleasing
|
||||
amp = process.amp
|
||||
}
|
||||
|
||||
private var stateColor: Color {
|
||||
if isReleasing { return .yellow }
|
||||
if isRunning { return .green }
|
||||
return .secondary.opacity(0.4)
|
||||
}
|
||||
|
||||
private var stateLabel: String {
|
||||
if isReleasing { return "Releasing" }
|
||||
if isRunning { return "Running" }
|
||||
return "Idle"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdProcessView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a process control view.
|
||||
///
|
||||
/// Use when no parent SwiftUI view is available — a script, REPL, or CLI
|
||||
/// demo can call this to surface process transport in its own window. The
|
||||
/// returned `LyrebirdWindow` retains the AppKit window; close it with
|
||||
/// `.close()`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - process: The `LyrebirdProcess` to control.
|
||||
/// - engine: The `SynthesisEngine` used by the **Start** button.
|
||||
/// - title: Window title bar text. Defaults to the process ID.
|
||||
/// - width: Initial window width in points. Defaults to `300`.
|
||||
/// - height: Initial window height in points. Defaults to `180`.
|
||||
/// - Returns: The `LyrebirdWindow` hosting the view. Caller retains it to
|
||||
/// keep the window alive.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
process: LyrebirdProcess,
|
||||
engine: SynthesisEngine,
|
||||
title: String? = nil,
|
||||
width: CGFloat = 300,
|
||||
height: CGFloat = 180
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(
|
||||
title: title ?? process.id,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
win.open {
|
||||
LyrebirdProcessView(process: process, engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,195 @@
|
||||
// LyrebirdRunningProcessesView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A panel that renders one ``LyrebirdProcessView`` per currently-running
|
||||
/// ``LyrebirdProcess`` owned by a ``LyrebirdEventList``.
|
||||
///
|
||||
/// Processes appear when they start (transition to running/releasing) and
|
||||
/// disappear when they finish (auto-free or are killed). Identity is tracked
|
||||
/// via `ObjectIdentifier`, not by `LyrebirdProcess.id`, so two processes that
|
||||
/// share an `id` string still render as distinct rows.
|
||||
///
|
||||
/// The list of running processes is refreshed on a 10 Hz poll loop, matching
|
||||
/// the cadence used by ``LyrebirdProcessView`` and ``LyrebirdEventListView``.
|
||||
/// The poll only re-assigns the `@State` snapshot when the set of running
|
||||
/// identities changes — otherwise each child ``LyrebirdProcessView`` keeps its
|
||||
/// own polling task running uninterrupted and per-row UI state (slider drag,
|
||||
/// focus) survives ticks.
|
||||
///
|
||||
/// ## Hosting
|
||||
///
|
||||
/// Embed inside any SwiftUI parent that already has an event list and engine
|
||||
/// in scope:
|
||||
///
|
||||
/// ```swift
|
||||
/// VStack(alignment: .leading, spacing: 12) {
|
||||
/// if let eventList = controller.eventList {
|
||||
/// LyrebirdEventListView(eventList: eventList)
|
||||
/// LyrebirdRunningProcessesView(eventList: eventList, engine: controller.engine)
|
||||
/// Spacer()
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// On macOS, ``presentInWindow(eventList:engine:title:width:height:)`` opens
|
||||
/// a standalone ``LyrebirdWindow``.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// The view body and refresh loop run on the main thread.
|
||||
/// ``LyrebirdEventList/allProcesses`` and ``LyrebirdProcess/isRunning`` are
|
||||
/// documented as safe to read from any thread — the main-thread read here is
|
||||
/// trivially valid.
|
||||
public struct LyrebirdRunningProcessesView: View {
|
||||
|
||||
public let eventList: LyrebirdEventList
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// Snapshot of currently-running processes. Identity-stable across refresh
|
||||
/// ticks: only re-assigned when the set of running identities changes.
|
||||
@State private var running: [LyrebirdProcess] = []
|
||||
|
||||
/// 10 Hz — matches ``LyrebirdProcessView`` and ``LyrebirdEventListView``.
|
||||
private static let pollIntervalNs: UInt64 = 100_000_000
|
||||
|
||||
/// Creates a running-processes panel bound to the given event list.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The ``LyrebirdEventList`` whose running processes will be
|
||||
/// rendered. Only processes registered with this list are visible —
|
||||
/// standalone processes (those not owned by an event list) do not
|
||||
/// appear here.
|
||||
/// - engine: The ``SynthesisEngine`` forwarded to each child
|
||||
/// ``LyrebirdProcessView`` for its **Start** button.
|
||||
public init(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine
|
||||
) {
|
||||
self.eventList = eventList
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
header
|
||||
Divider()
|
||||
if running.isEmpty {
|
||||
emptyRow
|
||||
} else {
|
||||
ForEach(running, id: \.lyrebirdObjectID) { proc in
|
||||
LyrebirdProcessView(process: proc, engine: engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 320)
|
||||
.task {
|
||||
// Seed once before the poll loop so the panel is correct on first
|
||||
// appearance (e.g. when re-hosted while processes are already running).
|
||||
refresh()
|
||||
while !Task.isCancelled {
|
||||
refresh()
|
||||
try? await Task.sleep(nanoseconds: LyrebirdRunningProcessesView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Running")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(running.count)")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyRow: some View {
|
||||
Text("No running processes")
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
|
||||
// MARK: - Refresh
|
||||
|
||||
private func refresh() {
|
||||
let snapshot: [LyrebirdProcess] = eventList.allProcesses.filter { $0.isRunning }
|
||||
if !LyrebirdRunningProcessesView.sameIdentities(snapshot, running) {
|
||||
running = snapshot
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when two arrays contain the same `LyrebirdProcess` instances in
|
||||
/// the same order. Identity-only — does not inspect process state.
|
||||
private static func sameIdentities(
|
||||
_ a: [LyrebirdProcess],
|
||||
_ b: [LyrebirdProcess]
|
||||
) -> Bool {
|
||||
guard a.count == b.count else { return false }
|
||||
for i: Int in 0..<a.count where a[i] !== b[i] { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ObjectIdentifier helper
|
||||
|
||||
private extension LyrebirdProcess {
|
||||
/// Stable identity for SwiftUI `ForEach`. `LyrebirdProcess` is a class, so
|
||||
/// `ObjectIdentifier` is the natural identity; not added to the core module
|
||||
/// because `ObjectIdentifier` conformance is a UI concern.
|
||||
var lyrebirdObjectID: ObjectIdentifier { ObjectIdentifier(self) }
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (macOS)
|
||||
|
||||
#if os(macOS)
|
||||
extension LyrebirdRunningProcessesView {
|
||||
|
||||
/// Opens a ``LyrebirdWindow`` hosting a running-processes panel.
|
||||
///
|
||||
/// Use when no parent SwiftUI view is available — a script, REPL, or CLI
|
||||
/// demo can call this to surface per-process transport in its own window.
|
||||
/// The returned ``LyrebirdWindow`` retains the AppKit window; close it
|
||||
/// with `.close()`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The ``LyrebirdEventList`` to track.
|
||||
/// - engine: The ``SynthesisEngine`` forwarded to each child
|
||||
/// ``LyrebirdProcessView``.
|
||||
/// - title: Window title bar text. Defaults to `"<eventList.id> — Running"`.
|
||||
/// - width: Initial window width in points. Defaults to `360`.
|
||||
/// - height: Initial window height in points. Defaults to `420`.
|
||||
/// - Returns: The ``LyrebirdWindow`` hosting the view. Caller retains it to
|
||||
/// keep the window alive.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine,
|
||||
title: String? = nil,
|
||||
width: CGFloat = 360,
|
||||
height: CGFloat = 420
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(
|
||||
title: title ?? "\(eventList.id) — Running",
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
win.open {
|
||||
LyrebirdRunningProcessesView(eventList: eventList, engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,119 @@
|
||||
// LyrebirdScatterView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// A Canvas-based scatter plot for an array of `Double` values.
|
||||
///
|
||||
/// Each sample is plotted as a filled circle. X position reflects sample index;
|
||||
/// Y position reflects value relative to the displayed range.
|
||||
///
|
||||
/// ```swift
|
||||
/// let data = DemandTemporalTendency(distribution: .gauss,
|
||||
/// parX: .value(0.5), parY: .value(0.0), seed: 1)
|
||||
/// .samples(count: 200)
|
||||
/// LyrebirdScatterView(data)
|
||||
/// .padding()
|
||||
/// ```
|
||||
public struct LyrebirdScatterView: View {
|
||||
|
||||
private let samples: [Double]
|
||||
private let yRange: ClosedRange<Double>?
|
||||
private let pointColor: Color
|
||||
private let showZeroLine: Bool
|
||||
private let width: CGFloat
|
||||
private let height: CGFloat
|
||||
|
||||
private static let backgroundColor: Color = Color(white: 0.08)
|
||||
private static let cornerRadius: CGFloat = 4
|
||||
private static let scatterDotRadius: CGFloat = 2.5
|
||||
private static let zeroLineOpacity: Double = 0.25
|
||||
private static let guideLineWidth: CGFloat = 0.5
|
||||
|
||||
public init(
|
||||
_ samples: [Double],
|
||||
yRange: ClosedRange<Double>? = nil,
|
||||
pointColor: Color = .cyan,
|
||||
showZeroLine: Bool = true,
|
||||
width: CGFloat = 300,
|
||||
height: CGFloat = 120
|
||||
) {
|
||||
self.samples = samples
|
||||
self.yRange = yRange
|
||||
self.pointColor = pointColor
|
||||
self.showZeroLine = showZeroLine
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
Canvas { ctx, size in
|
||||
_draw(ctx: ctx, size: size)
|
||||
}
|
||||
.frame(width: width, height: height)
|
||||
.background(LyrebirdScatterView.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: LyrebirdScatterView.cornerRadius))
|
||||
}
|
||||
|
||||
// MARK: - Drawing
|
||||
|
||||
private func _draw(
|
||||
ctx: GraphicsContext,
|
||||
size: CGSize
|
||||
) {
|
||||
guard !samples.isEmpty else { return }
|
||||
|
||||
let (yMin, yMax) = _yBounds()
|
||||
|
||||
if showZeroLine && yMin <= 0 && yMax >= 0 {
|
||||
let zy: CGFloat = _yFor(0, yMin: yMin, yMax: yMax, height: size.height)
|
||||
var guide: Path = Path()
|
||||
guide.move(to: CGPoint(x: 0, y: zy))
|
||||
guide.addLine(to: CGPoint(x: size.width, y: zy))
|
||||
ctx.stroke(guide,
|
||||
with: .color(.white.opacity(LyrebirdScatterView.zeroLineOpacity)),
|
||||
lineWidth: LyrebirdScatterView.guideLineWidth)
|
||||
}
|
||||
|
||||
let count: Int = samples.count
|
||||
let r: CGFloat = LyrebirdScatterView.scatterDotRadius
|
||||
|
||||
if count == 1 {
|
||||
let px: CGFloat = size.width / 2
|
||||
let py: CGFloat = size.height / 2
|
||||
var dot: Path = Path()
|
||||
dot.addEllipse(in: CGRect(x: px - r, y: py - r, width: 2 * r, height: 2 * r))
|
||||
ctx.fill(dot, with: .color(pointColor))
|
||||
return
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let px: CGFloat = CGFloat(i) / CGFloat(count - 1) * size.width
|
||||
let py: CGFloat = _yFor(samples[i], yMin: yMin, yMax: yMax, height: size.height)
|
||||
var dot: Path = Path()
|
||||
dot.addEllipse(in: CGRect(x: px - r, y: py - r, width: 2 * r, height: 2 * r))
|
||||
ctx.fill(dot, with: .color(pointColor))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func _yBounds() -> (Double, Double) {
|
||||
if let r: ClosedRange<Double> = yRange { return (r.lowerBound, r.upperBound) }
|
||||
return _envelopeYBounds(levels: samples)
|
||||
}
|
||||
|
||||
private func _yFor(
|
||||
_ v: Double,
|
||||
yMin: Double,
|
||||
yMax: Double,
|
||||
height: CGFloat
|
||||
) -> CGFloat {
|
||||
guard yMax > yMin else { return height / 2 }
|
||||
let t: Double = (v - yMin) / (yMax - yMin)
|
||||
return height * (1.0 - CGFloat(t))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// LyrebirdScopeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A real-time dual-channel oscilloscope view.
|
||||
///
|
||||
/// Polls `ScopeCapture` at ~30 Hz and renders each channel's waveform using
|
||||
/// `Canvas`. Channels are stacked vertically, separated by a hairline rule.
|
||||
///
|
||||
/// Channel 0 (left) is drawn in cyan; channel 1 (right) in orange.
|
||||
/// The zero line for each channel is drawn as a dim horizontal guide.
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdScopeView(capture: scopeCapture)
|
||||
/// .frame(height: 120)
|
||||
/// ```
|
||||
public struct LyrebirdScopeView: View {
|
||||
|
||||
public let capture: ScopeCapture
|
||||
|
||||
@State private var channels: [[Float]] = []
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
|
||||
private static let channelColors: [Color] = [.cyan, .orange, .green, .yellow]
|
||||
private static let backgroundColor: Color = Color(white: 0.08)
|
||||
private static let zeroLineOpacity: Double = 0.25
|
||||
private static let separatorOpacity: Double = 0.3
|
||||
/// Per-half-height fraction for waveform amplitude (0.44 × half-height = 0.88 total row
|
||||
/// excursion), leaving headroom so ±1 signals don't clip against channel boundaries.
|
||||
private static let waveformHeightFraction: CGFloat = 0.44
|
||||
|
||||
public init(capture: ScopeCapture) {
|
||||
self.capture = capture
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
Canvas { ctx, size in
|
||||
_drawBackground(ctx: ctx, size: size)
|
||||
guard !channels.isEmpty else { return }
|
||||
let count: Int = channels.count
|
||||
let rowH: CGFloat = size.height / CGFloat(count)
|
||||
|
||||
for (ch, samples) in channels.enumerated() {
|
||||
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
|
||||
let halfH: CGFloat = rowH * LyrebirdScopeView.waveformHeightFraction
|
||||
|
||||
// Zero guide line
|
||||
var guide: Path = Path()
|
||||
guide.move(to: CGPoint(x: 0, y: midY))
|
||||
guide.addLine(to: CGPoint(x: size.width, y: midY))
|
||||
ctx.stroke(guide, with: .color(.white.opacity(LyrebirdScopeView.zeroLineOpacity)),
|
||||
lineWidth: 0.5)
|
||||
|
||||
// Channel separator (between channels, not after last)
|
||||
if ch < count - 1 {
|
||||
let sepY: CGFloat = rowH * CGFloat(ch + 1)
|
||||
var sep: Path = Path()
|
||||
sep.move(to: CGPoint(x: 0, y: sepY))
|
||||
sep.addLine(to: CGPoint(x: size.width, y: sepY))
|
||||
ctx.stroke(sep, with: .color(.white.opacity(LyrebirdScopeView.separatorOpacity)),
|
||||
lineWidth: 0.5)
|
||||
}
|
||||
|
||||
guard samples.count > 1 else { continue }
|
||||
let color: Color = LyrebirdScopeView.channelColors[ch % LyrebirdScopeView.channelColors.count]
|
||||
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
|
||||
var path: Path = Path()
|
||||
for (i, sample) in samples.enumerated() {
|
||||
let x: CGFloat = CGFloat(i) * xStep
|
||||
let y: CGFloat = midY - CGFloat(sample) * halfH
|
||||
if i == 0 { path.move(to: CGPoint(x: x, y: y)) }
|
||||
else { path.addLine(to: CGPoint(x: x, y: y)) }
|
||||
}
|
||||
ctx.stroke(path, with: .color(color), lineWidth: 1.0)
|
||||
}
|
||||
}
|
||||
.background(LyrebirdScopeView.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
channels = capture.snapshot()
|
||||
try? await Task.sleep(nanoseconds: LyrebirdScopeView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func _drawBackground(
|
||||
ctx: GraphicsContext,
|
||||
size: CGSize
|
||||
) {
|
||||
ctx.fill(Path(CGRect(origin: .zero, size: size)),
|
||||
with: .color(LyrebirdScopeView.backgroundColor))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
// LyrebirdSpectrumView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A real-time spectrum analyzer / spectrogram view.
|
||||
///
|
||||
/// Polls `SpectrumCapture` at ~30 Hz and renders magnitude data using `Canvas`.
|
||||
///
|
||||
/// **Spectrum mode** (`waterfallRows == 0`, default):
|
||||
/// Draws the current magnitude frame as a line plot. The X axis uses a logarithmic
|
||||
/// frequency scale from `minHz` to `maxHz`. The Y axis shows magnitude in dB from
|
||||
/// `floorDB` to `ceilDB`, with high-magnitude (loud) signals drawn near the top.
|
||||
///
|
||||
/// **Waterfall mode** (`waterfallRows > 0`):
|
||||
/// Displays a scrolling spectrogram. Each row is one captured frame; new frames appear
|
||||
/// at the top and older frames scroll down. Frequency is on the X axis (log scale);
|
||||
/// time scrolls on the Y axis. Magnitude is encoded as color brightness on a
|
||||
/// black-to-green gradient.
|
||||
///
|
||||
/// ```swift
|
||||
/// // Spectrum only
|
||||
/// LyrebirdSpectrumView(capture: specCapture, sampleRate: 44100)
|
||||
/// .frame(height: 120)
|
||||
///
|
||||
/// // Waterfall spectrogram (80 history rows)
|
||||
/// LyrebirdSpectrumView(capture: specCapture, sampleRate: 44100, waterfallRows: 80)
|
||||
/// .frame(height: 200)
|
||||
/// ```
|
||||
public struct LyrebirdSpectrumView: View {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// The spectrum capture object to poll.
|
||||
public let capture: SpectrumCapture
|
||||
|
||||
/// Audio sample rate in Hz, used to map bin indices to frequencies.
|
||||
public let sampleRate: Double
|
||||
|
||||
/// Minimum displayed frequency in Hz. Default: 20 Hz.
|
||||
public let minHz: Double
|
||||
|
||||
/// Maximum displayed frequency in Hz. Default: 20 000 Hz.
|
||||
public let maxHz: Double
|
||||
|
||||
/// Lower dB bound for the magnitude axis. Default: −80 dB.
|
||||
public let floorDB: Double
|
||||
|
||||
/// Upper dB bound for the magnitude axis. Default: 0 dB.
|
||||
public let ceilDB: Double
|
||||
|
||||
/// Number of history rows shown in waterfall mode.
|
||||
/// `0` (default) selects spectrum-line mode; any positive value selects waterfall mode.
|
||||
public let waterfallRows: Int
|
||||
|
||||
// MARK: - State
|
||||
|
||||
@State private var magnitudes: [Float] = []
|
||||
@State private var history: [[Float]] = []
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
|
||||
private static let backgroundColor: Color = Color(white: 0.08)
|
||||
private static let spectrumColor: Color = Color.green
|
||||
private static let spectrumLineWidth: CGFloat = 1.0
|
||||
private static let zeroLineOpacity: Double = 0.2
|
||||
/// Prevent log(0) in dB conversion.
|
||||
private static let magnitudeFloor: Double = 1e-10
|
||||
private static let waterfallHue: Double = 0.33 // green
|
||||
private static let waterfallSaturationBoost: Double = 1.5
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - capture: The `SpectrumCapture` registered as a processor on a `SpectralChain.Audio`.
|
||||
/// - sampleRate: Audio sample rate in Hz. Used to compute bin-to-frequency mapping.
|
||||
/// - minHz: Minimum frequency displayed on the X axis. Default: 20 Hz.
|
||||
/// - maxHz: Maximum frequency displayed on the X axis. Default: 20 000 Hz.
|
||||
/// - floorDB: Minimum dB level displayed on the Y axis. Default: −80 dB.
|
||||
/// - ceilDB: Maximum dB level displayed on the Y axis. Default: 0 dB.
|
||||
/// - waterfallRows: Number of waterfall history rows. `0` = spectrum line, `> 0` = waterfall spectrogram.
|
||||
public init(
|
||||
capture: SpectrumCapture,
|
||||
sampleRate: Double,
|
||||
minHz: Double = 20,
|
||||
maxHz: Double = 20_000,
|
||||
floorDB: Double = -80,
|
||||
ceilDB: Double = 0,
|
||||
waterfallRows: Int = 0
|
||||
) {
|
||||
precondition(sampleRate > 0,
|
||||
"LyrebirdSpectrumView: sampleRate must be > 0, got \(sampleRate)")
|
||||
precondition(minHz > 0 && minHz < maxHz,
|
||||
"LyrebirdSpectrumView: minHz must be > 0 and < maxHz")
|
||||
precondition(floorDB < ceilDB,
|
||||
"LyrebirdSpectrumView: floorDB must be < ceilDB")
|
||||
self.capture = capture
|
||||
self.sampleRate = sampleRate
|
||||
self.minHz = minHz
|
||||
self.maxHz = maxHz
|
||||
self.floorDB = floorDB
|
||||
self.ceilDB = ceilDB
|
||||
self.waterfallRows = max(0, waterfallRows)
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
Canvas { ctx, size in
|
||||
ctx.fill(
|
||||
Path(CGRect(origin: .zero, size: size)),
|
||||
with: .color(Self.backgroundColor)
|
||||
)
|
||||
guard magnitudes.count > 1 else { return }
|
||||
if waterfallRows > 0 {
|
||||
_drawWaterfall(ctx: ctx, size: size)
|
||||
} else {
|
||||
_drawSpectrum(ctx: ctx, size: size)
|
||||
}
|
||||
}
|
||||
.background(Self.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
let snap: [Float] = capture.snapshot()
|
||||
magnitudes = snap
|
||||
if waterfallRows > 0 {
|
||||
var h: [[Float]] = history
|
||||
h.insert(snap, at: 0)
|
||||
if h.count > waterfallRows { h.removeLast() }
|
||||
history = h
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: Self.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Spectrum line
|
||||
|
||||
private func _drawSpectrum(ctx: GraphicsContext, size: CGSize) {
|
||||
// Zero-dB guide line
|
||||
let zeroY: Double = size.height * (1.0 - _dbFrac(Float(1.0)))
|
||||
var guide: Path = Path()
|
||||
guide.move(to: CGPoint(x: 0, y: zeroY))
|
||||
guide.addLine(to: CGPoint(x: size.width, y: zeroY))
|
||||
ctx.stroke(guide,
|
||||
with: .color(.white.opacity(Self.zeroLineOpacity)),
|
||||
lineWidth: 0.5)
|
||||
|
||||
let halfSize: Int = capture.fftSize / 2
|
||||
var path: Path = Path()
|
||||
var started: Bool = false
|
||||
|
||||
for k: Int in 0...halfSize {
|
||||
guard k < magnitudes.count else { break }
|
||||
let xFrac: Double = _xFrac(bin: k)
|
||||
guard xFrac >= 0 && xFrac <= 1 else { continue }
|
||||
let x: Double = xFrac * size.width
|
||||
let y: CGFloat = size.height * (1.0 - _dbFrac(magnitudes[k]))
|
||||
let pt: CGPoint = CGPoint(x: x, y: y)
|
||||
if !started {
|
||||
path.move(to: pt)
|
||||
started = true
|
||||
} else {
|
||||
path.addLine(to: pt)
|
||||
}
|
||||
}
|
||||
ctx.stroke(path, with: .color(Self.spectrumColor), lineWidth: Self.spectrumLineWidth)
|
||||
}
|
||||
|
||||
// MARK: - Waterfall
|
||||
|
||||
private func _drawWaterfall(ctx: GraphicsContext, size: CGSize) {
|
||||
guard !history.isEmpty else { return }
|
||||
let rowH: CGFloat = size.height / CGFloat(waterfallRows)
|
||||
let halfSize: Int = capture.fftSize / 2
|
||||
// Number of horizontal pixel columns to iterate over.
|
||||
let cols: Int = max(1, Int(size.width))
|
||||
|
||||
for (rowIdx, rowMags) in history.enumerated() {
|
||||
guard rowIdx < waterfallRows else { break }
|
||||
let y: CGFloat = CGFloat(rowIdx) * rowH
|
||||
|
||||
var prevX: CGFloat = 0
|
||||
for col: Int in 0..<cols {
|
||||
let xFrac: Double = Double(col) / Double(cols)
|
||||
// Invert log scale: freq = minHz × (maxHz/minHz)^xFrac
|
||||
let freq: Double = minHz * pow(maxHz / minHz, xFrac)
|
||||
let bin: Int = min(halfSize, Int(freq * Double(capture.fftSize) / sampleRate))
|
||||
guard bin >= 0 && bin < rowMags.count else { continue }
|
||||
|
||||
let x: CGFloat = CGFloat(col)
|
||||
let dbFrac: Double = _dbFrac(rowMags[bin])
|
||||
if x > prevX {
|
||||
let brightness: CGFloat = CGFloat(dbFrac)
|
||||
let color: Color = Color(
|
||||
hue: Self.waterfallHue,
|
||||
saturation: min(1.0, brightness * Self.waterfallSaturationBoost),
|
||||
brightness: brightness
|
||||
)
|
||||
ctx.fill(
|
||||
Path(CGRect(x: prevX, y: y, width: x - prevX, height: rowH)),
|
||||
with: .color(color)
|
||||
)
|
||||
}
|
||||
prevX = x
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Coordinate helpers
|
||||
|
||||
/// Normalized X position [0, 1] for `bin` on a log-frequency axis.
|
||||
/// Returns values outside [0, 1] for bins outside [minHz, maxHz].
|
||||
private func _xFrac(bin: Int) -> Double {
|
||||
let freq: Double = Double(bin) * sampleRate / Double(capture.fftSize)
|
||||
guard freq > 0 else { return -1 }
|
||||
return log(freq / minHz) / log(maxHz / minHz)
|
||||
}
|
||||
|
||||
/// Normalized Y position [0, 1] for a linear magnitude value.
|
||||
/// 0 = `floorDB`, 1 = `ceilDB`.
|
||||
private func _dbFrac(_ mag: Float) -> Double {
|
||||
let db: Double = 20.0 * log10(max(Self.magnitudeFloor, Double(mag)))
|
||||
return max(0, min(1, (db - floorDB) / (ceilDB - floorDB)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// LyrebirdStatusView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A compact view that displays real-time CPU usage statistics for a `SynthesisEngine`.
|
||||
///
|
||||
/// Embed in any SwiftUI hierarchy to monitor average and peak CPU load. The view polls the
|
||||
/// engine at 10 Hz and updates automatically while visible.
|
||||
///
|
||||
/// ```swift
|
||||
/// LyrebirdStatusView(engine: engine)
|
||||
/// ```
|
||||
///
|
||||
/// Values are expressed as a fraction of one block duration: `0.0` = idle, `1.0` = full block
|
||||
/// consumed, `> 1.0` = over budget (xruns likely). The bars are color-coded: green below 50 %,
|
||||
/// yellow 50–80 %, red above 80 %. Peak resets automatically every 5 s (engine default).
|
||||
public struct LyrebirdStatusView: View {
|
||||
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var averageCPU: Double = 0.0
|
||||
@State private var peakCPU: Double = 0.0
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 100_000_000 // 100 ms → 10 Hz
|
||||
|
||||
public init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
CPURow(label: "CPU Avg", value: averageCPU)
|
||||
CPURow(label: "CPU Peak", value: peakCPU)
|
||||
}
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
averageCPU = engine.averageCPU
|
||||
peakCPU = engine.peakCPU
|
||||
try? await Task.sleep(nanoseconds: LyrebirdStatusView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct CPURow: View {
|
||||
let label: String
|
||||
let value: Double // 0.0 = idle, 1.0 = full block, >1.0 = overload
|
||||
|
||||
private static let maxDisplayPercent: Double = 999.9
|
||||
private static let warningThreshold: Double = 0.5
|
||||
private static let criticalThreshold: Double = 0.8
|
||||
|
||||
private var displayPercent: Double { min(value * 100.0, CPURow.maxDisplayPercent) }
|
||||
|
||||
private var barColor: Color {
|
||||
switch value {
|
||||
case ..<CPURow.warningThreshold: return .green
|
||||
case ..<CPURow.criticalThreshold: return .yellow
|
||||
default: return .red
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(label)
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: 60, alignment: .leading)
|
||||
GeometryReader { geo in
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(Color.secondary.opacity(0.15))
|
||||
RoundedRectangle(cornerRadius: 2)
|
||||
.fill(barColor)
|
||||
.frame(width: geo.size.width * min(CGFloat(value), 1.0))
|
||||
.animation(.linear(duration: 0.1), value: value)
|
||||
}
|
||||
}
|
||||
.frame(height: 6)
|
||||
Text(String(format: "%.1f%%", displayPercent))
|
||||
.font(.caption.monospaced())
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: 46, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// LyrebirdSynthView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Auto-generated SwiftUI parameter grid for a `SynthesizerBase` subclass.
|
||||
///
|
||||
/// Walks the synth's `Mirror` hierarchy for `@UIParam` properties and renders
|
||||
/// one `ParameterKnob` per slot. Optional `metadata` (the same
|
||||
/// `[String: LyrebirdAUParameterInfo]` dictionary the AU subclass returns from
|
||||
/// `parameterMetadata()`) supplies the per-knob `range`.
|
||||
///
|
||||
/// **`@UIParam` only.** Slots declared with `@LiveParam` are skipped — they
|
||||
/// have no `@Observable` projected value and so cannot drive a SwiftUI knob
|
||||
/// without additional plumbing. If you want a slot to appear in the
|
||||
/// auto-generated UI, declare it as `@UIParam`. RT semantics are identical
|
||||
/// across both wrappers (both back onto an atomic store-and-ramp path).
|
||||
///
|
||||
/// **Usage from an AU view controller.** Inside a
|
||||
/// `LyrebirdAudioUnitViewController` subclass:
|
||||
///
|
||||
/// ```swift
|
||||
/// public override func viewDidLoad() {
|
||||
/// super.viewDidLoad()
|
||||
/// guard let au = audioUnit as? LyrebirdFMAudioUnit else { return }
|
||||
/// let host = NSHostingController(
|
||||
/// rootView: LyrebirdSynthView(
|
||||
/// synth: au.synthesizer,
|
||||
/// metadata: LyrebirdFMAudioUnit.parameterMetadata()
|
||||
/// )
|
||||
/// )
|
||||
/// addChild(host)
|
||||
/// view.addSubview(host.view)
|
||||
/// host.view.frame = view.bounds
|
||||
/// host.view.autoresizingMask = [.width, .height]
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// **Customising the layout.** The default lays out knobs in a wrap-around
|
||||
/// `LazyVGrid` with adaptive columns (minimum width 120 pt). For a hand-tuned
|
||||
/// view, do not use this view — assemble `ParameterKnob` instances directly,
|
||||
/// or use this view's `entries` static helper to discover the slots and
|
||||
/// build your own layout around it.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - synth: The `SynthesizerBase` instance to introspect. Walked via
|
||||
/// `Mirror` to discover `@UIParam` slots.
|
||||
/// - metadata: Optional per-parameter metadata keyed by property name —
|
||||
/// same dictionary the AU subclass returns from `parameterMetadata()`.
|
||||
/// Names absent from the dictionary fall back to
|
||||
/// `lyrebirdSynthViewDefaultMin...lyrebirdSynthViewDefaultMax`.
|
||||
/// - entries: Alternative init that takes a pre-built list of discovered
|
||||
/// entries (e.g. produced by a custom Mirror walk). Bypasses the
|
||||
/// `synth` + `metadata` discovery path.
|
||||
public struct LyrebirdSynthView: View {
|
||||
|
||||
public let entries: [Entry]
|
||||
|
||||
/// - Parameters:
|
||||
/// - synth: The `SynthesizerBase` instance to introspect.
|
||||
/// - metadata: Optional per-parameter metadata keyed by property name.
|
||||
public init(
|
||||
synth: SynthesizerBase,
|
||||
metadata: [String: LyrebirdAUParameterInfo] = [:]
|
||||
) {
|
||||
self.entries = LyrebirdSynthView.discover(synth: synth, metadata: metadata)
|
||||
}
|
||||
|
||||
/// - Parameter entries: Pre-built list of discovered entries.
|
||||
public init(entries: [Entry]) {
|
||||
self.entries = entries
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
ScrollView {
|
||||
LazyVGrid(
|
||||
columns: [GridItem(.adaptive(minimum: lyrebirdSynthViewColumnMinWidth),
|
||||
spacing: lyrebirdSynthViewGridSpacing)],
|
||||
spacing: lyrebirdSynthViewGridSpacing
|
||||
) {
|
||||
ForEach(entries) { entry in
|
||||
VStack(spacing: lyrebirdSynthViewItemSpacing) {
|
||||
ParameterKnob(
|
||||
entry.displayName,
|
||||
node: entry.node,
|
||||
range: entry.range
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered `@UIParam` slot, paired with its display name + range.
|
||||
public struct Entry: Identifiable {
|
||||
public let id: String
|
||||
public let propertyName: String
|
||||
public let displayName: String
|
||||
public let node: UIParamNode
|
||||
public let range: ClosedRange<Double>
|
||||
|
||||
public init(
|
||||
propertyName: String,
|
||||
displayName: String,
|
||||
node: UIParamNode,
|
||||
range: ClosedRange<Double>
|
||||
) {
|
||||
self.id = propertyName
|
||||
self.propertyName = propertyName
|
||||
self.displayName = displayName
|
||||
self.node = node
|
||||
self.range = range
|
||||
}
|
||||
}
|
||||
|
||||
/// Walks the synth's `Mirror` (with superclass chain) looking for `@UIParam`
|
||||
/// properties and emits one ``Entry`` per slot. Slot order matches the
|
||||
/// `Mirror` walk used by `SynthesizerBase._autoRegisterLiveParams()` and
|
||||
/// `LyrebirdAUParameterMapping.discoverLiveParameters(of:)`.
|
||||
public static func discover(
|
||||
synth: SynthesizerBase,
|
||||
metadata: [String: LyrebirdAUParameterInfo] = [:]
|
||||
) -> [Entry] {
|
||||
var entries: [Entry] = []
|
||||
var mirrors: [Mirror] = []
|
||||
var current: Mirror? = Mirror(reflecting: synth)
|
||||
while let m: Mirror = current {
|
||||
mirrors.append(m)
|
||||
current = m.superclassMirror
|
||||
}
|
||||
for mirror: Mirror in mirrors.reversed() {
|
||||
for child: Mirror.Child in mirror.children {
|
||||
guard let label: String = child.label else { continue }
|
||||
let key: String = label.hasPrefix("_") ? String(label.dropFirst()) : label
|
||||
guard let wrapper: any LiveParameterWrapper = child.value as? LiveParameterWrapper else { continue }
|
||||
guard let node: UIParamNode = wrapper._projectedAsValidInput as? UIParamNode else { continue }
|
||||
let info: LyrebirdAUParameterInfo? = metadata[key]
|
||||
let lo: Double = info.map { Double($0.minValue) } ?? lyrebirdSynthViewDefaultMin
|
||||
let hi: Double = info.map { Double($0.maxValue) } ?? lyrebirdSynthViewDefaultMax
|
||||
let range: ClosedRange<Double> = lo...hi
|
||||
let displayName: String = info?.displayName ?? key
|
||||
entries.append(Entry(
|
||||
propertyName: key,
|
||||
displayName: displayName,
|
||||
node: node,
|
||||
range: range
|
||||
))
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimum column width (points) for ``LyrebirdSynthView``'s adaptive grid.
|
||||
public let lyrebirdSynthViewColumnMinWidth: Double = 120
|
||||
|
||||
/// Spacing (points) between grid items, both horizontally and vertically.
|
||||
public let lyrebirdSynthViewGridSpacing: Double = 16
|
||||
|
||||
/// Spacing (points) between elements inside each grid item's `VStack`.
|
||||
public let lyrebirdSynthViewItemSpacing: Double = 6
|
||||
|
||||
/// Default lower bound used when `parameterMetadata` does not supply a range.
|
||||
/// Matches the conventional `[0, 1]` LFO / normalised parameter range —
|
||||
/// safer than `lyrebirdAUParameterDefaultBound` (`±1e10`) for UI knobs, which
|
||||
/// would be unusable.
|
||||
public let lyrebirdSynthViewDefaultMin: Double = 0
|
||||
|
||||
/// Default upper bound used when `parameterMetadata` does not supply a range.
|
||||
public let lyrebirdSynthViewDefaultMax: Double = 1
|
||||
@@ -0,0 +1,288 @@
|
||||
# GUI System
|
||||
|
||||
@Metadata {
|
||||
@PageKind(article)
|
||||
}
|
||||
|
||||
Native macOS SwiftUI controls that bind directly to `SynthesizerBase` parameters.
|
||||
|
||||
## Core Concept: @UIParam
|
||||
|
||||
A `struct` property wrapper that is simultaneously:
|
||||
|
||||
1. A `ValidGeneratorInput` (via its projected `UIParamNode`) — wire `$paramName` directly
|
||||
into the audio graph in `build()`.
|
||||
2. An `@Observable` value — SwiftUI views bind to the node and redraw automatically when the
|
||||
value changes.
|
||||
3. RT-safe — the audio render callback reads via a lock-free `Atomic<UInt64>` load; the main
|
||||
thread writes via a releasing atomic store. No locks, no queue drain.
|
||||
|
||||
```swift
|
||||
import LyrebirdUI
|
||||
|
||||
class MySynth: SynthesizerBase {
|
||||
@UIParam var amplitude: LyrebirdFloat = 0.5
|
||||
@UIParam var frequency: LyrebirdFloat = 440.0
|
||||
@UIParam var pan: LyrebirdFloat = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Projected Value
|
||||
|
||||
`$paramName` returns a `UIParamNode` — an `@Observable` class that conforms to
|
||||
`ValidGeneratorInput`. Pass it to UI controls:
|
||||
|
||||
```swift
|
||||
ParameterSlider("Freq", node: synth.$frequency, range: 20...20000)
|
||||
ParameterKnob("Pan", node: synth.$pan, range: -1...1)
|
||||
```
|
||||
|
||||
### Reading and Writing from Code
|
||||
|
||||
```swift
|
||||
synth.amplitude = 0.2 // atomic store → RT thread picks up next block
|
||||
synth.frequency = 880.0 // UI slider updates automatically via @Observable
|
||||
synth.pan = -0.5 // move left
|
||||
```
|
||||
|
||||
### By-name updates (OSC / MIDI / REPL)
|
||||
|
||||
`@UIParam` properties are auto-registered by `SynthesizerBase` under their property name
|
||||
(with the leading `_` of property-wrapper backing storage stripped). Both typed direct
|
||||
writes and by-name updates target the same atomic:
|
||||
|
||||
```swift
|
||||
synth.frequency = 880.0 // typed direct write
|
||||
try? synth.updateParameter("frequency", value: 880.0) // by-name (e.g. from OSC)
|
||||
```
|
||||
|
||||
No `declareParameter` call is needed.
|
||||
|
||||
## Opening a Control Window
|
||||
|
||||
`LyrebirdWindow` is a `@MainActor` class that wraps `NSWindow` + `NSHostingController`.
|
||||
|
||||
```swift
|
||||
let window = LyrebirdWindow(title: "My Synth", width: 400, height: 300)
|
||||
window.open {
|
||||
VStack {
|
||||
ParameterSlider("Amplitude", node: synth.$amplitude, range: 0...1)
|
||||
ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
|
||||
ParameterButton("Stop") { engine.remove(synth) }
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
|
||||
// Later
|
||||
window.close()
|
||||
```
|
||||
|
||||
`open` can be called again on the same instance to replace the content. Full SwiftUI is
|
||||
available inside the closure — mix Lyrebird controls with any standard SwiftUI views.
|
||||
|
||||
### LyrebirdWindow API
|
||||
|
||||
```swift
|
||||
LyrebirdWindow(title: String = "Lyrebird", width: CGFloat = 400, height: CGFloat = 300)
|
||||
func open<Content: View>(@ViewBuilder content: () -> Content)
|
||||
func close()
|
||||
```
|
||||
|
||||
## Built-In Controls
|
||||
|
||||
All controls accept a `UIParamNode` (the `$paramName` projected value). Changes are
|
||||
bidirectional: UI → audio (atomic store) and code → UI (`@Observable`).
|
||||
|
||||
### ParameterSlider
|
||||
|
||||
```swift
|
||||
ParameterSlider("Amplitude", node: synth.$amplitude, range: 0.0...1.0)
|
||||
ParameterSlider("Cutoff", node: synth.$cutoff, range: 20.0...20000.0, taper: .exponential)
|
||||
```
|
||||
|
||||
**Taper options:** `.linear` (default), `.exponential` — exponential maps equal visual
|
||||
steps to equal ratios, suited to frequency and time parameters.
|
||||
|
||||
### ParameterButton
|
||||
|
||||
```swift
|
||||
// Momentary — runs closure on press
|
||||
ParameterButton("Trigger") { synth.trigger() }
|
||||
|
||||
// Toggle — flips node between 0.0 and 1.0 on each press
|
||||
ParameterButton("Mute", node: synth.$muted, style: .toggle)
|
||||
```
|
||||
|
||||
The toggle renders with an accent-colour highlight when the node value ≥ 0.5.
|
||||
|
||||
### ParameterKnob
|
||||
|
||||
Rotary dial; drag vertically to change value. Equivalent in behaviour to `ParameterSlider`.
|
||||
|
||||
```swift
|
||||
ParameterKnob("Resonance", node: synth.$resonance, range: 0...1)
|
||||
ParameterKnob("Pan", node: synth.$pan, range: -1...1)
|
||||
```
|
||||
|
||||
### ParameterXY
|
||||
|
||||
Two-dimensional control pad for simultaneous X/Y parameter control.
|
||||
|
||||
```swift
|
||||
ParameterXY(
|
||||
xLabel: "Pan", xNode: synth.$pan, xRange: -1...1,
|
||||
yLabel: "Amplitude", yNode: synth.$amplitude, yRange: 0...1
|
||||
)
|
||||
```
|
||||
|
||||
### ParameterLabel
|
||||
|
||||
Read-only display that updates automatically via `@Observable`.
|
||||
|
||||
```swift
|
||||
ParameterLabel("Level", node: synth.$amplitude)
|
||||
ParameterLabel("Freq (Hz)", node: synth.$frequency, decimalPlaces: 1)
|
||||
```
|
||||
|
||||
## Engine Monitoring
|
||||
|
||||
### LyrebirdStatusView
|
||||
|
||||
Compact CPU load display. Polls `SynthesisEngine.averageCPU` and `peakCPU` at 10 Hz.
|
||||
Renders two color-coded bar rows (green < 50 %, yellow 50–80 %, red ≥ 80 %).
|
||||
|
||||
```swift
|
||||
LyrebirdStatusView(engine: engine)
|
||||
```
|
||||
|
||||
Takes a direct `SynthesisEngine` reference — no `@UIParam` needed. Peak resets automatically
|
||||
every 5 s; call `engine.resetPeakCPU()` for an immediate manual reset.
|
||||
|
||||
### LyrebirdScopeView
|
||||
|
||||
Real-time dual-channel oscilloscope. Requires a `ScopeCapture` tap wired to the
|
||||
engine before `start()`.
|
||||
|
||||
```swift
|
||||
// 1. Create and attach the capture tap
|
||||
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scope // must be set before engine.start()
|
||||
try engine.start()
|
||||
|
||||
// 2. Embed the view
|
||||
LyrebirdScopeView(capture: scope)
|
||||
.frame(height: 120)
|
||||
```
|
||||
|
||||
Channels are stacked vertically: channel 0 (left, bus 0) in cyan, channel 1 (right, bus 1)
|
||||
in orange. Each channel has a zero-line guide. Polls at ~30 Hz via `.task`.
|
||||
|
||||
`bufferSize` sets how many samples are displayed per frame. At 44100 Hz / 512 blockSize,
|
||||
`bufferSize: 2048` shows ~46 ms of history. `bufferSize` must be ≥ `engine.blockSize`.
|
||||
|
||||
## Threading Model
|
||||
|
||||
```
|
||||
UI gesture / code assignment (main thread)
|
||||
→ synth.amplitude = 0.2
|
||||
→ UIParamNode.update(0.2)
|
||||
→ @Observable value = 0.2 (SwiftUI re-renders on next run loop)
|
||||
→ Atomic<UInt64>.store(bitPattern, ordering: .releasing)
|
||||
|
||||
RT audio thread (render callback)
|
||||
→ UIParamNode.calculatedSamples(graph:count:)
|
||||
→ Atomic<UInt64>.load(ordering: .acquiring) (lock-free, no allocation)
|
||||
→ linear ramp from previous value to new target
|
||||
→ fills pre-allocated _result buffer in-place
|
||||
→ ScopeCapture.write(audioBuses:count:) [if scopeTap set]
|
||||
→ assign(from:) via UnsafeMutableBufferPointer — no allocation, no ARC
|
||||
|
||||
Main thread (30 Hz poll)
|
||||
→ ScopeCapture.snapshot()
|
||||
→ deep copy via withUnsafeBufferPointer { Array($0) }
|
||||
→ allocates on main thread only
|
||||
```
|
||||
|
||||
The RT thread never accesses `UIParamNode.value` or the `@Observable` registrar — it reads
|
||||
only the atomic bit pattern. The main thread never touches `_result` or `_previousValue`.
|
||||
These are disjoint fields; `@unchecked Sendable` is correct and safe.
|
||||
|
||||
## Full Example
|
||||
|
||||
```swift
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class SineTone: SynthesizerBase {
|
||||
@UIParam var frequency: LyrebirdFloat = 440.0
|
||||
@UIParam var amplitude: LyrebirdFloat = 0.25
|
||||
@UIParam var pan: LyrebirdFloat = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||
}
|
||||
}
|
||||
|
||||
@Observable
|
||||
final class SineController {
|
||||
let engine: SynthesisEngine
|
||||
let synth = SineTone()
|
||||
let scope: ScopeCapture
|
||||
private(set) var isPlaying = false
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scope
|
||||
}
|
||||
|
||||
func toggle() {
|
||||
isPlaying ? engine.remove(synth) : engine.add(synth)
|
||||
isPlaying.toggle()
|
||||
}
|
||||
}
|
||||
|
||||
struct SineView: View {
|
||||
let controller: SineController
|
||||
|
||||
var body: some View {
|
||||
VStack(spacing: 20) {
|
||||
HStack {
|
||||
Text("Sine Tone").font(.headline)
|
||||
Spacer()
|
||||
Button(controller.isPlaying ? "Stop" : "Start") { controller.toggle() }
|
||||
.buttonStyle(.bordered)
|
||||
.tint(controller.isPlaying ? .red : .green)
|
||||
}
|
||||
ParameterSlider("Frequency", node: controller.synth.$frequency, range: 440...880)
|
||||
HStack(spacing: 24) {
|
||||
ParameterKnob("Amplitude", node: controller.synth.$amplitude, range: 0...1)
|
||||
ParameterKnob("Pan", node: controller.synth.$pan, range: -1...1)
|
||||
}
|
||||
Divider()
|
||||
LyrebirdStatusView(engine: controller.engine)
|
||||
Divider()
|
||||
LyrebirdScopeView(capture: controller.scope)
|
||||
.frame(height: 120)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
// AppDelegate setup
|
||||
let scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scope
|
||||
try engine.start()
|
||||
|
||||
let controller = SineController(engine: engine)
|
||||
let window = LyrebirdWindow(title: "Sine Tone", width: 360, height: 480)
|
||||
window.open { SineView(controller: controller) }
|
||||
```
|
||||
@@ -0,0 +1,76 @@
|
||||
# ``LyrebirdUI``
|
||||
|
||||
Native macOS controls that bind directly to Lyrebird synthesizer parameters.
|
||||
|
||||
## Overview
|
||||
|
||||
`LyrebirdUI` provides SwiftUI controls that bind to `SynthesizerBase` parameters through
|
||||
the `@UIParam` property wrapper. Changes flow to the RT audio thread via a lock-free
|
||||
atomic store — no queues, no locks, no latency. The same path used by code is used by UI,
|
||||
so any parameter controllable from code is automatically controllable from a GUI control.
|
||||
|
||||
```swift
|
||||
import LyrebirdUI
|
||||
|
||||
class MySynth: SynthesizerBase {
|
||||
@UIParam var frequency: LyrebirdFloat = 440.0
|
||||
@UIParam var amplitude: LyrebirdFloat = 0.5
|
||||
@UIParam var pan: LyrebirdFloat = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||
}
|
||||
}
|
||||
|
||||
// Wire scope tap before start
|
||||
let scope = ScopeCapture(buses: [0, 1])
|
||||
engine.scopeTap = scope
|
||||
try engine.start()
|
||||
|
||||
let window = LyrebirdWindow(title: "My Synth", width: 400, height: 360)
|
||||
window.open {
|
||||
VStack {
|
||||
ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000, taper: .exponential)
|
||||
ParameterKnob("Amplitude", node: synth.$amplitude, range: 0...1)
|
||||
ParameterKnob("Pan", node: synth.$pan, range: -1...1)
|
||||
Divider()
|
||||
LyrebirdStatusView(engine: engine)
|
||||
LyrebirdScopeView(capture: scope).frame(height: 120)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
```
|
||||
|
||||
The core `Lyrebird` module has no UI dependency — `LyrebirdUI` is imported only by targets
|
||||
that need GUI windows.
|
||||
|
||||
## Topics
|
||||
|
||||
### Parameter Binding
|
||||
|
||||
- <doc:GUISystem>
|
||||
|
||||
### Engine Monitoring
|
||||
|
||||
- ``LyrebirdStatusView``
|
||||
- ``LyrebirdEngineStatusView``
|
||||
- ``LyrebirdScopeView``
|
||||
|
||||
### Performance Control
|
||||
|
||||
- ``LyrebirdEventListView``
|
||||
- ``LyrebirdProcessView``
|
||||
- ``LyrebirdRunningProcessesView``
|
||||
- ``LyrebirdEventListPerformanceView``
|
||||
|
||||
### Visualization
|
||||
|
||||
- ``LyrebirdEnvelopeView``
|
||||
- ``LyrebirdScatterView``
|
||||
|
||||
### Live Coding
|
||||
|
||||
The live-coding scratchpad (``LyrebirdScratchView`` / ``LyrebirdScratchModel``) lives
|
||||
in the separate `LyrebirdLiveCompileUI` module (sub-package `LiveCompile/`). See the
|
||||
`LyrebirdLiveCompileUI` docc archive for the `LiveCoding` article.
|
||||
@@ -0,0 +1,161 @@
|
||||
// LyrebirdWindow.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// LyrebirdWindow — a native macOS window hosting SwiftUI content.
|
||||
///
|
||||
/// Opens an `NSWindow` backed by an `NSHostingController`. Full SwiftUI is available
|
||||
/// inside the content closure — mix Lyrebird controls with any standard SwiftUI views.
|
||||
///
|
||||
/// Works identically from the REPL and from compiled projects.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdUI
|
||||
///
|
||||
/// let w = LyrebirdWindow(title: "My Synth", width: 400, height: 300)
|
||||
/// w.open {
|
||||
/// VStack {
|
||||
/// ParameterSlider("Amplitude", node: synth.$amplitude, range: 0...1)
|
||||
/// ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
|
||||
/// ParameterButton("Free") { engine.rootGroup.remove(synth) }
|
||||
/// }
|
||||
/// .padding()
|
||||
/// }
|
||||
///
|
||||
/// // Later...
|
||||
/// w.close()
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// All methods are `@MainActor`-isolated — `NSWindow` creation and AppKit mutations must
|
||||
/// happen on the main thread. Call `open` and `close` from the main thread or from a
|
||||
/// `@MainActor` context. In async code, use `await MainActor.run { w.open { ... } }`.
|
||||
@MainActor
|
||||
public final class LyrebirdWindow {
|
||||
|
||||
/// Internal `NSWindowDelegate` that nils out the parent's window reference when
|
||||
/// AppKit closes the window (e.g. user clicks the red close button). `NSWindow`
|
||||
/// defaults to `isReleasedWhenClosed = true`, so without this bookkeeping the
|
||||
/// stored Swift reference becomes a dangling pointer.
|
||||
private final class Delegate: NSObject, NSWindowDelegate {
|
||||
weak var owner: LyrebirdWindow?
|
||||
func windowWillClose(_ notification: Notification) {
|
||||
owner?.window = nil
|
||||
owner?.hostingController = nil
|
||||
owner?.delegate = nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// Window title bar text.
|
||||
public let title: String
|
||||
|
||||
/// Initial window width in points.
|
||||
public let width: CGFloat
|
||||
|
||||
/// Initial window height in points.
|
||||
public let height: CGFloat
|
||||
|
||||
// MARK: - Private state
|
||||
|
||||
private var window: NSWindow?
|
||||
private var hostingController: NSHostingController<AnyView>?
|
||||
private var delegate: Delegate?
|
||||
|
||||
// MARK: - Underlying AppKit window
|
||||
|
||||
/// The underlying `NSWindow`, available after `open(content:)` has been called.
|
||||
/// Use sparingly — exposed for callers that need AppKit-level configuration
|
||||
/// (custom origin, level, collection behavior, etc.) that the wrapper does not.
|
||||
public var nsWindow: NSWindow? { window }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a `LyrebirdWindow` with the given display properties.
|
||||
///
|
||||
/// The window is not shown until `open(content:)` is called.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - title: Text shown in the window's title bar.
|
||||
/// - width: Initial window width (default 400 pt).
|
||||
/// - height: Initial window height (default 300 pt).
|
||||
public init(
|
||||
title: String = "Lyrebird",
|
||||
width: CGFloat = 400,
|
||||
height: CGFloat = 300
|
||||
) {
|
||||
self.title = title
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
|
||||
// MARK: - Open
|
||||
|
||||
/// Opens the window and displays the provided SwiftUI content.
|
||||
///
|
||||
/// If a window is already open for this instance, it is closed and replaced with a
|
||||
/// new one hosting the updated content.
|
||||
///
|
||||
/// - Parameter content: A `@ViewBuilder` closure returning any SwiftUI `View`.
|
||||
public func open<Content: View>(@ViewBuilder content: () -> Content) {
|
||||
// Close any existing window before opening a new one.
|
||||
closeWindow()
|
||||
|
||||
let controller: NSHostingController<AnyView> = NSHostingController(rootView: AnyView(content()))
|
||||
let initialSize: CGSize = CGSize(width: width, height: height)
|
||||
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
)
|
||||
// NSWindow defaults to releasing itself on close — that would leave the
|
||||
// stored `self.window` pointing at freed memory after the user clicks the
|
||||
// red close button. Keep ownership in Swift; the delegate nils the ref.
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = title
|
||||
win.contentViewController = controller
|
||||
win.center()
|
||||
|
||||
let del: Delegate = Delegate()
|
||||
del.owner = self
|
||||
win.delegate = del
|
||||
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
|
||||
self.window = win
|
||||
self.hostingController = controller
|
||||
self.delegate = del
|
||||
}
|
||||
|
||||
// MARK: - Close
|
||||
|
||||
/// Closes and releases the window.
|
||||
public func close() {
|
||||
closeWindow()
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func closeWindow() {
|
||||
// Detach delegate first so `windowWillClose` does not re-enter and nil
|
||||
// refs mid-teardown.
|
||||
window?.delegate = nil
|
||||
window?.close()
|
||||
window = nil
|
||||
hostingController = nil
|
||||
delegate = nil
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,163 @@
|
||||
// MouseTracker.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import Synchronization
|
||||
import LyrebirdSynth
|
||||
|
||||
/// macOS `MouseInputBridge` conformer driven by AppKit `NSEvent` global monitors.
|
||||
///
|
||||
/// Tracks mouse position and button state on the main thread, exposing the values via
|
||||
/// lock-free `Synchronization.Atomic<Double>` reads suitable for the audio render thread.
|
||||
///
|
||||
/// Mouse position is normalised to `[0, 1]` against the main screen bounds:
|
||||
/// - `x` = 0 (left edge) … 1 (right edge)
|
||||
/// - `y` = 0 (bottom edge) … 1 (top edge) — screen Y is inverted from AppKit's coords
|
||||
/// - `button` = 0.0 (released) or 1.0 (left button held)
|
||||
///
|
||||
/// Install once at app startup so `Mouse.X.Control()` / `Mouse.Y.Control()` /
|
||||
/// `Mouse.Click.Control()` generators read live values:
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdSynth
|
||||
/// import LyrebirdUI
|
||||
///
|
||||
/// MouseTracker.installShared()
|
||||
/// ```
|
||||
///
|
||||
/// Without this call the generators output the no-op default constants from
|
||||
/// `Lyrebird.MouseInputBridge`.
|
||||
public final class MouseTracker: MouseInputBridge, @unchecked Sendable {
|
||||
// Sendable invariant: `_x`, `_y`, `_button`, and `_monitorsInstalled` are immutable
|
||||
// `Atomic`s — all reads/writes lock-free. Monitor token vars are written once on the
|
||||
// main thread via the dispatched `_installMonitors()` and never read after install
|
||||
// (kept only to retain the monitor-handler closures for the process lifetime).
|
||||
|
||||
/// Installs `MouseTracker.shared` as the active `MouseInput` bridge AND triggers
|
||||
/// the one-time `NSEvent` global-monitor install on the main thread.
|
||||
///
|
||||
/// Must be called from the main thread — traps in debug builds otherwise. Off-main
|
||||
/// callers would register the bridge synchronously while the monitor install runs
|
||||
/// in a deferred main-queue dispatch, leading to a window where `Mouse.*.Control`
|
||||
/// generators read the 0.5/0.5/0.0 init values until the dispatch fires.
|
||||
///
|
||||
/// Idempotent: both sides are gated by the `_monitorsInstalled` atomic CAS, so
|
||||
/// repeat calls are a pure no-op (no retain churn, no extra `dispatch_async`).
|
||||
/// Subject to the engine-stopped invariant documented on `MouseInput.install(_:)`.
|
||||
public static func installShared() {
|
||||
assert(Thread.isMainThread,
|
||||
"MouseTracker.installShared() must be called from the main thread")
|
||||
shared._installMonitorsIfNeeded()
|
||||
}
|
||||
|
||||
/// Process-wide `MouseTracker` instance. Touching this property does NOT install
|
||||
/// `NSEvent` monitors — call `installShared()` to wire monitors AND register as
|
||||
/// the `MouseInput` bridge.
|
||||
public static let shared: MouseTracker = MouseTracker()
|
||||
|
||||
// MARK: - Atomic state (RT-readable without locks)
|
||||
|
||||
private let _x: Atomic<Double>
|
||||
private let _y: Atomic<Double>
|
||||
private let _button: Atomic<Double>
|
||||
|
||||
// MARK: - NSEvent monitor tokens
|
||||
//
|
||||
// `Any?` storage that exists solely to retain the closure registered with
|
||||
// `NSEvent.addGlobalMonitorForEvents` — the API returns an opaque token whose
|
||||
// lifetime owns the handler closure. Written once from the main thread via the
|
||||
// `_installMonitorsOnMain` dispatch and never read afterwards (no `removeMonitor`
|
||||
// path because the singleton is process-lifetime).
|
||||
|
||||
private var _moveMonitorToken: Any?
|
||||
private var _downMonitorToken: Any?
|
||||
private var _upMonitorToken: Any?
|
||||
private let _monitorsInstalled: Atomic<Bool> = Atomic<Bool>(false)
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Allocates the atomic state slots. Does not install `NSEvent` monitors —
|
||||
/// `installShared()` does that.
|
||||
public override init() {
|
||||
_x = Atomic(mouseTrackerInitialPosition)
|
||||
_y = Atomic(mouseTrackerInitialPosition)
|
||||
_button = Atomic(mouseButtonReleased)
|
||||
super.init()
|
||||
}
|
||||
|
||||
// No `deinit`: `shared` retains the singleton for the process lifetime, so the
|
||||
// installed `NSEvent` monitors are released only at process exit. There is no
|
||||
// public init path that would create a second tracker to dispose.
|
||||
|
||||
// MARK: - MouseInputBridge overrides
|
||||
|
||||
public override var x: Double { _x.load(ordering: .relaxed) }
|
||||
public override var y: Double { _y.load(ordering: .relaxed) }
|
||||
public override var button: Double { _button.load(ordering: .relaxed) }
|
||||
|
||||
// MARK: - Monitor installation
|
||||
|
||||
/// Installs `NSEvent` global monitors on the main thread AND registers `self` as
|
||||
/// the active `MouseInput` bridge. Idempotent via `_monitorsInstalled` atomic CAS —
|
||||
/// repeat calls are a pure no-op.
|
||||
private func _installMonitorsIfNeeded() {
|
||||
let (exchanged, _) = _monitorsInstalled.compareExchange(
|
||||
expected: false, desired: true, ordering: .acquiringAndReleasing)
|
||||
guard exchanged else { return }
|
||||
|
||||
MouseInput.install(self)
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?._installMonitorsOnMain()
|
||||
}
|
||||
}
|
||||
|
||||
private func _installMonitorsOnMain() {
|
||||
let moveMask: NSEvent.EventTypeMask = [.mouseMoved, .leftMouseDragged, .rightMouseDragged]
|
||||
|
||||
_moveMonitorToken = NSEvent.addGlobalMonitorForEvents(matching: moveMask) { [weak self] event in
|
||||
self?.handleMouseMove(event)
|
||||
}
|
||||
|
||||
_downMonitorToken = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { [weak self] _ in
|
||||
self?._button.store(mouseButtonPressed, ordering: .relaxed)
|
||||
}
|
||||
|
||||
_upMonitorToken = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp) { [weak self] _ in
|
||||
self?._button.store(mouseButtonReleased, ordering: .relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Event handling
|
||||
|
||||
private func handleMouseMove(_ event: NSEvent) {
|
||||
guard let screen: NSScreen = NSScreen.main else { return }
|
||||
let screenBounds: NSRect = screen.frame
|
||||
let screenWidth: CGFloat = screenBounds.width
|
||||
let screenHeight: CGFloat = screenBounds.height
|
||||
|
||||
guard screenWidth > 0, screenHeight > 0 else { return }
|
||||
|
||||
let screenX: CGFloat = event.locationInWindow.x - screenBounds.minX
|
||||
let screenY: CGFloat = event.locationInWindow.y - screenBounds.minY
|
||||
|
||||
let normX: Double = min(max(screenX / screenWidth, normalizedMin), normalizedMax)
|
||||
let normY: Double = min(max(screenY / screenHeight, normalizedMin), normalizedMax)
|
||||
|
||||
_x.store(normX, ordering: .relaxed)
|
||||
_y.store(normY, ordering: .relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - MouseTracker constants
|
||||
|
||||
private let mouseTrackerInitialPosition: Double = 0.5
|
||||
private let mouseButtonPressed: Double = 1.0
|
||||
private let mouseButtonReleased: Double = 0.0
|
||||
private let normalizedMin: Double = 0.0
|
||||
private let normalizedMax: Double = 1.0
|
||||
|
||||
#endif // os(macOS)
|
||||
@@ -0,0 +1,83 @@
|
||||
// UIParam.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// `@UIParam` — property wrapper for synthesizer parameters that need both:
|
||||
/// - SwiftUI binding: controls like `ParameterSlider` observe `$paramName` via `@Observable`.
|
||||
/// - RT-safe audio delivery: the render callback reads via a lock-free `Atomic<UInt64>` load.
|
||||
///
|
||||
/// ## When to use @UIParam vs @LiveParam
|
||||
///
|
||||
/// Use `@UIParam` (this type, in `LyrebirdUI`) when SwiftUI controls bind to the parameter.
|
||||
/// Use `@LiveParam` (in `Lyrebird`) when no UI is involved.
|
||||
///
|
||||
/// `@UIParam` is a strict superset of `@LiveParam`: identical RT thread behavior — the
|
||||
/// projected `UIParamNode` is a `ControlGenerator` that delivers a linearly-interpolated
|
||||
/// ramp from the previous block's value to the new atomic target — plus an `@Observable`
|
||||
/// `value` that drives SwiftUI re-renders.
|
||||
///
|
||||
/// Both wrappers are auto-discovered by `SynthesizerBase` at `build()` time via `Mirror`
|
||||
/// reflection. The property name (with leading `_` stripped) becomes the parameter key for
|
||||
/// `updateParameter` / `LyrebirdMessageContext.set`.
|
||||
///
|
||||
/// ## Usage
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdUI
|
||||
///
|
||||
/// class MySynth: SynthesizerBase {
|
||||
/// @UIParam var frequency: Double = 440.0
|
||||
/// @UIParam var amplitude: Double = 0.5
|
||||
///
|
||||
/// override func build() {
|
||||
/// let osc = OscSin.Audio(freq: $frequency) // ramped delivery
|
||||
/// output(bus: 0, source: osc * $amplitude)
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Code update — RT-safe, triggers SwiftUI re-render
|
||||
/// synth.frequency = 880.0
|
||||
///
|
||||
/// // SwiftUI binding
|
||||
/// ParameterSlider("Frequency", node: synth.$frequency, range: 20...20000)
|
||||
/// ```
|
||||
///
|
||||
/// ## Threading model
|
||||
///
|
||||
/// Writes to `wrappedValue` go through `UIParamNode.update(_:)`, which posts a
|
||||
/// releasing atomic store and updates the `@Observable` value for the UI.
|
||||
/// The RT thread reads only the atomic — it never touches `wrappedValue` or SwiftUI state.
|
||||
@propertyWrapper
|
||||
public struct UIParam: LiveParameterWrapper {
|
||||
|
||||
// MARK: - Storage
|
||||
|
||||
/// The `UIParamNode` backing object. Use this as a `ValidGeneratorInput` in `build()`.
|
||||
///
|
||||
/// Accessible via the `$paramName` projected-value syntax.
|
||||
public let projectedValue: UIParamNode
|
||||
|
||||
/// `LiveParameterWrapper` conformance — used by `SynthesizerBase`'s Mirror walk to
|
||||
/// populate the parameter table without knowing the concrete wrapper type.
|
||||
public var _projectedAsValidInput: any ValidGeneratorInput { projectedValue }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates an `@UIParam` with the given initial value.
|
||||
public init(wrappedValue initialValue: Double) {
|
||||
self.projectedValue = UIParamNode(initialValue)
|
||||
}
|
||||
|
||||
// MARK: - wrappedValue
|
||||
|
||||
/// Read: returns the main-thread observable value from the backing node.
|
||||
/// Write: calls `UIParamNode.update(_:)` to keep the atomic and `@Observable` in sync.
|
||||
public var wrappedValue: Double {
|
||||
get { projectedValue.value }
|
||||
nonmutating set { projectedValue.update(newValue) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
// UIParamNode.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// UIParamNode — the `@Observable` backing object for an `@UIParam` property wrapper.
|
||||
///
|
||||
/// A `UIParamNode` is simultaneously:
|
||||
/// - A `ControlGenerator`: wired directly into a synthesizer's signal DAG, delivering a
|
||||
/// linearly-interpolated ramp from the previous block's value to the new atomic target.
|
||||
/// - An `@Observable` value: SwiftUI views bind to `value` and update automatically.
|
||||
/// - RT-thread-safe: the audio render callback reads via the internal `ParameterNode`
|
||||
/// which uses an `Atomic<UInt64>` for lock-free main→RT communication.
|
||||
///
|
||||
/// `@UIParam` is a strict superset of `@LiveParam`: identical RT-thread behavior plus
|
||||
/// SwiftUI binding. Use `@UIParam` when SwiftUI controls observe the parameter,
|
||||
/// `@LiveParam` when no UI is involved.
|
||||
///
|
||||
/// ## Threading model
|
||||
///
|
||||
/// | Thread | Reads | Writes |
|
||||
/// |-------------|------------------------------------------|------------------------------------------|
|
||||
/// | Main thread | `value` (observable) | `value` + `_node.value` (atomic store) |
|
||||
/// | RT thread | `_node`'s atomic backing, output buffer | `_node`'s output buffer |
|
||||
///
|
||||
/// The main thread never touches `_node`'s RT-only state; the RT thread never touches
|
||||
/// `value` or the `@Observable` registrar. The `Atomic<UInt64>` inside `_node` is the
|
||||
/// sole cross-thread communication channel.
|
||||
///
|
||||
/// ## Rate
|
||||
///
|
||||
/// `UIParamNode` conforms to `ControlGenerator`. When `controlBlockSize == blockSize`
|
||||
/// (engine default) the framework calls `_computeSamples(count: blockSize)` once per audio
|
||||
/// block. When `controlBlockSize < blockSize` the framework calls K = blockSize / controlBlockSize
|
||||
/// times per audio block, assembling into the inherited `_subBlockBuffer`. Each sub-block
|
||||
/// re-reads `_node`'s atomic, so a fresh main-thread write becomes audible at sub-block
|
||||
/// granularity rather than waiting until the next full audio block. Total work across the
|
||||
/// audio block is identical in both modes.
|
||||
///
|
||||
/// ## Fan-out
|
||||
///
|
||||
/// `ControlGenerator.calculatedSamples` extension caches the result in `_cachedResult`
|
||||
/// for the duration of the current segment. Multiple downstream consumers of the same
|
||||
/// `UIParamNode` see `_computeSamples` invoked exactly once per segment.
|
||||
@Observable
|
||||
// @unchecked Sendable: _node is read by RT generators via calculatedSamples and written on the
|
||||
// main thread; fan-out cache (segmentSerial) guarantees write-once-per-segment safety.
|
||||
public final class UIParamNode: GeneratorBase, ControlGenerator, LiveParameterValue, @unchecked Sendable {
|
||||
|
||||
// MARK: - Main-thread observable state
|
||||
|
||||
/// The current display / code-accessible value. Written and read on the main thread only.
|
||||
///
|
||||
/// `@Observable` tracks this property so SwiftUI views re-render when it changes.
|
||||
/// The RT audio thread never accesses this property — it reads the atomic inside `_node`.
|
||||
public internal(set) var value: Double
|
||||
|
||||
// MARK: - ControlGenerator conformance
|
||||
|
||||
/// Required by the `ControlGenerator` protocol but not used by this type's
|
||||
/// `_computeSamples` (which delegates to `_node`, where the actual ramp state lives).
|
||||
/// Kept in sync with `_node.previousOutputValue` for any caller that explicitly reads it.
|
||||
@ObservationIgnored
|
||||
public var previousOutputValue: Double {
|
||||
get { _node.previousOutputValue }
|
||||
set { _node.previousOutputValue = newValue }
|
||||
}
|
||||
|
||||
// MARK: - RT engine (delegation target)
|
||||
|
||||
/// The underlying RT-safe parameter node.
|
||||
///
|
||||
/// Owns the `Atomic<UInt64>`, the interpolation state, and the pre-allocated result buffer.
|
||||
/// All RT-thread work delegates here.
|
||||
@ObservationIgnored
|
||||
private let _node: ParameterNode
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a `UIParamNode` with the given initial value.
|
||||
public init(_ initialValue: Double) {
|
||||
self.value = initialValue
|
||||
self._node = ParameterNode(initialValue)
|
||||
super.init()
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// MARK: - Main-thread update
|
||||
|
||||
/// Update the parameter value from the main thread.
|
||||
///
|
||||
/// Sets the `@Observable` `value` property (triggering SwiftUI re-renders) and
|
||||
/// atomically stores the new bits for the RT thread to pick up at the next block.
|
||||
///
|
||||
/// - Important: must be called from the main thread. The `@Observable` registrar is not
|
||||
/// thread-safe; calling `update` from the RT audio thread is a data race.
|
||||
/// - Parameter newValue: The new parameter value.
|
||||
public func update(_ newValue: Double) {
|
||||
value = newValue
|
||||
_node.value = newValue
|
||||
}
|
||||
|
||||
// MARK: - LiveParameterValue conformance
|
||||
|
||||
/// Atomically writes `newValue`. Used by `SynthesizerBase.updateParameter(_:value:)`
|
||||
/// to dispatch by-name writes without knowing the concrete projected-node type.
|
||||
/// Main-thread-only — delegates to `update(_:)` to keep the `@Observable` `value`
|
||||
/// in sync with the atomic.
|
||||
public func _writeAtomicValue(_ newValue: Double) {
|
||||
update(newValue)
|
||||
}
|
||||
|
||||
// MARK: - Source property (delegates to _node)
|
||||
|
||||
/// Generator wired into this parameter slot. When non-nil, the parameter's
|
||||
/// output is driven by this generator instead of the scalar ramp path.
|
||||
/// Setting `nil` reverts to the scalar path.
|
||||
///
|
||||
/// Delegates to the underlying `ParameterNode`. See `ParameterNode.source`
|
||||
/// for the full threading contract and example.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// **Main thread only.** Same SPSC-enqueue path as `ParameterNode.source`.
|
||||
public var source: (any Generator)? {
|
||||
get { _node.source }
|
||||
set { _node.source = newValue }
|
||||
}
|
||||
|
||||
/// Swap the source with an optional crossfade. `crossfadeBlocks = 0`
|
||||
/// (default) matches the property setter — hard swap.
|
||||
///
|
||||
/// Delegates to the underlying `ParameterNode`. See `ParameterNode.setSource(_:crossfadeBlocks:)`
|
||||
/// for the full threading contract.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - source: Generator to wire in as the new source, or `nil` to revert
|
||||
/// to the scalar ramp path.
|
||||
/// - crossfadeBlocks: Number of audio blocks to crossfade. `0` = hard
|
||||
/// swap (default). Larger values produce a smooth linear mix from
|
||||
/// the old slot's output to the new one over N blocks.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// **Main thread only.** Same SPSC-enqueue path as `ParameterNode.setSource(_:crossfadeBlocks:)`.
|
||||
public func setSource(_ source: (any Generator)?, crossfadeBlocks: UInt16 = 0) {
|
||||
_node.setSource(source, crossfadeBlocks: crossfadeBlocks)
|
||||
}
|
||||
|
||||
// MARK: - ValidGeneratorInput / Generator (delegate to _node for RT work)
|
||||
|
||||
/// Returns the current target value as a block-constant scalar — direct atomic load,
|
||||
/// no ramp computation. Generators that detect `UIParamNode` as a `Generator` route
|
||||
/// through `calculatedSamples` instead.
|
||||
public func floatValue(graph: SynthGraph) -> Double {
|
||||
_node.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
/// Delegates to `_node._computeSamples`. Only reachable if a generator
|
||||
/// bypasses `calculatedSamples` and calls `_computeSamples` directly —
|
||||
/// unusual but kept as a fallback for protocol compliance. The
|
||||
/// runtime-source-swap path lives in `ParameterNode.calculatedSamples`,
|
||||
/// not `_computeSamples`, so see the `calculatedSamples` override below
|
||||
/// for the live signal path.
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_node._computeSamples(graph: graph, count: count)
|
||||
}
|
||||
|
||||
/// Forwards to `_node.calculatedSamples(graph:count:)`, which is the
|
||||
/// only path that drains `_node._sourceQueue` and runs the
|
||||
/// crossfade / source-slot state machine. If we instead let the
|
||||
/// `ControlGenerator.calculatedSamples` protocol extension dispatch
|
||||
/// to `_node._computeSamples` directly, the source-swap pipeline
|
||||
/// would be silently bypassed when a `UIParamNode` appears in a graph.
|
||||
///
|
||||
/// `_node` performs its own segment-serial caching, so we don't
|
||||
/// double-cache here.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_node.calculatedSamples(graph: graph, count: count)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user