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

511 lines
18 KiB
Swift

// 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..<segCount {
let region: _EnvelopeRegion = _regionForSegment(
index: seg,
loopNode: envelope.loopNode,
releaseNode: envelope.releaseNode,
segmentCount: segCount
)
let tStart: Double = boundaryTimes[seg]
let tEnd: Double = boundaryTimes[seg + 1]
let segDur: Double = tEnd - tStart
let frac: Double = segDur / envelope.totalDuration
// nSamples is a step count; the loop runs 0...nSamples (nSamples+1 points),
// so the final point lands exactly at tEnd, closing each segment cleanly.
let nSamples: Int = max(2, Int(ceil(CGFloat(totalSamples) * CGFloat(frac))))
var path: Path = Path()
for i: Int in 0...nSamples {
let t: Double = tStart + segDur * Double(i) / Double(nSamples)
let v: Double = envelope.valueAtTime(t)
let x: CGFloat = _xFor(t, width: size.width)
let y: CGFloat = _yFor(v, yMin: yMin, yMax: yMax, height: size.height)
let pt: CGPoint = CGPoint(x: x, y: y)
if i == 0 { path.move(to: pt) } else { path.addLine(to: pt) }
}
ctx.stroke(path, with: .color(region.color),
lineWidth: LyrebirdEnvelopeView.signalLineWidth)
}
// Vertical dashed markers — loopNode and releaseNode are pre-validated by Envelope.init
// to be in [0, segmentCount), so boundaryTimes[ln/rn] is always in bounds.
if let ln: Int = envelope.loopNode {
_drawMarker(ctx: ctx, time: boundaryTimes[ln], label: "L",
color: .green, size: size)
}
if let rn: Int = envelope.releaseNode {
_drawMarker(ctx: ctx, time: boundaryTimes[rn], label: "R",
color: .orange, size: size)
}
}
private func _drawMarker(
ctx: GraphicsContext,
time: Double,
label: String,
color: Color,
size: CGSize
) {
let x: CGFloat = _xFor(time, width: size.width)
var line: Path = Path()
line.move(to: CGPoint(x: x, y: 0))
line.addLine(to: CGPoint(x: x, y: size.height))
ctx.stroke(line,
with: .color(color.opacity(LyrebirdEnvelopeView.markerOpacity)),
style: StrokeStyle(lineWidth: LyrebirdEnvelopeView.markerLineWidth,
dash: LyrebirdEnvelopeView.markerDash))
ctx.draw(
Text(label)
.font(LyrebirdEnvelopeView.labelFont)
.foregroundStyle(color),
at: CGPoint(x: x + LyrebirdEnvelopeView.markerLabelOffsetX,
y: LyrebirdEnvelopeView.markerLabelOffsetY),
anchor: .leading
)
}
// MARK: - Coordinate helpers
private func _xFor(
_ t: Double,
width: CGFloat
) -> 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..<segCount {
let region: _LinuxEnvelopeRegion = _linuxRegionForSegment(
index: seg,
loopNode: envelope.loopNode,
releaseNode: envelope.releaseNode
)
let tStart: Double = boundaryTimes[seg]
let tEnd: Double = boundaryTimes[seg + 1]
let segDur: Double = tEnd - tStart
let frac: Double = segDur / envelope.totalDuration
// nSamples is a step count; the loop runs 0...nSamples so the final
// point lands exactly at tEnd, closing each segment cleanly.
let nSamples: Int = max(2, Int(ceil(Double(totalSamples) * frac)))
let rgb: (r: Double, g: Double, b: Double) = region.rgb
ctx.setColor(r: rgb.r, g: rgb.g, b: rgb.b)
ctx.setLineWidth(signalLineWidth)
for i: Int in 0...nSamples {
let t: Double = tStart + segDur * Double(i) / Double(nSamples)
let v: Double = envelope.valueAtTime(t)
let x: Double = xFor(t, width: w)
let y: Double = yFor(v, bounds: bounds, height: h)
if i == 0 {
ctx.moveTo(x: x, y: y)
} else {
ctx.lineTo(x: x, y: y)
}
}
ctx.stroke()
}
// Vertical dashed markers — loopNode/releaseNode are pre-validated by
// Envelope.init to be in [0, segmentCount), so boundaryTimes is in bounds.
if let ln: Int = envelope.loopNode {
drawMarker(ctx: ctx, time: boundaryTimes[ln], region: .loop, width: w, height: h)
}
if let rn: Int = envelope.releaseNode {
drawMarker(ctx: ctx, time: boundaryTimes[rn], region: .release, width: w, height: h)
}
}
private func drawMarker(
ctx: DrawingContext,
time: Double,
region: _LinuxEnvelopeRegion,
width w: Double,
height h: Double
) {
// Derive the marker colour from the region so it matches that region's
// segment trace exactly (green loop, orange release).
let rgb: (r: Double, g: Double, b: Double) = region.rgb
let color: Color = Color(red: rgb.r, green: rgb.g, blue: rgb.b)
let x: Double = xFor(time, width: w)
var line: Path = Path()
line.move(to: CGPoint(x: x, y: 0))
line.addLine(to: CGPoint(x: x, y: h))
ctx.stroke(
line,
with: .color(color.opacity(markerOpacity)),
style: StrokeStyle(lineWidth: markerLineWidth, dash: markerDash)
)
}
// MARK: - Coordinate helpers
private func xFor(_ t: Double, width w: Double) -> 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