Files
Lyrebird/Sources/LyrebirdUI/LyrebirdStatusView.swift
T
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

235 lines
8.3 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// LyrebirdStatusView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
import LyrebirdSynth
/// A compact view that displays real-time CPU usage statistics for a `SynthesisEngine`.
///
/// Embed in any SwiftUI hierarchy to monitor average and peak CPU load. The view polls the
/// engine at 10 Hz and updates automatically while visible.
///
/// ```swift
/// LyrebirdStatusView(engine: engine)
/// ```
///
/// Values are expressed as a fraction of one block duration: `0.0` = idle, `1.0` = full block
/// consumed, `> 1.0` = over budget (xruns likely). The bars are color-coded: green below 50 %,
/// yellow 50–80 %, red above 80 %. Peak resets automatically every 5 s (engine default).
public struct LyrebirdStatusView: View {
public let engine: SynthesisEngine
@State private var averageCPU: Double = 0.0
@State private var peakCPU: Double = 0.0
private static let pollIntervalNs: UInt64 = 100_000_000 // 100 ms → 10 Hz
public init(engine: SynthesisEngine) {
self.engine = engine
}
public var body: some View {
VStack(alignment: .leading, spacing: 6) {
CPURow(label: "CPU Avg", value: averageCPU)
CPURow(label: "CPU Peak", value: peakCPU)
}
.task {
while !Task.isCancelled {
averageCPU = engine.averageCPU
peakCPU = engine.peakCPU
try? await Task.sleep(nanoseconds: LyrebirdStatusView.pollIntervalNs)
}
}
}
}
private struct CPURow: View {
let label: String
let value: Double // 0.0 = idle, 1.0 = full block, >1.0 = overload
private static let maxDisplayPercent: Double = 999.9
private static let warningThreshold: Double = 0.5
private static let criticalThreshold: Double = 0.8
private var displayPercent: Double { min(value * 100.0, CPURow.maxDisplayPercent) }
private var barColor: Color {
switch value {
case ..<CPURow.warningThreshold: return .green
case ..<CPURow.criticalThreshold: return .yellow
default: return .red
}
}
var body: some View {
HStack(spacing: 8) {
Text(label)
.font(.caption.monospaced())
.foregroundStyle(.secondary)
.frame(width: 60, alignment: .leading)
GeometryReader { geo in
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 2)
.fill(Color.secondary.opacity(0.15))
RoundedRectangle(cornerRadius: 2)
.fill(barColor)
.frame(width: geo.size.width * min(CGFloat(value), 1.0))
.animation(.linear(duration: 0.1), value: value)
}
}
.frame(height: 6)
Text(String(format: "%.1f%%", displayPercent))
.font(.caption.monospaced())
.foregroundStyle(.primary)
.frame(width: 46, alignment: .trailing)
}
}
}
#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