// LyrebirdEnvelopeView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT #if canImport(SwiftUI) import SwiftUI import LyrebirdSynth // MARK: - Region /// Render region for one envelope segment. enum _EnvelopeRegion { case preLoop case loop case release var color: Color { switch self { case .preLoop: return .cyan case .loop: return .green case .release: return .orange } } } // MARK: - Pure helpers (internal for testability via @testable import LyrebirdUI) /// Returns the render region for a single segment index given loopNode/releaseNode. /// /// Loop-only semantics (loopNode set, releaseNode nil): only the segment *at* loopNode /// is colored `.loop`. Segments after it are the gate-off release path — they play once /// after gate drops and are correctly classified as `.preLoop`. func _regionForSegment( index: Int, loopNode: Int?, releaseNode: Int?, segmentCount: Int ) -> _EnvelopeRegion { switch (loopNode, releaseNode) { case (let ln?, let rn?): if index < ln { return .preLoop } if index < rn { return .loop } return .release case (let ln?, nil): return index == ln ? .loop : .preLoop case (nil, let rn?): return index < rn ? .preLoop : .release case (nil, nil): return .preLoop } } /// Returns cumulative boundary times: `[0, d0, d0+d1, …, totalDuration]`. /// Length is `durations.count + 1`. func _segmentBoundaryTimes(durations: [Double]) -> [Double] { var times: [Double] = [0] var elapsed: Double = 0 for d: Double in durations { elapsed += d times.append(elapsed) } return times } /// Returns Y display bounds for `levels` with 10 % headroom on each side. /// Returns `(0, 1)` when `levels` is empty. func _envelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) { let minimumLevelRange: Double = 1e-6 let headroomFactor: Double = 0.1 guard let lo: Double = levels.min(), let hi: Double = levels.max() else { return (0, 1) } let range: Double = max(hi - lo, minimumLevelRange) let headroom: Double = range * headroomFactor return (lo - headroom, hi + headroom) } // MARK: - LyrebirdEnvelopeView /// A SwiftUI view that plots an `Envelope` as a color-coded shape. /// /// Segments are drawn in distinct colors based on their role: /// - **Cyan** — normal segments before any loop or release point /// - **Green** — loop region `[loopNode, releaseNode)` /// - **Orange** — release region from `releaseNode` to the end /// /// Vertical dashed markers indicate `loopNode` ("L") and `releaseNode` ("R") boundaries. /// Horizontal hairlines show the target level for each segment endpoint. /// /// ```swift /// let env = Envelope( /// levels: [0, 1, 0.6, 0], /// durations: [0.01, 0.3, 0.2], /// curves: [.sine, .lin, .exponential], /// loopNode: 1, /// releaseNode: 2 /// ) /// LyrebirdEnvelopeView(env) /// .padding() /// ``` public struct LyrebirdEnvelopeView: View { private let envelope: Envelope private let width: Double private let height: Double private static let backgroundBrightness: CGFloat = 0.08 private static let backgroundColor: Color = Color(white: backgroundBrightness) /// 2 path points per canvas pixel — smooth enough for all curve shapes. private static let oversample: CGFloat = 2 private static let markerOpacity: Double = 0.7 private static let levelTickOpacity: Double = 0.2 private static let markerDash: [CGFloat] = [4, 3] private static let labelFontSize: CGFloat = 9 private static let labelFont: Font = .system(size: labelFontSize, weight: .semibold, design: .monospaced) private static let signalLineWidth: CGFloat = 1.5 private static let guideLineWidth: CGFloat = 0.5 private static let markerLineWidth: CGFloat = 1 private static let markerLabelOffsetX: CGFloat = 4 private static let markerLabelOffsetY: CGFloat = 6 private static let cornerRadius: CGFloat = 4 public init( _ envelope: Envelope, width: Double = 300, height: Double = 120 ) { self.envelope = envelope self.width = width self.height = height } public var body: some View { Canvas { ctx, size in _draw(ctx: ctx, size: size) } .frame(width: width, height: height) .background(LyrebirdEnvelopeView.backgroundColor) .clipShape(RoundedRectangle(cornerRadius: LyrebirdEnvelopeView.cornerRadius)) } // MARK: - Drawing private func _draw( ctx: GraphicsContext, size: CGSize ) { let (yMin, yMax) = _envelopeYBounds(levels: envelope.levels) let segCount: Int = envelope.segmentCount // Zero-segment or zero-duration: draw flat line at constant level. guard segCount > 0 && envelope.totalDuration > 0 else { let v: Double = envelope.levels.first ?? 0 let y: CGFloat = _yFor(v, yMin: yMin, yMax: yMax, height: size.height) var path: Path = Path() path.move(to: CGPoint(x: 0, y: y)) path.addLine(to: CGPoint(x: size.width, y: y)) ctx.stroke(path, with: .color(.cyan), lineWidth: LyrebirdEnvelopeView.signalLineWidth) return } let boundaryTimes: [Double] = _segmentBoundaryTimes(durations: envelope.durations) let totalSamples: Int = Int(ceil(size.width * LyrebirdEnvelopeView.oversample)) // Horizontal level hairlines for level: Double in envelope.levels { let y: CGFloat = _yFor(level, yMin: yMin, yMax: yMax, height: size.height) var tick: Path = Path() tick.move(to: CGPoint(x: 0, y: y)) tick.addLine(to: CGPoint(x: size.width, y: y)) ctx.stroke(tick, with: .color(.white.opacity(LyrebirdEnvelopeView.levelTickOpacity)), lineWidth: LyrebirdEnvelopeView.guideLineWidth) } // One colored path per segment for seg: Int in 0.. CGFloat { CGFloat(t / envelope.totalDuration) * width } private func _yFor( _ v: Double, yMin: Double, yMax: Double, height: CGFloat ) -> CGFloat { let t: Double = (v - yMin) / (yMax - yMin) return height * (1.0 - CGFloat(t)) } } #else // Linux/GTK4 counterpart to `LyrebirdUI.LyrebirdEnvelopeView`: plots a core // `Envelope` as a colour-coded shape on a single `Canvas`. Static — it draws a // fixed spec once, no timer or polling. // // Divergence from macOS: `DrawingContext` has no text drawing, so the "L"/"R" // letters beside the loop/release markers are omitted. The dashed marker line // still shows each boundary, colour-coded green (loop) / orange (release) to // match the segment colours. // // SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift). import SwiftOpenUI import BackendGTK4 import LyrebirdSynth import Foundation // MARK: - Region /// Render region for one envelope segment. enum _LinuxEnvelopeRegion { case preLoop case loop case release /// Trace colour as an RGB triple for `DrawingContext.setColor`. var rgb: (r: Double, g: Double, b: Double) { switch self { case .preLoop: return (0.0, 0.8, 1.0) // cyan case .loop: return (0.0, 0.8, 0.0) // green case .release: return (1.0, 0.53, 0.0) // orange } } } // MARK: - Pure helpers /// Returns the render region for a single segment index given loopNode/releaseNode. /// /// Loop-only semantics (loopNode set, releaseNode nil): only the segment *at* loopNode /// is coloured `.loop`. Segments after it are the gate-off release path — they play once /// after gate drops and are correctly classified as `.preLoop`. func _linuxRegionForSegment( index: Int, loopNode: Int?, releaseNode: Int? ) -> _LinuxEnvelopeRegion { switch (loopNode, releaseNode) { case (let ln?, let rn?): if index < ln { return .preLoop } if index < rn { return .loop } return .release case (let ln?, nil): return index == ln ? .loop : .preLoop case (nil, let rn?): return index < rn ? .preLoop : .release case (nil, nil): return .preLoop } } /// Returns cumulative boundary times: `[0, d0, d0+d1, …, totalDuration]`. /// Length is `durations.count + 1`. func _linuxSegmentBoundaryTimes(durations: [Double]) -> [Double] { var times: [Double] = [0] var elapsed: Double = 0 for d: Double in durations { elapsed += d times.append(elapsed) } return times } /// Returns Y display bounds for `levels` with 10 % headroom on each side. /// Returns `(0, 1)` when `levels` is empty. func _linuxEnvelopeYBounds(levels: [Double]) -> (yMin: Double, yMax: Double) { let minimumLevelRange: Double = 1e-6 let headroomFactor: Double = 0.1 guard let lo: Double = levels.min(), let hi: Double = levels.max() else { return (0, 1) } let range: Double = max(hi - lo, minimumLevelRange) let headroom: Double = range * headroomFactor return (lo - headroom, hi + headroom) } // MARK: - LyrebirdEnvelopeView /// Plots an `Envelope` as a colour-coded shape for the Linux/GTK4 UI. Segments /// are cyan before any loop/release, green in the loop region, orange in the /// release region; horizontal hairlines mark segment levels; dashed vertical /// lines mark the loop (green) and release (orange) boundaries. public struct LyrebirdEnvelopeView: View { private let envelope: Envelope private let width: Double private let height: Double // Presentation constants. private let cornerRadius: Double = 4 /// Path points per canvas pixel — smooth enough for all curve shapes. private let oversample: Double = 2 private let signalLineWidth: Double = 1.5 private let guideLineWidth: Double = 0.5 private let markerLineWidth: Double = 1 private let markerOpacity: Double = 0.7 private let levelTickOpacity: Double = 0.2 private let markerDash: [CGFloat] = [4, 3] /// Creates an envelope plot. /// /// - Parameters: /// - envelope: The `Envelope` to plot. /// - width: Canvas width in points. Default 300. /// - height: Canvas height in points. Default 120. public init( _ envelope: Envelope, width: Double = 300, height: Double = 120 ) { self.envelope = envelope self.width = width self.height = height } public var body: some View { Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in draw(ctx: ctx, size: size) }) .frame(width: width, height: height) .clipShape(RoundedRectangle(cornerRadius: cornerRadius)) } // MARK: - Drawing private func draw(ctx: DrawingContext, size: CGSize) { 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() let bounds: (yMin: Double, yMax: Double) = _linuxEnvelopeYBounds(levels: envelope.levels) let segCount: Int = envelope.segmentCount // Degenerate: no segments or zero duration → flat line at the first level. guard segCount > 0 && envelope.totalDuration > 0 else { let v: Double = envelope.levels.first ?? 0 let y: Double = yFor(v, bounds: bounds, height: h) ctx.setColor(r: 0.0, g: 0.8, b: 1.0) ctx.setLineWidth(signalLineWidth) ctx.moveTo(x: 0, y: y) ctx.lineTo(x: w, y: y) ctx.stroke() return } let boundaryTimes: [Double] = _linuxSegmentBoundaryTimes(durations: envelope.durations) let totalSamples: Int = Int(ceil(w * oversample)) // Horizontal level hairlines. ctx.setColor(r: 1.0, g: 1.0, b: 1.0, a: levelTickOpacity) ctx.setLineWidth(guideLineWidth) for level: Double in envelope.levels { let y: Double = yFor(level, bounds: bounds, height: h) ctx.moveTo(x: 0, y: y) ctx.lineTo(x: w, y: y) } ctx.stroke() // One coloured polyline per segment. for seg: Int in 0.. Double { (t / envelope.totalDuration) * w } private func yFor( _ v: Double, bounds: (yMin: Double, yMax: Double), height h: Double ) -> Double { let t: Double = (v - bounds.yMin) / (bounds.yMax - bounds.yMin) return h * (1.0 - t) } } #endif