Files
Lyrebird/Sources/LyrebirdUI/LyrebirdEngineStatusView.swift
josh b6fdee8bfc 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>
2026-09-10 21:09:11 -07:00

1349 lines
50 KiB
Swift

// LyrebirdEngineStatusView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
import LyrebirdSynth
/// A status panel showing the live state of a `SynthesisEngine`.
///
/// Displays:
/// - Running state (idle / running) with a coloured indicator dot.
/// - A start / stop button that toggles the engine.
/// - The current synthesizer and group counts (from `engine.synthesizerCount` /
/// `engine.groupCount`).
/// - Average and peak CPU usage as percentages of one block, mirroring
/// `LyrebirdStatusView`.
/// - Pre-run configuration controls — sample rate picker, output- and input-channel
/// steppers. Editable only while the engine is stopped; greyed out and disabled
/// once `engine.start()` succeeds.
/// - Master output volume slider (dB-tapered, `-90`…`+12 dB`) paired with a text
/// field accepting the same range — the two controls share state and update each
/// other so the user can type `0` to snap back to unity. UI clips entered values
/// to the bounded range. The underlying `engine.masterGain` API accepts any
/// finite scalar — programmatic callers can step outside the UI bounds when
/// needed. A mute toggle drives `engine.isMuted`. Changes are click-free —
/// the engine ramps gain across one block on each update.
///
/// All values are polled at 10 Hz (`pollIntervalNs`).
///
/// ## Hosting
///
/// Embed inside any SwiftUI parent:
///
/// ```swift
/// LyrebirdEngineStatusView(engine: engine)
/// .padding()
/// ```
///
/// On macOS, when no parent view is provided the convenience initializer
/// `presentInWindow(engine:title:width:height:)` opens a standalone
/// `LyrebirdWindow` hosting the view:
///
/// ```swift
/// let win = LyrebirdEngineStatusView.presentInWindow(engine: engine)
/// // … later …
/// win.close()
/// ```
///
/// ## Threading
///
/// The view body runs on the main thread. `engine.start()` / `engine.stop()` are
/// invoked from the SwiftUI button action; both are main-thread-safe per
/// `SynthesisEngine`'s public contract.
public struct LyrebirdEngineStatusView: View {
public let engine: SynthesisEngine
/// 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
@State private var averageCPU: Double = 0.0
@State private var peakCPU: Double = 0.0
@State private var lastStartError: String?
@State private var sampleRate: Double = 48000
@State private var numOutputChannels: Int = 2
@State private var numInputChannels: Int = 0
@State private var masterGainDb: Double = 0.0
@State private var masterGainDbText: String = "+0.0"
@FocusState private var gainTextFocused: Bool
@State private var isMuted: Bool = false
@State private var lastConfigError: String?
@State private var isMessagesExpanded: Bool = false
@State private var isNodeTreeExpanded: Bool = false
#if os(macOS)
@State private var messageWindow: LyrebirdWindow?
@State private var nodeTreeWindow: LyrebirdWindow?
#endif
private static let pollIntervalNs: UInt64 = 100_000_000
private static let sampleRateOptions: [Double] = [
44100, 48000, 88200, 96000, 176400, 192000
]
private static let outputChannelRange: ClosedRange<Int> = 1...32
private static let inputChannelRange: ClosedRange<Int> = 0...32
private static let gainDbRange: ClosedRange<Double> = -90.0...12.0
/// Persistent groups always present in the engine: rootGroup + mainGroup.
/// Surfaced in the displayed Groups count so the user sees the persistent
/// baseline (e.g. 2 after a `LyrebirdEventList.killAll()` rather than 0).
private static let persistentGroupCount: Int = 2
/// Creates a status view bound to the given engine.
///
/// - 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
// hard-coded default, and the volume display would briefly read +0.0
// when the caller had set a different master gain before mounting.
_sampleRate = State(initialValue: engine.sampleRate)
_numOutputChannels = State(initialValue: engine.numOutputChannels)
_numInputChannels = State(initialValue: engine.numInputChannels)
_isRunning = State(initialValue: engine.isRunning)
_isMuted = State(initialValue: engine.isMuted)
let initialDb: Double = LyrebirdEngineStatusView.linearToDb(engine.masterGain)
_masterGainDb = State(initialValue: initialDb)
_masterGainDbText = State(initialValue: String(format: "%+.1f", initialDb))
}
/// Linear amplitude → dB, with a finite floor at the slider's lower bound so
/// `masterGain == 0` (or near-zero) doesn't produce `-inf` in the text field.
private static func linearToDb(_ linear: Double) -> Double {
guard linear > 0, linear.isFinite else { return gainDbRange.lowerBound }
let db: Double = 20.0 * log10(linear)
return min(max(db, gainDbRange.lowerBound), gainDbRange.upperBound)
}
/// Picker rates = standard list plus the current `sampleRate` if it isn't
/// already represented. Keeps the menu sorted ascending so an odd
/// device-reported rate (e.g. 22050) slots in next to the closest standard.
private var sampleRatePickerOptions: [Double] {
var rates: [Double] = LyrebirdEngineStatusView.sampleRateOptions
if !rates.contains(sampleRate) {
rates.append(sampleRate)
rates.sort()
}
return rates
}
public var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack(spacing: 8) {
Circle()
.fill(isRunning ? Color.green : Color.secondary.opacity(0.4))
.frame(width: 10, height: 10)
Text(isRunning ? "Running" : "Stopped")
.font(.headline)
Spacer()
Button(isRunning ? "Stop" : "Start") {
toggleEngine()
}
}
if let err: String = lastStartError {
Text(err)
.font(.caption)
.foregroundStyle(.red)
}
Divider()
HStack(spacing: 16) {
CountTile(label: "Synths", value: synthesizerCount)
CountTile(
label: "Groups",
value: groupCount + LyrebirdEngineStatusView.persistentGroupCount,
subtitle: "incl. rootGroup, mainGroup"
)
}
Divider()
VStack(alignment: .leading, spacing: 6) {
CPURow(label: "CPU Avg", value: averageCPU)
CPURow(label: "CPU Peak", value: peakCPU)
}
Divider()
nodeTreeSection
Divider()
messagesSection
Divider()
configurationSection
Divider()
outputSection
}
.padding(12)
.background(Color.lyrebirdControlBackground)
.frame(minWidth: 260)
.task {
while !Task.isCancelled {
refresh()
try? await Task.sleep(nanoseconds: LyrebirdEngineStatusView.pollIntervalNs)
}
}
}
private var configurationSection: some View {
VStack(alignment: .leading, spacing: 6) {
Text("Configuration")
.font(.caption.monospaced())
.foregroundStyle(.secondary)
HStack {
Text("Sample Rate")
.frame(width: 110, alignment: .leading)
Picker("", selection: $sampleRate) {
ForEach(sampleRatePickerOptions, id: \.self) { rate in
Text("\(Int(rate)) Hz").tag(rate)
}
}
.labelsHidden()
.pickerStyle(.menu)
}
Stepper(
"Output Channels: \(numOutputChannels)",
value: $numOutputChannels,
in: LyrebirdEngineStatusView.outputChannelRange
)
Stepper(
"Input Channels: \(numInputChannels)",
value: $numInputChannels,
in: LyrebirdEngineStatusView.inputChannelRange
)
if let err: String = lastConfigError {
Text(err)
.font(.caption)
.foregroundStyle(.red)
}
}
.disabled(isRunning)
.opacity(isRunning ? 0.5 : 1.0)
.onChange(of: sampleRate) { _, newValue in
pushConfigToEngine { try engine.setSampleRate(newValue) }
}
.onChange(of: numOutputChannels) { _, newValue in
pushConfigToEngine { try engine.setNumOutputChannels(newValue) }
}
.onChange(of: numInputChannels) { _, newValue in
pushConfigToEngine { try engine.setNumInputChannels(newValue) }
}
}
/// Wrap a setter call so `.onChange` handlers fired while the engine is
/// running — e.g. the mirror assignment in `refresh()` triggered by an
/// external engine state change — don't bubble a spurious
/// `engineIsRunning` error into the UI. The user can never edit the
/// controls while running (`.disabled(isRunning)`), so the only path
/// through `.onChange` during a run is the mirror.
private func pushConfigToEngine(_ apply: () throws -> Void) {
guard !isRunning else { return }
applyConfig(apply)
}
private var outputSection: some View {
VStack(alignment: .leading, spacing: 6) {
Text("Output")
.font(.caption.monospaced())
.foregroundStyle(.secondary)
Toggle("Mute", isOn: $isMuted)
.onChange(of: isMuted) { _, newValue in
engine.isMuted = newValue
}
HStack(spacing: 8) {
Text("Volume")
.frame(width: 60, alignment: .leading)
Slider(value: $masterGainDb, in: LyrebirdEngineStatusView.gainDbRange)
.onChange(of: masterGainDb) { _, db in
engine.masterGain = pow(10.0, db / 20.0)
if !gainTextFocused {
masterGainDbText = String(format: "%+.1f", db)
}
}
TextField("dB", text: $masterGainDbText)
.font(.caption.monospaced())
.monospacedDigit()
.multilineTextAlignment(.trailing)
.focused($gainTextFocused)
.frame(width: 70)
.textFieldStyle(.roundedBorder)
.onSubmit(commitMasterGainText)
.onChange(of: gainTextFocused) { _, focused in
if !focused { commitMasterGainText() }
}
Text("dB")
.font(.caption.monospaced())
.foregroundStyle(.secondary)
}
}
}
private func commitMasterGainText() {
var trimmed: String = masterGainDbText.trimmingCharacters(in: .whitespaces)
// Strip only a leading `+` — `replacingOccurrences` would also remove the
// `+` inside scientific notation like `1e+2`.
if trimmed.first == "+" { trimmed.removeFirst() }
if let parsed: Double = Double(trimmed) {
let range: ClosedRange<Double> = LyrebirdEngineStatusView.gainDbRange
let clamped: Double = min(max(parsed, range.lowerBound), range.upperBound)
masterGainDb = clamped // triggers slider .onChange → engine update
masterGainDbText = String(format: "%+.1f", clamped)
} else {
// Bad input — revert text to the current model value.
masterGainDbText = String(format: "%+.1f", masterGainDb)
}
}
private func applyConfig(_ apply: () throws -> Void) {
do {
try apply()
lastConfigError = nil
} catch {
lastConfigError = "Config: \(error)"
}
}
private var nodeTreeSection: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Button {
isNodeTreeExpanded.toggle()
} label: {
HStack(spacing: 4) {
Image(systemName: isNodeTreeExpanded ? "chevron.down" : "chevron.right")
.font(.caption2)
Text("Node Tree")
.font(.caption.monospaced())
}
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
Spacer()
#if os(macOS)
Button("Open Window") {
openNodeTreeWindow()
}
.font(.caption)
#endif
}
// Persistent-groups strip — always visible (even when the full
// tree view is collapsed) so the user can see at a glance that
// `rootGroup` and `mainGroup` are alive.
persistentGroupsStrip
if isNodeTreeExpanded {
LyrebirdNodeTreeView(mirror: engine.nodeTreeMirror)
.frame(minHeight: 180, maxHeight: 300)
}
}
}
/// Always-visible row showing the persistent groups (`rootGroup` /
/// `mainGroup`) and their child counts from the live snapshot. Renders
/// whether the Node Tree section is expanded or collapsed.
private var persistentGroupsStrip: some View {
let snap: NodeTreeSnapshot = engine.nodeTreeMirror.snapshot
let root: NodeTreeSnapshot.Node = snap.root
let mainNode: NodeTreeSnapshot.Node? = root.children.first
let mainChildCount: Int = mainNode?.children.count ?? 0
return HStack(spacing: 6) {
Image(systemName: "chevron.down")
.font(.caption2)
.foregroundStyle(.tertiary)
Text("rootGroup")
.font(.caption2.monospaced())
.foregroundStyle(.secondary)
Text("(\(root.children.count))")
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
Text("▸")
.font(.caption2)
.foregroundStyle(.tertiary)
Text("mainGroup")
.font(.caption2.monospaced())
.foregroundStyle(.secondary)
Text("(\(mainChildCount))")
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
Spacer()
}
.padding(.leading, 6)
}
#if os(macOS)
private func openNodeTreeWindow() {
if let existing: LyrebirdWindow = nodeTreeWindow {
existing.close()
nodeTreeWindow = nil
}
nodeTreeWindow = LyrebirdNodeTreeView.presentInWindow(engine: engine)
}
#endif
private var messagesSection: some View {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 8) {
Button {
isMessagesExpanded.toggle()
} label: {
HStack(spacing: 4) {
Image(systemName: isMessagesExpanded ? "chevron.down" : "chevron.right")
.font(.caption2)
Text("Messages")
.font(.caption.monospaced())
}
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
Spacer()
#if os(macOS)
Button("Open Window") {
openMessageWindow()
}
.font(.caption)
#endif
}
if isMessagesExpanded {
LyrebirdMessageView()
.frame(minHeight: 160, maxHeight: 260)
} else {
LyrebirdMessageBanner(onOpenFull: {
isMessagesExpanded = true
})
}
}
}
#if os(macOS)
private func openMessageWindow() {
if let existing: LyrebirdWindow = messageWindow {
existing.close()
messageWindow = nil
}
messageWindow = LyrebirdMessageView.presentInWindow()
}
#endif
private func refresh() {
isRunning = engine.isRunning
synthesizerCount = engine.synthesizerCount
groupCount = engine.groupCount
averageCPU = engine.averageCPU
peakCPU = engine.peakCPU
// Mirror engine-side config into UI state. SwiftUI only fires `.onChange`
// on a real value change, so the engine-as-source-of-truth assignments
// converge after one tick without an infinite onChange loop.
if sampleRate != engine.sampleRate {
sampleRate = engine.sampleRate
}
if numOutputChannels != engine.numOutputChannels {
numOutputChannels = engine.numOutputChannels
}
if numInputChannels != engine.numInputChannels {
numInputChannels = engine.numInputChannels
}
}
private func toggleEngine() {
if engine.isRunning {
engine.stop()
lastStartError = nil
} else {
do {
try engine.start()
lastStartError = nil
onEngineStarted?()
} catch {
lastStartError = "Start failed: \(error)"
}
}
refresh()
}
}
// MARK: - Sub-views
private struct CountTile: View {
let label: String
let value: Int
let subtitle: String?
init(
label: String,
value: Int,
subtitle: String? = nil
) {
self.label = label
self.value = value
self.subtitle = subtitle
}
var body: some View {
VStack(alignment: .leading, spacing: 2) {
Text(label)
.font(.caption.monospaced())
.foregroundStyle(.secondary)
Text("\(value)")
.font(.title3.monospaced())
.foregroundStyle(.primary)
if let sub: String = subtitle {
Text(sub)
.font(.caption2.monospaced())
.foregroundStyle(.tertiary)
.lineLimit(1)
.truncationMode(.middle)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
private struct CPURow: View {
let label: String
let value: Double
private static let maxDisplayPercent: Double = 999.9
private static let warningThreshold: Double = 0.5
private static let criticalThreshold: Double = 0.8
private var displayPercent: Double {
min(value * 100.0, CPURow.maxDisplayPercent)
}
private var barColor: Color {
switch value {
case ..<CPURow.warningThreshold: return .green
case ..<CPURow.criticalThreshold: return .yellow
default: return .red
}
}
var body: some View {
HStack(spacing: 8) {
Text(label)
.font(.caption.monospaced())
.foregroundStyle(.secondary)
.frame(width: 60, alignment: .leading)
GeometryReader { geo in
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 2)
.fill(Color.secondary.opacity(0.15))
RoundedRectangle(cornerRadius: 2)
.fill(barColor)
.frame(width: geo.size.width * min(CGFloat(value), 1.0))
.animation(.linear(duration: 0.1), value: value)
}
}
.frame(height: 6)
Text(String(format: "%.1f%%", displayPercent))
.font(.caption.monospaced())
.foregroundStyle(.primary)
.frame(width: 56, alignment: .trailing)
}
}
}
// MARK: - Standalone window (macOS)
#if os(macOS)
extension LyrebirdEngineStatusView {
/// Opens a `LyrebirdWindow` hosting an engine status view.
///
/// Use when no parent SwiftUI view is available — a script, REPL session, or
/// command-line demo can call this to surface engine status in its own window.
/// The returned `LyrebirdWindow` retains the AppKit window; close it with
/// `.close()`.
///
/// - Parameters:
/// - engine: The `SynthesisEngine` to monitor.
/// - title: Window title bar text. Defaults to `"Engine Status"`.
/// - width: Initial window width in points. Defaults to `320`.
/// - height: Initial window height in points. Defaults to `480`.
/// - Returns: The `LyrebirdWindow` hosting the view. Caller retains it to keep
/// the window alive.
@MainActor
@discardableResult
public static func presentInWindow(
engine: SynthesisEngine,
title: String = "Engine Status",
width: CGFloat = 320,
height: CGFloat = 480
) -> LyrebirdWindow {
let win: LyrebirdWindow = LyrebirdWindow(title: title, width: width, height: height)
win.open {
LyrebirdEngineStatusView(engine: engine)
}
return win
}
}
#endif
#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