477 lines
21 KiB
Swift
477 lines
21 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 LyrebirdScratchDemo 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 = ""
|
|
|
|
/// 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
|
|
|
|
/// 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 }
|
|
reevalState = derivedIdleState()
|
|
}
|
|
|
|
/// 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(additive: additive)
|
|
case .graphDSL: return runGraphDSLBuffer(additive: additive)
|
|
}
|
|
}
|
|
|
|
/// Swift path: compile the buffer to a dylib off-main and run it.
|
|
private func runSwiftSnippet(additive: Bool) async -> Bool {
|
|
guard !isCompiling else { return false }
|
|
let body: String = text
|
|
diagnostics = []
|
|
statusMessage = "Compiling…"
|
|
isCompiling = true
|
|
reevalState = .compiling
|
|
defer {
|
|
isCompiling = false
|
|
trackedSynthCount = session.trackedSynthCount
|
|
loadedSnippetCount = session.loadedSnippetCount
|
|
}
|
|
do {
|
|
try await session.compileAndRunAsync(body, additive: additive)
|
|
let mode: String = additive ? "additive" : "replaced"
|
|
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
|
settleReevalAfterSuccess(body: body)
|
|
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 diagnostics below."
|
|
} 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)."
|
|
}
|
|
reevalState = .failed(diagnosticCount: diagnostics.count)
|
|
return false
|
|
} catch {
|
|
statusMessage = "Error: \(error)"
|
|
reevalState = .failed(diagnosticCount: diagnostics.count)
|
|
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
|
|
/// currently-playing graph untouched (the session builds before it mutates).
|
|
private func runGraphDSLBuffer(additive: Bool) -> Bool {
|
|
guard !isCompiling else { return false }
|
|
let body: String = text
|
|
diagnostics = []
|
|
defer {
|
|
trackedSynthCount = session.trackedSynthCount
|
|
loadedSnippetCount = session.loadedSnippetCount
|
|
}
|
|
do {
|
|
try session.runGraphDSL(body, additive: additive)
|
|
let mode: String = additive ? "additive" : "replaced"
|
|
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
|
settleReevalAfterSuccess(body: body)
|
|
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)"
|
|
}
|
|
reevalState = .failed(diagnosticCount: diagnostics.count)
|
|
return false
|
|
} catch {
|
|
statusMessage = "Error: \(error)"
|
|
reevalState = .failed(diagnosticCount: diagnostics.count)
|
|
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
|
|
let idle: ReevalState = derivedIdleState()
|
|
if idle == .clean, let beat: Double = session.pendingSwapBeat {
|
|
reevalState = .queued(untilBeat: beat)
|
|
} else {
|
|
reevalState = idle
|
|
}
|
|
}
|
|
|
|
/// 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()
|
|
}
|
|
|
|
/// 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
|