Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -133,3 +134,126 @@ public struct MultiSlider: View {
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.MultiSlider`: a row of `count` vertical
|
||||
// bars bound to consecutive `LyrebirdBuffer` cells, drawn on a `Canvas` with an
|
||||
// `.onDrag` gesture (the same custom-drawn approach as `ParameterSlider`). The
|
||||
// SwiftUI `GeometryReader`/`ZStack`/`DragGesture` are replaced: the Canvas has a
|
||||
// fixed total width (`count × columnWidth`) so the drag maps pointer-x to a
|
||||
// column directly, and pointer-y over the fixed `height` gives the value — a
|
||||
// Canvas renderer gets its `size`, so no `GeometryReader` is needed. Per-bar
|
||||
// writes go through `LyrebirdBuffer.setValue(_:at:)` exactly as on the Apple side.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Foundation
|
||||
|
||||
/// A row of adjacent vertical sliders bound to a `LyrebirdBuffer` for the
|
||||
/// Linux/GTK4 UI. Mirrors `LyrebirdUI.MultiSlider`; same public API/init as the
|
||||
/// Apple side.
|
||||
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]
|
||||
|
||||
// Fixed per-column width (points). The Apple side fills the available width
|
||||
// via GeometryReader; on Linux the Canvas needs a concrete width, so each bar
|
||||
// gets a fixed column and the row is `count × columnWidth` wide.
|
||||
private let columnWidth: Double = 14
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - buffer: Backing `LyrebirdBuffer`. Mono only. Initial values are read
|
||||
/// once from `buffer[startIndex + i]` at construction.
|
||||
/// - count: Number of sliders. Must be ≥ 1 and `startIndex + count <= buffer.count`.
|
||||
/// - startIndex: First buffer index this view writes to. Defaults to `0`.
|
||||
/// - range: Value range. Bar-top maps to `range.upperBound`, bar-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(wrappedValue: initial)
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
let totalWidth: Double = Double(count) * columnWidth
|
||||
return Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let h: Double = Double(size.height)
|
||||
let w: Double = columnWidth
|
||||
|
||||
// Panel background.
|
||||
ctx.setColor(r: 0.5, g: 0.5, b: 0.5, a: 0.08)
|
||||
ctx.rectangle(x: 0, y: 0, width: Double(size.width), height: h)
|
||||
ctx.fill()
|
||||
|
||||
// Bars.
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
|
||||
for i: Int in 0..<count {
|
||||
let v: Double = values[i]
|
||||
let norm: Double = (v - range.lowerBound) / span
|
||||
let barH: Double = h * norm
|
||||
let x: Double = Double(i) * w
|
||||
ctx.rectangle(x: x + 1, y: h - barH, width: max(1, w - 2), height: barH)
|
||||
ctx.fill()
|
||||
}
|
||||
})
|
||||
.frame(width: totalWidth, height: Double(height))
|
||||
.onDrag(
|
||||
minimumDistance: 0,
|
||||
onChanged: { (drag: DragGestureValue) in
|
||||
let column: Int = Int(drag.location.x / columnWidth)
|
||||
guard column >= 0 && column < count else { return }
|
||||
let hgt: Double = Double(height)
|
||||
let yClamped: Double = min(max(drag.location.y, 0), hgt)
|
||||
let norm: Double = 1 - (yClamped / hgt)
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let value: Double = range.lowerBound + norm * span
|
||||
values[column] = value
|
||||
buffer.setValue(value, at: startIndex + column)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -101,3 +102,124 @@ public struct ParameterButton: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.ParameterButton`. Two styles: a
|
||||
// `.momentary` button that runs a closure on press (no node), and a `.toggle`
|
||||
// that flips a bound core `UIParamNode` between `offValue` and `onValue`. Uses
|
||||
// SwiftOpenUI's native `Button`; no BackendGTK4 import (no Cairo drawing).
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift), so no
|
||||
// `canImport` guard is needed.
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A button for the Linux/GTK4 UI. Mirrors `LyrebirdUI.ParameterButton`:
|
||||
/// `.momentary` runs an action on press; `.toggle` flips a bound ``UIParamNode``
|
||||
/// between `offValue` and `onValue`, highlighting when on.
|
||||
public struct ParameterButton: View {
|
||||
|
||||
// MARK: - Style
|
||||
|
||||
public enum Style {
|
||||
/// Executes the action closure on each press.
|
||||
case momentary
|
||||
/// Flips the node between `offValue` and `onValue` 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
|
||||
|
||||
// Presentation constants.
|
||||
private let labelMinWidth: Double = 60
|
||||
private let cornerRadiusPoints: Double = 6
|
||||
private let onHighlightOpacity: Double = 0.3
|
||||
private let toggleThreshold: Double = 0.5
|
||||
|
||||
// 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 {
|
||||
// ONE static Button node — deliberately NOT a `@ViewBuilder` if/else.
|
||||
// A conditional builds a `_ConditionalView`, which the GTK4 backend's
|
||||
// descriptor differ can plan as a structural replace; because the narrow
|
||||
// in-place mutation path requires EVERY node in the plan to be
|
||||
// narrow-applicable (`allSatisfy`), a single such node poisons the whole
|
||||
// plan and forces a FULL rebuild of the window on every state change —
|
||||
// tearing down in-flight drag gestures on sibling controls (knob / XY)
|
||||
// and adding latency. A single static node keeps changes on the narrow
|
||||
// path. The `.momentary` case simply carries `isToggledOn == false` and a
|
||||
// `.clear` background; `press()` re-reads the node's value at click time
|
||||
// (not captured) so a fast second click before the async rebuild still
|
||||
// flips correctly.
|
||||
Button(action: { press() }) {
|
||||
Text(label)
|
||||
.frame(minWidth: labelMinWidth)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.background(isToggledOn ? Color.cyan.opacity(onHighlightOpacity) : Color.clear)
|
||||
.cornerRadius(cornerRadiusPoints)
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
private var isToggledOn: Bool {
|
||||
guard case .toggle = style else { return false }
|
||||
return (node?.value ?? 0) >= toggleThreshold
|
||||
}
|
||||
|
||||
private func press() {
|
||||
switch style {
|
||||
case .momentary:
|
||||
action?()
|
||||
case .toggle:
|
||||
node?.update(isToggledOn ? offValue : onValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -24,7 +25,7 @@ public struct ParameterKnob: View {
|
||||
private let range: ClosedRange<Double>
|
||||
|
||||
/// Pixels of vertical drag that span the full parameter range. Default 200.
|
||||
public var dragSensitivity: CGFloat = 200
|
||||
public var dragSensitivity: Double = 200
|
||||
|
||||
// MARK: - Private drag state
|
||||
|
||||
@@ -110,7 +111,7 @@ public struct ParameterKnob: View {
|
||||
}
|
||||
let delta: CGFloat = dragStartPosition - gesture.location.y // up = positive
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let change: Double = Double(delta / dragSensitivity) * span
|
||||
let change: Double = (Double(delta) / dragSensitivity) * span
|
||||
let clamped: Double = min(max(dragStartValue + change, range.lowerBound), range.upperBound)
|
||||
node.update(clamped)
|
||||
}
|
||||
@@ -134,3 +135,119 @@ public struct ParameterKnob: View {
|
||||
formattedParameterValue(node.value)
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Experimental Linux GUI, built only under `LYREBIRD_ENABLE_LINUX_UI=1`
|
||||
// (see Package.swift). This is the first control ported from `LyrebirdUI`'s
|
||||
// SwiftUI `ParameterKnob` to SwiftOpenUI's GTK4 surface: a rotary knob drawn
|
||||
// with the Cairo-backed `DrawingContext` (SwiftOpenUI's stand-in for SwiftUI's
|
||||
// `GraphicsContext`) and a `.onDrag` vertical drag-to-set.
|
||||
//
|
||||
// It binds to the same core `UIParamNode` the macOS `ParameterKnob` binds to,
|
||||
// so a synthesizer's `@UIParam` drives both platforms from one model. Because
|
||||
// `UIParamNode` is `@Observable`, a drag-driven `node.update(_:)` takes the
|
||||
// GTK4 backend's narrow mutation (redraw-in-place) path carried by the pinned
|
||||
// SwiftOpenUI fork, so the in-flight drag gesture survives and the knob tracks
|
||||
// continuously.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift),
|
||||
// so no `canImport` guard is needed; `BackendGTK4` carries the Cairo-backed
|
||||
// `DrawingContext` drawing methods (setColor/arc/moveTo/…), which are extensions
|
||||
// not present in SwiftOpenUI's core.
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Foundation
|
||||
|
||||
/// A rotary knob for the Linux/GTK4 UI, drawn on a `Canvas` and set by a
|
||||
/// vertical drag. Binds to a core ``UIParamNode`` (via a synthesizer's
|
||||
/// `@UIParam` projected value, `synth.$paramName`) — the same model the macOS
|
||||
/// `ParameterKnob` uses. Mirrors that control's behaviour: −135°…+135° sweep,
|
||||
/// drag-up increases.
|
||||
public struct ParameterKnob: View {
|
||||
private let label: String
|
||||
private let node: UIParamNode
|
||||
private let range: ClosedRange<Double>
|
||||
|
||||
/// Pixels of vertical drag spanning the full parameter range. Matches the
|
||||
/// macOS knob's default.
|
||||
public var dragSensitivity: Double = 200
|
||||
|
||||
// Drag origin, captured on the first `onChanged` of each gesture. An
|
||||
// explicit flag avoids a sentinel collision when the value is genuinely at
|
||||
// the range's lower bound.
|
||||
@State private var dragStartValue: Double = 0
|
||||
@State private var dragInProgress: Bool = false
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack {
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let cx: Double = Double(size.width) / 2
|
||||
let cy: Double = Double(size.height) / 2
|
||||
let radius: Double = min(cx, cy) - 4
|
||||
|
||||
// Dial face ring.
|
||||
ctx.setColor(r: 0.20, g: 0.20, b: 0.20)
|
||||
ctx.setLineWidth(3)
|
||||
ctx.arc(centerX: cx, centerY: cy, radius: radius,
|
||||
startAngle: 0, endAngle: 2 * Double.pi)
|
||||
ctx.stroke()
|
||||
|
||||
// Indicator: −135°…+135° sweep (270° total), like the macOS knob.
|
||||
let startAngleRadians: Double = 0.75 * Double.pi
|
||||
let sweepRadians: Double = 1.5 * Double.pi
|
||||
let angle: Double = startAngleRadians + normalise(node.value) * sweepRadians
|
||||
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
|
||||
ctx.setLineWidth(3)
|
||||
ctx.moveTo(x: cx, y: cy)
|
||||
ctx.lineTo(x: cx + radius * cos(angle), y: cy + radius * sin(angle))
|
||||
ctx.stroke()
|
||||
})
|
||||
.frame(width: 50, height: 50)
|
||||
.onDrag(
|
||||
minimumDistance: 0,
|
||||
onChanged: { (drag: DragGestureValue) in
|
||||
if !dragInProgress {
|
||||
dragInProgress = true
|
||||
dragStartValue = node.value
|
||||
}
|
||||
// Up (negative height) increases, matching the macOS knob.
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let change: Double = (-drag.height / dragSensitivity) * span
|
||||
let target: Double = min(range.upperBound,
|
||||
max(range.lowerBound, dragStartValue + change))
|
||||
node.update(target)
|
||||
},
|
||||
onEnded: { (_: DragGestureValue) in
|
||||
dragInProgress = false
|
||||
}
|
||||
)
|
||||
Text(label)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -59,3 +60,68 @@ public struct ParameterLabel: View {
|
||||
String(format: "%.\(decimalPlaces)f", node.value)
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.ParameterLabel`: a read-only display of
|
||||
// a core `UIParamNode`'s current value, updated automatically via `@Observable`
|
||||
// (no polling). Uses only the core View DSL; no BackendGTK4 import.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift), so no
|
||||
// `canImport` guard is needed.
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
import Foundation // String(format:) for the value readout
|
||||
|
||||
/// A read-only label for the Linux/GTK4 UI that shows a ``UIParamNode``'s
|
||||
/// current value. Mirrors `LyrebirdUI.ParameterLabel`: a leading descriptive
|
||||
/// label and a trailing monospaced value. Refreshes automatically because
|
||||
/// `UIParamNode` is `@Observable`.
|
||||
public struct ParameterLabel: View {
|
||||
|
||||
// MARK: - Properties
|
||||
|
||||
private let label: String
|
||||
private let node: UIParamNode
|
||||
private let decimalPlaces: Int
|
||||
|
||||
// Layout constants (points), matching the macOS label.
|
||||
private let labelMinWidth: Double = 80
|
||||
private let valueMinWidth: Double = 60
|
||||
|
||||
// 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: labelMinWidth, alignment: .leading)
|
||||
Text(formattedValue)
|
||||
.monospacedDigit()
|
||||
.frame(minWidth: valueMinWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Formatting
|
||||
|
||||
private var formattedValue: String {
|
||||
String(format: "%.\(decimalPlaces)f", node.value)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -84,6 +85,8 @@ public struct ParameterSlider: View {
|
||||
private func toLinear(_ value: Double) -> Double {
|
||||
let lo: Double = range.lowerBound
|
||||
let hi: Double = range.upperBound
|
||||
// Degenerate range: avoid a 0/0 NaN thumb position.
|
||||
guard hi > lo else { return 0 }
|
||||
switch taper {
|
||||
case .linear:
|
||||
return (value - lo) / (hi - lo)
|
||||
@@ -116,3 +119,167 @@ public struct ParameterSlider: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.ParameterSlider`. Drawn on a `Canvas`
|
||||
// with a `.onDrag` gesture — the same custom-drawn approach as
|
||||
// `ParameterKnob` — rather than a native `Slider` (GtkScale). This is what
|
||||
// lets a slider drag update the parameter on every motion event (like the knob
|
||||
// and the macOS slider), and, crucially, lets the slider **track live** when a
|
||||
// paired control bound to the same node is dragged: a Canvas closure reads
|
||||
// `node.value` at paint time, so the GTK4 backend's per-drag redraw of every
|
||||
// linked control repaints it in step. A native GtkScale, whose thumb position is
|
||||
// pushed on rebuild (deferred during a drag), could only reconcile on release.
|
||||
//
|
||||
// Binds to a core `UIParamNode` (via `synth.$paramName`) with the same linear /
|
||||
// exponential taper mapping the macOS slider uses. `BackendGTK4` carries the
|
||||
// Cairo-backed `DrawingContext` drawing methods.
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Foundation // log/pow for the exponential taper
|
||||
|
||||
/// A labelled continuous slider for the Linux/GTK4 UI, bound to a core
|
||||
/// ``UIParamNode``. Mirrors `LyrebirdUI.ParameterSlider`: a leading label, a
|
||||
/// horizontal Canvas-drawn track with a draggable thumb, and a trailing value
|
||||
/// readout, with an optional exponential taper for ratio-based parameters
|
||||
/// (frequency, time).
|
||||
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
|
||||
|
||||
// Layout constants (points), matching the macOS slider's proportions.
|
||||
private let labelMinWidth: Double = 80
|
||||
private let valueMinWidth: Double = 60
|
||||
/// Track dimensions. The drag maps pointer x over this fixed width, so it
|
||||
/// matches the Canvas's own size (`.frame(width: trackWidth, …)`).
|
||||
private let trackWidth: Double = 160
|
||||
private let trackHeight: Double = 24
|
||||
/// Thumb radius; the usable track is inset by this so the thumb stays fully
|
||||
/// visible at both ends.
|
||||
private let thumbRadius: Double = 7
|
||||
|
||||
// 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: labelMinWidth, alignment: .leading)
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
let cy: Double = h / 2
|
||||
let x0: Double = thumbRadius
|
||||
let x1: Double = w - thumbRadius
|
||||
let usable: Double = max(x1 - x0, 1)
|
||||
let pos: Double = toLinear(node.value)
|
||||
let thumbX: Double = x0 + pos * usable
|
||||
|
||||
// Track background (full width).
|
||||
ctx.setColor(r: 0.20, g: 0.20, b: 0.20)
|
||||
ctx.setLineWidth(4)
|
||||
ctx.moveTo(x: x0, y: cy)
|
||||
ctx.lineTo(x: x1, y: cy)
|
||||
ctx.stroke()
|
||||
|
||||
// Filled portion up to the thumb.
|
||||
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
|
||||
ctx.setLineWidth(4)
|
||||
ctx.moveTo(x: x0, y: cy)
|
||||
ctx.lineTo(x: thumbX, y: cy)
|
||||
ctx.stroke()
|
||||
|
||||
// Thumb.
|
||||
ctx.setColor(r: 0.90, g: 0.90, b: 0.95)
|
||||
ctx.arc(centerX: thumbX, centerY: cy, radius: thumbRadius,
|
||||
startAngle: 0, endAngle: 2 * Double.pi)
|
||||
ctx.fill()
|
||||
})
|
||||
.frame(width: trackWidth, height: trackHeight)
|
||||
.onDrag(
|
||||
minimumDistance: 0,
|
||||
onChanged: { (drag: DragGestureValue) in
|
||||
// Absolute: the thumb follows the pointer x within the track.
|
||||
let x0: Double = thumbRadius
|
||||
let usable: Double = max(trackWidth - 2 * thumbRadius, 1)
|
||||
let pos: Double = min(1, max(0, (drag.location.x - x0) / usable))
|
||||
node.update(fromLinear(pos))
|
||||
}
|
||||
)
|
||||
Text(formattedValue)
|
||||
.frame(minWidth: valueMinWidth, alignment: .trailing)
|
||||
.monospacedDigit()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Private helpers
|
||||
|
||||
private func toLinear(_ value: Double) -> Double {
|
||||
let lo: Double = range.lowerBound
|
||||
let hi: Double = range.upperBound
|
||||
// Degenerate range: avoid a 0/0 NaN thumb position.
|
||||
guard hi > lo else { return 0 }
|
||||
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 {
|
||||
formattedParameterValue(node.value)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -163,3 +164,148 @@ public struct ParameterXY: View {
|
||||
formattedParameterValue(v)
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.ParameterXY`: a two-dimensional pad that
|
||||
// drives two core `UIParamNode`s at once. Drawn on a single `Canvas` (background,
|
||||
// centre grid, cursor) with an absolute-position `.onDrag` — the touch point maps
|
||||
// straight to the cursor, X left→right, Y bottom→top.
|
||||
//
|
||||
// Same gesture path as `ParameterKnob`: the drag calls `node.update(_:)`,
|
||||
// and because `UIParamNode` is `@Observable` the Canvas redraw takes the GTK4
|
||||
// backend's narrow `.canvasContent` mutation path (the pinned fork's fix), so the
|
||||
// cursor tracks continuously without the gesture being torn down by a rebuild.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift),
|
||||
// so no `canImport` guard is needed; `BackendGTK4` carries the Cairo-backed
|
||||
// `DrawingContext` drawing methods.
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Foundation // CGSize (Canvas renderer size)
|
||||
|
||||
/// A two-axis control pad for the Linux/GTK4 UI, bound to two ``UIParamNode``s.
|
||||
/// Mirrors `LyrebirdUI.ParameterXY`: drag within the pad to set X (horizontal,
|
||||
/// left→right) and Y (vertical, bottom→top) independently.
|
||||
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>
|
||||
|
||||
// Presentation constants (points).
|
||||
private let padSize: Double = 160
|
||||
private let cursorRadius: Double = 6
|
||||
|
||||
// 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 {
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
|
||||
// Background fill.
|
||||
ctx.setColor(r: 0.15, g: 0.15, b: 0.15)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
|
||||
// Border.
|
||||
ctx.setColor(r: 0.40, g: 0.40, b: 0.40)
|
||||
ctx.setLineWidth(1)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.stroke()
|
||||
|
||||
// Centre grid lines (faint).
|
||||
let midX: Double = w / 2
|
||||
let midY: Double = h / 2
|
||||
ctx.setColor(r: 0.40, g: 0.40, b: 0.40, a: 0.4)
|
||||
ctx.setLineWidth(0.5)
|
||||
ctx.moveTo(x: midX, y: 0)
|
||||
ctx.lineTo(x: midX, y: h)
|
||||
ctx.moveTo(x: 0, y: midY)
|
||||
ctx.lineTo(x: w, y: midY)
|
||||
ctx.stroke()
|
||||
|
||||
// Cursor: X left→right, Y bottom→top (flip vertical).
|
||||
let nx: Double = normalise(xNode.value, range: xRange)
|
||||
let ny: Double = 1.0 - normalise(yNode.value, range: yRange)
|
||||
let cx: Double = nx * w
|
||||
let cy: Double = ny * h
|
||||
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
|
||||
ctx.arc(centerX: cx, centerY: cy, radius: cursorRadius,
|
||||
startAngle: 0, endAngle: 2 * Double.pi)
|
||||
ctx.fill()
|
||||
})
|
||||
.frame(width: padSize, height: padSize)
|
||||
.onDrag(
|
||||
minimumDistance: 0,
|
||||
onChanged: { (drag: DragGestureValue) in
|
||||
// Absolute position: the touch point is the cursor.
|
||||
let nx: Double = min(max(drag.location.x / padSize, 0), 1)
|
||||
let ny: Double = min(max(drag.location.y / padSize, 0), 1)
|
||||
xNode.update(denormalise(nx, range: xRange))
|
||||
yNode.update(denormalise(1.0 - ny, range: yRange)) // flip Y
|
||||
}
|
||||
)
|
||||
Text("\(xLabel): \(formattedParameterValue(xNode.value))")
|
||||
.monospacedDigit()
|
||||
Text("\(yLabel): \(formattedParameterValue(yNode.value))")
|
||||
.monospacedDigit()
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
@@ -20,3 +21,27 @@ extension Color {
|
||||
public static let lyrebirdSeparator = Color(UIColor.separator)
|
||||
#endif
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to the Apple `PlatformColors`. AppKit/UIKit system
|
||||
// colours have no GTK4 equivalent, so these are fixed neutral tones chosen to
|
||||
// read on both light and dark GTK themes: a faint panel fill and a mid-grey
|
||||
// hairline separator. `Color` here is SwiftOpenUI's, not SwiftUI's.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
|
||||
extension Color {
|
||||
// Computed (not stored) because SwiftOpenUI's `Color` is not `Sendable`, so a
|
||||
// `static let` would be a non-concurrency-safe global. A computed `static var`
|
||||
// rebuilds the value on each access — trivially cheap for a plain colour.
|
||||
/// Subtle panel background used behind grouped controls/diagnostics views.
|
||||
public static var lyrebirdControlBackground: Color {
|
||||
Color(red: 0.5, green: 0.5, blue: 0.5, opacity: 0.08)
|
||||
}
|
||||
/// Hairline separator/stroke colour.
|
||||
public static var lyrebirdSeparator: Color {
|
||||
Color(red: 0.5, green: 0.5, blue: 0.5, opacity: 0.35)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -57,6 +58,11 @@ public struct LyrebirdEngineStatusView: View {
|
||||
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// Called after the user starts the engine via this panel's Start button
|
||||
/// (immediately after a successful `engine.start()`). Use it to (re)add the
|
||||
/// synths the host wants running — `engine.stop()` tears down non-persistent
|
||||
/// nodes, so anything added earlier is gone after a stop/start cycle.
|
||||
public let onEngineStarted: (() -> Void)?
|
||||
@State private var isRunning: Bool = false
|
||||
@State private var synthesizerCount: Int = 0
|
||||
@State private var groupCount: Int = 0
|
||||
@@ -95,9 +101,16 @@ public struct LyrebirdEngineStatusView: View {
|
||||
|
||||
/// Creates a status view bound to the given engine.
|
||||
///
|
||||
/// - Parameter engine: The `SynthesisEngine` instance to monitor.
|
||||
public init(engine: SynthesisEngine) {
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` instance to monitor.
|
||||
/// - onEngineStarted: Optional closure run after the Start button
|
||||
/// successfully starts the engine (e.g. to re-add synths).
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
onEngineStarted: (() -> Void)? = nil
|
||||
) {
|
||||
self.engine = engine
|
||||
self.onEngineStarted = onEngineStarted
|
||||
// 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
|
||||
@@ -474,6 +487,7 @@ public struct LyrebirdEngineStatusView: View {
|
||||
do {
|
||||
try engine.start()
|
||||
lastStartError = nil
|
||||
onEngineStarted?()
|
||||
} catch {
|
||||
lastStartError = "Start failed: \(error)"
|
||||
}
|
||||
@@ -599,3 +613,736 @@ extension LyrebirdEngineStatusView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEngineStatusView`: the live engine
|
||||
// status panel (run state + Start/Stop, synth/group counts, CPU bars, node-tree +
|
||||
// messages sections, pre-run config, master output). The 10 Hz poll moves off
|
||||
// SwiftOpenUI's off-main `.task` onto a `Timer` on `RunLoop.main` inside an
|
||||
// `@Observable` model. CPU bars are `Canvas`-drawn (as in `LyrebirdStatusView`)
|
||||
// rather than `GeometryReader`/`ZStack`. Section chevrons become text glyphs
|
||||
// (▼ / ▶). The "Open Window" buttons work here too — `LyrebirdWindow` now has a
|
||||
// GTK4 body — opening the node-tree / messages panels in detached windows, in
|
||||
// addition to the inline expand.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// 10 Hz engine status poll interval.
|
||||
// Deliberately slower than the Apple side's 10 Hz. This view mixes a periodic
|
||||
// @Observable poll with native GTK widgets (Stop button, Mute switch, expand
|
||||
// buttons, volume GtkScale) AND several `if` conditionals. A conditional forces
|
||||
// SwiftOpenUI's GTK4 differ off its narrow in-place path onto a full-window
|
||||
// rebuild on every model tick; native-widget clicks that land mid-rebuild are
|
||||
// dropped. A 2 Hz poll leaves ~500 ms of stable tree between rebuilds so clicks
|
||||
// land reliably. (The proper fix is fork-side: narrow updates through
|
||||
// conditionals, or isolating each polled value in its own conditional-free leaf
|
||||
// child so its rebuild stays local.)
|
||||
private let linuxEngineStatusPollIntervalSeconds: TimeInterval = 0.5
|
||||
|
||||
/// Polls a `SynthesisEngine`'s live state on a main-thread timer and publishes it
|
||||
/// for ``LyrebirdEngineStatusView``. Internal — only the view is public.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`,
|
||||
/// same rationale as `LyrebirdScopeModel`.
|
||||
@Observable
|
||||
final class LinuxEngineStatusModel: @unchecked Sendable {
|
||||
|
||||
var isRunning: Bool = false
|
||||
var synthesizerCount: Int = 0
|
||||
var groupCount: Int = 0
|
||||
var averageCPU: Double = 0.0
|
||||
var peakCPU: Double = 0.0
|
||||
|
||||
var sampleRate: Double = 48000
|
||||
var numOutputChannels: Int = 2
|
||||
var numInputChannels: Int = 0
|
||||
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
@ObservationIgnored private let engine: SynthesisEngine
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.isRunning = engine.isRunning
|
||||
self.sampleRate = engine.sampleRate
|
||||
self.numOutputChannels = engine.numOutputChannels
|
||||
self.numInputChannels = engine.numInputChannels
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
refresh()
|
||||
let t: Timer = Timer.scheduledTimer(
|
||||
withTimeInterval: linuxEngineStatusPollIntervalSeconds,
|
||||
repeats: true
|
||||
) { [weak self] _ in
|
||||
self?.refresh()
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
isRunning = engine.isRunning
|
||||
synthesizerCount = engine.synthesizerCount
|
||||
groupCount = engine.groupCount
|
||||
averageCPU = engine.averageCPU
|
||||
peakCPU = engine.peakCPU
|
||||
if sampleRate != engine.sampleRate { sampleRate = engine.sampleRate }
|
||||
if numOutputChannels != engine.numOutputChannels { numOutputChannels = engine.numOutputChannels }
|
||||
if numInputChannels != engine.numInputChannels { numInputChannels = engine.numInputChannels }
|
||||
}
|
||||
}
|
||||
|
||||
/// A live engine status panel for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdEngineStatusView`; same public API/init as the Apple side.
|
||||
public struct LyrebirdEngineStatusView: View {
|
||||
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// Called after the user starts the engine via this panel's Start button.
|
||||
/// Use it to (re)add synths — `engine.stop()` tears down non-persistent
|
||||
/// nodes, so anything added earlier is gone after a stop/start cycle.
|
||||
public let onEngineStarted: (() -> Void)?
|
||||
@State private var model: LinuxEngineStatusModel
|
||||
|
||||
// Non-polled UI state.
|
||||
@State private var lastStartError: String?
|
||||
@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
|
||||
// Detached windows opened by the "Open Window" buttons — now that
|
||||
// `LyrebirdWindow` exists on Linux, these mirror the macOS panel.
|
||||
@State private var messageWindow: LyrebirdWindow?
|
||||
@State private var nodeTreeWindow: LyrebirdWindow?
|
||||
|
||||
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: rootGroup + mainGroup.
|
||||
private static let persistentGroupCount: Int = 2
|
||||
|
||||
// Layout constants (points).
|
||||
private let dotSize: Double = 10
|
||||
|
||||
/// Creates a status view bound to the given engine.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - engine: The `SynthesisEngine` instance to monitor.
|
||||
/// - onEngineStarted: Optional closure run after the Start button
|
||||
/// successfully starts the engine (e.g. to re-add synths).
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
onEngineStarted: (() -> Void)? = nil
|
||||
) {
|
||||
self.engine = engine
|
||||
self.onEngineStarted = onEngineStarted
|
||||
_model = State(wrappedValue: LinuxEngineStatusModel(engine: engine))
|
||||
_isMuted = State(wrappedValue: engine.isMuted)
|
||||
let initialDb: Double = LyrebirdEngineStatusView.linearToDb(engine.masterGain)
|
||||
_masterGainDb = State(wrappedValue: initialDb)
|
||||
_masterGainDbText = State(wrappedValue: String(format: "%+.1f", initialDb))
|
||||
}
|
||||
|
||||
/// Linear amplitude → dB with a finite floor at the slider's lower bound.
|
||||
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 rate if not already present.
|
||||
private var sampleRatePickerOptions: [Double] {
|
||||
var rates: [Double] = LyrebirdEngineStatusView.sampleRateOptions
|
||||
if !rates.contains(model.sampleRate) {
|
||||
rates.append(model.sampleRate)
|
||||
rates.sort()
|
||||
}
|
||||
return rates
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(model.isRunning ? Color.green : Color.secondary.opacity(0.4))
|
||||
.frame(width: dotSize, height: dotSize)
|
||||
Text(model.isRunning ? "Running" : "Stopped")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
// Use the `action:label:` form (not `Button(_ title:action:)`):
|
||||
// the string-title form's action was not firing on GTK4 here,
|
||||
// while this form — as used by the working expand buttons — does.
|
||||
Button {
|
||||
toggleEngine()
|
||||
} label: {
|
||||
Text(model.isRunning ? "Stop" : "Start")
|
||||
}
|
||||
}
|
||||
|
||||
if let err: String = lastStartError {
|
||||
Text(err)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
HStack(spacing: 16) {
|
||||
CountTile(label: "Synths", value: model.synthesizerCount)
|
||||
CountTile(
|
||||
label: "Groups",
|
||||
value: model.groupCount + LyrebirdEngineStatusView.persistentGroupCount,
|
||||
subtitle: "incl. rootGroup, mainGroup"
|
||||
)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
CPURow(label: "CPU Avg", value: model.averageCPU)
|
||||
CPURow(label: "CPU Peak", value: model.peakCPU)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
nodeTreeSection
|
||||
|
||||
Divider()
|
||||
|
||||
messagesSection
|
||||
|
||||
Divider()
|
||||
|
||||
configurationSection
|
||||
|
||||
Divider()
|
||||
|
||||
outputSection
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 260)
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
private var configurationSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Configuration")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
HStack {
|
||||
Text("Sample Rate")
|
||||
.frame(width: 110, alignment: .leading)
|
||||
Picker("", selection: Binding(
|
||||
get: { model.sampleRate },
|
||||
set: { newValue in
|
||||
model.sampleRate = newValue
|
||||
pushConfigToEngine { try engine.setSampleRate(newValue) }
|
||||
}
|
||||
)) {
|
||||
ForEach(sampleRatePickerOptions, id: \.self) { rate in
|
||||
Text("\(Int(rate)) Hz").tag(rate)
|
||||
}
|
||||
}
|
||||
.labelsHidden()
|
||||
}
|
||||
|
||||
Stepper(
|
||||
"Output Channels: \(model.numOutputChannels)",
|
||||
value: Binding(
|
||||
get: { model.numOutputChannels },
|
||||
set: { newValue in
|
||||
model.numOutputChannels = newValue
|
||||
pushConfigToEngine { try engine.setNumOutputChannels(newValue) }
|
||||
}
|
||||
),
|
||||
in: LyrebirdEngineStatusView.outputChannelRange
|
||||
)
|
||||
|
||||
Stepper(
|
||||
"Input Channels: \(model.numInputChannels)",
|
||||
value: Binding(
|
||||
get: { model.numInputChannels },
|
||||
set: { newValue in
|
||||
model.numInputChannels = newValue
|
||||
pushConfigToEngine { try engine.setNumInputChannels(newValue) }
|
||||
}
|
||||
),
|
||||
in: LyrebirdEngineStatusView.inputChannelRange
|
||||
)
|
||||
|
||||
if let err: String = lastConfigError {
|
||||
Text(err)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
}
|
||||
.disabled(model.isRunning)
|
||||
.opacity(model.isRunning ? 0.5 : 1.0)
|
||||
}
|
||||
|
||||
/// Guard config setters so a mirror-driven change while running can't bubble a
|
||||
/// spurious `engineIsRunning` error. Controls are `.disabled` while running,
|
||||
/// so the only path here during a run would be the mirror.
|
||||
private func pushConfigToEngine(_ apply: () throws -> Void) {
|
||||
guard !model.isRunning else { return }
|
||||
applyConfig(apply)
|
||||
}
|
||||
|
||||
private var outputSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
Text("Output")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Toggle("Mute", isOn: $isMuted)
|
||||
.onChange(of: isMuted) { _, newValue in
|
||||
engine.isMuted = newValue
|
||||
}
|
||||
|
||||
HStack(spacing: 8) {
|
||||
Text("Volume")
|
||||
.frame(width: 60, alignment: .leading)
|
||||
// Canvas-drawn, not a native GtkScale: the GtkScale drops/mis-hits
|
||||
// pointer events here (drag catches outside the thumb, misses clicks).
|
||||
// A Canvas + `.onDrag` maps pointer-x across a fixed track like
|
||||
// `ParameterSlider`. `onChange(of: masterGainDb)` still drives the
|
||||
// engine (fires for drag and for text-field commits).
|
||||
LinuxValueSlider(
|
||||
value: $masterGainDb,
|
||||
range: LyrebirdEngineStatusView.gainDbRange,
|
||||
// Applies live on every drag motion (rebuilds are deferred
|
||||
// during a drag, so onChange alone would lag to mouse-up).
|
||||
// Also updates the dB readout text here for the same reason.
|
||||
onEditing: { db in
|
||||
engine.masterGain = pow(10.0, db / 20.0)
|
||||
if !gainTextFocused {
|
||||
masterGainDbText = String(format: "%+.1f", db)
|
||||
}
|
||||
}
|
||||
)
|
||||
.onChange(of: masterGainDb) { _, db in
|
||||
// Handles the text-field commit path + final sync.
|
||||
engine.masterGain = pow(10.0, db / 20.0)
|
||||
if !gainTextFocused {
|
||||
masterGainDbText = String(format: "%+.1f", db)
|
||||
}
|
||||
}
|
||||
// The editable TextField tracks the drag live via the fork's
|
||||
// narrow-mutation path (SwiftOpenUI Patch F makes the full panel —
|
||||
// buttons, Picker/Stepper/Toggle, shapes, conditionals, the bound
|
||||
// TextField — narrow-applicable). `onEditing` above sets the text on
|
||||
// each motion; the field follows AND stays typeable.
|
||||
TextField("dB", text: $masterGainDbText)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.multilineTextAlignment(.trailing)
|
||||
.focused($gainTextFocused)
|
||||
.frame(width: 70)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.onSubmit(commitMasterGainText)
|
||||
.onChange(of: gainTextFocused) { _, focused in
|
||||
if !focused { commitMasterGainText() }
|
||||
}
|
||||
Text("dB")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func commitMasterGainText() {
|
||||
var trimmed: String = masterGainDbText.trimmingCharacters(in: .whitespaces)
|
||||
// Strip only a leading `+` — a blanket replace 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 {
|
||||
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) {
|
||||
Text(isNodeTreeExpanded ? "▼" : "▶")
|
||||
.font(.caption2)
|
||||
Text("Node Tree")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
Spacer()
|
||||
// `action:label:` form — the string-title `Button` form's action
|
||||
// does not fire on GTK4 here (see the Start/Stop button note).
|
||||
Button {
|
||||
openNodeTreeWindow()
|
||||
} label: {
|
||||
Text("Open Window")
|
||||
.font(.caption)
|
||||
}
|
||||
}
|
||||
|
||||
// Persistent-groups strip — always visible so the user sees at a
|
||||
// glance that `rootGroup` and `mainGroup` are alive.
|
||||
persistentGroupsStrip
|
||||
|
||||
if isNodeTreeExpanded {
|
||||
LyrebirdNodeTreeView(mirror: engine.nodeTreeMirror)
|
||||
.frame(minHeight: 180, maxHeight: 300)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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) {
|
||||
Text("▼")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
Text("rootGroup")
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
Text("(\(root.children.count))")
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.tertiary)
|
||||
Text("▸")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
Text("mainGroup")
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
Text("(\(mainChildCount))")
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.tertiary)
|
||||
Spacer()
|
||||
}
|
||||
.padding(.leading, 6)
|
||||
}
|
||||
|
||||
private var messagesSection: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
isMessagesExpanded.toggle()
|
||||
} label: {
|
||||
HStack(spacing: 4) {
|
||||
Text(isMessagesExpanded ? "▼" : "▶")
|
||||
.font(.caption2)
|
||||
Text("Messages")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
}
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
Spacer()
|
||||
Button {
|
||||
openMessageWindow()
|
||||
} label: {
|
||||
Text("Open Window")
|
||||
.font(.caption)
|
||||
}
|
||||
}
|
||||
|
||||
// `LyrebirdMessageView()` / `LyrebirdMessageBanner()` have @MainActor
|
||||
// inits (they read `LyrebirdMessageCenter.shared`) and return a
|
||||
// non-Sendable View, which can't cross back out of an `assumeIsolated`
|
||||
// closure. Instead resolve the (Sendable) shared center on the main
|
||||
// actor, then use the nonisolated `init(center:)`.
|
||||
let center: LyrebirdMessageCenter = MainActor.assumeIsolated { LyrebirdMessageCenter.shared }
|
||||
if isMessagesExpanded {
|
||||
LyrebirdMessageView(center: center)
|
||||
.frame(minHeight: 160, maxHeight: 260)
|
||||
} else {
|
||||
LyrebirdMessageBanner(center: center, onOpenFull: {
|
||||
isMessagesExpanded = true
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// `LyrebirdWindow` / `presentInWindow` are nonisolated on Linux (GTK-thread-
|
||||
// confined), so these fire directly from the nonisolated SwiftOpenUI button
|
||||
// action — no actor hop needed.
|
||||
private func openNodeTreeWindow() {
|
||||
if let existing: LyrebirdWindow = nodeTreeWindow {
|
||||
existing.close()
|
||||
nodeTreeWindow = nil
|
||||
}
|
||||
nodeTreeWindow = LyrebirdNodeTreeView.presentInWindow(engine: engine)
|
||||
}
|
||||
|
||||
private func openMessageWindow() {
|
||||
if let existing: LyrebirdWindow = messageWindow {
|
||||
existing.close()
|
||||
messageWindow = nil
|
||||
}
|
||||
messageWindow = LyrebirdMessageView.presentInWindow()
|
||||
}
|
||||
|
||||
private func toggleEngine() {
|
||||
if engine.isRunning {
|
||||
engine.stop()
|
||||
lastStartError = nil
|
||||
} else {
|
||||
do {
|
||||
try engine.start()
|
||||
lastStartError = nil
|
||||
onEngineStarted?()
|
||||
} catch {
|
||||
lastStartError = "Start failed: \(error)"
|
||||
}
|
||||
}
|
||||
model.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (Linux)
|
||||
|
||||
extension LyrebirdEngineStatusView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting an engine status view.
|
||||
///
|
||||
/// Use when no parent view is available — a script or command-line demo can
|
||||
/// call this to surface engine status in its own GTK window. Requires a
|
||||
/// running `GtkApplication` loop. The returned `LyrebirdWindow` owns the GTK
|
||||
/// 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.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
engine: SynthesisEngine,
|
||||
title: String = "Engine Status",
|
||||
width: Double = 320,
|
||||
height: Double = 480
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdEngineStatusView(engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
Text("\(value)")
|
||||
.font(.title3)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.primary)
|
||||
if let sub: String = subtitle {
|
||||
Text(sub)
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.tertiary)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
/// A labelled CPU-load bar for the Linux/GTK4 UI. The bar itself is `Canvas`-drawn
|
||||
/// (`DrawingContext` has no text primitive); label + percentage are real `Text`.
|
||||
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 let labelWidth: Double = 60
|
||||
private let barWidth: Double = 120
|
||||
private let barHeight: Double = 6
|
||||
private let percentWidth: Double = 56
|
||||
|
||||
private var displayPercent: Double {
|
||||
min(value * 100.0, CPURow.maxDisplayPercent)
|
||||
}
|
||||
|
||||
private var barRGB: (r: Double, g: Double, b: Double) {
|
||||
if value < CPURow.warningThreshold { return (0.0, 0.8, 0.0) } // green
|
||||
if value < CPURow.criticalThreshold { return (1.0, 0.8, 0.0) } // yellow
|
||||
return (1.0, 0.2, 0.2) // red
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(label)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: labelWidth, alignment: .leading)
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
// Track.
|
||||
ctx.setColor(r: 0.5, g: 0.5, b: 0.5, a: 0.15)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
// Filled portion, clamped to the track width.
|
||||
let frac: Double = min(max(value, 0.0), 1.0)
|
||||
let rgb: (r: Double, g: Double, b: Double) = barRGB
|
||||
ctx.setColor(r: rgb.r, g: rgb.g, b: rgb.b)
|
||||
ctx.rectangle(x: 0, y: 0, width: w * frac, height: h)
|
||||
ctx.fill()
|
||||
})
|
||||
.frame(width: barWidth, height: barHeight)
|
||||
Text(String(format: "%.1f%%", displayPercent))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: percentWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Canvas-drawn horizontal slider bound to a `Binding<Double>` for the
|
||||
/// Linux/GTK4 UI. Used instead of the native `Slider` (GtkScale), whose pointer
|
||||
/// hit-testing is unreliable here (drag catches outside the thumb, misses
|
||||
/// clicks). Same drawing/drag approach as `ParameterSlider`, but over a plain
|
||||
/// `Binding` + range (linear) rather than a `UIParamNode`.
|
||||
private struct LinuxValueSlider: View {
|
||||
@Binding var value: Double
|
||||
let range: ClosedRange<Double>
|
||||
/// Fired directly on every drag motion with the new value. The fork defers
|
||||
/// host rebuilds during a drag, so an `onChange(of:)` observer would not see
|
||||
/// intermediate values until mouse-up; this callback applies the live effect
|
||||
/// (e.g. the engine gain) on each motion, exactly as the Canvas knobs write
|
||||
/// their node in the drag handler.
|
||||
var onEditing: ((Double) -> Void)? = nil
|
||||
|
||||
private let trackWidth: Double = 240
|
||||
private let trackHeight: Double = 24
|
||||
private let thumbRadius: Double = 7
|
||||
|
||||
var body: some View {
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
let cy: Double = h / 2
|
||||
let x0: Double = thumbRadius
|
||||
let x1: Double = w - thumbRadius
|
||||
let usable: Double = max(x1 - x0, 1)
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let pos: Double = span > 0 ? (value - range.lowerBound) / span : 0
|
||||
let clampedPos: Double = min(1, max(0, pos))
|
||||
let thumbX: Double = x0 + clampedPos * usable
|
||||
|
||||
// Track background.
|
||||
ctx.setColor(r: 0.20, g: 0.20, b: 0.20)
|
||||
ctx.setLineWidth(4)
|
||||
ctx.moveTo(x: x0, y: cy)
|
||||
ctx.lineTo(x: x1, y: cy)
|
||||
ctx.stroke()
|
||||
|
||||
// Filled portion up to the thumb.
|
||||
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
|
||||
ctx.setLineWidth(4)
|
||||
ctx.moveTo(x: x0, y: cy)
|
||||
ctx.lineTo(x: thumbX, y: cy)
|
||||
ctx.stroke()
|
||||
|
||||
// Thumb.
|
||||
ctx.setColor(r: 0.90, g: 0.90, b: 0.95)
|
||||
ctx.arc(centerX: thumbX, centerY: cy, radius: thumbRadius,
|
||||
startAngle: 0, endAngle: 2 * Double.pi)
|
||||
ctx.fill()
|
||||
})
|
||||
.frame(width: trackWidth, height: trackHeight)
|
||||
.onDrag(
|
||||
minimumDistance: 0,
|
||||
onChanged: { (drag: DragGestureValue) in
|
||||
let x0: Double = thumbRadius
|
||||
let usable: Double = max(trackWidth - 2 * thumbRadius, 1)
|
||||
let pos: Double = min(1, max(0, (drag.location.x - x0) / usable))
|
||||
let span: Double = range.upperBound - range.lowerBound
|
||||
let newValue: Double = range.lowerBound + pos * span
|
||||
value = newValue
|
||||
onEditing?(newValue)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -100,8 +101,8 @@ func _envelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) {
|
||||
public struct LyrebirdEnvelopeView: View {
|
||||
|
||||
private let envelope: Envelope
|
||||
private let width: CGFloat
|
||||
private let height: CGFloat
|
||||
private let width: Double
|
||||
private let height: Double
|
||||
|
||||
private static let backgroundBrightness: CGFloat = 0.08
|
||||
private static let backgroundColor: Color = Color(white: backgroundBrightness)
|
||||
@@ -121,8 +122,8 @@ public struct LyrebirdEnvelopeView: View {
|
||||
|
||||
public init(
|
||||
_ envelope: Envelope,
|
||||
width: CGFloat = 300,
|
||||
height: CGFloat = 120
|
||||
width: Double = 300,
|
||||
height: Double = 120
|
||||
) {
|
||||
self.envelope = envelope
|
||||
self.width = width
|
||||
@@ -257,3 +258,253 @@ public struct LyrebirdEnvelopeView: View {
|
||||
return height * (1.0 - CGFloat(t))
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEnvelopeView`: plots a core
|
||||
// `Envelope` as a colour-coded shape on a single `Canvas`. Static — it draws a
|
||||
// fixed spec once, no timer or polling.
|
||||
//
|
||||
// Divergence from macOS: `DrawingContext` has no text drawing, so the "L"/"R"
|
||||
// letters beside the loop/release markers are omitted. The dashed marker line
|
||||
// still shows each boundary, colour-coded green (loop) / orange (release) to
|
||||
// match the segment colours.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Foundation
|
||||
|
||||
// MARK: - Region
|
||||
|
||||
/// Render region for one envelope segment.
|
||||
enum _LinuxEnvelopeRegion {
|
||||
case preLoop
|
||||
case loop
|
||||
case release
|
||||
|
||||
/// Trace colour as an RGB triple for `DrawingContext.setColor`.
|
||||
var rgb: (r: Double, g: Double, b: Double) {
|
||||
switch self {
|
||||
case .preLoop: return (0.0, 0.8, 1.0) // cyan
|
||||
case .loop: return (0.0, 0.8, 0.0) // green
|
||||
case .release: return (1.0, 0.53, 0.0) // orange
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Pure helpers
|
||||
|
||||
/// 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 coloured `.loop`. Segments after it are the gate-off release path — they play once
|
||||
/// after gate drops and are correctly classified as `.preLoop`.
|
||||
func _linuxRegionForSegment(
|
||||
index: Int,
|
||||
loopNode: Int?,
|
||||
releaseNode: Int?
|
||||
) -> _LinuxEnvelopeRegion {
|
||||
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 _linuxSegmentBoundaryTimes(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 _linuxEnvelopeYBounds(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
|
||||
|
||||
/// Plots an `Envelope` as a colour-coded shape for the Linux/GTK4 UI. Segments
|
||||
/// are cyan before any loop/release, green in the loop region, orange in the
|
||||
/// release region; horizontal hairlines mark segment levels; dashed vertical
|
||||
/// lines mark the loop (green) and release (orange) boundaries.
|
||||
public struct LyrebirdEnvelopeView: View {
|
||||
|
||||
private let envelope: Envelope
|
||||
private let width: Double
|
||||
private let height: Double
|
||||
|
||||
// Presentation constants.
|
||||
private let cornerRadius: Double = 4
|
||||
/// Path points per canvas pixel — smooth enough for all curve shapes.
|
||||
private let oversample: Double = 2
|
||||
private let signalLineWidth: Double = 1.5
|
||||
private let guideLineWidth: Double = 0.5
|
||||
private let markerLineWidth: Double = 1
|
||||
private let markerOpacity: Double = 0.7
|
||||
private let levelTickOpacity: Double = 0.2
|
||||
private let markerDash: [CGFloat] = [4, 3]
|
||||
|
||||
/// Creates an envelope plot.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - envelope: The `Envelope` to plot.
|
||||
/// - width: Canvas width in points. Default 300.
|
||||
/// - height: Canvas height in points. Default 120.
|
||||
public init(
|
||||
_ envelope: Envelope,
|
||||
width: Double = 300,
|
||||
height: Double = 120
|
||||
) {
|
||||
self.envelope = envelope
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
draw(ctx: ctx, size: size)
|
||||
})
|
||||
.frame(width: width, height: height)
|
||||
.clipShape(RoundedRectangle(cornerRadius: cornerRadius))
|
||||
}
|
||||
|
||||
// MARK: - Drawing
|
||||
|
||||
private func draw(ctx: DrawingContext, size: CGSize) {
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
|
||||
// Background.
|
||||
ctx.setColor(r: 0.08, g: 0.08, b: 0.08)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
|
||||
let bounds: (yMin: Double, yMax: Double) = _linuxEnvelopeYBounds(levels: envelope.levels)
|
||||
let segCount: Int = envelope.segmentCount
|
||||
|
||||
// Degenerate: no segments or zero duration → flat line at the first level.
|
||||
guard segCount > 0 && envelope.totalDuration > 0 else {
|
||||
let v: Double = envelope.levels.first ?? 0
|
||||
let y: Double = yFor(v, bounds: bounds, height: h)
|
||||
ctx.setColor(r: 0.0, g: 0.8, b: 1.0)
|
||||
ctx.setLineWidth(signalLineWidth)
|
||||
ctx.moveTo(x: 0, y: y)
|
||||
ctx.lineTo(x: w, y: y)
|
||||
ctx.stroke()
|
||||
return
|
||||
}
|
||||
|
||||
let boundaryTimes: [Double] = _linuxSegmentBoundaryTimes(durations: envelope.durations)
|
||||
let totalSamples: Int = Int(ceil(w * oversample))
|
||||
|
||||
// Horizontal level hairlines.
|
||||
ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: levelTickOpacity)
|
||||
ctx.setLineWidth(guideLineWidth)
|
||||
for level: Double in envelope.levels {
|
||||
let y: Double = yFor(level, bounds: bounds, height: h)
|
||||
ctx.moveTo(x: 0, y: y)
|
||||
ctx.lineTo(x: w, y: y)
|
||||
}
|
||||
ctx.stroke()
|
||||
|
||||
// One coloured polyline per segment.
|
||||
for seg: Int in 0..<segCount {
|
||||
let region: _LinuxEnvelopeRegion = _linuxRegionForSegment(
|
||||
index: seg,
|
||||
loopNode: envelope.loopNode,
|
||||
releaseNode: envelope.releaseNode
|
||||
)
|
||||
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 so the final
|
||||
// point lands exactly at tEnd, closing each segment cleanly.
|
||||
let nSamples: Int = max(2, Int(ceil(Double(totalSamples) * frac)))
|
||||
|
||||
let rgb: (r: Double, g: Double, b: Double) = region.rgb
|
||||
ctx.setColor(r: rgb.r, g: rgb.g, b: rgb.b)
|
||||
ctx.setLineWidth(signalLineWidth)
|
||||
for i: Int in 0...nSamples {
|
||||
let t: Double = tStart + segDur * Double(i) / Double(nSamples)
|
||||
let v: Double = envelope.valueAtTime(t)
|
||||
let x: Double = xFor(t, width: w)
|
||||
let y: Double = yFor(v, bounds: bounds, height: h)
|
||||
if i == 0 {
|
||||
ctx.moveTo(x: x, y: y)
|
||||
} else {
|
||||
ctx.lineTo(x: x, y: y)
|
||||
}
|
||||
}
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// Vertical dashed markers — loopNode/releaseNode are pre-validated by
|
||||
// Envelope.init to be in [0, segmentCount), so boundaryTimes is in bounds.
|
||||
if let ln: Int = envelope.loopNode {
|
||||
drawMarker(ctx: ctx, time: boundaryTimes[ln], region: .loop, width: w, height: h)
|
||||
}
|
||||
if let rn: Int = envelope.releaseNode {
|
||||
drawMarker(ctx: ctx, time: boundaryTimes[rn], region: .release, width: w, height: h)
|
||||
}
|
||||
}
|
||||
|
||||
private func drawMarker(
|
||||
ctx: DrawingContext,
|
||||
time: Double,
|
||||
region: _LinuxEnvelopeRegion,
|
||||
width w: Double,
|
||||
height h: Double
|
||||
) {
|
||||
// Derive the marker colour from the region so it matches that region's
|
||||
// segment trace exactly (green loop, orange release).
|
||||
let rgb: (r: Double, g: Double, b: Double) = region.rgb
|
||||
let color: Color = Color(red: rgb.r, green: rgb.g, blue: rgb.b)
|
||||
let x: Double = xFor(time, width: w)
|
||||
var line: Path = Path()
|
||||
line.move(to: CGPoint(x: x, y: 0))
|
||||
line.addLine(to: CGPoint(x: x, y: h))
|
||||
ctx.stroke(
|
||||
line,
|
||||
with: .color(color.opacity(markerOpacity)),
|
||||
style: StrokeStyle(lineWidth: markerLineWidth, dash: markerDash)
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Coordinate helpers
|
||||
|
||||
private func xFor(_ t: Double, width w: Double) -> Double {
|
||||
(t / envelope.totalDuration) * w
|
||||
}
|
||||
|
||||
private func yFor(
|
||||
_ v: Double,
|
||||
bounds: (yMin: Double, yMax: Double),
|
||||
height h: Double
|
||||
) -> Double {
|
||||
let t: Double = (v - bounds.yMin) / (bounds.yMax - bounds.yMin)
|
||||
return h * (1.0 - t)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -163,3 +164,180 @@ extension LyrebirdEventListPerformanceView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEventListPerformanceView`: a
|
||||
// ``LyrebirdEventListView`` on top plus a live stack of ``LyrebirdProcessView``
|
||||
// strips, one per running process. The 10 Hz membership poll moves off
|
||||
// SwiftOpenUI's off-main `.task` onto a `Timer` on `RunLoop.main` inside an
|
||||
// `@Observable` model, keeping the identity-stable reassignment so child strips
|
||||
// keep their own timers/state across ticks.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// 10 Hz — matches ``LyrebirdProcessView`` / ``LyrebirdEventListView``.
|
||||
private let linuxEventListPerformancePollIntervalSeconds: TimeInterval = 0.1
|
||||
|
||||
/// Polls an event list's running processes on a main-thread timer and publishes
|
||||
/// an identity-stable snapshot for ``LyrebirdEventListPerformanceView``. Internal.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`,
|
||||
/// same rationale as `LyrebirdScopeModel`.
|
||||
@Observable
|
||||
final class LinuxEventListPerformanceModel: @unchecked Sendable {
|
||||
|
||||
var runningProcesses: [LyrebirdProcess] = []
|
||||
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
@ObservationIgnored private let eventList: LyrebirdEventList
|
||||
|
||||
init(eventList: LyrebirdEventList) {
|
||||
self.eventList = eventList
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
refresh()
|
||||
let t: Timer = Timer.scheduledTimer(
|
||||
withTimeInterval: linuxEventListPerformancePollIntervalSeconds,
|
||||
repeats: true
|
||||
) { [weak self] _ in
|
||||
self?.refresh()
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
let snapshot: [LyrebirdProcess] = eventList.allProcesses.filter { $0.isRunning }
|
||||
if !snapshot.elementsEqualByIdentity(to: runningProcesses) {
|
||||
runningProcesses = snapshot
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A composite event-list performance view for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdEventListPerformanceView`; same public API/init as the
|
||||
/// Apple side.
|
||||
public struct LyrebirdEventListPerformanceView: View {
|
||||
|
||||
public let eventList: LyrebirdEventList
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var model: LinuxEventListPerformanceModel
|
||||
|
||||
/// 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
|
||||
_model = State(wrappedValue: LinuxEventListPerformanceModel(eventList: eventList))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
LyrebirdEventListView(eventList: eventList)
|
||||
|
||||
Divider()
|
||||
|
||||
if model.runningProcesses.isEmpty {
|
||||
emptyState
|
||||
} else {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
ForEach(model.runningProcesses, id: \.identityKey) { proc in
|
||||
LyrebirdProcessView(process: proc, engine: engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 360, minHeight: 320)
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Stable identity for ForEach
|
||||
|
||||
private extension LyrebirdProcess {
|
||||
/// `ObjectIdentifier`-based key used for `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 (Linux)
|
||||
|
||||
extension LyrebirdEventListPerformanceView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting an event-list performance view. Requires
|
||||
/// a running `GtkApplication` loop.
|
||||
///
|
||||
/// - 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.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine,
|
||||
title: String? = nil,
|
||||
width: Double = 420,
|
||||
height: Double = 520
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(
|
||||
title: title ?? eventList.id,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
win.open {
|
||||
LyrebirdEventListPerformanceView(eventList: eventList, engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -331,3 +332,359 @@ extension LyrebirdEventListView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEventListView`: transport for a
|
||||
// `LyrebirdEventList` (state dot + id, now/next event rows, dB amp slider,
|
||||
// Next/Back/Skip, Set Next, Reset/Release All/Kill All). The 10 Hz poll moves off
|
||||
// SwiftOpenUI's off-main `.task` onto a `Timer` on `RunLoop.main` inside an
|
||||
// `@Observable` model, which also carries the transport-derived UI flags. The
|
||||
// text field for "Set Next" stays plain `@State` on the view. dB↔amp maths reuse
|
||||
// the cross-platform `DbSliderConversion`; the amp control is a native `Slider`.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// 10 Hz event-list poll interval.
|
||||
private let linuxEventListPollIntervalSeconds: TimeInterval = 0.1
|
||||
|
||||
/// Polls a `LyrebirdEventList`'s transport state on a main-thread timer and
|
||||
/// publishes it for ``LyrebirdEventListView``. Internal — only the view is public.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`,
|
||||
/// same rationale as `LyrebirdScopeModel`.
|
||||
@Observable
|
||||
final class LinuxEventListModel: @unchecked Sendable {
|
||||
|
||||
var isRunning: Bool = false
|
||||
var currentEvent: Int? = nil
|
||||
var nextEvent: Int? = nil
|
||||
var playIndex: Int = 0
|
||||
var amp: Double = 1.0
|
||||
var hasBeenStopped: Bool = false
|
||||
|
||||
@ObservationIgnored let eventList: LyrebirdEventList
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
|
||||
init(eventList: LyrebirdEventList) {
|
||||
self.eventList = eventList
|
||||
// `amp` is @MainActor; construction happens on the GTK main thread.
|
||||
self.amp = MainActor.assumeIsolated { eventList.amp }
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
refresh()
|
||||
let t: Timer = Timer.scheduledTimer(
|
||||
withTimeInterval: linuxEventListPollIntervalSeconds,
|
||||
repeats: true
|
||||
) { [weak self] _ in
|
||||
self?.refresh()
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
|
||||
// Runs on the GTK main thread (view init / onAppear / RunLoop.main timer), so
|
||||
// `assumeIsolated` reaches the @MainActor `amp` safely. The other members are
|
||||
// nonisolated already.
|
||||
func refresh() {
|
||||
isRunning = eventList.isRunning
|
||||
currentEvent = eventList.currentEvent
|
||||
nextEvent = eventList.nextEvent
|
||||
playIndex = eventList.index
|
||||
amp = MainActor.assumeIsolated { eventList.amp }
|
||||
if !isRunning && currentEvent != nil {
|
||||
hasBeenStopped = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A control panel for driving a `LyrebirdEventList` on the Linux/GTK4 UI.
|
||||
/// Mirrors `LyrebirdUI.LyrebirdEventListView`; same public API/init as the Apple
|
||||
/// side.
|
||||
public struct LyrebirdEventListView: View {
|
||||
|
||||
public let eventList: LyrebirdEventList
|
||||
|
||||
@State private var model: LinuxEventListModel
|
||||
@State private var setNextField: String = ""
|
||||
|
||||
// Layout constants (points).
|
||||
private let dotSize: Double = 10
|
||||
private let ampLabelWidth: Double = 36
|
||||
private let dbReadoutWidth: Double = 56
|
||||
private let setNextFieldWidth: Double = 80
|
||||
private let disabledDotOpacity: Double = 0.4
|
||||
|
||||
/// Creates an event-list control view bound to the given list.
|
||||
///
|
||||
/// - Parameter eventList: The `LyrebirdEventList` to control.
|
||||
public init(eventList: LyrebirdEventList) {
|
||||
self.eventList = eventList
|
||||
_model = State(wrappedValue: LinuxEventListModel(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)
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(model.isRunning ? Color.green : Color.secondary.opacity(disabledDotOpacity))
|
||||
.frame(width: dotSize, height: dotSize)
|
||||
Text(eventList.id)
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(eventList.eventCount) events")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var currentNextRows: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
EventRow(
|
||||
label: "Now",
|
||||
index: model.currentEvent,
|
||||
description: descriptionForEvent(at: model.currentEvent)
|
||||
)
|
||||
EventRow(
|
||||
label: "Next",
|
||||
index: model.nextEvent,
|
||||
description: descriptionForEvent(at: model.nextEvent)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private var ampRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Amp")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: ampLabelWidth, alignment: .leading)
|
||||
Slider(value: Binding(
|
||||
get: { dbFromAmp(model.amp) },
|
||||
set: { newDb in
|
||||
let newAmp: Double = ampFromDb(newDb)
|
||||
model.amp = newAmp
|
||||
// Bind `eventList` (Sendable) to a local so the @MainActor
|
||||
// closure captures it, not `self` (the non-Sendable View).
|
||||
let el: LyrebirdEventList = eventList
|
||||
MainActor.assumeIsolated { el.amp = newAmp }
|
||||
}
|
||||
), in: LyrebirdEventListView.minDb ... LyrebirdEventListView.maxDb)
|
||||
Text(dbDisplay(dbFromAmp(model.amp)))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: dbReadoutWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - dB <-> linear amplitude (shared 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") {
|
||||
let el: LyrebirdEventList = eventList
|
||||
MainActor.assumeIsolated { el.next() }
|
||||
}
|
||||
.disabled(model.nextEvent == nil)
|
||||
|
||||
Spacer()
|
||||
|
||||
Button("Back") {
|
||||
let cur: Int = eventList.index
|
||||
guard cur > 0 else { return }
|
||||
eventList.index = cur - 1
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(model.playIndex <= 0)
|
||||
Button("Skip") {
|
||||
let cur: Int = eventList.index
|
||||
guard cur < eventList.eventCount else { return }
|
||||
eventList.index = cur + 1
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(model.nextEvent == nil)
|
||||
}
|
||||
}
|
||||
|
||||
private var setNextRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Set Next")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
TextField("index", text: $setNextField)
|
||||
.frame(maxWidth: setNextFieldWidth)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
Button("Apply") {
|
||||
applySetNext()
|
||||
}
|
||||
.disabled(parsedSetNext() == nil)
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
private var stopRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Button("Reset") {
|
||||
let el: LyrebirdEventList = eventList
|
||||
MainActor.assumeIsolated { el.reset() }
|
||||
model.hasBeenStopped = false
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(!model.hasBeenStopped)
|
||||
|
||||
Spacer()
|
||||
|
||||
Button("Release All") {
|
||||
let el: LyrebirdEventList = eventList
|
||||
MainActor.assumeIsolated { el.releaseAll() }
|
||||
model.hasBeenStopped = true
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(!model.isRunning || model.hasBeenStopped)
|
||||
|
||||
Button("Kill All") {
|
||||
let el: LyrebirdEventList = eventList
|
||||
MainActor.assumeIsolated { el.killAll() }
|
||||
model.hasBeenStopped = true
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(!model.isRunning || model.hasBeenStopped)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
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 = ""
|
||||
model.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sub-views
|
||||
|
||||
private struct EventRow: View {
|
||||
let label: String
|
||||
let index: Int?
|
||||
let description: String
|
||||
|
||||
private let labelWidth: Double = 36
|
||||
private let indexWidth: Double = 32
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(label)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: labelWidth, alignment: .leading)
|
||||
Text(indexText)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: indexWidth, 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 (Linux)
|
||||
|
||||
extension LyrebirdEventListView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting an event-list control view. Requires a
|
||||
/// running `GtkApplication` loop.
|
||||
///
|
||||
/// - 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.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
eventList: LyrebirdEventList,
|
||||
title: String = "Event List",
|
||||
width: Double = 360,
|
||||
height: Double = 260
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdEventListView(eventList: eventList)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -124,3 +125,117 @@ public struct LyrebirdMessageBanner: View {
|
||||
return Array(all[start..<all.count])
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdMessageBanner`: a compact banner
|
||||
// showing the most recent few messages from a `LyrebirdMessageCenter`, with a
|
||||
// tier-coloured left stripe, that runs `onOpenFull` on tap. Live updates come
|
||||
// from `@Bindable` on the `@Observable` center (reads inside the body are
|
||||
// observation-tracked, same as the Apple side — no polling). SF-Symbol art and
|
||||
// `RoundedRectangle` chrome are dropped; the layout is `HStack`/`VStack` + `Text`.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A compact recent-messages banner for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdMessageBanner`: up to ``lineCount`` recent messages with
|
||||
/// a tier-coloured stripe; tapping invokes ``onOpenFull``.
|
||||
public struct LyrebirdMessageBanner: View {
|
||||
|
||||
@Bindable private var center: LyrebirdMessageCenter
|
||||
|
||||
/// Number of recent messages shown when present. Defaults to `3`.
|
||||
public let lineCount: Int
|
||||
|
||||
/// Tap action. `nil` makes the banner non-interactive.
|
||||
public let onOpenFull: (() -> Void)?
|
||||
|
||||
// Presentation constants (points).
|
||||
private let stripeWidth: Double = 3
|
||||
private let stripeHeight: Double = 11
|
||||
private let cornerRadiusPoints: Double = 4
|
||||
|
||||
/// 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 {
|
||||
// A single static Button keeps state changes on the backend's narrow
|
||||
// in-place mutation path (see ParameterButton's Linux body for the
|
||||
// rationale). The empty state and the populated rows both live inside
|
||||
// the one button; `press()` re-reads at click time.
|
||||
Button(action: { onOpenFull?() }) {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
let recent: [LyrebirdMessage] = recentMessages
|
||||
if recent.isEmpty {
|
||||
Text("No messages")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
ForEach(recent) { msg in
|
||||
bannerRow(msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(6)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.cornerRadius(cornerRadiusPoints)
|
||||
.disabled(onOpenFull == nil)
|
||||
}
|
||||
|
||||
private func bannerRow(_ msg: LyrebirdMessage) -> some View {
|
||||
HStack(spacing: 6) {
|
||||
Capsule()
|
||||
.fill(LyrebirdMessageTierStyle.color(for: msg.tier))
|
||||
.frame(width: stripeWidth, height: stripeHeight)
|
||||
Text(msg.text)
|
||||
.font(.caption)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
}
|
||||
|
||||
private var recentMessages: [LyrebirdMessage] {
|
||||
// `LyrebirdMessageCenter` is @MainActor; the SwiftOpenUI body runs on the
|
||||
// GTK main thread, so `assumeIsolated` reaches `messages` safely. Bind the
|
||||
// center to a local first so the `@MainActor` closure captures the
|
||||
// (Sendable) center, not `self` (the non-Sendable View).
|
||||
let c: LyrebirdMessageCenter = center
|
||||
let all: [LyrebirdMessage] = MainActor.assumeIsolated { c.messages }
|
||||
guard all.count > lineCount else { return all }
|
||||
let start: Int = all.count - lineCount
|
||||
return Array(all[start..<all.count])
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -29,3 +30,32 @@ enum LyrebirdMessageTierStyle {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to the Apple `LyrebirdMessageTierStyle`. Identical
|
||||
// per-tier colour/label mapping; `Color` here is SwiftOpenUI's, not SwiftUI's.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Module-internal styling helpers shared between ``LyrebirdMessageView``
|
||||
/// and ``LyrebirdMessageBanner`` on Linux/GTK4.
|
||||
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"
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -81,6 +82,12 @@ public struct LyrebirdMessageView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Current messages. On Apple the body is `@MainActor`, so this is a plain
|
||||
/// read (the Linux counterpart hops via `assumeIsolated`).
|
||||
private var messagesSnapshot: [LyrebirdMessage] {
|
||||
center.messages
|
||||
}
|
||||
|
||||
private var filterRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
ForEach(LyrebirdMessageTier.allCases, id: \.self) { tier in
|
||||
@@ -129,17 +136,17 @@ public struct LyrebirdMessageView: View {
|
||||
// MARK: - Helpers
|
||||
|
||||
private var filteredMessages: [LyrebirdMessage] {
|
||||
center.messages.filter { enabledTiers.contains($0.tier) }
|
||||
messagesSnapshot.filter { enabledTiers.contains($0.tier) }
|
||||
}
|
||||
|
||||
private var emptyStateText: String {
|
||||
if center.messages.isEmpty { return "No messages." }
|
||||
if messagesSnapshot.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 {
|
||||
for msg: LyrebirdMessage in messagesSnapshot where msg.tier == tier {
|
||||
n += 1
|
||||
}
|
||||
return n
|
||||
@@ -273,3 +280,296 @@ extension LyrebirdMessageView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdMessageView`: a full scrollable
|
||||
// view over a `LyrebirdMessageCenter` ring — a header (title, count, Clear), a
|
||||
// per-tier filter row with live counts, and a scrolling list of rows. Live
|
||||
// updates come from `@Bindable` on the `@Observable` center (body reads are
|
||||
// observation-tracked, same as the Apple side). Text is drawn with real `Text`
|
||||
// widgets, so the readout is complete.
|
||||
//
|
||||
// Dropped vs the Apple side (document per project rule): the auto-scroll to the
|
||||
// newest row (`ScrollViewReader`/`onChange`/`withAnimation`) and per-row text
|
||||
// selection are omitted; the list simply scrolls. `presentInWindow` opens a
|
||||
// detached GTK window (needs a running `GtkApplication`).
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
import Foundation // DateFormatter for the row timestamp
|
||||
|
||||
/// Full scrollable view over a `LyrebirdMessageCenter` ring for the Linux/GTK4
|
||||
/// UI. Mirrors `LyrebirdUI.LyrebirdMessageView` (minus auto-scroll and text
|
||||
/// selection); same public API/init as the Apple side.
|
||||
public struct LyrebirdMessageView: View {
|
||||
|
||||
@Bindable private var center: LyrebirdMessageCenter
|
||||
|
||||
@State private var enabledTiers: Set<LyrebirdMessageTier> =
|
||||
Set(LyrebirdMessageTier.allCases)
|
||||
|
||||
// Presentation constants (points).
|
||||
private let minPanelWidth: Double = 360
|
||||
private let minPanelHeight: Double = 200
|
||||
private let timeColumnWidth: Double = 80
|
||||
private let stripeWidth: Double = 3
|
||||
private let stripeHeight: Double = 14
|
||||
|
||||
/// 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: minPanelWidth, minHeight: minPanelHeight)
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
// `LyrebirdMessageCenter` is @MainActor; the SwiftOpenUI body / actions run on
|
||||
// the GTK main thread, so `assumeIsolated` reaches `messages` / `clear()`
|
||||
// safely. The center is bound to a local first so the `@MainActor` closure
|
||||
// captures the (Sendable) center rather than `self` (the non-Sendable View).
|
||||
private var messagesSnapshot: [LyrebirdMessage] {
|
||||
let c: LyrebirdMessageCenter = center
|
||||
return MainActor.assumeIsolated { c.messages }
|
||||
}
|
||||
|
||||
private var headerRow: some View {
|
||||
let all: [LyrebirdMessage] = messagesSnapshot
|
||||
let c: LyrebirdMessageCenter = center
|
||||
return HStack(spacing: 8) {
|
||||
Text("Messages")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(all.count)")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
// action:label: form — the string-title Button's action does not
|
||||
// fire on GTK4 here (same as the EngineStatus Stop button).
|
||||
Button {
|
||||
MainActor.assumeIsolated { c.clear() }
|
||||
} label: {
|
||||
Text("Clear")
|
||||
}
|
||||
.disabled(all.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 ScrollView {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
if visible.isEmpty {
|
||||
Text(emptyStateText)
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
ForEach(visible) { msg in
|
||||
MessageRow(
|
||||
message: msg,
|
||||
timeColumnWidth: timeColumnWidth,
|
||||
stripeWidth: stripeWidth,
|
||||
stripeHeight: stripeHeight
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private var filteredMessages: [LyrebirdMessage] {
|
||||
messagesSnapshot.filter { enabledTiers.contains($0.tier) }
|
||||
}
|
||||
|
||||
private var emptyStateText: String {
|
||||
if messagesSnapshot.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 messagesSnapshot 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
|
||||
|
||||
private let dotSize: Double = 8
|
||||
private let cornerRadiusPoints: Double = 4
|
||||
private let disabledDotOpacity: Double = 0.35
|
||||
private let disabledChipOpacity: Double = 0.55
|
||||
|
||||
var body: some View {
|
||||
Button(action: toggle) {
|
||||
HStack(spacing: 4) {
|
||||
Circle()
|
||||
.fill(LyrebirdMessageTierStyle.color(for: tier))
|
||||
.frame(width: dotSize, height: dotSize)
|
||||
.opacity(isEnabled ? 1.0 : disabledDotOpacity)
|
||||
Text(LyrebirdMessageTierStyle.shortLabel(for: tier))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
Text("\(count)")
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 3)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.cornerRadius(cornerRadiusPoints)
|
||||
.opacity(isEnabled ? 1.0 : disabledChipOpacity)
|
||||
}
|
||||
}
|
||||
|
||||
private struct MessageRow: View {
|
||||
let message: LyrebirdMessage
|
||||
let timeColumnWidth: Double
|
||||
let stripeWidth: Double
|
||||
let stripeHeight: Double
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text(MessageRow.formatTime(message.timestamp))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: timeColumnWidth, alignment: .leading)
|
||||
Capsule()
|
||||
.fill(LyrebirdMessageTierStyle.color(for: message.tier))
|
||||
.frame(width: stripeWidth, height: stripeHeight)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
if let src: String = message.source, !src.isEmpty {
|
||||
Text(src)
|
||||
.font(.caption2)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Text(message.text)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.primary)
|
||||
}
|
||||
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 (Linux)
|
||||
|
||||
extension LyrebirdMessageView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a message view bound to the shared
|
||||
/// `LyrebirdMessageCenter`. Requires a running `GtkApplication` loop.
|
||||
///
|
||||
/// - Important: Call on the GTK main thread (as the "Open Window" buttons and
|
||||
/// any top-level demo/`main()` code do). It reaches the `@MainActor`
|
||||
/// `LyrebirdMessageCenter.shared` via `assumeIsolated`, which traps if
|
||||
/// invoked off the main thread — from a background/script thread, use the
|
||||
/// `presentInWindow(center:...)` overload with an explicitly-resolved center.
|
||||
///
|
||||
/// - 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.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
title: String = "Messages",
|
||||
width: Double = 460,
|
||||
height: Double = 360
|
||||
) -> LyrebirdWindow {
|
||||
// `LyrebirdMessageCenter.shared` is `@MainActor`; this runs on the GTK
|
||||
// main thread, so `assumeIsolated` reaches it (no `self` captured — no
|
||||
// sending-race), same hop the messages section uses.
|
||||
let center: LyrebirdMessageCenter = MainActor.assumeIsolated {
|
||||
LyrebirdMessageCenter.shared
|
||||
}
|
||||
return presentInWindow(
|
||||
center: center,
|
||||
title: title,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
}
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a message view bound to `center`.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
center: LyrebirdMessageCenter,
|
||||
title: String = "Messages",
|
||||
width: Double = 460,
|
||||
height: Double = 360
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdMessageView(center: center)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -262,3 +263,251 @@ extension LyrebirdNodeTreeView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdNodeTreeView`: a live indented
|
||||
// tree of the engine's `NodeTreeMirror`, rows head→tail. Live updates come from
|
||||
// reading `mirror.snapshot` in the body (observation-tracked, `NodeTreeMirror`
|
||||
// is `@Observable`). Groups expand/collapse via a tapped glyph.
|
||||
//
|
||||
// Differences vs the Apple side: SF-Symbol chevrons/dots become text glyphs
|
||||
// (▼ / ▶ / •) — `DrawingContext` has no image atlas and Text is available here;
|
||||
// monospaced fonts fall back to the default font. `presentInWindow` opens a
|
||||
// detached GTK window (needs a running `GtkApplication`).
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Live indented tree of the engine's `NodeTreeMirror` for the Linux/GTK4 UI.
|
||||
/// Mirrors `LyrebirdUI.LyrebirdNodeTreeView`; same public API/init as the Apple
|
||||
/// side.
|
||||
public struct LyrebirdNodeTreeView: View {
|
||||
|
||||
private let mirror: NodeTreeMirror
|
||||
|
||||
@State private var expanded: Set<ObjectIdentifier> = []
|
||||
|
||||
private let minPanelWidth: Double = 320
|
||||
private let minPanelHeight: Double = 220
|
||||
|
||||
/// 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(top: 4, bottom: 4, leading: 0, trailing: 0)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: minPanelWidth, minHeight: minPanelHeight)
|
||||
.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)
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
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: Double = 14
|
||||
private static let glyphWidth: Double = 12
|
||||
private static let identityHexSuffixLen: Int = 4
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 6) {
|
||||
Spacer()
|
||||
.frame(width: Double(depth) * NodeRow.indentPoints)
|
||||
|
||||
Text(glyph)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: NodeRow.glyphWidth, alignment: .center)
|
||||
|
||||
Text(node.displayName)
|
||||
.font(.callout)
|
||||
.foregroundStyle(.primary)
|
||||
|
||||
if let badge: String = childCountBadge {
|
||||
Text(badge)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
Text(_identityShort(node.id))
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.tertiary)
|
||||
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.onTapGesture { if isContainer { toggle() } }
|
||||
}
|
||||
|
||||
/// Expand/collapse glyph for containers; a bullet for leaf synth nodes.
|
||||
private var glyph: String {
|
||||
guard isContainer else { return "•" }
|
||||
return isExpanded ? "▼" : "▶"
|
||||
}
|
||||
|
||||
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 (Linux)
|
||||
|
||||
extension LyrebirdNodeTreeView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a node-tree view. Requires a running
|
||||
/// `GtkApplication` loop.
|
||||
///
|
||||
/// - 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`.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
engine: SynthesisEngine,
|
||||
title: String = "Node Tree",
|
||||
width: Double = 420,
|
||||
height: Double = 420
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
|
||||
win.open {
|
||||
LyrebirdNodeTreeView(engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -220,3 +221,250 @@ extension LyrebirdProcessView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdProcessView`: a control panel for
|
||||
// one `LyrebirdProcess` (state dot + id, dB amp slider, Start/Release). The 10 Hz
|
||||
// lifecycle poll moves off SwiftOpenUI's off-main `.task` onto a `Timer` on
|
||||
// `RunLoop.main` inside an `@Observable` model — the amp/running/releasing state
|
||||
// lives there so the `@Bindable` body tracks it. dB↔amp maths reuse the
|
||||
// cross-platform `DbSliderConversion`.
|
||||
//
|
||||
// The amp control uses SwiftOpenUI's native `Slider` (GtkScale). Unlike the
|
||||
// Canvas-drawn `ParameterSlider`, a native scale does not live-track other
|
||||
// controls mid-drag — acceptable here (a single transport slider, not a linked
|
||||
// modulation source).
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// 10 Hz process lifecycle poll interval.
|
||||
private let linuxProcessPollIntervalSeconds: TimeInterval = 0.1
|
||||
|
||||
/// Polls one `LyrebirdProcess`'s lifecycle + amp on a main-thread timer and
|
||||
/// publishes them for ``LyrebirdProcessView``. Internal — only the view is public.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`,
|
||||
/// same rationale as `LyrebirdScopeModel`.
|
||||
@Observable
|
||||
final class LinuxProcessModel: @unchecked Sendable {
|
||||
|
||||
var isRunning: Bool = false
|
||||
var isReleasing: Bool = false
|
||||
var amp: Double = 1.0
|
||||
|
||||
@ObservationIgnored let process: LyrebirdProcess
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
|
||||
init(process: LyrebirdProcess) {
|
||||
self.process = process
|
||||
// `amp` is @MainActor; construction happens on the GTK main thread.
|
||||
self.amp = MainActor.assumeIsolated { process.amp }
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
refresh()
|
||||
let t: Timer = Timer.scheduledTimer(
|
||||
withTimeInterval: linuxProcessPollIntervalSeconds,
|
||||
repeats: true
|
||||
) { [weak self] _ in
|
||||
self?.refresh()
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
|
||||
// SwiftOpenUI view/timer callbacks are nonisolated but always run on the GTK
|
||||
// main thread, so `assumeIsolated` reaches `LyrebirdProcess`'s @MainActor
|
||||
// `amp` safely. `isRunning` / `isReleasing` are nonisolated already.
|
||||
func refresh() {
|
||||
isRunning = process.isRunning
|
||||
isReleasing = process.isReleasing
|
||||
amp = MainActor.assumeIsolated { process.amp }
|
||||
}
|
||||
}
|
||||
|
||||
/// A control panel for a single `LyrebirdProcess` on the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdProcessView`; same public API/init as the Apple side.
|
||||
public struct LyrebirdProcessView: View {
|
||||
|
||||
public let process: LyrebirdProcess
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var model: LinuxProcessModel
|
||||
|
||||
// Layout constants (points).
|
||||
private let dotSize: Double = 10
|
||||
private let ampLabelWidth: Double = 36
|
||||
private let dbReadoutWidth: Double = 56
|
||||
private let disabledDotOpacity: Double = 0.4
|
||||
|
||||
/// 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
|
||||
_model = State(wrappedValue: LinuxProcessModel(process: process))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
header
|
||||
Divider()
|
||||
ampRow
|
||||
Divider()
|
||||
transportRow
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 280)
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Circle()
|
||||
.fill(stateColor)
|
||||
.frame(width: dotSize, height: dotSize)
|
||||
Text(process.id)
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text(stateLabel)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var ampRow: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Amp")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: ampLabelWidth, alignment: .leading)
|
||||
Slider(value: Binding(
|
||||
get: { dbFromAmp(model.amp) },
|
||||
set: { newDb in
|
||||
let newAmp: Double = ampFromDb(newDb)
|
||||
model.amp = newAmp
|
||||
// Bind `process` (Sendable) to a local so the @MainActor
|
||||
// closure captures it, not `self` (the non-Sendable View).
|
||||
let p: LyrebirdProcess = process
|
||||
MainActor.assumeIsolated { p.amp = newAmp }
|
||||
}
|
||||
), in: LyrebirdProcessView.minDb ... maxDb)
|
||||
Text(dbDisplay(dbFromAmp(model.amp)))
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.primary)
|
||||
.frame(width: dbReadoutWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - dB <-> linear amplitude (shared via `DbSliderConversion`)
|
||||
|
||||
private static let minDb: Double = DbSliderConversion.minDb
|
||||
|
||||
/// Per-process slider ceiling, sourced from ``LyrebirdProcess/maxUIAmpDb``.
|
||||
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` is Sendable; `engine` is not, so bind it via
|
||||
// `nonisolated(unsafe)` (safe — all runs on the GTK main thread).
|
||||
// Capturing these locals keeps `self` (the View) out of the
|
||||
// @MainActor closure.
|
||||
let p: LyrebirdProcess = process
|
||||
nonisolated(unsafe) let e: SynthesisEngine = engine
|
||||
MainActor.assumeIsolated { p.play(engine: e) }
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(model.isRunning)
|
||||
|
||||
Button("Release") {
|
||||
let p: LyrebirdProcess = process
|
||||
MainActor.assumeIsolated { p.release() }
|
||||
model.refresh()
|
||||
}
|
||||
.disabled(!model.isRunning || model.isReleasing)
|
||||
|
||||
Spacer()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private var stateColor: Color {
|
||||
if model.isReleasing { return .yellow }
|
||||
if model.isRunning { return .green }
|
||||
return Color.secondary.opacity(disabledDotOpacity)
|
||||
}
|
||||
|
||||
private var stateLabel: String {
|
||||
if model.isReleasing { return "Releasing" }
|
||||
if model.isRunning { return "Running" }
|
||||
return "Idle"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Standalone window (Linux)
|
||||
|
||||
extension LyrebirdProcessView {
|
||||
|
||||
/// Opens a `LyrebirdWindow` hosting a process control view. Requires a
|
||||
/// running `GtkApplication` loop.
|
||||
///
|
||||
/// - 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.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
process: LyrebirdProcess,
|
||||
engine: SynthesisEngine,
|
||||
title: String? = nil,
|
||||
width: Double = 300,
|
||||
height: Double = 180
|
||||
) -> LyrebirdWindow {
|
||||
let win: LyrebirdWindow = LyrebirdWindow(
|
||||
title: title ?? process.id,
|
||||
width: width,
|
||||
height: height
|
||||
)
|
||||
win.open {
|
||||
LyrebirdProcessView(process: process, engine: engine)
|
||||
}
|
||||
return win
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -193,3 +194,188 @@ extension LyrebirdRunningProcessesView {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdRunningProcessesView`: one
|
||||
// ``LyrebirdProcessView`` per currently-running `LyrebirdProcess` in an event
|
||||
// list. The 10 Hz refresh moves off SwiftOpenUI's off-main `.task` onto a `Timer`
|
||||
// on `RunLoop.main` inside an `@Observable` model. The identity-stable
|
||||
// reassignment (only swap the array when the running set changes) is preserved so
|
||||
// child rows keep their own poll timers and per-row state across ticks.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// 10 Hz — matches ``LyrebirdProcessView``.
|
||||
private let linuxRunningProcessesPollIntervalSeconds: TimeInterval = 0.1
|
||||
|
||||
/// Polls an event list's running processes on a main-thread timer and publishes
|
||||
/// an identity-stable snapshot for ``LyrebirdRunningProcessesView``. Internal.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined; the `Timer` block is `@Sendable`,
|
||||
/// same rationale as `LyrebirdScopeModel`.
|
||||
@Observable
|
||||
final class LinuxRunningProcessesModel: @unchecked Sendable {
|
||||
|
||||
var running: [LyrebirdProcess] = []
|
||||
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
@ObservationIgnored private let eventList: LyrebirdEventList
|
||||
|
||||
init(eventList: LyrebirdEventList) {
|
||||
self.eventList = eventList
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
refresh()
|
||||
let t: Timer = Timer.scheduledTimer(
|
||||
withTimeInterval: linuxRunningProcessesPollIntervalSeconds,
|
||||
repeats: true
|
||||
) { [weak self] _ in
|
||||
self?.refresh()
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
|
||||
func refresh() {
|
||||
let snapshot: [LyrebirdProcess] = eventList.allProcesses.filter { $0.isRunning }
|
||||
if !LinuxRunningProcessesModel.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
|
||||
}
|
||||
}
|
||||
|
||||
/// A panel of the currently-running processes in an event list for the Linux/GTK4
|
||||
/// UI. Mirrors `LyrebirdUI.LyrebirdRunningProcessesView`; same public API/init.
|
||||
public struct LyrebirdRunningProcessesView: View {
|
||||
|
||||
public let eventList: LyrebirdEventList
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
@State private var model: LinuxRunningProcessesModel
|
||||
|
||||
/// Creates a running-processes panel bound to the given event list.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - eventList: The `LyrebirdEventList` whose running processes are shown.
|
||||
/// - engine: The `SynthesisEngine` forwarded to each child
|
||||
/// ``LyrebirdProcessView`` for its **Start** button.
|
||||
public init(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine
|
||||
) {
|
||||
self.eventList = eventList
|
||||
self.engine = engine
|
||||
_model = State(wrappedValue: LinuxRunningProcessesModel(eventList: eventList))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
header
|
||||
Divider()
|
||||
if model.running.isEmpty {
|
||||
emptyRow
|
||||
} else {
|
||||
ForEach(model.running, id: \.lyrebirdObjectID) { proc in
|
||||
LyrebirdProcessView(process: proc, engine: engine)
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(12)
|
||||
.background(Color.lyrebirdControlBackground)
|
||||
.frame(minWidth: 320)
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
// MARK: - Sub-rows
|
||||
|
||||
private var header: some View {
|
||||
HStack(spacing: 8) {
|
||||
Text("Running")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(model.running.count)")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
private var emptyRow: some View {
|
||||
Text("No running processes")
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ObjectIdentifier helper
|
||||
|
||||
private extension LyrebirdProcess {
|
||||
/// Stable identity for `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 (Linux)
|
||||
|
||||
extension LyrebirdRunningProcessesView {
|
||||
|
||||
/// Opens a ``LyrebirdWindow`` hosting a running-processes panel. Requires a
|
||||
/// running `GtkApplication` loop.
|
||||
///
|
||||
/// - 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.
|
||||
@discardableResult
|
||||
public static func presentInWindow(
|
||||
eventList: LyrebirdEventList,
|
||||
engine: SynthesisEngine,
|
||||
title: String? = nil,
|
||||
width: Double = 360,
|
||||
height: Double = 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
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
|
||||
/// A Canvas-based scatter plot for an array of `Double` values.
|
||||
@@ -117,3 +118,128 @@ public struct LyrebirdScatterView: View {
|
||||
return height * (1.0 - CGFloat(t))
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdScatterView`: a Canvas scatter
|
||||
// plot of an array of `Double`s, one filled dot per sample. The SwiftUI
|
||||
// `GraphicsContext`/`Path` drawing is rewritten to imperative `DrawingContext`
|
||||
// (Cairo) calls: a background fill, an optional zero guide line, and one
|
||||
// `arc`+`fill` per dot. Y-bounds reuse the shared `_linuxEnvelopeYBounds`.
|
||||
//
|
||||
// No axis text is drawn (`DrawingContext` has no text primitive) — the Apple
|
||||
// side draws none either, so there is no feature loss here.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import Foundation // CGSize / CGFloat
|
||||
|
||||
/// A Canvas scatter plot for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdScatterView`; same public API/init as the Apple side.
|
||||
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
|
||||
|
||||
// Background is a fixed dark panel; drawn inside the renderer since the
|
||||
// Cairo backend has no `clipShape`.
|
||||
private static let backgroundRGB: (r: Double, g: Double, b: Double) = (0.08, 0.08, 0.08)
|
||||
private static let scatterDotRadius: Double = 2.5
|
||||
private static let zeroLineOpacity: Double = 0.25
|
||||
private static let guideLineWidth: Double = 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(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
_draw(ctx: ctx, size: size)
|
||||
})
|
||||
.frame(width: Double(width), height: Double(height))
|
||||
}
|
||||
|
||||
// MARK: - Drawing
|
||||
|
||||
private func _draw(
|
||||
ctx: DrawingContext,
|
||||
size: CGSize
|
||||
) {
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
|
||||
// Background panel.
|
||||
let bg: (r: Double, g: Double, b: Double) = LyrebirdScatterView.backgroundRGB
|
||||
ctx.setColor(r: bg.r, g: bg.g, b: bg.b)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
|
||||
guard !samples.isEmpty else { return }
|
||||
|
||||
let (yMin, yMax): (Double, Double) = _yBounds()
|
||||
|
||||
if showZeroLine && yMin <= 0 && yMax >= 0 {
|
||||
let zy: Double = _yFor(0, yMin: yMin, yMax: yMax, height: h)
|
||||
ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: LyrebirdScatterView.zeroLineOpacity)
|
||||
ctx.setLineWidth(LyrebirdScatterView.guideLineWidth)
|
||||
ctx.moveTo(x: 0, y: zy)
|
||||
ctx.lineTo(x: w, y: zy)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
let count: Int = samples.count
|
||||
let r: Double = LyrebirdScatterView.scatterDotRadius
|
||||
let fullCircle: Double = 2.0 * Double.pi
|
||||
ctx.setColor(r: pointColor.red, g: pointColor.green, b: pointColor.blue, a: pointColor.alpha)
|
||||
|
||||
if count == 1 {
|
||||
let px: Double = w / 2
|
||||
let py: Double = h / 2
|
||||
ctx.arc(centerX: px, centerY: py, radius: r, startAngle: 0, endAngle: fullCircle)
|
||||
ctx.fill()
|
||||
return
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let px: Double = Double(i) / Double(count - 1) * w
|
||||
let py: Double = _yFor(samples[i], yMin: yMin, yMax: yMax, height: h)
|
||||
ctx.arc(centerX: px, centerY: py, radius: r, startAngle: 0, endAngle: fullCircle)
|
||||
ctx.fill()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private func _yBounds() -> (Double, Double) {
|
||||
if let r: ClosedRange<Double> = yRange { return (r.lowerBound, r.upperBound) }
|
||||
return _linuxEnvelopeYBounds(levels: samples)
|
||||
}
|
||||
|
||||
private func _yFor(
|
||||
_ v: Double,
|
||||
yMin: Double,
|
||||
yMax: Double,
|
||||
height: Double
|
||||
) -> Double {
|
||||
guard yMax > yMin else { return height / 2 }
|
||||
let t: Double = (v - yMin) / (yMax - yMin)
|
||||
return height * (1.0 - t)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// LyrebirdScopeModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if !canImport(SwiftUI)
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// Observable model that polls a `ScopeCapture` on a main-thread timer and
|
||||
/// publishes the latest per-channel sample frame for ``LyrebirdScopeView`` to draw.
|
||||
///
|
||||
/// `@unchecked Sendable`: every access is confined to the UI (GTK main) thread —
|
||||
/// the poll `Timer` fires on `RunLoop.main`, and `start`/`stop`/`channels` are
|
||||
/// only touched from that thread — but `Timer`'s block is `@Sendable`, so the
|
||||
/// capture requires the conformance. The confinement, not the type system, is
|
||||
/// what makes it safe (same rationale as `UIParamNode`).
|
||||
@Observable
|
||||
public final class LyrebirdScopeModel: @unchecked Sendable {
|
||||
|
||||
/// Latest snapshot: `[channelIndex][sampleIndex]`. Written on the main thread
|
||||
/// by the poll timer; read by the `Canvas` renderer.
|
||||
public internal(set) var channels: [[Float]] = []
|
||||
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
@ObservationIgnored private let capture: ScopeCapture
|
||||
@ObservationIgnored private let pollInterval: TimeInterval
|
||||
|
||||
/// - Parameters:
|
||||
/// - capture: The `ScopeCapture` to poll (typically the engine's `scopeTap`).
|
||||
/// - pollInterval: Seconds between snapshots. Default ≈ 30 Hz.
|
||||
public init(
|
||||
capture: ScopeCapture,
|
||||
pollInterval: TimeInterval = 1.0 / 30.0
|
||||
) {
|
||||
self.capture = capture
|
||||
self.pollInterval = pollInterval
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
/// Begin polling. Idempotent. Must be called on the main thread.
|
||||
public func start() {
|
||||
guard timer == nil else { return }
|
||||
let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.channels = self.capture.snapshot()
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
/// Stop polling. Idempotent.
|
||||
public func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -97,3 +98,130 @@ public struct LyrebirdScopeView: View {
|
||||
with: .color(LyrebirdScopeView.backgroundColor))
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdScopeView`: a real-time
|
||||
// oscilloscope that polls a core `ScopeCapture` (via ``LyrebirdScopeModel``) and
|
||||
// draws each channel's waveform stacked vertically on a single `Canvas`.
|
||||
//
|
||||
// Periodic redraw uses a Foundation `Timer` on `RunLoop.main` (in the model),
|
||||
// which the GTK4 backend pumps (~every 5 ms) from its GLib main loop — so the
|
||||
// poll fires on the GTK main thread and the `@Observable` model write is
|
||||
// main-thread-safe. That is deliberately NOT SwiftOpenUI's `.task`, whose closure
|
||||
// runs off the main thread (unlike SwiftUI's main-actor `.task`) and would race
|
||||
// the observation registrar. The model write is an `@Observable` change read by
|
||||
// the `Canvas`, so it takes the backend's narrow `.canvasContent` redraw path
|
||||
// (the pinned fork's fix).
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Foundation
|
||||
|
||||
/// A real-time dual-channel oscilloscope for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdScopeView`: channels stacked vertically, each with a dim
|
||||
/// zero-line, separated by a hairline; channel 0 cyan, 1 orange, 2 green, 3 yellow.
|
||||
public struct LyrebirdScopeView: View {
|
||||
|
||||
@State private var model: LyrebirdScopeModel
|
||||
|
||||
// Presentation constants.
|
||||
private let scopeWidth: Double = 320
|
||||
private let scopeHeight: Double = 120
|
||||
private let cornerRadius: Double = 4
|
||||
/// Fraction of each channel's half-row height used for waveform excursion,
|
||||
/// leaving headroom so ±1 signals don't touch the channel boundary.
|
||||
private let waveformHeightFraction: Double = 0.44
|
||||
private let zeroLineOpacity: Double = 0.25
|
||||
private let separatorOpacity: Double = 0.3
|
||||
|
||||
/// Creates a scope bound to a `ScopeCapture` (e.g. the engine's `scopeTap`).
|
||||
///
|
||||
/// - Parameter capture: The capture to visualise.
|
||||
public init(capture: ScopeCapture) {
|
||||
_model = State(wrappedValue: LyrebirdScopeModel(capture: capture))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
// Read the observed `channels` at BODY level, not only inside the Canvas
|
||||
// renderer below. `withObservationTracking` wraps body evaluation, but the
|
||||
// renderer closure runs at DRAW time (outside that scope), so a
|
||||
// `model.channels` read there registers no dependency — the observation is
|
||||
// one-shot and the trace freezes after the first frame. Reading it here
|
||||
// re-registers on every timer tick, so the body re-evaluates and the
|
||||
// Canvas redraws continuously (the same reason the CPU-bar view, which
|
||||
// reads its model for the percentage labels, animates).
|
||||
let chans: [[Float]] = model.channels
|
||||
return Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
|
||||
// Background.
|
||||
ctx.setColor(r: 0.08, g: 0.08, b: 0.08)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
|
||||
guard !chans.isEmpty else { return }
|
||||
let count: Int = chans.count
|
||||
let rowH: Double = h / Double(count)
|
||||
|
||||
for ch: Int in 0..<count {
|
||||
let midY: Double = rowH * (Double(ch) + 0.5)
|
||||
let halfH: Double = rowH * waveformHeightFraction
|
||||
|
||||
// Zero guide.
|
||||
ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: zeroLineOpacity)
|
||||
ctx.setLineWidth(0.5)
|
||||
ctx.moveTo(x: 0, y: midY)
|
||||
ctx.lineTo(x: w, y: midY)
|
||||
ctx.stroke()
|
||||
|
||||
// Channel separator (between channels, not after the last).
|
||||
if ch < count - 1 {
|
||||
let sepY: Double = rowH * Double(ch + 1)
|
||||
ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: separatorOpacity)
|
||||
ctx.setLineWidth(0.5)
|
||||
ctx.moveTo(x: 0, y: sepY)
|
||||
ctx.lineTo(x: w, y: sepY)
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
let samples: [Float] = chans[ch]
|
||||
guard samples.count > 1 else { continue }
|
||||
let color: (r: Double, g: Double, b: Double) = channelColor(ch)
|
||||
let xStep: Double = w / Double(samples.count - 1)
|
||||
ctx.setColor(r: color.r, g: color.g, b: color.b)
|
||||
ctx.setLineWidth(1.0)
|
||||
for i: Int in 0..<samples.count {
|
||||
let x: Double = Double(i) * xStep
|
||||
let y: Double = midY - Double(samples[i]) * halfH
|
||||
if i == 0 {
|
||||
ctx.moveTo(x: x, y: y)
|
||||
} else {
|
||||
ctx.lineTo(x: x, y: y)
|
||||
}
|
||||
}
|
||||
ctx.stroke()
|
||||
}
|
||||
})
|
||||
.frame(width: scopeWidth, height: scopeHeight)
|
||||
.clipShape(RoundedRectangle(cornerRadius: cornerRadius))
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Per-channel trace colour: cyan, orange, green, yellow, then repeats.
|
||||
private func channelColor(_ ch: Int) -> (r: Double, g: Double, b: Double) {
|
||||
let palette: [(r: Double, g: Double, b: Double)] = [
|
||||
(0.0, 0.8, 1.0),
|
||||
(1.0, 0.53, 0.0),
|
||||
(0.0, 0.8, 0.0),
|
||||
(1.0, 0.8, 0.0)
|
||||
]
|
||||
return palette[ch % palette.count]
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -230,3 +231,268 @@ public struct LyrebirdSpectrumView: View {
|
||||
return max(0, min(1, (db - floorDB) / (ceilDB - floorDB)))
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdSpectrumView`: a real-time
|
||||
// spectrum / waterfall analyzer. The SwiftUI `GraphicsContext`/`Path` drawing is
|
||||
// rewritten to imperative `DrawingContext` (Cairo) calls. Polling moves off
|
||||
// SwiftOpenUI's `.task` (which runs OFF the main thread) onto a Foundation
|
||||
// `Timer` on `RunLoop.main` inside an `@Observable` model — the same pattern as
|
||||
// `LyrebirdStatusView` / `LyrebirdScopeModel`.
|
||||
//
|
||||
// No axis/frequency text is drawn (`DrawingContext` has no text primitive) — the
|
||||
// Apple side draws none either, so there is no feature loss.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// Poll interval for the spectrum model (~30 Hz).
|
||||
private let linuxSpectrumPollIntervalSeconds: TimeInterval = 1.0 / 30.0
|
||||
|
||||
/// Polls a `SpectrumCapture` on a main-thread timer and publishes the current
|
||||
/// magnitude frame (plus a bounded history for waterfall mode) for
|
||||
/// ``LyrebirdSpectrumView`` to draw. Internal — only the view is public.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined (the poll `Timer` fires on
|
||||
/// `RunLoop.main`), but `Timer`'s block is `@Sendable`, so the capture requires
|
||||
/// the conformance — same rationale as `LyrebirdScopeModel`.
|
||||
@Observable
|
||||
final class LinuxSpectrumModel: @unchecked Sendable {
|
||||
|
||||
var magnitudes: [Float] = []
|
||||
var history: [[Float]] = []
|
||||
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
@ObservationIgnored private let capture: SpectrumCapture
|
||||
@ObservationIgnored private let waterfallRows: Int
|
||||
|
||||
init(capture: SpectrumCapture, waterfallRows: Int) {
|
||||
self.capture = capture
|
||||
self.waterfallRows = waterfallRows
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
let t: Timer = Timer.scheduledTimer(
|
||||
withTimeInterval: linuxSpectrumPollIntervalSeconds,
|
||||
repeats: true
|
||||
) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
let snap: [Float] = self.capture.snapshot()
|
||||
self.magnitudes = snap
|
||||
if self.waterfallRows > 0 {
|
||||
var h: [[Float]] = self.history
|
||||
h.insert(snap, at: 0)
|
||||
if h.count > self.waterfallRows { h.removeLast() }
|
||||
self.history = h
|
||||
}
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A real-time spectrum analyzer / waterfall for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdSpectrumView`; same public API/init as the Apple side.
|
||||
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 model: LinuxSpectrumModel
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let backgroundRGB: (r: Double, g: Double, b: Double) = (0.08, 0.08, 0.08)
|
||||
private static let spectrumRGB: (r: Double, g: Double, b: Double) = (0.0, 0.667, 0.0) // green
|
||||
private static let spectrumLineWidth: Double = 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
|
||||
let rows: Int = max(0, waterfallRows)
|
||||
self.waterfallRows = rows
|
||||
_model = State(wrappedValue: LinuxSpectrumModel(capture: capture, waterfallRows: rows))
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
|
||||
public var body: some View {
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
let bg: (r: Double, g: Double, b: Double) = Self.backgroundRGB
|
||||
ctx.setColor(r: bg.r, g: bg.g, b: bg.b)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
guard model.magnitudes.count > 1 else { return }
|
||||
if waterfallRows > 0 {
|
||||
_drawWaterfall(ctx: ctx, width: w, height: h)
|
||||
} else {
|
||||
_drawSpectrum(ctx: ctx, width: w, height: h)
|
||||
}
|
||||
})
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
|
||||
// MARK: - Spectrum line
|
||||
|
||||
private func _drawSpectrum(ctx: DrawingContext, width: Double, height: Double) {
|
||||
let mags: [Float] = model.magnitudes
|
||||
|
||||
// Zero-dB guide line.
|
||||
let zeroY: Double = height * (1.0 - _dbFrac(Float(1.0)))
|
||||
ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: Self.zeroLineOpacity)
|
||||
ctx.setLineWidth(0.5)
|
||||
ctx.moveTo(x: 0, y: zeroY)
|
||||
ctx.lineTo(x: width, y: zeroY)
|
||||
ctx.stroke()
|
||||
|
||||
let halfSize: Int = capture.fftSize / 2
|
||||
let line: (r: Double, g: Double, b: Double) = Self.spectrumRGB
|
||||
ctx.setColor(r: line.r, g: line.g, b: line.b)
|
||||
ctx.setLineWidth(Self.spectrumLineWidth)
|
||||
var started: Bool = false
|
||||
for k: Int in 0...halfSize {
|
||||
guard k < mags.count else { break }
|
||||
let xFrac: Double = _xFrac(bin: k)
|
||||
guard xFrac >= 0 && xFrac <= 1 else { continue }
|
||||
let x: Double = xFrac * width
|
||||
let y: Double = height * (1.0 - _dbFrac(mags[k]))
|
||||
if !started {
|
||||
ctx.moveTo(x: x, y: y)
|
||||
started = true
|
||||
} else {
|
||||
ctx.lineTo(x: x, y: y)
|
||||
}
|
||||
}
|
||||
ctx.stroke()
|
||||
}
|
||||
|
||||
// MARK: - Waterfall
|
||||
|
||||
private func _drawWaterfall(ctx: DrawingContext, width: Double, height: Double) {
|
||||
let hist: [[Float]] = model.history
|
||||
guard !hist.isEmpty else { return }
|
||||
let rowH: Double = height / Double(waterfallRows)
|
||||
let halfSize: Int = capture.fftSize / 2
|
||||
// Number of horizontal pixel columns to iterate over.
|
||||
let cols: Int = max(1, Int(width))
|
||||
|
||||
for (rowIdx, rowMags) in hist.enumerated() {
|
||||
guard rowIdx < waterfallRows else { break }
|
||||
let y: Double = Double(rowIdx) * rowH
|
||||
|
||||
var prevX: Double = 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: Double = Double(col)
|
||||
let dbFrac: Double = _dbFrac(rowMags[bin])
|
||||
if x > prevX {
|
||||
let brightness: Double = dbFrac
|
||||
let color: Color = Color(
|
||||
hue: Self.waterfallHue,
|
||||
saturation: min(1.0, brightness * Self.waterfallSaturationBoost),
|
||||
brightness: brightness
|
||||
)
|
||||
ctx.setColor(r: color.red, g: color.green, b: color.blue)
|
||||
ctx.rectangle(x: prevX, y: y, width: x - prevX, height: rowH)
|
||||
ctx.fill()
|
||||
}
|
||||
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)))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -89,3 +90,145 @@ private struct CPURow: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdStatusView`: a compact live
|
||||
// readout of a `SynthesisEngine`'s average and peak CPU load, as two colour-coded
|
||||
// bars with percentage labels.
|
||||
//
|
||||
// Live update reuses the scope's pattern — an `@Observable` model polled by a
|
||||
// Foundation `Timer` on `RunLoop.main` (pumped by the GTK4 backend), NOT
|
||||
// SwiftOpenUI's off-main `.task`. Labels and percentages are real `Text` views
|
||||
// (`DrawingContext` has no text drawing); only the bar itself is a `Canvas`.
|
||||
//
|
||||
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift).
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
import LyrebirdSynth
|
||||
import Observation
|
||||
import Foundation
|
||||
|
||||
/// Default CPU-meter poll interval, in seconds (≈ 10 Hz).
|
||||
private let linuxStatusDefaultPollInterval: TimeInterval = 0.1
|
||||
|
||||
/// Polls a `SynthesisEngine`'s CPU meters on a main-thread timer and publishes
|
||||
/// them for ``LyrebirdStatusView`` to draw. Internal — only the view is public.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined (the poll `Timer` fires on
|
||||
/// `RunLoop.main`; all access is on that thread), but `Timer`'s block is
|
||||
/// `@Sendable`, so the capture requires the conformance — same rationale as
|
||||
/// `LyrebirdScopeModel` / `UIParamNode`.
|
||||
@Observable
|
||||
final class LyrebirdStatusModel: @unchecked Sendable {
|
||||
|
||||
var averageCPU: Double = 0.0
|
||||
var peakCPU: Double = 0.0
|
||||
|
||||
@ObservationIgnored private var timer: Timer?
|
||||
@ObservationIgnored private let engine: SynthesisEngine
|
||||
@ObservationIgnored private let pollInterval: TimeInterval
|
||||
|
||||
init(
|
||||
engine: SynthesisEngine,
|
||||
pollInterval: TimeInterval = linuxStatusDefaultPollInterval
|
||||
) {
|
||||
self.engine = engine
|
||||
self.pollInterval = pollInterval
|
||||
}
|
||||
|
||||
deinit {
|
||||
timer?.invalidate()
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard timer == nil else { return }
|
||||
let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.averageCPU = self.engine.averageCPU
|
||||
self.peakCPU = self.engine.peakCPU
|
||||
}
|
||||
timer = t
|
||||
}
|
||||
|
||||
func stop() {
|
||||
timer?.invalidate()
|
||||
timer = nil
|
||||
}
|
||||
}
|
||||
|
||||
/// A compact real-time CPU-load readout for the Linux/GTK4 UI. Mirrors
|
||||
/// `LyrebirdUI.LyrebirdStatusView`: average and peak block-fraction load as two
|
||||
/// bars — green below 50 %, yellow 50–80 %, red above 80 %. `1.0` = one full
|
||||
/// block consumed; `> 1.0` = over budget (xruns likely).
|
||||
public struct LyrebirdStatusView: View {
|
||||
|
||||
@State private var model: LyrebirdStatusModel
|
||||
|
||||
/// Creates a CPU-load readout for the given engine.
|
||||
///
|
||||
/// - Parameter engine: The `SynthesisEngine` to monitor.
|
||||
public init(engine: SynthesisEngine) {
|
||||
_model = State(wrappedValue: LyrebirdStatusModel(engine: engine))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading) {
|
||||
LinuxCPURow(label: "CPU Avg", value: model.averageCPU)
|
||||
LinuxCPURow(label: "CPU Peak", value: model.peakCPU)
|
||||
}
|
||||
.onAppear { model.start() }
|
||||
.onDisappear { model.stop() }
|
||||
}
|
||||
}
|
||||
|
||||
/// One labelled CPU bar. Private — an implementation detail of ``LyrebirdStatusView``.
|
||||
private struct LinuxCPURow: View {
|
||||
let label: String
|
||||
let value: Double // 0.0 = idle, 1.0 = full block, > 1.0 = overload
|
||||
|
||||
private let labelWidth: Double = 60
|
||||
private let percentWidth: Double = 52
|
||||
private let barWidth: Double = 120
|
||||
private let barHeight: Double = 8
|
||||
private let maxDisplayPercent: Double = 999.9
|
||||
private let warningThreshold: Double = 0.5
|
||||
private let criticalThreshold: Double = 0.8
|
||||
|
||||
var body: some View {
|
||||
HStack {
|
||||
Text(label)
|
||||
.monospacedDigit()
|
||||
.frame(minWidth: labelWidth, alignment: .leading)
|
||||
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
|
||||
let w: Double = Double(size.width)
|
||||
let h: Double = Double(size.height)
|
||||
// Track.
|
||||
ctx.setColor(r: 0.5, g: 0.5, b: 0.5, a: 0.15)
|
||||
ctx.rectangle(x: 0, y: 0, width: w, height: h)
|
||||
ctx.fill()
|
||||
// Filled portion, clamped to the track width.
|
||||
let frac: Double = min(max(value, 0.0), 1.0)
|
||||
let rgb: (r: Double, g: Double, b: Double) = barColor
|
||||
ctx.setColor(r: rgb.r, g: rgb.g, b: rgb.b)
|
||||
ctx.rectangle(x: 0, y: 0, width: w * frac, height: h)
|
||||
ctx.fill()
|
||||
})
|
||||
.frame(width: barWidth, height: barHeight)
|
||||
Text(percentText)
|
||||
.monospacedDigit()
|
||||
.frame(minWidth: percentWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
private var barColor: (r: Double, g: Double, b: Double) {
|
||||
if value < warningThreshold { return (0.0, 0.8, 0.0) } // green
|
||||
if value < criticalThreshold { return (1.0, 0.8, 0.0) } // yellow
|
||||
return (1.0, 0.2, 0.2) // red
|
||||
}
|
||||
|
||||
private var percentText: String {
|
||||
let displayPercent: Double = min(value * 100.0, maxDisplayPercent)
|
||||
return String(format: "%.1f%%", displayPercent)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -97,7 +98,7 @@ public struct LyrebirdSynthView: View {
|
||||
}
|
||||
|
||||
/// One discovered `@UIParam` slot, paired with its display name + range.
|
||||
public struct Entry: Identifiable {
|
||||
public struct Entry: Identifiable, Sendable {
|
||||
public let id: String
|
||||
public let propertyName: String
|
||||
public let displayName: String
|
||||
@@ -173,3 +174,129 @@ public let lyrebirdSynthViewDefaultMin: Double = 0
|
||||
|
||||
/// Default upper bound used when `parameterMetadata` does not supply a range.
|
||||
public let lyrebirdSynthViewDefaultMax: Double = 1
|
||||
|
||||
#else
|
||||
// Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdSynthView`: an auto-generated
|
||||
// parameter grid for a `SynthesizerBase` subclass, one ``ParameterKnob`` per
|
||||
// `@UIParam` slot. The `@UIParam` discovery (`Mirror` walk), the ``Entry`` type,
|
||||
// and the range/default constants are identical to the Apple side — only the
|
||||
// `body` swaps the SwiftUI `ScrollView`/`LazyVGrid` for SwiftOpenUI's data-based
|
||||
// `LazyVGrid` (`columns:data:content:`, no per-item ForEach). Adaptive columns
|
||||
// map onto GtkGridView's min-column-count behaviour.
|
||||
//
|
||||
// SwiftOpenUI is always present in this target (see Package.swift), so no
|
||||
// `canImport` guard is needed.
|
||||
import SwiftOpenUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Auto-generated parameter grid for a `SynthesizerBase` subclass on Linux/GTK4.
|
||||
/// Mirrors `LyrebirdUI.LyrebirdSynthView`: walks the synth's `Mirror` chain for
|
||||
/// `@UIParam` slots and renders one ``ParameterKnob`` per slot in an adaptive
|
||||
/// grid. Same public API/init as the Apple side.
|
||||
///
|
||||
/// **`@UIParam` only.** `@LiveParam` slots are skipped — they have no
|
||||
/// `@Observable` projected value to drive a knob.
|
||||
public struct LyrebirdSynthView: View {
|
||||
|
||||
public let entries: [Entry]
|
||||
|
||||
/// - Parameter synth: The `SynthesizerBase` instance to introspect.
|
||||
///
|
||||
/// > Note: The Apple side also accepts a `[String: LyrebirdAUParameterInfo]`
|
||||
/// > metadata dictionary for per-knob ranges, but that type lives under
|
||||
/// > `#if canImport(AudioToolbox)` (Apple-only), so on Linux every slot uses
|
||||
/// > the default `lyrebirdSynthViewDefaultMin...Max` range. Pass pre-built
|
||||
/// > ``Entry`` values via `init(entries:)` for custom ranges.
|
||||
public init(synth: SynthesizerBase) {
|
||||
self.entries = LyrebirdSynthView.discover(synth: synth)
|
||||
}
|
||||
|
||||
/// - 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))],
|
||||
data: entries
|
||||
) { entry in
|
||||
ParameterKnob(
|
||||
entry.displayName,
|
||||
node: entry.node,
|
||||
range: entry.range
|
||||
)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
/// One discovered `@UIParam` slot, paired with its display name + range.
|
||||
public struct Entry: Identifiable, Sendable {
|
||||
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()`. Every
|
||||
/// slot uses the default range (no `LyrebirdAUParameterInfo` on Linux).
|
||||
public static func discover(synth: SynthesizerBase) -> [Entry] {
|
||||
var entries: [Entry] = []
|
||||
var mirrors: [Mirror] = []
|
||||
var current: Mirror? = Mirror(reflecting: synth)
|
||||
while let m: Mirror = current {
|
||||
mirrors.append(m)
|
||||
current = m.superclassMirror
|
||||
}
|
||||
let range: ClosedRange<Double> = lyrebirdSynthViewDefaultMin...lyrebirdSynthViewDefaultMax
|
||||
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 }
|
||||
entries.append(Entry(
|
||||
propertyName: key,
|
||||
displayName: key,
|
||||
node: node,
|
||||
range: range
|
||||
))
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimum column width (points) for ``LyrebirdSynthView``'s adaptive grid.
|
||||
public let lyrebirdSynthViewColumnMinWidth: Double = 120
|
||||
|
||||
// NOTE: the Apple side's `lyrebirdSynthViewGridSpacing` / `lyrebirdSynthViewItemSpacing`
|
||||
// are intentionally absent on Linux — SwiftOpenUI's `LazyVGrid(columns:data:content:)`
|
||||
// exposes no per-item spacing parameter (grid layout is driven by GtkGridView's
|
||||
// column count), so there is nothing to apply them to. The Linux grid uses
|
||||
// GtkGridView's default gutter.
|
||||
|
||||
/// Default lower bound used when `parameterMetadata` does not supply a range.
|
||||
public let lyrebirdSynthViewDefaultMin: Double = 0
|
||||
|
||||
/// Default upper bound used when `parameterMetadata` does not supply a range.
|
||||
public let lyrebirdSynthViewDefaultMax: Double = 1
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// LyrebirdUIExports.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(SwiftUI)
|
||||
// Re-export SwiftUI so downstream Apple app / synth code needs only
|
||||
// `import LyrebirdUI` to get both the Lyrebird controls and the SwiftUI View
|
||||
// DSL they build on. The Linux counterpart is `LyrebirdUILinuxExports.swift`
|
||||
// in this same module (guarded `#if !canImport(SwiftUI)`), which re-exports
|
||||
// SwiftOpenUI + BackendGTK4. Downstream code writes one `import LyrebirdUI` on
|
||||
// every platform; the control bodies switch backend by `#if canImport(SwiftUI)`
|
||||
// beneath, both binding the same core `@UIParam` / `UIParamNode` model.
|
||||
@_exported import SwiftUI
|
||||
#endif
|
||||
@@ -0,0 +1,24 @@
|
||||
// LyrebirdUILinuxExports.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Re-exports so downstream Linux app / synth code needs only
|
||||
// `import LyrebirdUILinux` to get the SwiftOpenUI View DSL *and* the GTK4
|
||||
// backend's `DrawingContext` drawing methods (setColor/arc/moveTo/stroke),
|
||||
// which live as extensions in `BackendGTK4` rather than SwiftOpenUI's core.
|
||||
//
|
||||
// This mirrors how, on Apple platforms, importing a UI umbrella brings the
|
||||
// underlying toolkit along — the goal is one platform `#if` at the import site
|
||||
// (`import LyrebirdUI` vs `import LyrebirdUILinux`) and identical body code
|
||||
// beneath it, since both bind the same core `@UIParam` / `UIParamNode` model.
|
||||
//
|
||||
// Both modules are guaranteed present inside this target: `Package.swift` only
|
||||
// appends `LyrebirdUILinux` together with its `SwiftOpenUI` + `BackendGTK4`
|
||||
// dependencies (Linux, `LYREBIRD_ENABLE_LINUX_UI=1`), so no `canImport` guard
|
||||
// is needed here.
|
||||
#if !canImport(SwiftUI)
|
||||
@_exported import SwiftOpenUI
|
||||
@_exported import BackendGTK4
|
||||
#endif
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if canImport(SwiftUI)
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
@@ -159,3 +160,125 @@ public final class LyrebirdWindow {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#elseif os(Linux)
|
||||
import Foundation
|
||||
import SwiftOpenUI
|
||||
import BackendGTK4
|
||||
|
||||
/// LyrebirdWindow — a standalone GTK4 window hosting SwiftOpenUI content.
|
||||
///
|
||||
/// The Linux counterpart to the macOS `NSWindow` + `NSHostingController` host.
|
||||
/// Opens a top-level `GtkApplicationWindow` (via
|
||||
/// `GTK4Backend.openStandaloneWindow`) whose child is the rendered SwiftOpenUI
|
||||
/// view. Same public shape as the macOS side — `init(title:width:height:)`,
|
||||
/// `open(content:)`, `close()` — so `presentInWindow(...)` convenience methods
|
||||
/// work identically on both platforms.
|
||||
///
|
||||
/// ## Requirements
|
||||
///
|
||||
/// A `GtkApplication` main loop must already be running — i.e. the process is
|
||||
/// inside `GTK4Backend().run(App)`. Opening a window from a CLI/REPL with no
|
||||
/// running application is a no-op (`open` leaves the window closed); use the
|
||||
/// declarative `App`/`WindowGroup` scene as the process entry point, then open
|
||||
/// further windows imperatively with `LyrebirdWindow`.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// GTK is single-threaded; every method must run on the GTK main thread. Unlike
|
||||
/// the macOS `@MainActor` class, this is left nonisolated to match the rest of
|
||||
/// the Linux/GTK4 UI and the SwiftOpenUI backend, which are all confined to the
|
||||
/// GTK main loop rather than the Swift main actor — a nonisolated SwiftOpenUI
|
||||
/// `body` and `Button` action can then drive it without an actor hop.
|
||||
public final class LyrebirdWindow {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// Window title-bar text.
|
||||
public let title: String
|
||||
|
||||
/// Initial window width in points.
|
||||
public let width: Double
|
||||
|
||||
/// Initial window height in points.
|
||||
public let height: Double
|
||||
|
||||
// MARK: - Private state
|
||||
|
||||
private var handle: GTK4StandaloneWindowHandle?
|
||||
|
||||
/// Bumped on every `open()`. The `onClose` closure captures the generation
|
||||
/// live at open time and only clears `handle` if it still matches, so a stale
|
||||
/// destroy signal from a previously-closed window (were it ever delivered
|
||||
/// asynchronously) can't null out a newer window's handle on rapid reuse.
|
||||
private var generation: Int = 0
|
||||
|
||||
// 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: Double = 400,
|
||||
height: Double = 300
|
||||
) {
|
||||
self.title = title
|
||||
self.width = width
|
||||
self.height = height
|
||||
}
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// Whether a window is currently open for this instance.
|
||||
public var isOpen: Bool { handle?.isOpen ?? false }
|
||||
|
||||
// MARK: - Open
|
||||
|
||||
/// Opens the window and displays the provided SwiftOpenUI content.
|
||||
///
|
||||
/// If a window is already open for this instance, it is closed and replaced
|
||||
/// with a new one hosting the updated content. If no `GtkApplication` is
|
||||
/// running, this is a no-op.
|
||||
///
|
||||
/// - Parameter content: A `@ViewBuilder` closure returning any SwiftOpenUI
|
||||
/// `View`.
|
||||
public func open<Content: View>(@ViewBuilder content: () -> Content) {
|
||||
closeWindow()
|
||||
generation &+= 1
|
||||
let token: Int = generation
|
||||
// `onClose` fires on the GTK main thread when the user closes the window;
|
||||
// clear our handle so `isOpen` reflects it — but only if this is still the
|
||||
// current window (guard against a stale callback from a replaced one).
|
||||
handle = GTK4Backend.openStandaloneWindow(
|
||||
title: title,
|
||||
width: Int(width),
|
||||
height: Int(height),
|
||||
onClose: { [weak self] in
|
||||
guard let self, self.generation == token else { return }
|
||||
self.handle = nil
|
||||
},
|
||||
content: content
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Close
|
||||
|
||||
/// Closes and destroys the window.
|
||||
public func close() {
|
||||
closeWindow()
|
||||
}
|
||||
|
||||
// MARK: - Private
|
||||
|
||||
private func closeWindow() {
|
||||
handle?.close()
|
||||
handle = nil
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if canImport(SwiftUI)
|
||||
import AppKit
|
||||
import Synchronization
|
||||
import LyrebirdSynth
|
||||
@@ -160,4 +161,113 @@ private let mouseButtonReleased: Double = 0.0
|
||||
private let normalizedMin: Double = 0.0
|
||||
private let normalizedMax: Double = 1.0
|
||||
|
||||
#endif // os(macOS)
|
||||
#endif // canImport(SwiftUI)
|
||||
|
||||
#elseif os(Linux)
|
||||
import Synchronization
|
||||
import LyrebirdSynth
|
||||
import BackendGTK4
|
||||
|
||||
/// Linux `MouseInputBridge` conformer driven by a window-local GTK pointer
|
||||
/// source (`GtkEventControllerMotion` + `GtkGestureClick`), the GTK4 counterpart
|
||||
/// to the macOS `NSEvent`-monitor `MouseTracker`.
|
||||
///
|
||||
/// Position is normalised to the window the pointer is over:
|
||||
/// - `x` = 0 (left edge) … 1 (right edge)
|
||||
/// - `y` = 0 (bottom edge) … 1 (top edge) — flipped from GTK's top-left origin
|
||||
/// - `button` = 0.0 (released) or 1.0 (primary button held)
|
||||
///
|
||||
/// Values are exposed via lock-free `Synchronization.Atomic<Double>` reads,
|
||||
/// safe for the audio render thread, exactly like the macOS tracker.
|
||||
///
|
||||
/// Install once at app startup so `Mouse.X.Control()` / `Mouse.Y.Control()` /
|
||||
/// `Mouse.Click.Control()` read live values:
|
||||
///
|
||||
/// ```swift
|
||||
/// import LyrebirdSynth
|
||||
/// import LyrebirdUI
|
||||
///
|
||||
/// MouseTracker.installShared()
|
||||
/// ```
|
||||
///
|
||||
/// Unlike macOS this is window-local: it reports while the pointer is over one
|
||||
/// of the app's windows (SwiftOpenUI attaches the controllers to every window
|
||||
/// it opens). `x` / `y` are fully covered; `button` is best-effort — a
|
||||
/// window-level click gesture sees presses not consumed by an interactive child.
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// `installShared()` and the forwarded pointer callbacks run on the GTK main
|
||||
/// thread. No `@MainActor` — the Linux UI is GTK-main-loop-confined, not on the
|
||||
/// Swift main actor (see `LyrebirdWindow`).
|
||||
public final class MouseTracker: MouseInputBridge, @unchecked Sendable {
|
||||
// Sendable invariant: `_x`/`_y`/`_button`/`_installed` are immutable `Atomic`s —
|
||||
// all reads/writes lock-free. The pointer-sink closures are set once (gated by
|
||||
// the `_installed` CAS) and only store into those atomics.
|
||||
|
||||
/// Process-wide `MouseTracker` instance.
|
||||
public static let shared: MouseTracker = MouseTracker()
|
||||
|
||||
private let _x: Atomic<Double>
|
||||
private let _y: Atomic<Double>
|
||||
private let _button: Atomic<Double>
|
||||
private let _installed: Atomic<Bool> = Atomic<Bool>(false)
|
||||
|
||||
/// Allocates the atomic state slots. Does not install the pointer sink —
|
||||
/// `installShared()` does that.
|
||||
public override init() {
|
||||
_x = Atomic(mouseTrackerInitialPosition)
|
||||
_y = Atomic(mouseTrackerInitialPosition)
|
||||
_button = Atomic(mouseButtonReleased)
|
||||
super.init()
|
||||
}
|
||||
|
||||
// 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: - Install
|
||||
|
||||
/// Installs `MouseTracker.shared` as the active `MouseInput` bridge AND
|
||||
/// registers the GTK pointer sink. Idempotent via the `_installed` atomic CAS.
|
||||
///
|
||||
/// Install timing is not sensitive: SwiftOpenUI attaches the pointer
|
||||
/// controllers to every window it opens and reads the installed sink at event
|
||||
/// time, so calling this before or after `GTK4Backend().run(_:)` both work.
|
||||
public static func installShared() {
|
||||
shared._installIfNeeded()
|
||||
}
|
||||
|
||||
private func _installIfNeeded() {
|
||||
let (exchanged, _) = _installed.compareExchange(
|
||||
expected: false, desired: true, ordering: .acquiringAndReleasing)
|
||||
guard exchanged else { return }
|
||||
|
||||
MouseInput.install(self)
|
||||
GTK4PointerTracking.install(
|
||||
onMove: { [weak self] (nx: Double, ny: Double) in
|
||||
// Clamp to [0, 1] to honour the normalized-range contract even if
|
||||
// an edge/drag-out event reports slightly out of bounds — parity
|
||||
// with the macOS tracker's clamp.
|
||||
self?._x.store(min(max(nx, 0.0), 1.0), ordering: .relaxed)
|
||||
self?._y.store(min(max(ny, 0.0), 1.0), ordering: .relaxed)
|
||||
},
|
||||
onButton: { [weak self] (pressed: Bool) in
|
||||
self?._button.store(
|
||||
pressed ? mouseButtonPressed : mouseButtonReleased,
|
||||
ordering: .relaxed
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - MouseTracker constants
|
||||
|
||||
private let mouseTrackerInitialPosition: Double = 0.5
|
||||
private let mouseButtonPressed: Double = 1.0
|
||||
private let mouseButtonReleased: Double = 0.0
|
||||
|
||||
#endif // os(macOS) / os(Linux)
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
// 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) }
|
||||
}
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
// 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