66 lines
2.5 KiB
Swift
66 lines
2.5 KiB
Swift
// SnippetContext.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
// LyrebirdLiveCompile — Phase 143
|
|
//
|
|
// `SnippetContext` is the public API surface the user's snippet talks to. The
|
|
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
|
|
// opaque pointer to the snippet's `lyrebird_snippet_entry`, and the preamble
|
|
// hands the snippet a typed `context: SnippetContext` reference.
|
|
//
|
|
// Surface is intentionally minimal for v1 (open question 4 in the plan). Snippets
|
|
// read `context.engine` for `SynthesisEngine`, call `context.play(_:)` to add a
|
|
// synth that the host will track for re-evaluation cleanup, and report back via
|
|
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
|
|
|
|
#if os(macOS)
|
|
import LyrebirdSynth
|
|
|
|
public final class SnippetContext {
|
|
/// Owning session. `unowned` because the host guarantees the session
|
|
/// outlives the snippet `entry` call (entry is invoked synchronously inside
|
|
/// `LiveSession.compileAndRun` under a `withExtendedLifetime` on `self`).
|
|
public unowned let session: LiveSession
|
|
|
|
/// Convenience accessor — same as `session.engine`.
|
|
public var engine: SynthesisEngine { session.engine }
|
|
|
|
init(session: LiveSession) {
|
|
self.session = session
|
|
}
|
|
|
|
/// Add `synth` to the engine and track it so the next non-additive
|
|
/// re-evaluation (`LiveSession.compileAndRun(_:additive: false)`) removes it.
|
|
/// - Returns: `true` if the engine accepted the enqueue; `false` if
|
|
/// `engine.add` threw (e.g. cross-engine binding, double-add, queue full).
|
|
@discardableResult
|
|
public func play(_ synth: any Synthesizer) -> Bool {
|
|
do {
|
|
try session.engine.add(synth)
|
|
session.track(synth)
|
|
return true
|
|
} catch {
|
|
session.lastSnippetMessage = "engine.add failed: \(error)"
|
|
return false
|
|
}
|
|
}
|
|
|
|
/// 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.
|
|
public func reportSampleRate(_ rate: Double) {
|
|
session.reportedSampleRate = rate
|
|
}
|
|
|
|
/// 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
|
|
}
|
|
}
|
|
|
|
#endif
|