From 8519cabe42706ce5c51c2b534acdee6d581782a1 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Tue, 21 Jul 2026 11:09:30 -0700 Subject: [PATCH] =?UTF-8?q?v1.4.2=20release:=20live-coding=20editor=20?= =?UTF-8?q?=E2=80=94=20Run=20Selection,=20slot=20release,=20engine=20panel?= =?UTF-8?q?,=20console,=20manual=20completion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../LyrebirdScratchDemo/AppDelegate.swift | 16 +- .../LyrebirdLiveCompile/LiveSession.swift | 106 ++++- .../LyrebirdLiveCompile/SnippetContext.swift | 41 +- .../LyrebirdLiveCompileUI.docc/LiveCoding.md | 144 ++++++- .../LyrebirdScratchMenuController.swift | 62 +++ .../LyrebirdScratchModel.swift | 194 +++++++-- .../LyrebirdScratchView.swift | 382 ++++++++++++++---- .../ScratchConsoleEntry.swift | 42 ++ .../ScratchScopeView.swift | 85 ++++ .../MessageLogTests.swift | 43 ++ .../ScopeAttachTests.swift | 63 +++ .../SlotReleaseTests.swift | 94 +++++ .../SnippetScheduledLoopTests.swift | 76 ++++ .../LyrebirdScratchModelTests.swift | 4 +- .../ScratchModelConsoleTests.swift | 76 ++++ .../ScratchModelResetTests.swift | 58 +++ .../ScratchModelRunSelectionTests.swift | 104 +++++ .../ScratchTextViewTests.swift | 43 +- RELEASES.md | 79 ++++ .../lyrebird_release_prep/prepare_release.sh | 3 + claude/skills/lyrebird_release_prep/skill.md | 8 +- 21 files changed, 1578 insertions(+), 145 deletions(-) create mode 100644 LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchConsoleEntry.swift create mode 100644 LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchScopeView.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelConsoleTests.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelResetTests.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRunSelectionTests.swift diff --git a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift index c31b355..147de9b 100644 --- a/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift +++ b/Demos/LyrebirdScratchDemo/LyrebirdScratchDemo/AppDelegate.swift @@ -48,13 +48,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { menuController.installMainMenu() self.menuController = menuController - let windowWidth: CGFloat = 720 - let windowHeight: CGFloat = 560 let hosting: NSHostingController = NSHostingController(rootView: LyrebirdScratchView(model: model)) - let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight) let win: NSWindow = NSWindow( - contentRect: NSRect(origin: .zero, size: initialSize), + contentRect: NSRect(origin: .zero, size: CGSize(width: 720, height: 560)), styleMask: [.titled, .closable, .resizable, .miniaturizable], backing: .buffered, defer: false @@ -63,7 +60,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate { win.isReleasedWhenClosed = false win.title = "Lyrebird — Live Scratch" win.contentViewController = hosting - win.center() + // Base geometry: three-quarters of the screen wide, three-quarters tall, + // anchored to the left edge and vertically centered in the visible area + // (below the menu bar, above the Dock). + let visible: NSRect = (win.screen ?? NSScreen.main)?.visibleFrame + ?? NSRect(x: 0, y: 0, width: 1440, height: 900) + let width: CGFloat = visible.width * 0.75 + let height: CGFloat = visible.height * 0.75 + let originX: CGFloat = visible.minX + let originY: CGFloat = visible.minY + (visible.height - height) / 2 + win.setFrame(NSRect(x: originX, y: originY, width: width, height: height), display: true) win.makeKeyAndOrderFront(nil) self.window = win } diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift index 19a6e71..bc85cc4 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/LiveSession.swift @@ -40,6 +40,14 @@ public final class LiveSession: @unchecked Sendable { public let engine: SynthesisEngine + /// Output-tapping oscilloscope capture for the editor's scope view. When a + /// fresh tap is installed at init (the engine is not yet running and has no + /// tap), this is that capture; if the engine already had a `scopeTap`, this + /// reuses it; it is `nil` only when no tap is present (attachment declined, + /// or the engine was already running with no tap). Must be installed before + /// `start()`. + public let scope: ScopeCapture? + /// `-I` paths threaded to `swiftc` for module discovery. public let importPaths: [URL] @@ -64,9 +72,27 @@ public final class LiveSession: @unchecked Sendable { /// via `@testable import`; not part of the public API. internal var reportedSampleRate: Double? - /// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read - /// via `@testable import`; not part of the public API. - internal var lastSnippetMessage: String? + /// Most recent snippet `context.reportMessage(_:)` value (tests read this via + /// `@testable import`). Backed by the internal message log (`_messageLog`). + internal var lastSnippetMessage: String? { _messageLog.last } + + /// Accumulated `context.reportMessage(_:)` output (and host-side notices like + /// a dropped slot swap) since the last drain. Main-thread only — appended + /// during the synchronous snippet entry, drained by the host after each run. + private var _messageLog: [String] = [] + + /// Append a snippet/host message to the log. Main-thread only. + internal func appendMessage(_ message: String) { + _messageLog.append(message) + } + + /// Return and clear the accumulated messages. Called by the host after a run + /// to move them into its console. + public func drainMessages() -> [String] { + let out: [String] = _messageLog + _messageLog.removeAll() + return out + } // Tracked state — all access guarded by `trackingLock`. private let trackingLock: NSLock = NSLock() @@ -100,14 +126,31 @@ public final class LiveSession: @unchecked Sendable { private var _swapQuantize: SwapQuantize = .immediate private var _pendingSwapBeat: Double? + /// Samples per channel the scope captures per display frame. + private static let scopeBufferSize: Int = 1024 + + /// - Parameter attachScope: When `true` (default) and the engine is not yet + /// running and has no existing tap, install a ``ScopeCapture`` on the first + /// one or two output buses for the editor's scope view. public init( engine: SynthesisEngine, + attachScope: Bool = true, importPaths: [URL] = LiveSession.defaultImportPaths(), librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(), libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"], rpaths: [URL] = LiveSession.defaultRpaths() ) { self.engine = engine + // Install the scope tap before the host calls `start()` (the RT thread + // caches `scopeTap` at start; setting it afterwards is a no-op). + if attachScope, !engine.isRunning, engine.scopeTap == nil, engine.numOutputChannels >= 1 { + let buses: [Int] = Array(0.. Bool { + let entry: SlotEntry? + do { + trackingLock.lock(); defer { trackingLock.unlock() } + entry = slottedSynths[name] + } + guard let entry: SlotEntry = entry else { return false } + do { + try entry.synth.release(engine: engine) + // Released — free the name for reuse and keep the voice reachable by + // the tracked-synth sweep (its safety net until it self-frees). + trackingLock.lock(); defer { trackingLock.unlock() } + if slottedSynths[name]?.synth === entry.synth { + slottedSynths[name] = nil + trackedSynths.append(entry.synth) + } + return true + } catch { + appendMessage( + "slot '\(name)': release failed (\(error)) — use clearSlot() to stop it") + return false + } + } + /// Remove a slot occupant, scheduling the removal no earlier than the /// occupant's own add time (`max(desired, addTime)`) so a still-pending /// scheduled add is never orphaned. `desired` is the caller's intended @@ -474,8 +570,8 @@ public final class LiveSession: @unchecked Sendable { if let previous: SlotEntry = previous { let removed: Bool = removeSlotOccupant(previous, desired: time) if !removed { - lastSnippetMessage = - "slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap" + appendMessage( + "slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap") } } } diff --git a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift index a476c5a..d221bf7 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompile/SnippetContext.swift @@ -43,7 +43,7 @@ public final class SnippetContext { session.track(synth) return true } catch { - session.lastSnippetMessage = "engine.add failed: \(error)" + session.appendMessage("engine.add failed: \(error)") return false } } @@ -79,7 +79,7 @@ public final class SnippetContext { try session.swapSlot(name, synth: synth) return true } catch { - session.lastSnippetMessage = "play(slot: \"\(name)\") failed: \(error)" + session.appendMessage("play(slot: \"\(name)\") failed: \(error)") return false } } @@ -136,6 +136,41 @@ public final class SnippetContext { play(ClosureSynthesizer(bus: bus, make)) } + /// **Gracefully release** the voice in a named slot — trigger its envelope + /// release phase and let it tail out and free itself — then drop the slot. + /// + /// The live-coding "start a voice, let go of it later" gesture: name a slot + /// with ``play(slot:_:)``, then release it from a *separate* evaluation (e.g. + /// select the line and hit ⌘E): + /// + /// ```swift + /// context.play(slot: "pad") { EnvGen(gate: 1, ...) * OscSaw.Audio(freq: 110) } + /// // …later, in another evaluation: + /// context.release(slot: "pad") + /// ``` + /// + /// The released voice must free itself (an `EnvGen`/gate with a free-on-done + /// action) to leave the engine. For an immediate hard stop instead, use + /// ``free(slot:)``. + /// + /// - Parameter name: Slot to release. + /// - Returns: `true` if a gated voice was released; `false` if the slot was + /// empty or its occupant has no gate. + @discardableResult + @MainActor public func release(slot name: String) -> Bool { + session.releaseSlot(name) + } + + /// **Immediately** stop and remove the voice in a named slot — a hard cut, + /// no release tail. The counterpart to ``release(slot:)``. + /// + /// - Parameter name: Slot to free. + /// - Returns: `true` if a voice was removed; `false` if the slot was empty. + @discardableResult + @MainActor public func free(slot name: String) -> Bool { + session.clearSlot(name) + } + /// Snippet-side hook for test verification: report the engine's sample rate /// back through the session so tests can confirm the `context.engine` /// linkage compiled and called correctly. @@ -146,7 +181,7 @@ public final class SnippetContext { /// Snippet-side hook for test verification: record an arbitrary message /// back on the session. Lets tests confirm the snippet body executed. public func reportMessage(_ message: String) { - session.lastSnippetMessage = message + session.appendMessage(message) } } diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md index c7127c1..53d5407 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md @@ -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:) { }` — 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: diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift index 7ed55e4..752cd84 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift @@ -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() } diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift index c52d4bf..5d1b001 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift index c89787e..4e902e6 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift @@ -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) diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchConsoleEntry.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchConsoleEntry.swift new file mode 100644 index 0000000..fd456c2 --- /dev/null +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchConsoleEntry.swift @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchScopeView.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchScopeView.swift new file mode 100644 index 0000000..5df22da --- /dev/null +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/ScratchScopeView.swift @@ -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 diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift new file mode 100644 index 0000000..4c5dc25 --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/MessageLogTests.swift @@ -0,0 +1,43 @@ +// MessageLogTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Testing +import LyrebirdSynth +@testable import LyrebirdLiveCompile + +@MainActor +@Suite("LiveSession message log") +struct MessageLogTests { + + private func makeSession() -> LiveSession { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + return LiveSession(engine: engine) + } + + @Test func accumulatesAndDrains() { + let session: LiveSession = makeSession() + session.appendMessage("a") + session.appendMessage("b") + #expect(session.lastSnippetMessage == "b") // last value, for tests + #expect(session.drainMessages() == ["a", "b"]) + // Drained → empty. + #expect(session.lastSnippetMessage == nil) + #expect(session.drainMessages().isEmpty) + } +} + +#endif diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift new file mode 100644 index 0000000..00e46bc --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/ScopeAttachTests.swift @@ -0,0 +1,63 @@ +// ScopeAttachTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Testing +import LyrebirdSynth +@testable import LyrebirdLiveCompile + +@MainActor +@Suite("LiveSession scope attach") +struct ScopeAttachTests { + + private func makeEngine(outChannels: Int = 2) -> SynthesisEngine { + SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: outChannels, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + } + + @Test func attachesStereoScopeByDefault() { + let engine: SynthesisEngine = makeEngine(outChannels: 2) + let session: LiveSession = LiveSession(engine: engine) + let scope: ScopeCapture? = session.scope + #expect(scope != nil) + #expect(scope?.buses == [0, 1]) + // Installed on the engine so the RT thread writes to it. + #expect(engine.scopeTap === scope) + } + + @Test func attachScopeFalseInstallsNothing() { + let engine: SynthesisEngine = makeEngine() + let session: LiveSession = LiveSession(engine: engine, attachScope: false) + #expect(session.scope == nil) + #expect(engine.scopeTap == nil) + } + + @Test func monoEngineTapsOneBus() { + let engine: SynthesisEngine = makeEngine(outChannels: 1) + let session: LiveSession = LiveSession(engine: engine) + #expect(session.scope?.buses == [0]) + } + + @Test func reusesExistingTapRatherThanReplacing() { + let engine: SynthesisEngine = makeEngine() + let existing: ScopeCapture = ScopeCapture(buses: [0], bufferSize: 256) + engine.scopeTap = existing + let session: LiveSession = LiveSession(engine: engine) // attach on, but a tap exists + #expect(session.scope === existing) + #expect(engine.scopeTap === existing) + } +} + +#endif diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift new file mode 100644 index 0000000..5073bdd --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SlotReleaseTests.swift @@ -0,0 +1,94 @@ +// SlotReleaseTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Testing +import LyrebirdSynth +@testable import LyrebirdLiveCompile + +@MainActor +@Suite("LiveSession slot release") +struct SlotReleaseTests { + + /// A synth whose graceful `release` succeeds (records the call) — stands in + /// for a gated `EnvGen` voice. + private final class GatedSynth: SynthesizerBase, @unchecked Sendable { + var released: Bool = false + override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) } + override func release(engine: SynthesisEngine) throws { released = true } + } + + /// A synth with no gate — inherits the default `release` that throws `.noGate`. + private final class GatelessSynth: SynthesizerBase, @unchecked Sendable { + override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) } + } + + private func makeStartedSession() throws -> LiveSession { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + let session: LiveSession = LiveSession(engine: engine) + try engine.start() + return session + } + + @Test func releaseGatedSlotTriggersReleaseAndDropsHandle() throws { + let session: LiveSession = try makeStartedSession() + let voice: GatedSynth = GatedSynth() + try session.swapSlot("pad", synth: voice) + #expect(session.slotNames.contains("pad")) + + let released: Bool = session.releaseSlot("pad") + #expect(released) + #expect(voice.released) // graceful release fired + #expect(session.slotNames.contains("pad") == false) // handle dropped, name free + // Safety net: the released voice moves to the tracked list so it stays + // reclaimable by resetAll() / Clear Synths even if it never self-frees. + #expect(session.trackedSynthCount == 1) + session.resetAll() + #expect(session.trackedSynthCount == 0) + session.engine.stop() + } + + @Test func nameIsReusableAfterRelease() throws { + let session: LiveSession = try makeStartedSession() + try session.swapSlot("pad", synth: GatedSynth()) + #expect(session.releaseSlot("pad")) + // The name is free again — a fresh voice claims the slot cleanly. + try session.swapSlot("pad", synth: GatedSynth()) + #expect(session.slotNames.contains("pad")) + #expect(session.slotCount == 1) + session.engine.stop() + } + + @Test func releaseGatelessSlotFailsAndKeepsHandle() throws { + let session: LiveSession = try makeStartedSession() + try session.swapSlot("bass", synth: GatelessSynth()) + + let released: Bool = session.releaseSlot("bass") + #expect(released == false) + // Not orphaned — still in the slot, still stoppable with a hard clear. + #expect(session.slotNames.contains("bass")) + #expect(session.clearSlot("bass")) + session.engine.stop() + } + + @Test func releaseEmptySlotReturnsFalse() throws { + let session: LiveSession = try makeStartedSession() + #expect(session.releaseSlot("nothing-here") == false) + session.engine.stop() + } +} + +#endif diff --git a/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift new file mode 100644 index 0000000..b0def14 --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileTests/SnippetScheduledLoopTests.swift @@ -0,0 +1,76 @@ +// SnippetScheduledLoopTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Testing +import LyrebirdSynth +@testable import LyrebirdLiveCompile + +/// Proves the scratch editor runs *functional* Swift — a real `for` loop that +/// schedules a timed sequence — not just single-graph expressions. +@MainActor +@Suite("Snippet scheduled loop") +struct SnippetScheduledLoopTests { + + @Test func loopSchedulesTenSelfFreeingTones() throws { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 512, + controlBlockSize: 64, + sampleRate: 44_100, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + let session: LiveSession = LiveSession(engine: engine) + try engine.start() + + // A `for` loop that schedules ten short sine tones, 0.35 s apart. Each is + // a decaying amplitude envelope (`Line` with `doneAction: .freeNode`) + // times a sine, so it plays ~0.2 s and then frees itself — no manual + // cleanup, no blocking the main thread. + let snippet: String = """ + 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 failed: \\(error)") } + } + context.reportMessage("scheduled 10 tones") + """ + + try session.compileAndRun(snippet) + // The `for` loop and the scheduling calls compiled and ran. + #expect(session.lastSnippetMessage == "scheduled 10 tones") + + // Advance ~4.5 s of audio; the scheduled adds fire over time. (Each + // tone's `.freeNode` self-frees via the engine's async auto-free watcher + // in the running app — that background timer doesn't get a turn inside + // this synchronous processBlock loop, so here the tones accumulate; the + // auto-free path itself is covered by `AutoFreeOnDoneTests`.) + let blocks: Int = Int(4.5 * 44_100 / 512) + var peakActive: Int = 0 + var producedAudio: Bool = false + for _ in 0.. LyrebirdScratchModel { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text) + } + + @Test func successfulRunLogsInfo() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) + #expect(model.consoleEntries.contains { $0.kind == .info }) + } + + @Test func failedRunLogsErrorEntries() async { + let model: LyrebirdScratchModel = makeModel(text: "NotAGenerator(freq: 1)") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) + #expect(model.consoleEntries.contains { $0.kind == .error }) + #expect(model.consoleEntries.contains { $0.text.contains("NotAGenerator") }) + } + + @Test func reportMessagesAppearAsMessages() async { + // A DSL run pushes no messages; drive the log directly to prove the + // message → console wiring (drainMessages → .message entries). + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + model.session.appendMessage("hello from snippet") + _ = await model.run(additive: false) + #expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello from snippet" }) + } + + @Test func clearConsoleEmpties() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) + #expect(!model.consoleEntries.isEmpty) + model.clearConsole() + #expect(model.consoleEntries.isEmpty) + } + + @Test func resetSessionClearsConsole() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) + #expect(!model.consoleEntries.isEmpty) + model.resetSession() + #expect(model.consoleEntries.isEmpty) + } +} + +#endif diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelResetTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelResetTests.swift new file mode 100644 index 0000000..7dcc726 --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelResetTests.swift @@ -0,0 +1,58 @@ +// ScratchModelResetTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Testing +import LyrebirdSynth +@testable import LyrebirdLiveCompile +@testable import LyrebirdLiveCompileUI + +@Suite("LyrebirdScratchModel resetSession") +@MainActor +struct ScratchModelResetTests { + + private func makeModel(text: String) -> LyrebirdScratchModel { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text) + } + + @Test func resetStopsAudioAndClearsDiagnosticsButKeepsBuffer() async { + let source: String = "OscSin(freq: 440) * 0.1" + let model: LyrebirdScratchModel = makeModel(text: source) + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) // tracked 1 + #expect(model.trackedSynthCount == 1) + + model.resetSession() + + #expect(model.trackedSynthCount == 0) // audio stopped + #expect(model.diagnostics.isEmpty) + // Non-destructive: the user's buffer is preserved. + #expect(model.text == source) + #expect(model.statusMessage.contains("reset")) + } + + @Test func resetLeavesAFreshDirtyBaseline() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) // .clean + model.resetSession() + // The placeholder buffer was never run in this fresh session → .dirty. + #expect(model.reevalState == .dirty) + } +} + +#endif diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRunSelectionTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRunSelectionTests.swift new file mode 100644 index 0000000..8cf9b5c --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRunSelectionTests.swift @@ -0,0 +1,104 @@ +// ScratchModelRunSelectionTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +#if os(macOS) +import Testing +import LyrebirdSynth +@testable import LyrebirdLiveCompile +@testable import LyrebirdLiveCompileUI + +@Suite("LyrebirdScratchModel run selection") +@MainActor +struct ScratchModelRunSelectionTests { + + private func makeModel(text: String) -> LyrebirdScratchModel { + let engine: SynthesisEngine = SynthesisEngine( + blockSize: 64, + controlBlockSize: 16, + sampleRate: 48_000, + numOutputChannels: 2, + numInputChannels: 0, + numAudioBuses: 16, + numControlBuses: 16, + eventQueueCapacity: lyrebirdDefaultEventQueueCapacity, + driver: OfflineDriver() + ) + return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text) + } + + @Test func hasSelectionReflectsNonWhitespaceSelection() { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + #expect(model.hasSelection == false) + model.updateSelection("OscSin(freq: 220) * 0.1") + #expect(model.hasSelection) + model.updateSelection(" \n ") // whitespace only + #expect(model.hasSelection == false) + model.updateSelection("") + #expect(model.hasSelection == false) + } + + @Test func runSelectionWithNoSelectionIsNoOp() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + let ok: Bool = await model.runSelection() + #expect(ok == false) + #expect(model.trackedSynthCount == 0) + } + + @Test func runSelectionAddsToRunningWithoutDisturbingBaseline() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + + // Whole-buffer run establishes the baseline → clean, one synth. + _ = await model.run(additive: false) + #expect(model.reevalState == .clean) + #expect(model.trackedSynthCount == 1) + + // Run a selected fragment: additive (adds a second synth) and leaves the + // whole-buffer baseline intact (buffer still matches the last whole run). + model.updateSelection("OscSin(freq: 220) * 0.1") + let ok: Bool = await model.runSelection() + #expect(ok) + #expect(model.trackedSynthCount == 2) + #expect(model.reevalState == .clean) // baseline untouched + #expect(model.diagnostics.isEmpty) + } + + @Test func selectionRunAddsEvenFromADirtyBuffer() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) // tracked 1, .clean + // Dirty the buffer (edited since the last whole run). + model.text = "OscSin(freq: 440) * 0.1\n# edited" + #expect(model.reevalState == .dirty) + + model.updateSelection("OscSin(freq: 330) * 0.1") + _ = await model.runSelection() // additive → tracked 2 + model.updateSelection("OscSin(freq: 110) * 0.1") + _ = await model.runSelection() // additive → tracked 3 + #expect(model.trackedSynthCount == 3) + // The selection runs never replaced, and the buffer stays dirty. + #expect(model.reevalState == .dirty) + } + + @Test func failedSelectionRunLeavesWholeBufferBadgeUntouched() async { + let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1") + model.switchMode(to: .graphDSL) + _ = await model.run(additive: false) // .clean + #expect(model.reevalState == .clean) + + // A selection with an unknown generator fails to build. + model.updateSelection("NotAGenerator(freq: 1)") + let ok: Bool = await model.runSelection() + #expect(ok == false) + #expect(!model.diagnostics.isEmpty) + // The whole-buffer badge must stay clean — the buffer itself is fine. + #expect(model.reevalState == .clean) + #expect(model.statusMessage.hasPrefix("Selection")) + } +} + +#endif diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchTextViewTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchTextViewTests.swift index b6345c5..cdd4d46 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchTextViewTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchTextViewTests.swift @@ -38,14 +38,49 @@ struct ScratchTextViewTests { #expect(range == NSRange(location: text.utf16.count, length: 0)) } - /// Mid-identifier (no preceding dot) falls through to the default behavior, - /// which covers the whole partial word so it gets replaced on completion. - @Test func partialIdentifierUsesDefaultWordRange() { + /// Mid-identifier (no preceding dot): the range covers the run of identifier + /// characters before the caret, so the partial word gets replaced. + @Test func partialIdentifierCoversWordRange() { let tv: ScratchTextView = makeTextView("OscSi", caret: 5) let range: NSRange = tv.rangeForUserCompletion - // Default range spans the partial word `OscSi` (length 5 from offset 0). #expect(range == NSRange(location: 0, length: 5)) } + + /// Right after an open paren, the range is EMPTY at the caret — an argument + /// label (`freq:`) inserts there instead of replacing the receiver + /// (`OscSin.Audio(` → erases `OscSin.Audio` bug). + @Test func afterOpenParenRangeIsEmptyAtCaret() { + let text: String = "OscSin.Audio(" + let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count) + let range: NSRange = tv.rangeForUserCompletion + #expect(range == NSRange(location: text.utf16.count, length: 0)) + } + + /// After a comma + space (next argument position), the range is empty too. + @Test func afterCommaSpaceRangeIsEmptyAtCaret() { + let text: String = "OscSin.Audio(freq: 440, " + let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count) + let range: NSRange = tv.rangeForUserCompletion + #expect(range == NSRange(location: text.utf16.count, length: 0)) + } + + /// A partial argument label inside parens replaces just that partial word, + /// not the receiver expression. + @Test func partialArgLabelCoversOnlyThePartial() { + let text: String = "OscSin.Audio(fr" + let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count) + let range: NSRange = tv.rangeForUserCompletion + // `fr` starts at offset 13 (after `OscSin.Audio(`), length 2. + #expect(range == NSRange(location: 13, length: 2)) + } + + /// Underscore is an identifier character, so a leading-underscore partial is + /// covered whole. + @Test func underscoreIsIdentifierChar() { + let tv: ScratchTextView = makeTextView("_foo", caret: 4) + let range: NSRange = tv.rangeForUserCompletion + #expect(range == NSRange(location: 0, length: 4)) + } } #endif diff --git a/RELEASES.md b/RELEASES.md index 725b828..85350b8 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,85 @@ functionality in a backward-compatible way. --- +## 1.4.2 — Live-coding: Run Selection + graceful slot release + +A minor release. Backward-compatible — additive conveniences to the (macOS-only) +live-coding editor that make per-fragment evaluation and voice lifecycle feel +like a proper live-coding environment. No changes to existing public API. + +### New — Run Selection (⌘E) + +Evaluate just the **highlighted text** and *add* it to whatever is already +playing — always additively, never a replace. It leaves the rest of the buffer +and the whole-buffer re-evaluation baseline (the clean/dirty badge still reflects +your last full run) untouched. This is the live-coding "evaluate this line/region, +keep going" gesture: audition a single voice, layer it in, iterate. Works in both +Swift and Graph DSL modes; no-op with no selection. ⌘↩ / ⌘⇧↩ (whole buffer) are +unchanged. + +### New — Start a voice, release it later (`context.release(slot:)`) + +Named slots are the persistent **handle** across evaluations — the slot *name* is +your reference (Swift `let`/`var` bindings can't carry from one snippet to the +next, since each ⌘↩/⌘E is a separately-compiled unit). Pair that with Run +Selection to start a voice in one evaluation and let it go in another: + +```swift +// ⌘E this line — start a persistent, gated voice named "pad": +context.play(slot: "pad") { EnvGen(gate: 1, /* free-on-done */) * OscSaw.Audio(freq: 110) } + +// …later, ⌘E this line — graceful release: the envelope tails out, then frees: +context.release(slot: "pad") +``` + +- `context.release(slot:)` triggers the voice's envelope **release** phase and + frees the name; the voice self-frees via its done-action (and, as a safety net, + stays reclaimable by **Clear Synths** if it never does). +- `context.free(slot:)` is the **immediate** hard stop — the counterpart, no tail. + +### New — Engine panel (scope + status) + +A panel at the bottom of the scratch window gives an always-on view of the +running engine: a live dual-channel **oscilloscope** of the output (fed by a +`ScopeCapture` the session attaches to the output buses), plus **CPU +average/peak** meter bars and **synth / group / snippet** counts. + +### New — Reset Session + Restart to Reclaim Memory + +Two Run-menu commands for the by-design snippet-dylib cost: + +- **Reset Session** — an in-process, *non-destructive* reset: stops all snippet + audio, shuts down the code-completion server (freeing its subprocess and temp + files), and clears diagnostics. Your buffer is untouched. +- **Restart to Reclaim Memory…** — relaunches the app (with a confirmation), the + only way to actually free the mapped snippet dylibs, which cannot be unloaded + in-process. + +### New — Console panel + +An always-open panel down the right side logs everything: snippet +`context.reportMessage(_:)` output (the live-coding `print`), compile / Graph DSL +**errors** with their `line:col`, and a one-line notice per run — oldest first, +auto-scrolled, with a **Clear** button. Errors moved here from the old transient +bottom strip so they stay visible while you fix them. + +### Faster typing + +Cut the per-keystroke cost in the editor: syntax highlighting is debounced +(coalesced after a brief pause instead of a full-buffer re-tokenize on every +key), `updateNSView` fast-paths a pure text change, and redundant `@Published` +republishes (selection, re-eval state) are elided. + +### Changed — code completion is now manual (Esc / F5) + +Completion no longer auto-opens on `.`. The auto-trigger ambushed typing — after +`Pan2.` the popup opened and couldn't be dismissed by deleting, trapping the +caret until a candidate was picked. Invoke completion deliberately with **Esc** +(or **F5**); a member request after a dot still resolves. Wider default scratch +window too (75% of the visible screen width). + +--- + ## 1.4.1 — "Learning Swift for Lyrebird" intro guide A documentation-only release, continuing the doc improvements begun in 1.3. No diff --git a/claude/skills/lyrebird_release_prep/prepare_release.sh b/claude/skills/lyrebird_release_prep/prepare_release.sh index 22b8fac..9d23dff 100755 --- a/claude/skills/lyrebird_release_prep/prepare_release.sh +++ b/claude/skills/lyrebird_release_prep/prepare_release.sh @@ -30,6 +30,9 @@ ALLOW_DIRTY=0 EXCLUSIONS=( "legacy" "PLAN.md" + "DOC_UPDATE_PLAN.md" + "docs/00-working-order.md" + "docs/01-completed-working-order.md" ".claude" ".githooks" ".swiftpm" diff --git a/claude/skills/lyrebird_release_prep/skill.md b/claude/skills/lyrebird_release_prep/skill.md index b10b36c..12f7e68 100644 --- a/claude/skills/lyrebird_release_prep/skill.md +++ b/claude/skills/lyrebird_release_prep/skill.md @@ -23,6 +23,9 @@ Then it strips the maintainer-only paths that are tracked in dev but must **not* |---|---| | `legacy/` | old pre-modernization reference code | | `PLAN.md` | private planning doc | +| `DOC_UPDATE_PLAN.md` | private planning doc | +| `docs/00-working-order.md` | maintainer phase-planning doc (what to build next) | +| `docs/01-completed-working-order.md` | maintainer phase-planning doc (completed phases) | | `.claude/` | agent working-copy mirror (release ships `claude/` installer source only) | | `.githooks/` | dev-only pre-commit hooks | | `.swiftpm/` | local Xcode package state | @@ -31,8 +34,9 @@ The sync uses `rsync -a -c --delete` (checksum-based, so only real content diffe transfer; `--delete` clears stale files + Finder cruft on the release side). A moo-URL guard on the release remote prevents `--apply` from ever touching the wrong directory. -`docs/` (including `00-working-order.md` / `01-completed-working-order.md`) **does** ship — -only top-level `PLAN.md` is excluded from the planning material. +Most of `docs/` ships. The two phase-planning docs (`docs/00-working-order.md`, +`docs/01-completed-working-order.md`) are **excluded** — they're maintainer-internal and +mean nothing to consumers — along with the top-level `PLAN.md` / `DOC_UPDATE_PLAN.md`. ## Steps