v1.4.2 release: live-coding editor — Run Selection, slot release, engine panel, console, manual completion

Additive conveniences to the macOS-only Live Scratch editor. No changes to
existing public API.

- Run Selection (⌘E): evaluate just the highlighted text, additively.
- Graceful slot release: context.release(slot:) / free(slot:).
- Engine panel: live oscilloscope (ScopeCapture) + CPU avg/peak + counts.
- Reset Session / Restart to Reclaim Memory.
- Always-open console panel (report messages + errors with line:col).
- Faster typing: debounced highlight, updateNSView fast-path, publish guards.
- Manual code completion (Esc / F5), no auto-trigger on `.`; completion
  replaces the partial word, not the receiver expression.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-21 11:09:30 -07:00
parent abc64df4d7
commit 8519cabe42
21 changed files with 1578 additions and 145 deletions
@@ -41,19 +41,41 @@ window.open {
| Shortcut | Action |
|----------|--------|
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
anonymous tracked synths and every named slot.
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
running graph, without touching the rest of the buffer or the whole-buffer
re-evaluation baseline (the buffer's clean/dirty status still reflects the last
whole run). This is the live-coding "evaluate this line/region" gesture: audition
a single voice or tweak, layer it in, keep going. It reads the editor selection
via ``LyrebirdScratchModel/updateSelection(_:)`` and runs it through
``LyrebirdScratchModel/runSelection()``; disabled when nothing is selected.
The engine status pill at the top-left is also a **Start/Stop** button
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
red "▶ start engine" when stopped. A snippet is only audible while the engine
is running; the host normally starts it at launch, but this lets the user
recover from a failed start (e.g. no output device) without relaunching.
## Engine panel (scope + status)
The panel at the bottom of the window is a small always-on view of the running
engine:
- A live dual-channel **oscilloscope** of the output (``ScratchScopeView``),
fed by a ``ScopeCapture`` that ``LiveSession`` attaches to the first one or two
output buses at init (it must be installed before `start()`). Pass
`attachScope: false` to `LiveSession.init` to opt out.
- **CPU average / peak** meter bars and the **synth / group / snippet** counts,
so overrun and node growth are visible at a glance.
## Snippet API surface
A snippet has one local in scope:
@@ -71,8 +93,61 @@ context: SnippetContext
subclass needed (wraps it in a `ClosureSynthesizer`).
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
**named slot** (see below).
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
`print`-style probes during development).
- `context.reportMessage(_:)` — print a line to the **Console** panel (see
below); the live-coding equivalent of `print`.
## Console
An always-open panel down the right side of the window is the log:
- **Report messages** — every `context.reportMessage(_:)` line (and host notices
like a failed `engine.add` or a dropped slot swap).
- **Errors** — compile and Graph DSL diagnostics, with their `line:col`, shown
here rather than in a transient bottom strip so they stay visible while you
fix them.
- **Run notices** — a one-line result for each run.
Oldest first, auto-scrolled to the newest, capped at
``LyrebirdScratchModel/maxConsoleEntries`` lines. **Clear** empties it; a
**Reset Session** clears it too. The model exposes the log as
``LyrebirdScratchModel/consoleEntries``.
## Functional snippets & scheduling
A Swift-mode snippet is **real Swift**, not just a graph expression — loops,
`let` bindings, functions, arrays all work. The one rule for anything
time-based: **schedule** events, don't `Thread.sleep`. The snippet body runs
once, synchronously, on the main thread; sleeping in a loop would freeze the UI
(the audio thread is separate, but the editor isn't). Use
`engine.schedule(_:after:)` for sample-accurate timing instead.
For example, a `for` loop that plays ten short sine tones a third of a second
apart — a C-major run — each a decaying `Line` envelope times a sine that frees
itself when done (`doneAction: .freeNode`), so the voices never pile up:
```swift
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
440.0, 493.88, 523.25, 587.33, 659.25]
for i in 0..<10 {
let freq: Double = scale[i]
let tone = ClosureSynthesizer {
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
* OscSin.Audio(freq: freq)
}
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
catch { context.reportMessage("schedule \(i) failed: \(error)") }
}
context.reportMessage("scheduled 10 tones")
```
The loop returns immediately after scheduling all ten adds; the engine fires
each at its time (`0, 0.35, 0.70 … s`). A 0.2 s tone with 0.35 s spacing leaves a
short gap between each. (This is *fire-and-forget* scheduling for a fixed
sequence; for an open-ended or reactive sequence — a repeating pattern, tempo
following — reach for `LyrebirdRoutine` / `LyrebirdClock` on the language side.)
> Note: **Graph DSL mode** evaluates only generator-graph expressions — no loops
> or scheduling. Functional code like the above needs **Swift mode**.
## Named slots (hot-swap)
@@ -95,11 +170,35 @@ voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
Clear a slot with `context.session.clearSlot("bass")`, all slots with
`context.session.clearSlots()`. The toolbar **Clear Synths** button is a full
reset — anonymous synths *and* every slot. A slot definition you delete from the
buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear
it explicitly or hit Clear Synths.
### Start a voice, release it later
The slot **name is the handle** — the persistent reference you keep across
evaluations. (Swift `let`/`var` bindings do not carry from one snippet to the
next: each ⌘↩ / ⌘E is a separately-compiled unit, so a variable declared in one
run is invisible to the next.) So the "start something, let go of it later"
gesture is: name a slot in one evaluation, then release it by name from another —
a natural pairing with **Run Selection** (⌘E):
```swift
// Select this line, ⌘E — starts a persistent, gated voice named "pad":
context.play(slot: "pad") { EnvGen(gate: 1, /* … release-on-done */) * OscSaw.Audio(freq: 110) }
// …later, select this line, ⌘E — graceful release: the envelope tails out,
// then the voice frees itself:
context.release(slot: "pad")
```
- `context.release(slot:)` triggers the voice's envelope **release** phase and
drops the handle; the voice must free itself (an `EnvGen`/gate with a
free-on-done action) to leave the engine.
- `context.free(slot:)` is the **immediate** hard stop (no tail) — the
counterpart to `release`.
Clear a slot with `context.free(slot: "bass")` (or `context.session.clearSlot`),
all slots with `context.session.clearSlots()`. The toolbar **Clear Synths**
button is a full reset — anonymous synths *and* every slot. A slot definition you
delete from the buffer and stop re-running is *not* auto-removed (a `Pdef`-style
gotcha) — release/free it explicitly or hit Clear Synths.
## Threading
@@ -194,11 +293,13 @@ through its own diagnostics.
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
stdio by ``SourceKitLSPClient`` and bridged to the editor by
``SnippetCompletionService``. Typing `.` after an expression pops the standard
completion window; the candidates are the real symbols the snippet would see at
compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`, …),
the injected `context` (`context.` → `play`, `engine`, …), and the Swift
standard library.
``SnippetCompletionService``. Press **Esc** (or **F5** — the standard macOS
completion keys) to complete at the caret; the candidates are the real symbols the snippet would
see at compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`,
…), the injected `context` (`context.` → `play`, `engine`, …), and the Swift
standard library. Completion is **manual, never auto-triggered on `.`** — an
unrequested popup ambushes typing and the built-in completion window is awkward
to dismiss mid-edit.
How it resolves those symbols for an otherwise free-standing file: the service
maintains a small temp workspace holding the snippet **wrapped** in the same
@@ -216,8 +317,8 @@ candidates rather than an error.
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
approximate by design, not a full parser. Completion (above) uses the real
compiler via sourcekit-lsp; the two are independent.
- Completion currently triggers on `.`; a manual-invoke shortcut is a possible
follow-up.
- Completion is invoked manually with **Esc** (or **F5**); there is no
auto-trigger on `.`.
- The host `.app` must not be sandboxed and must allow library validation to be
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
dylib is `dlopen`'d.
@@ -251,6 +352,17 @@ orange and a warning banner appears — nudging the user to restart to reclaim t
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
a hard stop: the choice stays with the user.
Two Run-menu commands act on this:
- **Reset Session** (``LyrebirdScratchModel/resetSession()``) — an *in-process*
reset: stops all snippet audio, shuts down the code-completion server (freeing
its subprocess and temp workspace), and clears diagnostics and the run
baseline. **Non-destructive** — your buffer is left untouched, so it needs no
confirmation. It does **not** unload the mapped snippet dylibs.
- **Restart to Reclaim Memory…** — relaunches the app (after a confirmation,
since unsaved buffer edits are lost), the only way to actually free the mapped
dylibs. The fresh process starts at zero.
## Graph DSL mode (instant, no compile)
The status-bar toggle switches the editor between two evaluators:
@@ -152,10 +152,20 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
keyEquivalent: "\r")
runAdd.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(runAdd))
menu.addItem(target(NSMenuItem(title: "Run Selection",
action: #selector(runSelection(_:)),
keyEquivalent: "e")))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
action: #selector(clearSynths(_:)),
keyEquivalent: "k")))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Reset Session",
action: #selector(resetSession(_:)),
keyEquivalent: "")))
menu.addItem(target(NSMenuItem(title: "Restart to Reclaim Memory…",
action: #selector(restartApp(_:)),
keyEquivalent: "")))
item.submenu = menu
return item
}
@@ -215,6 +225,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
switch menuItem.action {
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
return model.reevalState.canEvaluate
case #selector(runSelection(_:)):
// Needs a selection to run and an evaluator that isn't mid-compile.
return model.hasSelection && model.reevalState.canEvaluate
case #selector(resetSession(_:)):
// Don't tear the session down mid-compile.
return !model.isCompiling
default:
return true
}
@@ -280,6 +296,52 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
Task { @MainActor in _ = await model.run(additive: true) }
}
@objc private func runSelection(_ sender: Any?) {
Task { @MainActor in _ = await model.runSelection() }
}
@objc private func resetSession(_ sender: Any?) {
model.resetSession()
}
@objc private func restartApp(_ sender: Any?) {
let alert: NSAlert = NSAlert()
alert.messageText = "Restart to reclaim memory?"
alert.informativeText =
"Relaunches the app to free the \(model.loadedSnippetCount) mapped snippet "
+ "dylibs (compiled snippets can't be unloaded any other way). Unsaved changes "
+ "in the buffer will be lost."
alert.addButton(withTitle: "Restart")
alert.addButton(withTitle: "Cancel")
guard alert.runModal() == .alertFirstButtonReturn else { return }
LyrebirdScratchMenuController.relaunchApp()
}
/// Relaunch the host `.app`: open a fresh instance, then terminate this one
/// once it is confirmed on its way. The new process starts with zero mapped
/// snippet dylibs — the only way to reclaim that memory. On a launch failure
/// the current process is **kept** (and the user informed) rather than
/// terminated into oblivion.
private static func relaunchApp() {
let url: URL = Bundle.main.bundleURL
let config: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
config.createsNewApplicationInstance = true
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
DispatchQueue.main.async {
if let error: Error = error {
let alert: NSAlert = NSAlert()
alert.messageText = "Restart failed"
alert.informativeText =
"Could not relaunch the app (\(error.localizedDescription)). "
+ "The current session is unchanged."
alert.runModal()
} else if app != nil {
NSApp.terminate(nil)
}
}
}
}
@objc private func clearSynths(_ sender: Any?) {
model.clearTracked()
}
@@ -99,6 +99,48 @@ public final class LyrebirdScratchModel: ObservableObject {
/// Updated by `run(additive:)` and `clearTracked()`.
@Published public private(set) var statusMessage: String = ""
/// Accumulated console log shown in the always-open right panel: snippet
/// `context.reportMessage(_:)` output, compile/DSL errors, and run notices,
/// oldest first. Capped at ``maxConsoleEntries``.
@Published public private(set) var consoleEntries: [ScratchConsoleEntry] = []
/// Upper bound on retained console lines; the oldest are dropped past it.
public nonisolated static let maxConsoleEntries: Int = 500
private var _consoleSeq: Int = 0
/// Append one console line, trimming the log to ``maxConsoleEntries``.
private func appendConsole(_ kind: ScratchConsoleEntry.Kind, _ text: String, location: String? = nil) {
_consoleSeq += 1
consoleEntries.append(ScratchConsoleEntry(id: _consoleSeq, kind: kind, text: text, location: location))
let overflow: Int = consoleEntries.count - LyrebirdScratchModel.maxConsoleEntries
if overflow > 0 { consoleEntries.removeFirst(overflow) }
}
/// Empty the console.
public func clearConsole() {
consoleEntries.removeAll()
}
/// After a run resolves, move the snippet's report messages into the console
/// (they arrive in order during the run), then the run outcome: on failure,
/// each diagnostic as an error line; on success, a one-line notice.
private func recordRunConsole(succeeded: Bool) {
for message: String in session.drainMessages() {
appendConsole(.message, message)
}
if succeeded {
appendConsole(.info, statusMessage)
} else if diagnostics.isEmpty {
appendConsole(.error, statusMessage)
} else {
for diagnostic: Diagnostic in diagnostics {
let location: String? = diagnostic.line.map { "\($0):\(diagnostic.column)" }
appendConsole(.error, diagnostic.message, location: location)
}
}
}
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
/// `clearTracked` call so the toolbar can show the count without polling.
@Published public private(set) var trackedSynthCount: Int
@@ -151,6 +193,23 @@ public final class LyrebirdScratchModel: ObservableObject {
/// horizontally.
@Published public var wrapsLines: Bool = true
/// The current editor selection text (empty when nothing is selected).
/// Pushed by the editor on selection change; drives ``hasSelection`` and
/// ``runSelection()``.
@Published public private(set) var selectionText: String = ""
/// `true` when the editor has a non-whitespace selection available to run.
public var hasSelection: Bool {
!selectionText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
}
/// Record the editor's current selection. Called by the editor's
/// selection-change delegate; empty string clears it.
public func updateSelection(_ text: String) {
guard text != selectionText else { return } // avoid redundant republish
selectionText = text
}
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
@@ -229,7 +288,11 @@ public final class LyrebirdScratchModel: ObservableObject {
/// resolves (edits made mid-compile are re-evaluated once it finishes).
private func recomputeReevalStateAfterEdit() {
guard !isCompiling else { return }
reevalState = derivedIdleState()
// Assign only on a real change: after the first edit dirties the buffer,
// every later keystroke re-derives `.dirty` — republishing an unchanged
// value would re-render the whole view for nothing.
let next: ReevalState = derivedIdleState()
if next != reevalState { reevalState = next }
}
/// Settle a `.queued` state once its scheduled swap has become audible.
@@ -268,29 +331,48 @@ public final class LyrebirdScratchModel: ObservableObject {
@discardableResult
public func run(additive: Bool) async -> Bool {
switch evalMode {
case .swift: return await runSwiftSnippet(additive: additive)
case .graphDSL: return runGraphDSLBuffer(additive: additive)
case .swift: return await runSwiftSnippet(body: text, additive: additive, recordBaseline: true)
case .graphDSL: return runGraphDSLBuffer(body: text, additive: additive, recordBaseline: true)
}
}
/// Swift path: compile the buffer to a dylib off-main and run it.
private func runSwiftSnippet(additive: Bool) async -> Bool {
/// Evaluate just the current editor selection as an **additive** run: the
/// selected text is compiled/interpreted and added to whatever is already
/// playing (never a non-additive replace), and it does not disturb the
/// whole-buffer re-evaluation baseline — the buffer's `.clean`/`.dirty`
/// status still reflects the last *whole* run. No-op when nothing is
/// selected. Works in both Swift and Graph DSL modes.
@discardableResult
public func runSelection() async -> Bool {
guard hasSelection else { return false }
let body: String = selectionText
switch evalMode {
case .swift: return await runSwiftSnippet(body: body, additive: true, recordBaseline: false)
case .graphDSL: return runGraphDSLBuffer(body: body, additive: true, recordBaseline: false)
}
}
/// Swift path: compile `body` to a dylib off-main and run it.
/// `recordBaseline` distinguishes a whole-buffer run (updates the `.clean`
/// baseline) from a selection run (leaves it untouched).
private func runSwiftSnippet(body: String, additive: Bool, recordBaseline: Bool) async -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
statusMessage = "Compiling…"
isCompiling = true
reevalState = .compiling
var runSucceeded: Bool = false
defer {
isCompiling = false
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
recordRunConsole(succeeded: runSucceeded)
}
do {
try await session.compileAndRunAsync(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
settleReevalAfterSuccess(body: body)
statusMessage = "Ran \(runDescription(additive: additive, recordBaseline: recordBaseline))."
settleReeval(body: body, recordBaseline: recordBaseline)
runSucceeded = true
return true
} catch let sessionError as LiveSessionError {
switch sessionError {
@@ -303,7 +385,7 @@ public final class LyrebirdScratchModel: ObservableObject {
message: "\(underlying)",
rawLine: 0
)]
statusMessage = "Compile failed — see diagnostics below."
statusMessage = "Compile failed — see console."
} else {
diagnostics = diags
let plural: String = diags.count == 1 ? "" : "s"
@@ -316,31 +398,32 @@ public final class LyrebirdScratchModel: ObservableObject {
diagnostics = diags
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
}
reevalState = .failed(diagnosticCount: diagnostics.count)
settleReevalAfterFailure(recordBaseline: recordBaseline)
return false
} catch {
statusMessage = "Error: \(error)"
reevalState = .failed(diagnosticCount: diagnostics.count)
settleReevalAfterFailure(recordBaseline: recordBaseline)
return false
}
}
/// Graph-DSL path: interpret the buffer in-process — instant, no swiftc, so
/// no `isCompiling` spinner and no `await`. A parse/build failure leaves the
/// Graph-DSL path: interpret `body` in-process — instant, no swiftc, so no
/// `isCompiling` spinner and no `await`. A parse/build failure leaves the
/// currently-playing graph untouched (the session builds before it mutates).
private func runGraphDSLBuffer(additive: Bool) -> Bool {
private func runGraphDSLBuffer(body: String, additive: Bool, recordBaseline: Bool) -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
var runSucceeded: Bool = false
defer {
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
recordRunConsole(succeeded: runSucceeded)
}
do {
try session.runGraphDSL(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
settleReevalAfterSuccess(body: body)
statusMessage = "Ran DSL \(runDescription(additive: additive, recordBaseline: recordBaseline))."
settleReeval(body: body, recordBaseline: recordBaseline)
runSucceeded = true
return true
} catch let sessionError as LiveSessionError {
if case .graphDSLFailed(let diags, _) = sessionError {
@@ -350,21 +433,23 @@ public final class LyrebirdScratchModel: ObservableObject {
} else {
statusMessage = "Error: \(sessionError)"
}
reevalState = .failed(diagnosticCount: diagnostics.count)
settleReevalAfterFailure(recordBaseline: recordBaseline)
return false
} catch {
statusMessage = "Error: \(error)"
reevalState = .failed(diagnosticCount: diagnostics.count)
settleReevalAfterFailure(recordBaseline: recordBaseline)
return false
}
}
/// Record the just-run text as the baseline and settle the readiness state:
/// `.queued` when the buffer is unchanged and a quantized slot swap is
/// scheduled but not yet audible, otherwise the derived idle state (`.clean`,
/// or `.dirty` if the buffer was edited while the run was in flight).
private func settleReevalAfterSuccess(body: String) {
lastEvaluatedText = body
/// Settle the readiness state after a successful run. For a whole-buffer run
/// (`recordBaseline`), record the run text as the `.clean` baseline; for a
/// selection run, leave the baseline untouched (the buffer's status still
/// reflects the last whole run). Either way resolve to `.queued` when the
/// buffer is unchanged and a quantized swap is pending, else the derived
/// idle state.
private func settleReeval(body: String, recordBaseline: Bool) {
if recordBaseline { lastEvaluatedText = body }
let idle: ReevalState = derivedIdleState()
if idle == .clean, let beat: Double = session.pendingSwapBeat {
reevalState = .queued(untilBeat: beat)
@@ -373,6 +458,33 @@ public final class LyrebirdScratchModel: ObservableObject {
}
}
/// Settle the readiness state after a *failed* run. A whole-buffer failure
/// sets `.failed` (the badge should reflect that the buffer doesn't run). A
/// selection failure must NOT touch the whole-buffer badge — the buffer and
/// its last whole-run baseline are unaffected — so it recomputes the derived
/// idle state and marks the status line as a selection failure. Diagnostics
/// (already set by the caller) still surface the error either way.
private func settleReevalAfterFailure(recordBaseline: Bool) {
if recordBaseline {
reevalState = .failed(diagnosticCount: diagnostics.count)
} else {
statusMessage = "Selection — " + statusMessage
reevalState = derivedIdleState()
}
}
/// Status-line phrase for a run: distinguishes a whole-buffer replace/add
/// from a selection add, and includes the live tracked-synth count.
private func runDescription(additive: Bool, recordBaseline: Bool) -> String {
let what: String
if !recordBaseline {
what = "selection (added)"
} else {
what = additive ? "additive" : "replaced"
}
return "(\(what)). Tracked synths: \(session.trackedSynthCount)"
}
/// Switch evaluation mode. When the buffer still holds the *current* mode's
/// untouched placeholder, swap in the target mode's placeholder so the seed
/// example matches the mode; any edited buffer is left as-is.
@@ -392,6 +504,34 @@ public final class LyrebirdScratchModel: ObservableObject {
reevalState = derivedIdleState()
}
/// In-process session reset: stop all snippet audio, shut down the code-
/// completion server (freeing its subprocess + temp workspace), and clear
/// diagnostics and the run baseline. **Non-destructive** — the editor buffer
/// (the user's code) is left untouched, so this needs no confirmation.
///
/// It reclaims everything it *can* in-process — but **not** the compiled
/// snippet dylibs (`loadedSnippetCount`), which cannot be unloaded safely
/// (`dlclose` is unsafe for Swift dylibs). Only relaunching the process frees
/// those; the status line says so, and the "Restart" command does it.
///
/// No-op while a compile is in flight (matching the run methods' guard) — a
/// reset must not tear the session down under an active `compileAndRunAsync`.
public func resetSession() {
guard !isCompiling else { return }
session.resetAll()
_completion?.shutdownSynchronously()
_completion = nil // recreated lazily on next completion
diagnostics = []
consoleEntries.removeAll()
lastEvaluatedText = nil
trackedSynthCount = session.trackedSynthCount
loadedSnippetCount = session.loadedSnippetCount
reevalState = derivedIdleState()
statusMessage = loadedSnippetCount > 0
? "Session reset. \(loadedSnippetCount) snippet dylibs still mapped — Restart to reclaim that memory."
: "Session reset."
}
/// Start the audio engine if stopped, or stop it if running. Surfaces the
/// outcome (including a start failure — e.g. no audio device) on the status
/// line. The host normally starts the engine at launch; this lets the user
@@ -85,6 +85,28 @@ public struct LyrebirdScratchView: View {
}
public var body: some View {
HStack(spacing: 0) {
mainColumn
Divider()
consolePanel
.frame(width: consoleWidth)
}
.frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight)
.onAppear {
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
// Idempotent — safe if `onAppear` fires again.
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
}
/// The editor column: engine controls, editor, status, engine panel.
private var mainColumn: some View {
VStack(spacing: 0) {
engineBar
if let hint: String = model.snippetMemoryHint {
@@ -101,27 +123,50 @@ public struct LyrebirdScratchView: View {
wrapsLines: model.wrapsLines,
requestCompletions: { line, character in
await model.completionItems(line: line, character: character)
}
},
onSelectionChanged: { selected in model.updateSelection(selected) }
)
.frame(minHeight: editorMinHeight)
Divider()
statusBar
if !model.diagnostics.isEmpty {
Divider()
diagnosticsList
Divider()
enginePanel
}
}
/// Always-open right-side console: report messages, errors, and run notices,
/// oldest first, auto-scrolled to the newest.
private var consolePanel: some View {
VStack(spacing: 0) {
HStack {
Text("Console")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer()
Button("Clear") { model.clearConsole() }
.buttonStyle(.plain)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
.disabled(model.consoleEntries.isEmpty)
}
.padding(.horizontal, statusHPad)
.padding(.vertical, statusVPad)
Divider()
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 2) {
ForEach(model.consoleEntries) { entry in
ConsoleRow(entry: entry)
}
Color.clear.frame(height: 1).id(consoleBottomID)
}
.padding(diagnosticListPadding)
.frame(maxWidth: .infinity, alignment: .leading)
}
.onChange(of: model.consoleEntries.count) { _, _ in
proxy.scrollTo(consoleBottomID, anchor: .bottom)
}
}
}
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
.onAppear {
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
// Idempotent — safe if `onAppear` fires again.
model.session.prewarm()
}
.onReceive(engineRefresh) { _ in
engineTick &+= 1
// Settle a `.queued` readiness badge once its swap has fired.
model.refreshQueuedState()
}
}
@@ -180,6 +225,73 @@ public struct LyrebirdScratchView: View {
.background(Color.orange.opacity(0.12))
}
/// 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)`.
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)
}
/// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts.
private var engineStatusRow: some View {
let engine: SynthesisEngine = model.session.engine
return VStack(alignment: .leading, spacing: 6) {
HStack {
Text("Engine")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch")
.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)")
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
}
/// One labelled CPU meter bar. `value` is a fraction of one block period
/// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun.
private func cpuMeter(label: String, value: Double) -> some View {
let clamped: CGFloat = CGFloat(min(max(value, 0), 1))
let fill: Color = value > cpuMeterCriticalThreshold
? .red
: (value > cpuMeterWarningThreshold ? .orange : .green)
return HStack(spacing: 6) {
Text(label)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
.frame(width: cpuLabelWidth, alignment: .leading)
GeometryReader { geo in
ZStack(alignment: .leading) {
RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15))
RoundedRectangle(cornerRadius: 2).fill(fill)
.frame(width: geo.size.width * clamped)
}
}
.frame(height: meterHeight)
Text(formatCPU(value))
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
.frame(width: cpuValueWidth, alignment: .trailing)
}
}
private func formatCPU(_ value: Double) -> String {
String(format: "%.0f%%", value * 100)
}
@@ -190,6 +302,14 @@ public struct LyrebirdScratchView: View {
}
}
/// Evaluate just the current selection, additively. No-op when nothing is
/// selected.
public func runSelection() {
Task { @MainActor in
_ = await model.runSelection()
}
}
public func presentOpenPanel() {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
@@ -322,18 +442,6 @@ public struct LyrebirdScratchView: View {
}
}
private var diagnosticsList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
DiagnosticRow(diagnostic: diag)
}
}
.padding(diagnosticListPadding)
}
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
}
// Layout constants — all in points. Kept private; tuned to match
// LyrebirdEngineStatusView's visual density.
private let scratchMinWidth: CGFloat = 520
@@ -350,26 +458,38 @@ public struct LyrebirdScratchView: View {
private let diagnosticsMaxHeight: CGFloat = 200
private let engineDotSize: CGFloat = 8
private let reevalBadgeSpacing: CGFloat = 4
private let scopeHeight: CGFloat = 88
private let meterHeight: CGFloat = 6
private let consoleWidth: CGFloat = 300
private let consoleBottomID: String = "scratch.console.bottom"
private let cpuLabelWidth: CGFloat = 58
private let cpuValueWidth: CGFloat = 40
/// CPU-meter fill turns orange above this fraction of one block period, red
/// above ``cpuMeterCriticalThreshold``.
private let cpuMeterWarningThreshold: Double = 0.5
private let cpuMeterCriticalThreshold: Double = 0.8
}
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
/// message in a compact monospaced row.
private struct DiagnosticRow: View {
private struct ConsoleRow: View {
let diagnostic: Diagnostic
let entry: ScratchConsoleEntry
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
Text(locationString)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.frame(minWidth: locationColumnWidth, alignment: .leading)
Text(diagnostic.severity.rawValue)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(color(for: diagnostic.severity))
.frame(minWidth: severityColumnWidth, alignment: .leading)
Text(diagnostic.message)
HStack(alignment: .firstTextBaseline, spacing: 6) {
Text(glyph)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(color)
.frame(width: 14, alignment: .leading)
if let location: String = entry.location {
Text(location)
.font(.system(.caption2, design: .monospaced))
.foregroundStyle(.secondary)
}
Text(entry.text)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(entry.kind == .error ? Color.primary : color)
.textSelection(.enabled)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
@@ -377,58 +497,88 @@ private struct DiagnosticRow: View {
}
}
private var locationString: String {
if let line: Int = diagnostic.line {
return "\(line):\(diagnostic.column)"
/// Leading glyph per kind: an X for errors, an arrow for messages, a dot for
/// info notices.
private var glyph: String {
switch entry.kind {
case .error: return "✗"
case .message: return "›"
case .info: return "·"
}
// No user-body line. A swiftc preamble hit carries a real (1-based)
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
// harness/preamble at all), so label the two cases distinctly.
return diagnostic.rawLine >= 1
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
: "(file)"
}
private func color(for severity: DiagnosticSeverity) -> Color {
switch severity {
private var color: Color {
switch entry.kind {
case .error: return .red
case .warning: return .orange
case .note: return .secondary
case .message: return .cyan
case .info: return .secondary
}
}
private let rowGutter: CGFloat = 8
private let locationColumnWidth: CGFloat = 80
private let severityColumnWidth: CGFloat = 56
}
/// `NSTextView` subclass that fixes member-completion behavior.
///
/// The default `rangeForUserCompletion` scans back over the whole dotted
/// expression, so completing a member right after a `.` (e.g. `context.` →
/// `engine`) would *replace* the receiver (`context`) with the chosen member
/// instead of inserting after the dot. When the character before the insertion
/// point is a `.`, this override returns an empty range at the caret, so the
/// completion is a pure insertion and `context.engine` is produced.
/// UTF-16 code unit for `.` (the member-access operator that triggers and
/// shapes completion).
private let dotCharacterCode: unichar = 46
/// expression, so a candidate would *replace* the receiver rather than the
/// partial word being typed. Completing a member after `context.` → `engine`
/// would replace `context`; accepting an argument label after `OscSin.Audio(`
/// → `freq:` would replace `OscSin.Audio`. The correct replace range is just
/// the run of identifier characters immediately before the caret (empty after
/// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there.
/// Whether `selection` is a bare insertion point sitting immediately after a
/// `.` in `text` — the member-completion trigger condition.
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
guard selection.length == 0, selection.location > 0, selection.location <= text.length
else { return false }
return text.character(at: selection.location - 1) == dotCharacterCode
/// Whether `c` (a UTF-16 code unit) is a Swift identifier character —
/// ASCII letter, digit, or underscore. Sufficient for completion-range
/// scanning; identifiers with non-ASCII scalars are not a concern here.
private func isIdentifierCodeUnit(_ c: unichar) -> Bool {
let underscore: unichar = 95
let zero: unichar = 48, nine: unichar = 57
let upperA: unichar = 65, upperZ: unichar = 90
let lowerA: unichar = 97, lowerZ: unichar = 122
return c == underscore
|| (c >= zero && c <= nine)
|| (c >= upperA && c <= upperZ)
|| (c >= lowerA && c <= lowerZ)
}
final class ScratchTextView: NSTextView {
/// Invoked when the user asks for completion (the standard completion key —
/// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then
/// shows the completion window. Completion is manual only.
var onManualComplete: (() -> Void)?
override var rangeForUserCompletion: NSRange {
let sel: NSRange = selectedRange()
if caretFollowsDot(in: string as NSString, selection: sel) {
return NSRange(location: sel.location, length: 0)
// Never replace across an actual selection — defer to the default.
guard sel.length == 0, sel.location <= (string as NSString).length else {
return super.rangeForUserCompletion
}
return super.rangeForUserCompletion
let ns: NSString = string as NSString
var start: Int = sel.location
while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) {
start -= 1
}
return NSRange(location: start, length: sel.location - start)
}
/// Intercept the built-in `complete:` command (bound to Esc / F5) so the
/// candidates are fetched asynchronously first, then shown. Without this,
/// pressing Esc would call the delegate with an empty (never-fetched) list.
/// Everything else falls through to the normal editor commands.
override func doCommand(by selector: Selector) {
if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) {
onManualComplete?()
return
}
super.doCommand(by: selector)
}
/// Esc is delivered as `cancelOperation:` (not `complete:`) by the default
/// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm —
/// only F5 does. Route it here too so Esc invokes completion as documented.
/// The completion window, once open, consumes Esc itself to dismiss, so this
/// only fires when the window is closed.
override func cancelOperation(_ sender: Any?) {
onManualComplete?()
}
}
@@ -444,6 +594,9 @@ private struct ScratchEditor: NSViewRepresentable {
/// Async source of code-completion candidates for a zero-based user-space
/// (line, UTF-16 character). Supplied by the view from the model.
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
/// Called with the current selected substring whenever the selection
/// changes (empty when nothing is selected). Drives "Run Selection".
let onSelectionChanged: @MainActor (String) -> Void
@MainActor
final class Coordinator: NSObject, NSTextViewDelegate {
@@ -455,17 +608,67 @@ private struct ScratchEditor: NSViewRepresentable {
/// applies its results if it is still the newest (so a slow older request
/// can't clobber a fresher one that landed first).
private var _completionGeneration: Int = 0
/// Pending debounced re-highlight; cancelled and rescheduled on each edit
/// so a burst of keystrokes re-tokenizes the buffer once, not per key.
private var _highlightWork: DispatchWorkItem?
/// Last selection substring pushed to the model, so an unchanged selection
/// (the common case while typing — caret moves, selection stays empty)
/// doesn't republish `@Published` state and re-render the whole view.
private var _lastSelectionPushed: String = ""
/// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying
/// wrap/paragraph settings on a pure text republish (every keystroke).
var lastWraps: Bool?
/// Idle delay before re-highlighting after an edit. Short enough to feel
/// instant once typing pauses; long enough to coalesce a fast burst.
private static let highlightDebounce: TimeInterval = 0.045
init(_ parent: ScratchEditor) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
parent.text = tv.string
parent.applyHighlight(to: tv)
// Auto-trigger member completion right after a `.` is typed.
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
triggerCompletion(tv)
scheduleHighlight(tv)
// Completion is manual (Esc), never auto-triggered on `.`: an
// unrequested popup ambushes typing and the built-in completion
// window is awkward to dismiss mid-edit.
}
/// Coalesce full-buffer re-highlighting: cancel any pending pass and run
/// one shortly after the edits stop. Newly typed characters render in the
/// base color immediately (via `typingAttributes`); syntax colors catch
/// up a beat later, avoiding an O(n) tokenize on every keystroke.
private func scheduleHighlight(_ tv: NSTextView) {
_highlightWork?.cancel()
let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in
guard let self: Coordinator = self, let tv: NSTextView = tv else { return }
self.parent.applyHighlight(to: tv)
}
_highlightWork = work
DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work)
}
/// Push the current selected substring up to the model so "Run Selection"
/// knows what (if anything) is selected — but only when it actually
/// changed, to avoid a per-caret-move `@Published` republish.
func textViewDidChangeSelection(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
let sel: NSRange = tv.selectedRange()
let selected: String
if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length {
selected = (tv.string as NSString).substring(with: sel)
} else {
selected = ""
}
guard selected != _lastSelectionPushed else { return }
_lastSelectionPushed = selected
// Defer the @Published mutation: a programmatic text change (via
// `updateNSView` → `replaceText`) can clamp the selection and re-post
// this notification from inside a SwiftUI update pass. Scheduling on
// the next main-actor tick keeps that off the render pass ("Publishing
// changes from within view updates is not allowed").
let notify: @MainActor (String) -> Void = parent.onSelectionChanged
Task { @MainActor in notify(selected) }
}
/// The text view calls this synchronously from `complete(_:)`; return the
@@ -525,6 +728,12 @@ private struct ScratchEditor: NSViewRepresentable {
scroll.documentView = tv
configure(tv, in: scroll, with: context.coordinator)
// Manual completion (Esc): fetch candidates, then show the window.
let coordinator: Coordinator = context.coordinator
tv.onManualComplete = { [weak coordinator, weak tv] in
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
coordinator.triggerCompletion(tv)
}
return scroll
}
@@ -533,14 +742,23 @@ private struct ScratchEditor: NSViewRepresentable {
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
if fontChanged {
tv.font = font
}
let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines
context.coordinator.lastWraps = wrapsLines
let textChanged: Bool = tv.string != text
// Fast path: a pure text republish (the per-keystroke case) needs no work
// here — the `NSTextView` already holds the text (it's the editor of
// record), highlighting is debounced in the Coordinator, and font/wrap
// are unchanged. Skip the paragraph-style measure + attribute churn.
guard textChanged || fontChanged || wrapChanged else { return }
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
if fontChanged { tv.font = font }
tv.defaultParagraphStyle = paragraphStyle
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
applyWrap(to: tv, in: scroll)
if tv.string != text {
if textChanged {
// External change (load, reset, mode switch) — replace + re-highlight.
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
} else if fontChanged {
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
@@ -0,0 +1,42 @@
// ScratchConsoleEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// One line in the scratch editor's console panel — a report message, an error,
// or a run notice.
#if os(macOS)
/// A single entry in the always-open console.
public struct ScratchConsoleEntry: Identifiable, Equatable {
/// What kind of line this is, for coloring.
public enum Kind: Equatable {
/// `context.reportMessage(_:)` output (and host notices).
case message
/// A compile / DSL error.
case error
/// A run outcome / informational notice.
case info
}
/// Monotonic id (also the display order).
public let id: Int
public let kind: Kind
public let text: String
/// `"line:col"` for an error with a known source position, else `nil`.
public let location: String?
public init(id: Int, kind: Kind, text: String, location: String? = nil) {
self.id = id
self.kind = kind
self.text = text
self.location = location
}
}
#endif
@@ -0,0 +1,85 @@
// ScratchScopeView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile
//
// A compact real-time oscilloscope for the scratch editor's engine panel.
// Reimplemented here (rather than reusing `LyrebirdUI.LyrebirdScopeView`) because
// the LiveCompile stack must not link `LyrebirdUI` — that would static-fold a
// second copy of `LyrebirdSynth`'s ObjC classes. It reads the same core
// `ScopeCapture` the engine writes to.
#if os(macOS)
import SwiftUI
import LyrebirdSynth
/// Polls a ``ScopeCapture`` at ~30 Hz and draws each captured channel's waveform
/// with `Canvas`. Channels stack vertically; channel 0 cyan, channel 1 orange.
struct ScratchScopeView: View {
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
private static let waveformHeightFraction: CGFloat = 0.44
var body: some View {
Canvas { ctx, size in
ctx.fill(Path(CGRect(origin: .zero, size: size)),
with: .color(ScratchScopeView.backgroundColor))
guard !channels.isEmpty else { return }
let count: Int = channels.count
let rowH: CGFloat = size.height / CGFloat(count)
for (ch, samples): (Int, [Float]) in channels.enumerated() {
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
let halfH: CGFloat = rowH * ScratchScopeView.waveformHeightFraction
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(ScratchScopeView.zeroLineOpacity)),
lineWidth: 0.5)
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(ScratchScopeView.separatorOpacity)),
lineWidth: 0.5)
}
guard samples.count > 1 else { continue }
let color: Color = ScratchScopeView.channelColors[ch % ScratchScopeView.channelColors.count]
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
var path: Path = Path()
for (i, sample): (Int, Float) 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(ScratchScopeView.backgroundColor)
.clipShape(RoundedRectangle(cornerRadius: 4))
.task {
while !Task.isCancelled {
channels = capture.snapshot()
try? await Task.sleep(nanoseconds: ScratchScopeView.pollIntervalNs)
}
}
}
}
#endif