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:
2026-09-10 21:09:11 -07:00
parent 77580ee98e
commit b6fdee8bfc
293 changed files with 16800 additions and 775 deletions
@@ -0,0 +1,30 @@
// EventVoiceSynth.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A fixed-pitch sine voice added by a `LyrebirdProcess` body in the events demo
/// (`LYREBIRD_DEMO=events`). The process's own envelope gates it, so firing an
/// event in the `LyrebirdEventListPerformanceView` starts an audible, visibly
/// "running" process strip.
final class EventVoiceSynth: SynthesizerBase {
/// Output gain, kept low so several stacked voices don't clip.
private let voiceGain: Double = 0.12
private let voiceFreq: Double
/// - Parameter freq: Oscillator frequency in Hz.
init(freq: Double) {
self.voiceFreq = freq
super.init()
}
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: voiceFreq)
output(bus: 0, source: Pan2(input: osc * voiceGain))
}
}
@@ -0,0 +1,22 @@
// KnobDemoSynth.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A minimal sine-tone synthesizer whose frequency and amplitude are `@UIParam`
/// slots, so the Linux GTK4 knobs bind to the same RT-safe parameter model the
/// macOS SwiftUI controls use. Turning a knob updates the atomic the render
/// thread reads at the next block — audible immediately when a live ALSA device
/// is present.
final class KnobDemoSynth: SynthesizerBase {
@UIParam var frequency: Double = 220.0
@UIParam var amplitude: Double = 0.2
override func build() {
let osc: OscSin.Audio = OscSin.Audio(freq: $frequency)
output(bus: 0, source: Pan2(input: osc * $amplitude))
}
}
@@ -0,0 +1,391 @@
// KnobDemoView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth // UIParamNode
import LyrebirdUI // View DSL + ParameterKnob, via @_exported re-exports
import Foundation // CGSize (narrowtest Canvas renderer)
import Observation // @Observable (mouse readout model)
/// Two knobs bound to a synthesizer's `@UIParam` slots — frequency and
/// amplitude. Drag up to increase; the sine tone tracks in real time.
///
/// The view holds the projected `UIParamNode`s directly rather than the
/// `SynthesizerBase`. `SynthesizerBase` is `@MainActor`-isolated, so reading
/// `synth.$frequency` is only legal from a main-actor context — and SwiftOpenUI's
/// `View.body` is *nonisolated* (unlike SwiftUI's `@MainActor` body). So the
/// caller extracts the nodes on the main actor (`main.swift` top-level code is
/// `@MainActor`) and hands them in; `UIParamNode` itself is not actor-isolated,
/// so reading `node.value` from the nonisolated body is fine.
struct KnobDemoView: View {
let frequencyNode: UIParamNode
let amplitudeNode: UIParamNode
let scope: ScopeCapture
let envelope: Envelope
let engine: SynthesisEngine
/// Frequency knob range, in Hz — roughly A2…A5.
private let freqMin: Double = 110.0
private let freqMax: Double = 880.0
/// Values the reset button restores.
private let resetFreq: Double = 220.0
private let resetAmp: Double = 0.2
var body: some View {
VStack {
Text("Lyrebird — Linux UI demo")
// Live CPU-load meters (engine average / peak).
LyrebirdStatusView(engine: engine)
// Live oscilloscope of the stereo output.
LyrebirdScopeView(capture: scope)
// Static plot of an example envelope (cyan pre-loop, green loop,
// orange release; dashed markers at the loop/release boundaries).
LyrebirdEnvelopeView(envelope)
// XY pad drives both nodes at once (X = freq, Y = amp); it shares the
// same nodes as the controls below, so all of them stay in sync.
ParameterXY(
xLabel: "freq", xNode: frequencyNode, xRange: freqMin...freqMax,
yLabel: "amp", yNode: amplitudeNode, yRange: 0.0...1.0
)
// Knob and slider bind the SAME node, so moving one updates the
// other — the shared `@UIParam` model observed from several controls.
ParameterKnob("freq", node: frequencyNode, range: freqMin...freqMax)
ParameterSlider("freq", node: frequencyNode, range: freqMin...freqMax, taper: .exponential)
ParameterLabel("freq (Hz)", node: frequencyNode, decimalPlaces: 1)
ParameterKnob("amp", node: amplitudeNode, range: 0.0...1.0)
ParameterSlider("amp", node: amplitudeNode, range: 0.0...1.0)
// Toggle gates the amp node on/off (0 ↔ 1); the amp knob/slider
// follow it, since all three observe the same node. Highlights when on.
ParameterButton("gate", node: amplitudeNode, style: .toggle)
// Momentary: restores defaults. Writes through the nodes (not the
// @MainActor synth), so it is callable from the nonisolated handler.
ParameterButton("reset") {
frequencyNode.update(resetFreq)
amplitudeNode.update(resetAmp)
}
}
.padding()
}
}
// MARK: - Diagnostic variants (selected by the LYREBIRD_DEMO env var)
/// Diagnostic: a single knob, nothing else. Isolates the control from the
/// multi-view / animation context.
struct DemoKnobOnlyView: View {
let frequencyNode: UIParamNode
private let freqMin: Double = 110.0
private let freqMax: Double = 880.0
var body: some View {
VStack {
Text("knob only")
ParameterKnob("freq", node: frequencyNode, range: freqMin...freqMax)
}
.padding()
}
}
/// Diagnostic: all parameter controls, but NO animated views (scope / CPU) and
/// no envelope. Isolates the interactive controls from the timer-driven redraws.
struct DemoControlsView: View {
let frequencyNode: UIParamNode
let amplitudeNode: UIParamNode
private let freqMin: Double = 110.0
private let freqMax: Double = 880.0
private let resetFreq: Double = 220.0
private let resetAmp: Double = 0.2
var body: some View {
VStack {
Text("controls (no animated views)")
ParameterXY(
xLabel: "freq", xNode: frequencyNode, xRange: freqMin...freqMax,
yLabel: "amp", yNode: amplitudeNode, yRange: 0.0...1.0
)
ParameterKnob("freq", node: frequencyNode, range: freqMin...freqMax)
ParameterSlider("freq", node: frequencyNode, range: freqMin...freqMax, taper: .exponential)
ParameterLabel("freq (Hz)", node: frequencyNode, decimalPlaces: 1)
ParameterKnob("amp", node: amplitudeNode, range: 0.0...1.0)
ParameterSlider("amp", node: amplitudeNode, range: 0.0...1.0)
ParameterButton("gate", node: amplitudeNode, style: .toggle)
ParameterButton("reset") {
frequencyNode.update(resetFreq)
amplitudeNode.update(resetAmp)
}
}
.padding()
}
}
/// Showcase of the ported diagnostics / monitor views (`LYREBIRD_DEMO=monitors`):
/// the parameter knobs, a `LyrebirdScatterView`, a per-bin `MultiSlider`, and
/// `LyrebirdEngineStatusView` — the last of which itself embeds the node-tree and
/// message sections, so it exercises `LyrebirdNodeTreeView` +
/// `LyrebirdMessageBanner`/`LyrebirdMessageView` too.
///
/// No outer `ScrollView`: a GTK `ScrolledWindow` pans on pointer-drag, which
/// fights the Canvas controls' own drag gestures (dragging a knob or the
/// MultiSlider would scroll the page). Instead the panels are split into two
/// side-by-side columns so the total height fits without scrolling — the tall
/// `LyrebirdEngineStatusView` gets its own column. Widen (or the panels stack
/// off-screen); the knobs are placed directly (not the scrolling
/// `LyrebirdSynthView` grid) to keep them drag-friendly.
struct DemoMonitorsView: View {
let entries: [LyrebirdSynthView.Entry]
let scatter: [Double]
let multiBuffer: LyrebirdBuffer
let multiCount: Int
let engine: SynthesisEngine
let onEngineStarted: (() -> Void)?
var body: some View {
HStack(alignment: .top, spacing: 20) {
// Left column: knobs + read-only visualisers + the per-bin slider.
VStack(alignment: .leading) {
Text("Lyrebird — Linux monitors demo")
HStack {
ForEach(entries) { entry in
ParameterKnob(entry.displayName, node: entry.node, range: entry.range)
}
}
Text("Scatter (LyrebirdScatterView)")
LyrebirdScatterView(scatter)
Text("Per-bin MultiSlider — drag to edit")
MultiSlider(buffer: multiBuffer, count: multiCount, range: 0.0...1.0, height: 100)
}
// Right column: the tall engine-status panel (embeds node tree +
// messages + config + output).
LyrebirdEngineStatusView(
engine: engine,
onEngineStarted: onEngineStarted
)
}
.padding()
}
}
/// Narrow-path isolation view (`LYREBIRD_DEMO=narrowtest`). A Canvas slider plus a
/// `Text` readout and an editable `TextField`, each wrapped in the modifiers that
/// used to poison the narrow-mutation path (`.onChange` / `.focused` /
/// `.textFieldStyle` / `.onSubmit` / `.monospacedDigit`). Crucially it contains NO
/// opaque Class-2 widgets (no Picker/Stepper/Toggle), so it isolates the Phase-1a
/// transparent-describe fix: if dragging the slider updates the label AND the
/// field LIVE (not only at mouse-up), the transparent-describe fix works and the opaque-leaf fix is worth doing.
struct DemoNarrowTestView: View {
@State private var db: Double = -6.0
@State private var dbText: String = "-6.0"
@FocusState private var focused: Bool
private let lo: Double = -12
private let hi: Double = 12
private let trackWidth: Double = 220
private let trackHeight: Double = 24
private let thumbRadius: Double = 7
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Narrow-path test")
Text("Drag the slider: the label and the text field should track LIVE.")
.font(.caption)
.foregroundStyle(.secondary)
HStack(spacing: 8) {
Text("Gain")
.frame(width: 44, alignment: .leading)
slider
// Live label wrapped in ex-poison modifiers.
Text(String(format: "%+.1f dB", db))
.font(.caption)
.monospacedDigit()
.frame(width: 70, alignment: .trailing)
.onChange(of: db) { _, _ in }
// Editable field wrapped in ex-poison modifiers.
TextField("dB", text: $dbText)
.font(.caption)
.monospacedDigit()
.focused($focused)
.frame(width: 70)
.textFieldStyle(.roundedBorder)
.onSubmit { }
.onChange(of: dbText) { _, _ in }
}
}
.padding()
}
private var slider: 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 = hi - lo
let pos: Double = span > 0 ? (db - lo) / span : 0
let thumbX: Double = x0 + min(1, max(0, pos)) * usable
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()
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()
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 usable: Double = max(trackWidth - 2 * thumbRadius, 1)
let pos: Double = min(1, max(0, (drag.location.x - thumbRadius) / usable))
let v: Double = lo + pos * (hi - lo)
db = v
dbText = String(format: "%+.1f", v)
})
}
}
// MARK: - Mouse input demo (LYREBIRD_DEMO=mouse)
/// Polls the installed `MouseInput` bridge (fed by `MouseTracker`) on a
/// main-thread `Timer`, publishing normalized pointer state for the readout —
/// same idiom as the CPU / scope models.
///
/// `@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` / `LyrebirdStatusModel`.
@Observable
final class MouseReadoutModel: @unchecked Sendable {
var x: Double = 0.5
var y: Double = 0.5
var button: Double = 0.0
@ObservationIgnored private var timer: Timer?
private let pollInterval: TimeInterval = 0.05 // 20 Hz — snappy readout
deinit {
timer?.invalidate()
}
func start() {
guard timer == nil else { return }
refresh()
let t: Timer = Timer.scheduledTimer(withTimeInterval: pollInterval, repeats: true) { [weak self] _ in
self?.refresh()
}
timer = t
}
func stop() {
timer?.invalidate()
timer = nil
}
private func refresh() {
x = MouseInput.currentX
y = MouseInput.currentY
button = MouseInput.currentButton
}
}
/// Live readout of the pointer source (`LYREBIRD_DEMO=mouse`). Move the pointer
/// over the window: X→frequency, Y→amplitude drive the `MouseDemoSynth` sine, and
/// the values here should track. Validates the Linux `MouseTracker` +
/// `GtkEventControllerMotion` pointer bridge.
struct DemoMouseView: View {
@State private var model: MouseReadoutModel = MouseReadoutModel()
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Mouse input demo")
Text("Move the pointer over this window (X → frequency, Y → amplitude); click to test the button.")
.font(.caption)
.foregroundStyle(.secondary)
Text(String(format: "Mouse.X: %.3f", model.x))
.monospacedDigit()
Text(String(format: "Mouse.Y: %.3f", model.y))
.monospacedDigit()
Text(String(format: "Mouse.Click: %.0f", model.button))
.monospacedDigit()
}
.padding()
.onAppear { model.start() }
.onDisappear { model.stop() }
}
}
// MARK: - Events / process views demo (LYREBIRD_DEMO=events)
/// On-display exercise of the ported process/event-list views
/// (`LYREBIRD_DEMO=events`). Embeds `LyrebirdEventListPerformanceView` — which
/// itself hosts `LyrebirdEventListView` (transport) plus one `LyrebirdProcessView`
/// strip per running process — and offers buttons to open each view in its own
/// detached `LyrebirdWindow` via `presentInWindow`, so the standalone-window path
/// is exercised for these views too (not just EngineStatus).
///
/// Press **Next** in the transport to fire the queued events; each starts a
/// sustaining `EventVoiceSynth`, so a running-process strip appears (and a tone
/// sounds when a live audio backend is present).
struct DemoEventsView: View {
let eventList: LyrebirdEventList
let engine: SynthesisEngine
@State private var perfWindow: LyrebirdWindow?
@State private var listWindow: LyrebirdWindow?
@State private var runningWindow: LyrebirdWindow?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Lyrebird — Linux events / processes demo")
Text("Press Next to fire events; each starts a process strip below.")
.font(.caption)
.foregroundStyle(.secondary)
LyrebirdEventListPerformanceView(eventList: eventList, engine: engine)
HStack(spacing: 8) {
Button {
perfWindow?.close()
perfWindow = LyrebirdEventListPerformanceView.presentInWindow(
eventList: eventList, engine: engine
)
} label: {
Text("Open Perf Window").font(.caption)
}
Button {
listWindow?.close()
listWindow = LyrebirdEventListView.presentInWindow(eventList: eventList)
} label: {
Text("Open EventList Window").font(.caption)
}
Button {
runningWindow?.close()
runningWindow = LyrebirdRunningProcessesView.presentInWindow(
eventList: eventList, engine: engine
)
} label: {
Text("Open Running Window").font(.caption)
}
}
}
.padding()
}
}
@@ -0,0 +1,28 @@
// MouseDemoSynth.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import LyrebirdSynth
/// A sine tone driven entirely by the pointer via the `Mouse.*` control
/// generators — no `@UIParam`s. Horizontal position sets frequency, vertical
/// sets amplitude, so moving the pointer over the window sweeps the tone. Used
/// by `LYREBIRD_DEMO=mouse` to validate the Linux `MouseTracker` pointer source.
final class MouseDemoSynth: SynthesizerBase {
/// Frequency sweep range (Hz), mapped from `Mouse.X` (0…1).
private let freqBase: Double = 110.0
private let freqSpan: Double = 770.0 // → 110…880 Hz
/// Amplitude ceiling, mapped from `Mouse.Y` (0…1).
private let ampMax: Double = 0.3
override func build() {
let freq: any ValidGeneratorInput = Mouse.X.Control() * freqSpan + freqBase
let amp: any ValidGeneratorInput = Mouse.Y.Control() * ampMax
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
output(bus: 0, source: Pan2(input: osc * amp))
}
}
+320
View File
@@ -0,0 +1,320 @@
// main.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// Runnable Linux GUI demo for LyrebirdUILinux. Build/run on a Linux host with
// libgtk-4-dev (and libasound2-dev for sound):
//
// LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo
//
// Note the import shape: only LyrebirdSynth (engine + @UIParam) and
// LyrebirdUILinux (View DSL + GTK4 backend, via @_exported re-exports). No
// direct SwiftOpenUI / BackendGTK4 imports needed here.
import LyrebirdSynth
import LyrebirdUI
import Foundation // ProcessInfo (demo-mode env var)
// MARK: - Audio engine
private let demoBlockSize: Int = 512
private let demoSampleRate: Double = 44_100.0
private let demoOutputChannels: Int = 2
private let demoInputChannels: Int = 0
// Core Audio on Apple, ALSA on a Linux build with libasound, else a silent
// OfflineDriver. The GUI runs either way; `isLiveAudioAvailable` reports which.
let demoDriver: any AudioDriver = makeDefaultAudioDriver()
let demoEngine: SynthesisEngine = SynthesisEngine(
blockSize: demoBlockSize,
sampleRate: demoSampleRate,
numOutputChannels: demoOutputChannels,
numInputChannels: demoInputChannels,
driver: demoDriver
)
// Oscilloscope tap on the stereo output buses. Must be set before start().
private let demoScopeBufferSize: Int = 2048
let demoScope: ScopeCapture = ScopeCapture(buses: [0, 1], bufferSize: demoScopeBufferSize)
demoEngine.scopeTap = demoScope
let demoSynth: KnobDemoSynth = KnobDemoSynth()
// Pointer-driven sine for the `mouse` mode (Mouse.X → freq, Mouse.Y → amp).
let mouseSynth: MouseDemoSynth = MouseDemoSynth()
// Which demo to run — read early so the `monitors` mode can launch with the
// engine OFF (its EngineStatus panel drives Start/Stop). Every other mode starts
// the engine and adds the synth now, since they have no transport control.
let demoMode: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"] ?? "full"
let launchEngineRunning: Bool = (demoMode != "monitors")
// Install the GTK pointer bridge BEFORE `engine.start()` so the `Mouse.*.Control`
// generators see live values with proper happens-before visibility on the RT
// thread (see MouseInput.install docs). Harmless in non-mouse modes — it just
// registers the bridge; SwiftOpenUI only attaches the pointer controllers to the
// windows it opens, and no generator reads it unless a patch uses Mouse.*.
MouseTracker.installShared()
if launchEngineRunning {
do {
try demoEngine.start()
switch demoMode {
case "mouse":
try demoEngine.add(mouseSynth)
case "events":
break // the LyrebirdEventList schedules its own processes on Next.
default:
try demoEngine.add(demoSynth)
}
} catch {
print("[Lyrebird] demo engine setup failed: \(error)")
}
}
if !isLiveAudioAvailable {
print("[Lyrebird] no live audio backend — the knobs still work, but there is no sound.")
}
// `engine.stop()` tears down the node tree AND unbinds every non-persistent synth
// (see the stop() contract in docs/engine/synthesis-engine.md), so no manual
// teardown is needed — the synth just has to be re-added on the next Start. The
// EngineStatus panel's `onEngineStarted` runs this after a successful start.
// `add` is @MainActor; the Start action fires on the GTK main thread, so
// `assumeIsolated` is valid. `demoSynth` is Sendable (@MainActor class); the
// engine is not, so it is bound `nonisolated(unsafe)`.
nonisolated(unsafe) let addEngine: SynthesisEngine = demoEngine
nonisolated(unsafe) let reAddSynthOnStart: () -> Void = {
MainActor.assumeIsolated {
do {
try addEngine.add(demoSynth)
} catch {
print("[Lyrebird] re-add synth on start failed: \(error)")
}
}
}
// Extract the projected parameter nodes here, in main.swift's top-level
// `@MainActor` context: `SynthesizerBase` is `@MainActor`, so `demoSynth.$…` is
// only reachable on the main actor. The nodes themselves are not actor-isolated,
// so the (nonisolated) SwiftOpenUI view body can read them freely.
let frequencyNode: UIParamNode = demoSynth.$frequency
let amplitudeNode: UIParamNode = demoSynth.$amplitude
// SwiftOpenUI's scene closure is nonisolated and `SynthesisEngine` is not
// Sendable, so the main-actor top-level `demoEngine` can't be referenced inside
// it directly (unlike the Sendable nodes/scope/envelope). This demo runs entirely
// on the GTK main thread and the status view only reads `engine.averageCPU` /
// `peakCPU` (plain Double loads), so a nonisolated handle is safe here.
nonisolated(unsafe) let statusEngine: SynthesisEngine = demoEngine
// A static example envelope for the envelope plot (loop node 1, release node 2).
let demoEnvelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.6, 0.0],
durations: [0.01, 0.3, 0.2],
curves: [.sine, .lin, .exponential],
loopNode: 1,
releaseNode: 2
)
// MARK: - "monitors" demo scaffolding
//
// Extra data sources for the diagnostics/monitor views ported to Linux. All are
// Sendable (`UIParamNode` / `LyrebirdBuffer` are `@unchecked Sendable`, `Entry`
// is `Sendable`, `[Double]` is Sendable) so they cross into SwiftOpenUI's
// nonisolated scene closure like the nodes above.
// Parameter entries with EXPLICIT ranges. `LyrebirdSynthView.discover` can't
// carry per-slot ranges on Linux (that metadata type is Apple-only), so it would
// default every knob to 0…1 — wrong for frequency (Hz). Build them by hand from
// the already-extracted nodes so the frequency knob spans a musical range.
let demoFreqRange: ClosedRange<Double> = 110.0...880.0
let demoAmpRange: ClosedRange<Double> = 0.0...1.0
let demoSynthEntries: [LyrebirdSynthView.Entry] = [
LyrebirdSynthView.Entry(
propertyName: "frequency", displayName: "frequency",
node: frequencyNode, range: demoFreqRange
),
LyrebirdSynthView.Entry(
propertyName: "amplitude", displayName: "amplitude",
node: amplitudeNode, range: demoAmpRange
),
]
// A per-bin buffer driven by the MultiSlider (a rising ramp to start).
private let demoMultiBinCount: Int = 48
let demoMultiBuffer: LyrebirdBuffer = {
let buf: LyrebirdBuffer = LyrebirdBuffer(count: demoMultiBinCount)
buf.fill { (i: Int, n: Int) in Double(i) / Double(n) }
return buf
}()
// A static scatter of one Gaussian-ish cloud for the scatter plot.
let demoScatterData: [Double] = (0..<160).map { (i: Int) in
let t: Double = Double(i) / 160.0
return 0.5 + 0.4 * sin(t * .pi * 6) * (1.0 - t)
}
// MARK: - "events" demo scaffolding
//
// A `LyrebirdEventList` of four one-shot events, each starting a sustaining
// `EventVoiceSynth` at a distinct pitch. `LyrebirdEventList` is `@unchecked
// Sendable`, so (like the nodes) it crosses into SwiftOpenUI's nonisolated scene
// closure. Built after `engine.start()` above.
let eventDemoPitches: [Double] = [220.0, 277.18, 329.63, 440.0] // A3, C#4, E4, A4
let eventDemoEnvelope: Envelope = Envelope(
levels: [0.0, 1.0, 0.0],
durations: [0.08, 0.6],
curves: [.lin, .lin],
releaseNode: 2
)
let eventDemoEvents: [LyrebirdEvent] = eventDemoPitches.enumerated().map { (index: Int, pitch: Double) in
let proc: LyrebirdProcess = LyrebirdProcess(
id: "voice-\(index)",
envelope: eventDemoEnvelope,
numChannels: 2,
body: { (ctx: LyrebirdProcessContext) in ctx.add(EventVoiceSynth(freq: pitch)) }
)
return LyrebirdEvent(starts: [proc])
}
let eventDemoList: LyrebirdEventList? = {
do {
return try LyrebirdEventList(
id: "events-demo",
events: eventDemoEvents,
engine: demoEngine,
bus: AudioBus(index: 0, channelCount: 2)
)
} catch {
print("[Lyrebird] events demo list build failed: \(error)")
return nil
}
}()
// Seed a few diagnostics messages so the message views/banner have content.
LyrebirdMessageCenter.shared.info("Linux UI demo started", source: "LyrebirdUILinuxDemo")
LyrebirdMessageCenter.shared.warning("This is an example warning", source: "demo")
LyrebirdMessageCenter.shared.error("This is an example error", source: "demo")
// MARK: - GTK4 app
//
// Diagnostic selector: set LYREBIRD_DEMO to isolate what breaks interaction.
// knob → a single knob (control in isolation)
// controls → all controls, no animated views (isolates the timer redraws)
// monitors → the ported diagnostics/monitor views (SynthView grid, Scatter,
// MultiSlider, EngineStatus incl. node-tree + messages)
// narrowtest → narrow-path isolation: Canvas slider + Text/TextField wrapped in the
// ex-poison modifiers, NO opaque widgets — label+field should track live
// mouse → pointer-source test: live Mouse.X/Y/Click readout over a
// pointer-driven sine (validates the Linux MouseTracker)
// events → process/event-list views on-display: LyrebirdEventListPerformanceView
// (EventListView transport + RunningProcesses/ProcessView strips) +
// presentInWindow buttons for each
// (unset) → the full demo
// Each mode is a distinct App/View with a FIXED body — no in-body @ViewBuilder
// conditional, which would itself change the rebuild plan under test.
struct KnobDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Knob Demo") {
KnobDemoView(
frequencyNode: frequencyNode,
amplitudeNode: amplitudeNode,
scope: demoScope,
envelope: demoEnvelope,
engine: statusEngine
)
}
}
}
struct KnobOnlyDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Knob Demo") {
DemoKnobOnlyView(frequencyNode: frequencyNode)
}
}
}
struct ControlsDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Knob Demo") {
DemoControlsView(
frequencyNode: frequencyNode,
amplitudeNode: amplitudeNode
)
}
}
}
/// Showcase of the ported diagnostics / monitor views: the auto-generated
/// parameter grid, a scatter plot, a per-bin MultiSlider, and the engine status
/// panel (which itself embeds the node-tree and message sections).
struct MonitorsDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Monitors Demo") {
DemoMonitorsView(
entries: demoSynthEntries,
scatter: demoScatterData,
multiBuffer: demoMultiBuffer,
multiCount: demoMultiBinCount,
engine: statusEngine,
onEngineStarted: reAddSynthOnStart
)
}
}
}
/// Narrow-path isolation test (no engine, no opaque widgets).
struct NarrowTestApp: App {
var body: some Scene {
WindowGroup("Lyrebird Narrow-Path Test") {
DemoNarrowTestView()
}
}
}
/// Pointer-source test: a live Mouse.X/Y/Click readout over a pointer-driven
/// sine. Validates the Linux `MouseTracker`.
struct MouseDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Mouse Demo") {
DemoMouseView()
}
}
}
/// On-display exercise of the ported process/event-list views: the composite
/// `LyrebirdEventListPerformanceView` inline plus buttons to open each view in a
/// detached `LyrebirdWindow`.
struct EventsDemoApp: App {
var body: some Scene {
WindowGroup("Lyrebird Events Demo") {
if let list: LyrebirdEventList = eventDemoList {
DemoEventsView(eventList: list, engine: statusEngine)
} else {
Text("Events demo failed to build — see console.")
.padding()
}
}
}
}
switch demoMode {
case "knob":
GTK4Backend().run(KnobOnlyDemoApp.self)
case "narrowtest":
GTK4Backend().run(NarrowTestApp.self)
case "mouse":
GTK4Backend().run(MouseDemoApp.self)
case "events":
GTK4Backend().run(EventsDemoApp.self)
case "controls":
GTK4Backend().run(ControlsDemoApp.self)
case "monitors":
GTK4Backend().run(MonitorsDemoApp.self)
default:
GTK4Backend().run(KnobDemoApp.self)
}