// 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.. 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.. (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