Files
Lyrebird/Sources/LyrebirdUI/LyrebirdScopeView.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

228 lines
9.3 KiB
Swift
Raw 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.
// LyrebirdScopeView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
import LyrebirdSynth
/// A real-time dual-channel oscilloscope view.
///
/// Polls `ScopeCapture` at ~30 Hz and renders each channel's waveform using
/// `Canvas`. Channels are stacked vertically, separated by a hairline rule.
///
/// Channel 0 (left) is drawn in cyan; channel 1 (right) in orange.
/// The zero line for each channel is drawn as a dim horizontal guide.
///
/// ```swift
/// LyrebirdScopeView(capture: scopeCapture)
/// .frame(height: 120)
/// ```
public struct LyrebirdScopeView: View {
public let capture: ScopeCapture
@State private var channels: [[Float]] = []
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
private static let channelColors: [Color] = [.cyan, .orange, .green, .yellow]
private static let backgroundColor: Color = Color(white: 0.08)
private static let zeroLineOpacity: Double = 0.25
private static let separatorOpacity: Double = 0.3
/// Per-half-height fraction for waveform amplitude (0.44 × half-height = 0.88 total row
/// excursion), leaving headroom so ±1 signals don't clip against channel boundaries.
private static let waveformHeightFraction: CGFloat = 0.44
public init(capture: ScopeCapture) {
self.capture = capture
}
public var body: some View {
Canvas { ctx, size in
_drawBackground(ctx: ctx, size: size)
guard !channels.isEmpty else { return }
let count: Int = channels.count
let rowH: CGFloat = size.height / CGFloat(count)
for (ch, samples) in channels.enumerated() {
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
let halfH: CGFloat = rowH * LyrebirdScopeView.waveformHeightFraction
// Zero guide line
var guide: Path = Path()
guide.move(to: CGPoint(x: 0, y: midY))
guide.addLine(to: CGPoint(x: size.width, y: midY))
ctx.stroke(guide, with: .color(.white.opacity(LyrebirdScopeView.zeroLineOpacity)),
lineWidth: 0.5)
// Channel separator (between channels, not after last)
if ch < count - 1 {
let sepY: CGFloat = rowH * CGFloat(ch + 1)
var sep: Path = Path()
sep.move(to: CGPoint(x: 0, y: sepY))
sep.addLine(to: CGPoint(x: size.width, y: sepY))
ctx.stroke(sep, with: .color(.white.opacity(LyrebirdScopeView.separatorOpacity)),
lineWidth: 0.5)
}
guard samples.count > 1 else { continue }
let color: Color = LyrebirdScopeView.channelColors[ch % LyrebirdScopeView.channelColors.count]
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
var path: Path = Path()
for (i, sample) in samples.enumerated() {
let x: CGFloat = CGFloat(i) * xStep
let y: CGFloat = midY - CGFloat(sample) * halfH
if i == 0 { path.move(to: CGPoint(x: x, y: y)) }
else { path.addLine(to: CGPoint(x: x, y: y)) }
}
ctx.stroke(path, with: .color(color), lineWidth: 1.0)
}
}
.background(LyrebirdScopeView.backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: 4))
.task {
while !Task.isCancelled {
channels = capture.snapshot()
try? await Task.sleep(nanoseconds: LyrebirdScopeView.pollIntervalNs)
}
}
}
private func _drawBackground(
ctx: GraphicsContext,
size: CGSize
) {
ctx.fill(Path(CGRect(origin: .zero, size: size)),
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