8eb64f883f
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
724 lines
33 KiB
Swift
724 lines
33 KiB
Swift
// LyrebirdScratchModel.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdUI/LiveCompile
|
|
//
|
|
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
|
|
// most recent compile result, and the host `LiveSession`. Pulled out of the
|
|
// view so logic can be exercised without instantiating SwiftUI.
|
|
//
|
|
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
|
|
|
|
#if os(macOS)
|
|
import Foundation
|
|
import CoreGraphics
|
|
import LyrebirdSynth
|
|
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
|
// (e.g. the LyrebirdScratch app) get the `LyrebirdLiveCompile` API
|
|
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
|
// dynamic product — which clashes in Xcode with the static target embed.
|
|
@_exported import LyrebirdLiveCompile
|
|
|
|
/// Observable backing model for `LyrebirdScratchView`.
|
|
///
|
|
/// Drives one live-coding editor pane. `run(additive:)` awaits
|
|
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
|
|
/// actor and the editor stays responsive. ``isCompiling`` flips around the
|
|
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
|
|
/// status while the dylib build is in flight.
|
|
@MainActor
|
|
public final class LyrebirdScratchModel: ObservableObject {
|
|
|
|
/// Default placeholder text loaded into a fresh model. Walks the user
|
|
/// through the two keyboard shortcuts and the in-snippet API surface.
|
|
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
|
|
/// default-argument evaluation, which is not implicitly main-actor) can
|
|
/// reference it without a Swift 6 isolation diagnostic.
|
|
public nonisolated static let defaultPlaceholder: String = """
|
|
// ⌘↩ — compile + run (removes synths from the previous run first).
|
|
// ⌘⇧↩ — additive run (keep previously played synths around).
|
|
//
|
|
// The snippet body has `context: SnippetContext` in scope.
|
|
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
|
|
// `context.play(synth)` → add a `Synthesizer` you declared.
|
|
// `context.engine` → the host `SynthesisEngine`.
|
|
// `context.reportMessage(_)` → write back to the host (`print`-style probes).
|
|
|
|
context.play { Pan2(input: OscSin.Audio(freq: 440, mul: 0.15), pan: 0) }
|
|
context.reportMessage("playing 440 Hz sine — stereo, centered")
|
|
|
|
"""
|
|
|
|
/// Placeholder for the interpreted graph-DSL mode. Shows the instant path:
|
|
/// no `context`, no subclass — just generator-graph expressions, one per
|
|
/// line, spelled exactly as they would be in a Lyrebird `build()`.
|
|
public nonisolated static let graphDSLPlaceholder: String = """
|
|
# Graph DSL — instant, no compile. One graph expression per line.
|
|
# A bare line plays anonymously; `name = …` plays a named, hot-swappable slot.
|
|
# Generators are spelled exactly as in Swift: OscSin.Audio(freq: 440) * 0.1
|
|
|
|
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
|
|
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
|
|
|
|
"""
|
|
|
|
/// The seed text for a given evaluation mode.
|
|
public nonisolated static func defaultPlaceholder(for mode: ScratchEvalMode) -> String {
|
|
switch mode {
|
|
case .swift: return defaultPlaceholder
|
|
case .graphDSL: return graphDSLPlaceholder
|
|
}
|
|
}
|
|
|
|
/// Current editor text. View binds to this; user edits flow back here via
|
|
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
|
|
///
|
|
/// Edits recompute ``reevalState`` (unless a compile is in flight, which
|
|
/// owns the state until it resolves).
|
|
@Published public var text: String {
|
|
didSet { recomputeReevalStateAfterEdit() }
|
|
}
|
|
|
|
/// Structured re-evaluation readiness signal. See ``ReevalState``. The view
|
|
/// binds a status badge to this and gates the Run controls on
|
|
/// ``ReevalState/canEvaluate``.
|
|
@Published public private(set) var reevalState: ReevalState
|
|
|
|
/// Text of the most recent *successful* run. `nil` before the first
|
|
/// successful run. Compared against ``text`` to decide `.clean` vs `.dirty`.
|
|
private var lastEvaluatedText: String?
|
|
|
|
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
|
|
/// Empty when the last run compiled cleanly or has not yet been attempted.
|
|
@Published public private(set) var diagnostics: [Diagnostic] = []
|
|
|
|
/// Single-line human-readable status line shown beneath the editor.
|
|
/// 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
|
|
|
|
/// Mirror of `session.loadedSnippetCount` — compiled snippet dylibs mapped
|
|
/// into the process this session. Each successful **Swift-mode** run maps
|
|
/// one; they are never unloaded (`dlclose` is unsafe for Swift dylibs — see
|
|
/// ``LiveSession/resetAll()``), so this only grows until a process restart.
|
|
/// Graph-DSL runs add nothing. Refreshed alongside ``trackedSynthCount``.
|
|
@Published public private(set) var loadedSnippetCount: Int
|
|
|
|
/// Count of mapped snippet dylibs past which the editor nudges the user to
|
|
/// restart (or switch to the leak-free Graph DSL mode).
|
|
public nonisolated static let snippetRestartThreshold: Int = 50
|
|
|
|
/// A restart suggestion once ``loadedSnippetCount`` reaches
|
|
/// ``snippetRestartThreshold``, else `nil`. The mapped dylibs cannot be
|
|
/// reclaimed without a process restart (by design), so this is the
|
|
/// user-facing safety valve over that leak.
|
|
public var snippetMemoryHint: String? {
|
|
LyrebirdScratchModel.snippetMemoryHint(count: loadedSnippetCount)
|
|
}
|
|
|
|
/// Pure form of ``snippetMemoryHint`` — the message for `count` mapped
|
|
/// snippets, or `nil` below `threshold`. Factored out so the boundary is
|
|
/// unit-testable without running dozens of real compiles.
|
|
nonisolated static func snippetMemoryHint(
|
|
count: Int,
|
|
threshold: Int = LyrebirdScratchModel.snippetRestartThreshold
|
|
) -> String? {
|
|
guard count >= threshold else { return nil }
|
|
return "\(count) compiled snippets are mapped and can't be freed without "
|
|
+ "restarting. Restart to reclaim memory, or use Graph DSL mode (no compile, no leak)."
|
|
}
|
|
|
|
/// `true` while a `run(additive:)` invocation is awaiting the background
|
|
/// swiftc compile. View code disables Run / Run Additive buttons against
|
|
/// this so a second compile cannot stack on top of a still-running one.
|
|
@Published public private(set) var isCompiling: Bool = false
|
|
|
|
/// URL of the file the editor text was last saved to or loaded from. `nil`
|
|
/// when the editor holds unsaved scratch content. The view uses this to
|
|
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
|
|
@Published public private(set) var documentURL: URL?
|
|
|
|
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
|
|
@Published public var fontSize: CGFloat = 13
|
|
|
|
/// When `true`, lines wrap at the editor's right edge instead of scrolling
|
|
/// 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
|
|
/// with the mode. See ``ScratchEvalMode``.
|
|
@Published public private(set) var evalMode: ScratchEvalMode = .swift
|
|
|
|
public let session: LiveSession
|
|
|
|
/// Lazily-created code-completion service (Swift mode only). Spun up on the
|
|
/// first completion request so a session that never triggers completion
|
|
/// never launches `sourcekit-lsp`.
|
|
private var _completion: SnippetCompletionService?
|
|
|
|
/// Fetch Swift code-completion candidates for the current buffer at a
|
|
/// zero-based user-space `line` / `character` (UTF-16). Returns `[]` in
|
|
/// graph-DSL mode (the interpreter needs no LSP) or on any LSP failure —
|
|
/// completion is best-effort and never surfaces an error to the editor.
|
|
public func completionItems(line: Int, character: Int) async -> [LSPCompletionItem] {
|
|
guard evalMode == .swift else { return [] }
|
|
let service: SnippetCompletionService
|
|
if let existing: SnippetCompletionService = _completion {
|
|
service = existing
|
|
} else {
|
|
service = SnippetCompletionService(session: session)
|
|
_completion = service
|
|
}
|
|
do {
|
|
return try await service.completions(userBody: text, line: line, character: character)
|
|
} catch {
|
|
return []
|
|
}
|
|
}
|
|
|
|
public nonisolated static let minFontSize: CGFloat = 9
|
|
public nonisolated static let maxFontSize: CGFloat = 32
|
|
public nonisolated static let defaultFontSize: CGFloat = 13
|
|
|
|
public func bumpFontSize(by delta: CGFloat) {
|
|
fontSize = max(LyrebirdScratchModel.minFontSize,
|
|
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
|
|
}
|
|
|
|
public func resetFontSize() {
|
|
fontSize = LyrebirdScratchModel.defaultFontSize
|
|
}
|
|
|
|
public func toggleWrapsLines() {
|
|
wrapsLines.toggle()
|
|
}
|
|
|
|
/// - Parameters:
|
|
/// - session: Host `LiveSession` the model forwards compile + cleanup
|
|
/// calls to. Retained for the model's lifetime.
|
|
/// - initialText: Seed text loaded into `text`. Defaults to
|
|
/// ``defaultPlaceholder``.
|
|
public init(
|
|
session: LiveSession,
|
|
initialText: String = LyrebirdScratchModel.defaultPlaceholder
|
|
) {
|
|
self.session = session
|
|
self.text = initialText
|
|
self.trackedSynthCount = session.trackedSynthCount
|
|
self.loadedSnippetCount = session.loadedSnippetCount
|
|
// No run yet: blank buffer is `.empty`, otherwise `.dirty` (runnable,
|
|
// never evaluated). `lastEvaluatedText` stays nil until a run succeeds.
|
|
self.reevalState = LyrebirdScratchModel.isBlank(initialText) ? .empty : .dirty
|
|
}
|
|
|
|
/// Whether `text` is empty once whitespace and newlines are stripped.
|
|
private nonisolated static func isBlank(_ text: String) -> Bool {
|
|
text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
|
}
|
|
|
|
/// Recompute ``reevalState`` from the current buffer after a user edit.
|
|
/// A no-op while a compile is in flight — the run owns the state until it
|
|
/// resolves (edits made mid-compile are re-evaluated once it finishes).
|
|
private func recomputeReevalStateAfterEdit() {
|
|
guard !isCompiling else { return }
|
|
// 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.
|
|
/// Called on the editor's heartbeat (the view's refresh timer): when the
|
|
/// session no longer reports a pending swap, drop back to the idle state
|
|
/// (`.clean`, or `.dirty` if the buffer was edited while queued). No-op
|
|
/// unless the current state is `.queued`.
|
|
public func refreshQueuedState() {
|
|
guard case .queued = reevalState else { return }
|
|
if session.pendingSwapBeat == nil {
|
|
reevalState = derivedIdleState()
|
|
}
|
|
}
|
|
|
|
/// The readiness state implied by the current buffer when no compile is in
|
|
/// flight: `.empty` for a blank buffer, `.clean` when it matches the last
|
|
/// successful run, `.dirty` otherwise.
|
|
private func derivedIdleState() -> ReevalState {
|
|
if LyrebirdScratchModel.isBlank(text) { return .empty }
|
|
if let last: String = lastEvaluatedText, last == text { return .clean }
|
|
return .dirty
|
|
}
|
|
|
|
/// Compile and execute the current `text`. Updates `diagnostics`,
|
|
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
|
|
///
|
|
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
|
|
/// `Task.detached`. The view's Run / Run Additive buttons bind to
|
|
/// ``isCompiling`` and stay disabled until this method returns.
|
|
///
|
|
/// - Parameter additive: When `false`, the session removes every
|
|
/// previously tracked synth before running. When `true`, prior synths
|
|
/// stay in the engine (⌘⇧↩ in the view).
|
|
/// - Returns: `true` when the snippet compiled and its entry returned
|
|
/// without throwing; `false` otherwise.
|
|
@discardableResult
|
|
public func run(additive: Bool) async -> Bool {
|
|
switch evalMode {
|
|
case .swift: return await runSwiftSnippet(body: text, additive: additive, recordBaseline: true)
|
|
case .graphDSL: return runGraphDSLBuffer(body: text, additive: additive, recordBaseline: true)
|
|
}
|
|
}
|
|
|
|
/// 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 }
|
|
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)
|
|
statusMessage = "Ran \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
|
settleReeval(body: body, recordBaseline: recordBaseline)
|
|
runSucceeded = true
|
|
return true
|
|
} catch let sessionError as LiveSessionError {
|
|
switch sessionError {
|
|
case .snippetCompileFailed(let diags, let underlying):
|
|
if diags.isEmpty {
|
|
diagnostics = [Diagnostic(
|
|
line: nil,
|
|
column: 0,
|
|
severity: .error,
|
|
message: "\(underlying)",
|
|
rawLine: 0
|
|
)]
|
|
statusMessage = "Compile failed — see console."
|
|
} else {
|
|
diagnostics = diags
|
|
let plural: String = diags.count == 1 ? "" : "s"
|
|
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
|
|
}
|
|
case .compilerError(let underlying):
|
|
statusMessage = "Compiler error: \(underlying)"
|
|
case .graphDSLFailed(let diags, _):
|
|
// Not expected on the Swift path, but map it faithfully.
|
|
diagnostics = diags
|
|
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
|
|
}
|
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
|
return false
|
|
} catch {
|
|
statusMessage = "Error: \(error)"
|
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
|
return false
|
|
}
|
|
}
|
|
|
|
/// 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(body: String, additive: Bool, recordBaseline: Bool) -> Bool {
|
|
guard !isCompiling else { return false }
|
|
diagnostics = []
|
|
var runSucceeded: Bool = false
|
|
defer {
|
|
trackedSynthCount = session.trackedSynthCount
|
|
loadedSnippetCount = session.loadedSnippetCount
|
|
recordRunConsole(succeeded: runSucceeded)
|
|
}
|
|
do {
|
|
try session.runGraphDSL(body, additive: additive)
|
|
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 {
|
|
diagnostics = diags
|
|
let plural: String = diags.count == 1 ? "" : "s"
|
|
statusMessage = "DSL error — \(diags.count) diagnostic\(plural)."
|
|
} else {
|
|
statusMessage = "Error: \(sessionError)"
|
|
}
|
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
|
return false
|
|
} catch {
|
|
statusMessage = "Error: \(error)"
|
|
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
|
return false
|
|
}
|
|
}
|
|
|
|
/// 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)
|
|
} else {
|
|
reevalState = idle
|
|
}
|
|
}
|
|
|
|
/// 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.
|
|
///
|
|
/// The new mode's evaluator has not run whatever is on screen, so the last-run
|
|
/// baseline is dropped (the buffer reads as `.dirty`) and any diagnostics from
|
|
/// a prior run in the old mode are cleared — leaving them would show gutter
|
|
/// markers against a buffer the current mode never evaluated.
|
|
public func switchMode(to mode: ScratchEvalMode) {
|
|
guard mode != evalMode else { return }
|
|
if text == LyrebirdScratchModel.defaultPlaceholder(for: evalMode) {
|
|
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
|
|
}
|
|
lastEvaluatedText = nil
|
|
diagnostics = []
|
|
evalMode = mode
|
|
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`.
|
|
/// Pretty-print the buffer with `swift-format` (off the main thread),
|
|
/// replacing the text on success. Logs the outcome to the console; on a
|
|
/// parse error or missing toolchain the buffer is left untouched.
|
|
public func formatBuffer() async {
|
|
guard !isCompiling else { return }
|
|
let source: String = text
|
|
guard !LyrebirdScratchModel.isBlank(source) else { return }
|
|
// Hold the busy flag across the subprocess round-trip so a second Format
|
|
// (or a Run) can't overlap, and re-check the buffer before applying: the
|
|
// user may keep typing while `swift-format` runs, and a result computed
|
|
// from the now-stale `source` must not clobber those edits. `reevalState`
|
|
// goes `.compiling` too so the Run/Render menu items (validated on
|
|
// `reevalState.canEvaluate`) actually disable during the format.
|
|
isCompiling = true
|
|
reevalState = .compiling
|
|
defer {
|
|
isCompiling = false
|
|
reevalState = derivedIdleState()
|
|
}
|
|
do {
|
|
let formatted: String = try await Task.detached(priority: .userInitiated) {
|
|
try SwiftFormatter.format(source: source)
|
|
}.value
|
|
guard text == source else {
|
|
appendConsole(.error, "Buffer changed during formatting — result discarded.")
|
|
return
|
|
}
|
|
if formatted != source {
|
|
text = formatted
|
|
}
|
|
appendConsole(.info, "Formatted.")
|
|
} catch {
|
|
appendConsole(.error, "Format failed: \(error)")
|
|
}
|
|
}
|
|
|
|
/// Render the current selection (or the whole buffer when nothing is
|
|
/// selected) to an audio file, offline. Builds the snippet graph on a
|
|
/// throwaway engine driven by an `NRTDriver` — matching the live engine's
|
|
/// sample rate / channel count / bus layout — then renders `duration`
|
|
/// seconds off the main thread (`NRTDriver.start()` blocks). Logs the
|
|
/// outcome to the console.
|
|
///
|
|
/// - Parameters:
|
|
/// - url: Destination file. Its extension should match `format`.
|
|
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to
|
|
/// `.cafFloat32`. RF64/CAF are uncapped; plain WAV/AIFF throw past 4 GB.
|
|
/// - duration: Render length in seconds. Must be finite and > 0.
|
|
/// - Returns: `true` when the file was rendered (so the caller can reveal it).
|
|
@discardableResult
|
|
public func renderToFile(
|
|
url: URL,
|
|
format: AudioFileFormat = .cafFloat32,
|
|
duration: Double
|
|
) async -> Bool {
|
|
guard !isCompiling else { return false }
|
|
guard duration > 0, duration.isFinite else {
|
|
appendConsole(.error, "Render duration must be a positive number of seconds.")
|
|
return false
|
|
}
|
|
let code: String = hasSelection ? selectionText : text
|
|
guard !LyrebirdScratchModel.isBlank(code) else {
|
|
appendConsole(.error, "Nothing to render.")
|
|
return false
|
|
}
|
|
// Gate the Run/Render menu items (validated on `reevalState.canEvaluate`)
|
|
// and any re-entrancy for the render's duration.
|
|
isCompiling = true
|
|
reevalState = .compiling
|
|
defer {
|
|
isCompiling = false
|
|
reevalState = derivedIdleState()
|
|
}
|
|
|
|
let live: SynthesisEngine = session.engine
|
|
let offline: SynthesisEngine = SynthesisEngine(
|
|
blockSize: live.blockSize,
|
|
controlBlockSize: live.controlBlockSize,
|
|
sampleRate: live.sampleRate,
|
|
numOutputChannels: live.numOutputChannels,
|
|
numInputChannels: 0,
|
|
numAudioBuses: live.numAudioBuses,
|
|
numControlBuses: live.numControlBuses,
|
|
driver: NRTDriver(outputURL: url, duration: duration, format: format)
|
|
)
|
|
let offlineSession: LiveSession = LiveSession(engine: offline, attachScope: false)
|
|
do {
|
|
// Build the graph on the offline engine (compile off-main, add on main).
|
|
try await offlineSession.compileAndRunAsync(code, additive: true)
|
|
// Render synchronously, off the main thread; NRTDriver writes the CAF.
|
|
// `stop()` runs inside the detached task (where `offline` lives): the
|
|
// driver returns with the engine still `isRunning`, and only `stop()`
|
|
// drains the node tree — without it every rendered graph leaks
|
|
// (matches EngineHost's NRT job teardown). Keeping it here also avoids
|
|
// a cross-actor use of the non-Sendable engine after the detached run.
|
|
try await Task.detached(priority: .userInitiated) {
|
|
defer { offline.stop() }
|
|
try offline.start()
|
|
}.value
|
|
appendConsole(.info, "Rendered \(String(format: "%.2f", duration)) s → \(url.lastPathComponent)")
|
|
return true
|
|
} catch {
|
|
appendConsole(.error, "Render failed: \(error)")
|
|
return false
|
|
}
|
|
}
|
|
|
|
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
|
|
/// see the state and recover from a failed start without relaunching.
|
|
public func toggleEngine() {
|
|
let engine: SynthesisEngine = session.engine
|
|
if engine.isRunning {
|
|
engine.stop()
|
|
statusMessage = "Engine stopped."
|
|
} else {
|
|
do {
|
|
try engine.start()
|
|
statusMessage = "Engine started."
|
|
} catch {
|
|
statusMessage = "Engine failed to start: \(error)"
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Full reset: remove both the anonymous tracked synths *and* every named
|
|
/// slot from the engine, then refresh `trackedSynthCount`.
|
|
///
|
|
/// Clearing the engine means nothing the buffer produced is still playing,
|
|
/// so the "last run" baseline is dropped and the buffer reads as `.dirty`
|
|
/// (or `.empty`) — a re-evaluation is again meaningful.
|
|
public func clearTracked() {
|
|
session.resetAll()
|
|
trackedSynthCount = session.trackedSynthCount
|
|
// `resetAll` stops audio but does NOT unload the compiled snippet dylibs
|
|
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
|
|
// so the UI stays truthful about it.
|
|
loadedSnippetCount = session.loadedSnippetCount
|
|
statusMessage = "Cleared all synths (tracked + slots)."
|
|
lastEvaluatedText = nil
|
|
reevalState = derivedIdleState()
|
|
}
|
|
|
|
// MARK: - Snippet save / load
|
|
|
|
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
|
|
/// for subsequent saves, and refresh the status line.
|
|
///
|
|
/// - Parameter url: File to read. Caller (view) is responsible for the
|
|
/// `NSOpenPanel` UI; this method does the IO.
|
|
public func load(from url: URL) throws {
|
|
let loaded: String = try String(contentsOf: url, encoding: .utf8)
|
|
// Drop the run baseline first so the `text` didSet — and the explicit
|
|
// recompute below — treat freshly loaded content as unrun (`.dirty`).
|
|
lastEvaluatedText = nil
|
|
text = loaded
|
|
documentURL = url
|
|
diagnostics = []
|
|
statusMessage = "Loaded \(url.lastPathComponent)."
|
|
reevalState = derivedIdleState()
|
|
}
|
|
|
|
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
|
|
///
|
|
/// - Parameter url: Destination. Overwrites if present. Caller drives the
|
|
/// `NSSavePanel` UI.
|
|
public func save(to url: URL) throws {
|
|
try text.write(to: url, atomically: true, encoding: .utf8)
|
|
documentURL = url
|
|
statusMessage = "Saved \(url.lastPathComponent)."
|
|
}
|
|
|
|
/// Surface a load failure on the status line without throwing across the
|
|
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
|
|
/// `load(from:)` rejected.
|
|
public func reportLoadError(url: URL, error: Error) {
|
|
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
|
}
|
|
|
|
/// Surface a save failure on the status line without throwing across the
|
|
/// view layer. Called by the view after `NSSavePanel` returned a URL that
|
|
/// `save(to:)` rejected.
|
|
public func reportSaveError(url: URL, error: Error) {
|
|
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
|
|
}
|
|
}
|
|
|
|
#endif
|