v1.5.0 release: LyrebirdRandom + Live Scratch editor

LyrebirdRandom scalar distribution sampling (seedable value type + shared
Random) with DistributionKind.sample dispatcher. Live Scratch editor: rename to
LyrebirdScratch, App Support artifact staging, Format Code (⌥⌘F), Render to File
(⌥⌘R offline CAF), line-number gutter, manual completion, Foundation in snippets,
scroll-jump fix, scheduling/NRT docs.
This commit is contained in:
2026-07-22 07:53:12 -07:00
parent 8519cabe42
commit 62b2f5dbec
43 changed files with 2249 additions and 376 deletions
@@ -58,9 +58,35 @@ import LyrebirdLiveCompile
public struct LyrebirdScratchView: View {
@StateObject private var model: LyrebirdScratchModel
@State private var engineTick: Int = 0
/// Snapshot of the engine's non-`@Published` live stats, refreshed on the
/// heartbeat. Bound in place by the status rows — deliberately NOT via
/// `.id(tick)`, which forces a subview teardown/rebuild every tick and churns
/// the surrounding layout, nudging the editor's scroll position ("screen
/// jumping" while scrolled down). Updating an `@State` value re-renders the
/// labels in place with stable identity, so the layout stays put.
@State private var stats: EngineStats = EngineStats()
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
/// Non-`@Published` engine values polled on the heartbeat.
private struct EngineStats: Equatable {
var isRunning: Bool = false
var averageCPU: Double = 0
var peakCPU: Double = 0
var synthesizerCount: Int = 0
var groupCount: Int = 0
}
private func snapshotStats() -> EngineStats {
let e: SynthesisEngine = model.session.engine
return EngineStats(
isRunning: e.isRunning,
averageCPU: e.averageCPU,
peakCPU: e.peakCPU,
synthesizerCount: e.synthesizerCount,
groupCount: e.groupCount
)
}
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
///
/// - Parameters:
@@ -99,7 +125,8 @@ public struct LyrebirdScratchView: View {
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
let next: EngineStats = snapshotStats()
if next != stats { stats = next }
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
@@ -175,21 +202,21 @@ public struct LyrebirdScratchView: View {
return HStack(spacing: toolbarSpacing) {
Button {
model.toggleEngine()
engineTick &+= 1
stats = snapshotStats()
} label: {
HStack(spacing: reevalBadgeSpacing) {
Circle()
.fill(engine.isRunning ? Color.green : Color.red)
.fill(stats.isRunning ? Color.green : Color.red)
.frame(width: engineDotSize, height: engineDotSize)
Text(engine.isRunning ? "engine running" : "▶ start engine")
Text(stats.isRunning ? "engine running" : "▶ start engine")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
.foregroundStyle(stats.isRunning ? Color.secondary : Color.primary)
}
}
.buttonStyle(.plain)
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
.help(stats.isRunning ? "Stop the audio engine" : "Start the audio engine")
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(stats.averageCPU))")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer().frame(width: 8)
@@ -205,7 +232,6 @@ public struct LyrebirdScratchView: View {
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.id(engineTick)
}
/// Warning strip shown once mapped snippet dylibs cross the restart
@@ -226,19 +252,16 @@ public struct LyrebirdScratchView: View {
}
/// Bottom engine panel: a live output oscilloscope plus a compact status
/// readout (sample rate, CPU average/peak meters, node counts). Refreshed on
/// the editor heartbeat via `.id(engineTick)`.
/// readout (sample rate, CPU average/peak meters, node counts). The status
/// text refreshes in place off the ``stats`` snapshot — no `.id(tick)`
/// teardown, so the surrounding layout (and the editor's scroll) stays put.
private var enginePanel: some View {
VStack(alignment: .leading, spacing: 6) {
// The scope keeps a stable identity so its 30 Hz `.task` poll loop
// is NOT cancelled/restarted by the `.id(engineTick)` heartbeat —
// that only wraps the status text below.
if let scope: ScopeCapture = model.session.scope {
ScratchScopeView(capture: scope)
.frame(height: scopeHeight)
}
engineStatusRow
.id(engineTick)
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
@@ -257,9 +280,9 @@ public struct LyrebirdScratchView: View {
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
cpuMeter(label: "CPU avg", value: engine.averageCPU)
cpuMeter(label: "CPU peak", value: engine.peakCPU)
Text("synths \(engine.synthesizerCount) · groups \(engine.groupCount) · snippets \(model.loadedSnippetCount)")
cpuMeter(label: "CPU avg", value: stats.averageCPU)
cpuMeter(label: "CPU peak", value: stats.peakCPU)
Text("synths \(stats.synthesizerCount) · groups \(stats.groupCount) · snippets \(model.loadedSnippetCount)")
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
@@ -580,6 +603,11 @@ final class ScratchTextView: NSTextView {
override func cancelOperation(_ sender: Any?) {
onManualComplete?()
}
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
/// `ScratchEditor.configure` reserves this as the text view's left inset so
/// the gutter overlay doesn't cover the text.
static let lineNumberGutterWidth: CGFloat = 40
}
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
@@ -718,6 +746,10 @@ private struct ScratchEditor: NSViewRepresentable {
scroll.autoresizingMask = [.width, .height]
let tv: ScratchTextView = ScratchTextView(frame: .zero)
// Opt into TextKit 1: accessing `layoutManager` permanently switches the
// text view off TextKit 2, where `self.layoutManager` is nil — the gutter
// drawing needs it to place numbers against laid-out line rects.
_ = tv.layoutManager
tv.autoresizingMask = [.width]
tv.isVerticallyResizable = true
tv.isHorizontallyResizable = false
@@ -734,6 +766,10 @@ private struct ScratchEditor: NSViewRepresentable {
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
coordinator.triggerCompletion(tv)
}
// Line-number gutter: a floating overlay pinned to the left of the visible
// area (see `ScratchLineNumberGutter` for why not an `NSRulerView`).
let gutter: ScratchLineNumberGutter = ScratchLineNumberGutter(scrollView: scroll, textView: tv)
scroll.addFloatingSubview(gutter, for: .vertical)
return scroll
}
@@ -791,6 +827,15 @@ private struct ScratchEditor: NSViewRepresentable {
tv.textStorage?.setAttributedString(attributed)
tv.typingAttributes = attrs
applyHighlight(to: tv, font: font, paragraph: paragraph)
// A direct `setAttributedString` bypasses `NSTextView`'s edit path, so the
// gutter (which redraws on `NSText.didChangeNotification`) isn't told to
// refresh. Nudge it explicitly after a programmatic replace (format /
// load / reset) so the line count doesn't go stale.
if let scroll: NSScrollView = tv.enclosingScrollView {
for sub: NSView in scroll.subviews {
(sub as? ScratchLineNumberGutter)?.refresh()
}
}
}
// MARK: - Syntax highlighting
@@ -856,7 +901,11 @@ private struct ScratchEditor: NSViewRepresentable {
tv.smartInsertDeleteEnabled = false
tv.allowsUndo = true
tv.usesFindBar = true
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
// Left inset reserves the column the `ScratchLineNumberGutter` overlay
// draws line numbers into (see `ScratchLineNumberGutter.draw(_:)`).
// `textContainerInset` is symmetric, so the right margin matches —
// harmless whitespace.
tv.textContainerInset = NSSize(width: ScratchTextView.lineNumberGutterWidth, height: editorInset)
tv.drawsBackground = true
tv.backgroundColor = .textBackgroundColor
tv.textColor = .labelColor