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