v1.4.0 release: live-coding scratch editor, interpreted Graph DSL, ClosureSynthesizer + SampleLoop
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
// EditorPositionMapping.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Maps an `NSTextView` UTF-16 insertion offset to a zero-based (line, character)
|
||||
// position. LSP positions are UTF-16-based, matching `NSTextView`'s own offsets,
|
||||
// so no re-encoding is needed — only newline counting.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Convert a UTF-16 offset into `text` to a zero-based `(line, character)`
|
||||
/// where `character` is a UTF-16 code-unit column — the coordinate space
|
||||
/// `sourcekit-lsp` expects. An offset past the end clamps to the final position.
|
||||
func editorLineAndUTF16Char(in text: String, utf16Offset: Int) -> (line: Int, character: Int) {
|
||||
let units: String.UTF16View = text.utf16
|
||||
var idx: String.UTF16View.Index = units.startIndex
|
||||
var consumed: Int = 0
|
||||
var line: Int = 0
|
||||
var character: Int = 0
|
||||
let newline: UInt16 = 10
|
||||
while consumed < utf16Offset, idx < units.endIndex {
|
||||
if units[idx] == newline {
|
||||
line += 1
|
||||
character = 0
|
||||
} else {
|
||||
character += 1
|
||||
}
|
||||
idx = units.index(after: idx)
|
||||
consumed += 1
|
||||
}
|
||||
return (line, character)
|
||||
}
|
||||
|
||||
#endif
|
||||
+221
-10
@@ -41,11 +41,18 @@ window.open {
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
|
||||
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
`LiveSession.clearTracked()` directly.
|
||||
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
||||
anonymous tracked synths and every named slot.
|
||||
|
||||
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.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
@@ -55,32 +62,236 @@ A snippet has one local in scope:
|
||||
context: SnippetContext
|
||||
```
|
||||
|
||||
`SnippetContext` is intentionally minimal in v1:
|
||||
`SnippetContext`:
|
||||
|
||||
- `context.engine` — the host `SynthesisEngine`.
|
||||
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
|
||||
cleanup on the next non-additive run.
|
||||
- `context.play { <graph> }` — play a bare generator graph, no `SynthesizerBase`
|
||||
subclass needed (wraps it in a `ClosureSynthesizer`).
|
||||
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
|
||||
**named slot** (see below).
|
||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
||||
`print`-style probes during development).
|
||||
|
||||
## Named slots (hot-swap)
|
||||
|
||||
`context.play(slot: "name") { … }` installs a voice under a name. Re-running a
|
||||
slot definition **replaces just that voice in place** — the new voice starts
|
||||
before the old one is removed (a brief overlap, no gap), while everything else
|
||||
keeps playing:
|
||||
|
||||
```swift
|
||||
context.play(slot: "bass") { OscSaw.Audio(freq: 55, mul: 0.2) }
|
||||
context.play(slot: "lead") { Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0) }
|
||||
```
|
||||
|
||||
Unlike anonymous `context.play`, a slotted voice is **not** torn down by the
|
||||
next non-additive (⌘↩) run — that is what lets you edit and re-evaluate one
|
||||
voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
|
||||
|
||||
| API | Lifetime |
|
||||
|-----|----------|
|
||||
| `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.
|
||||
|
||||
## Threading
|
||||
|
||||
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
|
||||
synchronously inside the button action, so the editor freezes for the duration
|
||||
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
|
||||
accepts that trade-off; an off-main compile path is on the polish list.
|
||||
All UI is `@MainActor`-isolated. The Run / Run Additive actions dispatch a
|
||||
`Task` that awaits ``LyrebirdScratchModel/run(additive:)``, which awaits
|
||||
`LiveSession.compileAndRunAsync` — the `swiftc` subprocess runs on a background
|
||||
`Task.detached`, so the editor stays responsive while a compile is in flight.
|
||||
The snippet entry then resumes on the main actor to touch engine + UI state.
|
||||
`LyrebirdScratchMenuController` disables the Run / Run Additive commands
|
||||
whenever ``ReevalState/canEvaluate`` is `false` (a compile is in flight or the
|
||||
buffer is empty); `run(additive:)` additionally guards re-entrancy on
|
||||
``LyrebirdScratchModel/isCompiling``.
|
||||
|
||||
## Re-evaluation readiness
|
||||
|
||||
``LyrebirdScratchModel/reevalState`` publishes a ``ReevalState`` — a structured
|
||||
signal for *when* a re-evaluation is available and whether it would change
|
||||
anything:
|
||||
|
||||
| State | Meaning |
|
||||
|-------|---------|
|
||||
| `.empty` | Buffer is blank. Nothing to run. |
|
||||
| `.dirty` | Edited since the last run (or never run). An eval is available. |
|
||||
| `.compiling` | A compile + run is in flight. |
|
||||
| `.queued(untilBeat:)` | Compiled; a quantized slot swap is scheduled but not yet audible (see below). |
|
||||
| `.clean` | Buffer matches what is currently playing. |
|
||||
| `.failed(diagnosticCount:)` | The last run failed to compile. |
|
||||
|
||||
The editor renders this as a colored dot + label in the status bar.
|
||||
``ReevalState/canEvaluate`` is `true` whenever a run can be triggered right now
|
||||
(non-blank buffer, no compile already running) — hosts can gate their own Run
|
||||
controls on it.
|
||||
|
||||
## Quantized swaps (on-beat latency masking)
|
||||
|
||||
A `swiftc` build finishes a few hundred milliseconds after ⌘↩ — long enough to
|
||||
feel loose against a running groove. Point the session at a `LyrebirdClock` and
|
||||
choose a `SwapQuantize` mode, and named-slot swaps land on the next musical
|
||||
boundary instead of whenever the compile happens to finish:
|
||||
|
||||
```swift
|
||||
let clock = LyrebirdClock(engine: engine, bpm: 120)
|
||||
let session = LiveSession(engine: engine)
|
||||
session.swapClock = clock
|
||||
session.swapQuantize = .nextBar(beatsPerBar: 4) // .immediate | .nextBeat | .nextBar
|
||||
```
|
||||
|
||||
Now `context.play(slot: "bass") { … }` **schedules** the new voice's add and the
|
||||
old voice's removal at the same upcoming boundary sample time (`engine.schedule` /
|
||||
`engine.remove(_:at:)`), so the swap is glitch-free and on-grid. Because the
|
||||
change is quantized to a boundary that is comfortably past the compile, the
|
||||
compile latency is hidden: you edit, hit ⌘↩, and the change drops exactly on the
|
||||
downbeat.
|
||||
|
||||
While the swap is pending, ``LyrebirdScratchModel/reevalState`` reads
|
||||
`.queued(untilBeat:)` (a purple badge); it settles to `.clean` once the clock
|
||||
passes the boundary (or `.dirty` if you edit again first). ``LiveSession/pendingSwapBeat``
|
||||
exposes the target beat. `.immediate` (or no `swapClock`) makes swaps take effect
|
||||
at once. Anonymous `context.play` is unaffected; quantization applies to named
|
||||
slots only.
|
||||
|
||||
Re-running a slot while its previous quantized swap is still pending is safe: the
|
||||
previous voice's removal is always scheduled no earlier than its own add, so a
|
||||
just-scheduled voice is never left orphaned.
|
||||
|
||||
## First-run latency (module-cache prewarm)
|
||||
|
||||
A snippet compiles in ~0.1 s once the Swift/Clang module cache is warm — but the
|
||||
*first* compile of a session pays ~2–3 s to build the precompiled module for the
|
||||
large `LyrebirdSynth` interface. Left alone, that cost lands on the user's first
|
||||
⌘↩ (the "time to first sound").
|
||||
|
||||
``LiveSession/prewarm()`` moves it into the background: it type-checks a trivial
|
||||
import-only snippet on a detached `.utility` task, warming swiftc's default
|
||||
module cache so the first real compile is already fast. `LyrebirdScratchView`
|
||||
calls it from `onAppear` (idempotent — safe to call again). It is *not* wired
|
||||
into `LyrebirdScratchModel.init`, so constructing a model never shells out to
|
||||
swiftc; a headless host should call `session.prewarm()` at launch itself.
|
||||
|
||||
A prewarm never throws: a failure (e.g. a missing toolchain) leaves
|
||||
``LiveSession/isPrewarmed`` `false` — so a later call retries, and the first
|
||||
real compile simply pays the cold build itself and surfaces any real error
|
||||
through its own diagnostics.
|
||||
|
||||
> Note: the prewarm deliberately uses swiftc's default module cache rather than a
|
||||
> pinned `-module-cache-path`. A freshly-built dedicated cache produces module
|
||||
> metadata that diverges from the already-loaded `libLyrebirdLiveCompileDynamic`,
|
||||
> which turns a benign ObjC class-duplication warning into a hard cast crash when
|
||||
> a snippet is `dlopen`'d.
|
||||
|
||||
## Code completion
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
`SnippetHarness` preamble the compiler uses, next to a `compile_commands.json`
|
||||
carrying the host `LiveSession`'s `-I` / module-map / link flags. sourcekit-lsp's
|
||||
compilation-database build system reads that file. The caret is mapped through
|
||||
the harness line offset, so a completion request at the user's row hits the right
|
||||
row in the wrapped document. Completion is Swift-mode only — graph-DSL mode is
|
||||
interpreted and needs no compiler — and best-effort: any LSP failure yields no
|
||||
candidates rather than an error.
|
||||
|
||||
## Limitations
|
||||
|
||||
- macOS only.
|
||||
- No syntax highlighting, code completion, or line-number gutter (deferred).
|
||||
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
|
||||
referenced by tracked synths; unloading is unsafe.
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
## Snippet memory (the dylib leak)
|
||||
|
||||
Every ⌘↩ compiles a fresh dylib and `dlopen`s it; those dylibs are **never
|
||||
unloaded**, so a session's mapped memory grows one dylib per successful
|
||||
evaluation. ``LiveSession/loadedSnippetCount`` reports how many are mapped — a
|
||||
host can nudge the user to restart after a very long session.
|
||||
|
||||
This is a hard limit of the compiled approach, not an oversight. Reclaiming the
|
||||
memory would require `dlclose`, which is **unsafe** for these dylibs: `dlopen`
|
||||
registers a Swift dylib's type metadata and protocol-conformance records into
|
||||
process-global runtime caches, and `dlclose` unmaps the dylib without
|
||||
deregistering them — leaving those caches pointing into freed memory, so a later
|
||||
type operation can crash. That holds even after every synth a snippet produced
|
||||
has been removed. A refcount-gated `dlclose` was therefore considered and
|
||||
rejected rather than shipped as a crash-prone flag.
|
||||
|
||||
``LiveSession/resetAll()`` (the toolbar **Clear Synths**) is the pressure-relief
|
||||
valve: it stops all snippet audio — removing every anonymous and slotted synth —
|
||||
and gives a clean slate without tearing down the engine, but it does not reclaim
|
||||
the mapped dylibs. Only restarting the process does. The **Graph DSL mode**
|
||||
below sidesteps dylibs entirely and is the structural fix.
|
||||
|
||||
The editor makes this visible rather than silent: the engine bar shows a
|
||||
**"snippets: N"** count (`LyrebirdScratchModel.loadedSnippetCount`), and once it
|
||||
crosses ``LyrebirdScratchModel/snippetRestartThreshold`` (50) the count turns
|
||||
orange and a warning banner appears — nudging the user to restart to reclaim the
|
||||
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.
|
||||
|
||||
## Graph DSL mode (instant, no compile)
|
||||
|
||||
The status-bar toggle switches the editor between two evaluators:
|
||||
|
||||
- **Swift** — the full snippet path above: swiftc compiles a dylib, which is
|
||||
`dlopen`'d and run. The whole language, `SynthesizerBase` subclasses, arbitrary
|
||||
code — at the cost of a compile and a permanently mapped dylib.
|
||||
- **Graph DSL** — the interpreted graph-DSL. The buffer is lexed, parsed, and
|
||||
built into a generator graph **in-process**: no swiftc, no dylib, microseconds
|
||||
instead of a compile round-trip, and nothing leaks. The trade is scope — only
|
||||
generator-graph *expressions*, not arbitrary Swift.
|
||||
|
||||
A DSL buffer is one statement per line:
|
||||
|
||||
```
|
||||
bass = OscSawtooth.Audio(freq: 55, mul: 0.15)
|
||||
Pan2(input: OscSin.Audio(freq: 440, mul: 0.1), pan: 0)
|
||||
```
|
||||
|
||||
- A **bare** line plays anonymously and is tracked, so a non-additive re-run
|
||||
(⌘↩) replaces it — exactly like `context.play { … }`.
|
||||
- A **named** line (`name = …`) installs a persistent, hot-swappable named slot
|
||||
(like `context.play(slot:)`): it survives a non-additive re-run and is swapped
|
||||
in place on the next evaluation, so you can mutate one voice while others keep
|
||||
playing. Quantized swaps apply here too.
|
||||
|
||||
Generators are spelled **exactly** as in a Lyrebird `build()` —
|
||||
`OscSin.Audio(freq:)`, `.Control` for the control-rate variant — so a graph you
|
||||
like in the editor pastes into a project unchanged (only the wrapping differs;
|
||||
see the `LyrebirdGraphDSL` design notes). The bare `OscSin(…)` no-rate form is a
|
||||
DSL shorthand for the audio variant.
|
||||
|
||||
The whole program is built **before** any engine mutation, so a syntax or build
|
||||
error leaves the currently-playing graph untouched — a bad edit never drops
|
||||
audio. Errors surface in the same gutter as swiftc diagnostics: a parse error
|
||||
points at its line/column; a build error (unknown generator, bad argument)
|
||||
reports at file scope. See ``LyrebirdScratchModel/switchMode(to:)`` and
|
||||
``LiveSession/runGraphDSL(_:additive:resources:)``.
|
||||
|
||||
## Topics
|
||||
|
||||
- ``LyrebirdScratchView``
|
||||
- ``LyrebirdScratchModel``
|
||||
- ``ScratchEvalMode``
|
||||
|
||||
@@ -13,8 +13,12 @@ import LyrebirdLiveCompile
|
||||
/// Builds and installs the macOS application menu bar for a live-coding host
|
||||
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
|
||||
/// stay wired for the lifetime of the controller.
|
||||
///
|
||||
/// Conforms to `NSMenuItemValidation` so the Run / Run Additive commands
|
||||
/// disable when the buffer cannot be evaluated — i.e. while a compile is in
|
||||
/// flight or the buffer is empty (``ReevalState/canEvaluate``).
|
||||
@MainActor
|
||||
public final class LyrebirdScratchMenuController: NSObject {
|
||||
public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation {
|
||||
|
||||
public let model: LyrebirdScratchModel
|
||||
|
||||
@@ -201,6 +205,21 @@ public final class LyrebirdScratchMenuController: NSObject {
|
||||
return item
|
||||
}
|
||||
|
||||
// MARK: - Menu validation
|
||||
|
||||
/// Disable the Run / Run Additive commands whenever the buffer cannot be
|
||||
/// evaluated (a compile is in flight, or the buffer is empty). All other
|
||||
/// items stay enabled. AppKit calls this automatically for items whose
|
||||
/// target is this controller.
|
||||
public func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
|
||||
switch menuItem.action {
|
||||
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
|
||||
return model.reevalState.canEvaluate
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Action targets
|
||||
|
||||
private func target(_ item: NSMenuItem) -> NSMenuItem {
|
||||
|
||||
@@ -42,27 +42,54 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||
//
|
||||
// The snippet body has `context: SnippetContext` in scope.
|
||||
// `context.engine` → the host `SynthesisEngine`.
|
||||
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
|
||||
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
|
||||
// `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).
|
||||
|
||||
class SineSynth: SynthesizerBase {
|
||||
override func build() {
|
||||
let sine = OscSin.Audio(freq: 440, mul: 0.15)
|
||||
let stereo = Pan2(input: sine, pan: 0)
|
||||
output(bus: 0, source: stereo)
|
||||
}
|
||||
}
|
||||
|
||||
let synth = SineSynth()
|
||||
_ = context.play(synth)
|
||||
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`.
|
||||
@Published public var text: String
|
||||
///
|
||||
/// 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.
|
||||
@@ -76,6 +103,37 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// `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.
|
||||
@@ -93,8 +151,39 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// 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
|
||||
@@ -124,6 +213,44 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
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`,
|
||||
@@ -140,19 +267,30 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// 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 {
|
||||
@@ -173,19 +311,122 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
|
||||
/// 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.clearTracked()
|
||||
session.resetAll()
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
statusMessage = "Cleared tracked synths."
|
||||
// `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
|
||||
@@ -197,10 +438,14 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// `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.
|
||||
|
||||
@@ -45,12 +45,15 @@ import LyrebirdLiveCompile
|
||||
///
|
||||
/// ## Threading
|
||||
///
|
||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
|
||||
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
|
||||
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
|
||||
/// on a background `Task.detached`; the snippet entry then resumes on the
|
||||
/// main actor so it can touch UI-side state. Both Run buttons disable while
|
||||
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
|
||||
/// All UI work is `@MainActor`-isolated. The Run / Run Additive commands (in the
|
||||
/// menu bar built by ``LyrebirdScratchMenuController``) dispatch a `Task` that
|
||||
/// awaits `LyrebirdScratchModel.run(additive:)`, which itself awaits
|
||||
/// `LiveSession.compileAndRunAsync`. The swiftc subprocess runs on a background
|
||||
/// `Task.detached`; the snippet entry then resumes on the main actor so it can
|
||||
/// touch UI-side state. The menu controller gates the Run commands on
|
||||
/// ``ReevalState/canEvaluate`` (disabled while a compile is in flight or the
|
||||
/// buffer is empty); `run(additive:)` additionally guards re-entrancy on
|
||||
/// ``LyrebirdScratchModel/isCompiling``.
|
||||
@MainActor
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@@ -84,6 +87,10 @@ public struct LyrebirdScratchView: View {
|
||||
public var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
if let hint: String = model.snippetMemoryHint {
|
||||
Divider()
|
||||
snippetMemoryBanner(hint)
|
||||
}
|
||||
Divider()
|
||||
ScratchEditor(
|
||||
text: Binding(
|
||||
@@ -91,7 +98,10 @@ public struct LyrebirdScratchView: View {
|
||||
set: { model.text = $0 }
|
||||
),
|
||||
fontSize: model.fontSize,
|
||||
wrapsLines: model.wrapsLines
|
||||
wrapsLines: model.wrapsLines,
|
||||
requestCompletions: { line, character in
|
||||
await model.completionItems(line: line, character: character)
|
||||
}
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
@@ -102,18 +112,37 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
|
||||
.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()
|
||||
}
|
||||
}
|
||||
|
||||
private var engineBar: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "engine stopped")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Button {
|
||||
model.toggleEngine()
|
||||
engineTick &+= 1
|
||||
} label: {
|
||||
HStack(spacing: reevalBadgeSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "▶ start engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
@@ -122,12 +151,35 @@ public struct LyrebirdScratchView: View {
|
||||
Text("synths: \(model.trackedSynthCount)")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
Text("snippets: \(model.loadedSnippetCount)")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(model.snippetMemoryHint == nil ? Color.secondary : Color.orange)
|
||||
.help("Compiled snippet dylibs mapped this session. They can't be "
|
||||
+ "unloaded without restarting (Graph DSL mode maps none).")
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
/// Warning strip shown once mapped snippet dylibs cross the restart
|
||||
/// threshold — the user-facing safety valve over the by-design leak.
|
||||
private func snippetMemoryBanner(_ hint: String) -> some View {
|
||||
HStack(spacing: reevalBadgeSpacing) {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.foregroundStyle(.orange)
|
||||
Text(hint)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.primary)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.background(Color.orange.opacity(0.12))
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
@@ -180,18 +232,96 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
|
||||
private var statusBar: some View {
|
||||
HStack {
|
||||
HStack(spacing: toolbarSpacing) {
|
||||
reevalBadge
|
||||
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.middle)
|
||||
Spacer()
|
||||
modePicker
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
}
|
||||
|
||||
/// Segmented toggle between the Swift-compile and instant graph-DSL
|
||||
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
|
||||
/// seed placeholder follows the mode.
|
||||
private var modePicker: some View {
|
||||
Picker("Mode", selection: Binding(
|
||||
get: { model.evalMode },
|
||||
// Defer to the next main-actor tick: the Picker's `set` runs inside
|
||||
// SwiftUI's view-update pass, and `switchMode` mutates @Published
|
||||
// state ("Publishing changes from within view updates is not
|
||||
// allowed"). Scheduling it off the current pass avoids that.
|
||||
set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } }
|
||||
)) {
|
||||
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
|
||||
Text(mode.title).tag(mode)
|
||||
}
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
.labelsHidden()
|
||||
.fixedSize()
|
||||
.help("Swift compiles a snippet dylib; Graph DSL interprets a generator graph instantly, no compile.")
|
||||
}
|
||||
|
||||
/// Re-evaluation readiness indicator: a colored dot + short label bound to
|
||||
/// ``LyrebirdScratchModel/reevalState``. Tells the user at a glance whether
|
||||
/// an eval is available (dirty), in flight (compiling), matches what is
|
||||
/// playing (clean), or failed.
|
||||
private var reevalBadge: some View {
|
||||
HStack(spacing: reevalBadgeSpacing) {
|
||||
Circle()
|
||||
.fill(reevalColor)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(reevalLabel)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.help(reevalHelp)
|
||||
}
|
||||
|
||||
private var reevalColor: Color {
|
||||
switch model.reevalState {
|
||||
case .empty: return .secondary
|
||||
case .clean: return .green
|
||||
case .dirty: return .yellow
|
||||
case .compiling: return .blue
|
||||
case .queued: return .purple
|
||||
case .failed: return .red
|
||||
}
|
||||
}
|
||||
|
||||
private var reevalLabel: String {
|
||||
switch model.reevalState {
|
||||
case .empty: return "empty"
|
||||
case .clean: return "clean"
|
||||
case .dirty: return "dirty"
|
||||
case .compiling: return "compiling"
|
||||
case .queued: return "queued"
|
||||
case .failed: return "failed"
|
||||
}
|
||||
}
|
||||
|
||||
private var reevalHelp: String {
|
||||
switch model.reevalState {
|
||||
case .empty: return "Nothing to evaluate."
|
||||
case .clean: return "Buffer matches what is playing. ⌘↩ re-runs it."
|
||||
case .dirty: return "Edited since the last run — ⌘↩ to re-evaluate."
|
||||
case .compiling: return "Compiling…"
|
||||
case .queued(let beat):
|
||||
return String(format: "Compiled — swap lands on beat %.0f.", beat)
|
||||
case .failed(let count):
|
||||
let plural: String = count == 1 ? "" : "s"
|
||||
return count == 0
|
||||
? "Last run failed to compile."
|
||||
: "Last run failed — \(count) diagnostic\(plural)."
|
||||
}
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
@@ -219,6 +349,7 @@ public struct LyrebirdScratchView: View {
|
||||
private let diagnosticsMinHeight: CGFloat = 80
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
private let reevalBadgeSpacing: CGFloat = 4
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
@@ -250,7 +381,12 @@ private struct DiagnosticRow: View {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
}
|
||||
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
// 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 {
|
||||
@@ -266,7 +402,37 @@ private struct DiagnosticRow: View {
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
|
||||
/// `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
|
||||
|
||||
/// 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
|
||||
}
|
||||
|
||||
final class ScratchTextView: NSTextView {
|
||||
override var rangeForUserCompletion: NSRange {
|
||||
let sel: NSRange = selectedRange()
|
||||
if caretFollowsDot(in: string as NSString, selection: sel) {
|
||||
return NSRange(location: sel.location, length: 0)
|
||||
}
|
||||
return super.rangeForUserCompletion
|
||||
}
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
|
||||
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
|
||||
/// auto-correct interference — matches the editor expectations of someone
|
||||
/// typing Swift code.
|
||||
@@ -275,24 +441,90 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
@Binding var text: String
|
||||
let fontSize: CGFloat
|
||||
let wrapsLines: Bool
|
||||
/// 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]
|
||||
|
||||
@MainActor
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
var parent: ScratchEditor
|
||||
/// Candidate insert-texts from the most recent completion fetch; served
|
||||
/// synchronously to the text view's completion window via the delegate.
|
||||
private var _completionStrings: [String] = []
|
||||
/// Monotonic id of the latest completion request; a resolving fetch only
|
||||
/// 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
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// The text view calls this synchronously from `complete(_:)`; return the
|
||||
/// candidates fetched asynchronously just before. Replaces the default
|
||||
/// dictionary-word completions entirely.
|
||||
func textView(_ textView: NSTextView,
|
||||
completions words: [String],
|
||||
forPartialWordRange charRange: NSRange,
|
||||
indexOfSelectedItem index: UnsafeMutablePointer<Int>?) -> [String] {
|
||||
_completionStrings
|
||||
}
|
||||
|
||||
/// Fetch completions for the current caret position, then show the text
|
||||
/// view's completion window. No-op when the selection is non-empty (a
|
||||
/// range is selected, not an insertion point) or the fetch is empty.
|
||||
func triggerCompletion(_ tv: NSTextView) {
|
||||
let sel: NSRange = tv.selectedRange()
|
||||
guard sel.length == 0 else { return }
|
||||
let (line, character): (Int, Int) = editorLineAndUTF16Char(
|
||||
in: tv.string, utf16Offset: sel.location)
|
||||
let request: @MainActor (Int, Int) async -> [LSPCompletionItem] = parent.requestCompletions
|
||||
_completionGeneration += 1
|
||||
let generation: Int = _completionGeneration
|
||||
Task { @MainActor [weak self, weak tv] in
|
||||
let items: [LSPCompletionItem] = await request(line, character)
|
||||
guard let self: Coordinator = self, let tv: NSTextView = tv,
|
||||
!items.isEmpty else { return }
|
||||
// Ignore a superseded request (a newer trigger fired meanwhile)
|
||||
// and one whose caret has since moved.
|
||||
guard generation == self._completionGeneration,
|
||||
tv.selectedRange() == sel else { return }
|
||||
self._completionStrings = items.map { $0.insertText }
|
||||
tv.complete(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||
|
||||
func makeNSView(context: Context) -> NSScrollView {
|
||||
let scroll: NSScrollView = NSTextView.scrollableTextView()
|
||||
if let tv: NSTextView = scroll.documentView as? NSTextView {
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
}
|
||||
// Build the scroll view around a `ScratchTextView` subclass so its
|
||||
// `rangeForUserCompletion` override can keep member completion from
|
||||
// eating the receiver expression (see the class doc).
|
||||
let scroll: NSScrollView = NSScrollView()
|
||||
scroll.borderType = .noBorder
|
||||
scroll.hasVerticalScroller = true
|
||||
scroll.autoresizingMask = [.width, .height]
|
||||
|
||||
let tv: ScratchTextView = ScratchTextView(frame: .zero)
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
tv.minSize = NSSize(width: 0, height: 0)
|
||||
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
|
||||
height: CGFloat.greatestFiniteMagnitude)
|
||||
tv.textContainer?.widthTracksTextView = true
|
||||
scroll.documentView = tv
|
||||
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
return scroll
|
||||
}
|
||||
|
||||
@@ -311,7 +543,7 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
if tv.string != text {
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,16 +572,28 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraph)
|
||||
}
|
||||
|
||||
private func reapplyAttrs(to tv: NSTextView,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
// MARK: - Syntax highlighting
|
||||
|
||||
/// Re-tokenize the buffer and paint token colors via
|
||||
/// ``ScratchSyntaxHighlighter``. Attribute-only — the string and the
|
||||
/// selection are untouched.
|
||||
private func applyHighlight(to tv: NSTextView,
|
||||
font: NSFont,
|
||||
paragraph: NSParagraphStyle) {
|
||||
guard let storage: NSTextStorage = tv.textStorage else { return }
|
||||
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
let range: NSRange = NSRange(location: 0, length: storage.length)
|
||||
storage.setAttributes(attrs, range: range)
|
||||
tv.typingAttributes = attrs
|
||||
let base: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
|
||||
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
||||
tv.typingAttributes = base
|
||||
}
|
||||
|
||||
/// Convenience for the delegate path, which has only the text view: rebuilds
|
||||
/// the font/paragraph from the current `fontSize`.
|
||||
func applyHighlight(to tv: NSTextView) {
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
applyHighlight(to: tv, font: font, paragraph: makeParagraphStyle(for: font))
|
||||
}
|
||||
|
||||
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
|
||||
@@ -378,7 +622,15 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.delegate = coordinator
|
||||
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
tv.font = editorFont
|
||||
tv.isRichText = false
|
||||
// Rich text so per-token foreground colors render. User styling can't
|
||||
// creep in: every edit re-runs `applyHighlight`, which normalizes the
|
||||
// font/paragraph over the whole buffer before recoloring, and the smart
|
||||
// substitutions below stay disabled.
|
||||
tv.isRichText = true
|
||||
// Rich text would otherwise allow dragged/pasted images to inject
|
||||
// NSTextAttachment glyphs into the buffer; keep it plain-text-only so the
|
||||
// content is always compilable Swift source.
|
||||
tv.importsGraphics = false
|
||||
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||
tv.isAutomaticDashSubstitutionEnabled = false
|
||||
tv.isAutomaticTextReplacementEnabled = false
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// ReevalState.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// `ReevalState` is the structured re-evaluation readiness signal published by
|
||||
// `LyrebirdScratchModel`. It answers "can I re-evaluate, and would it change
|
||||
// anything?" for the editor UI — distinct from the free-text `statusMessage`.
|
||||
// A snippet's buffer becomes `.dirty` when edited away from the last
|
||||
// successfully-run text, flips to `.compiling` while a run is in flight, and
|
||||
// settles to `.clean` (buffer matches what is playing) or `.failed` afterward.
|
||||
//
|
||||
// macOS only — the whole LiveCompile UI surface is macOS-only.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Re-evaluation readiness of a live-coding buffer.
|
||||
///
|
||||
/// Published by ``LyrebirdScratchModel/reevalState`` so the editor can show a
|
||||
/// status badge and enable/disable the Run controls without inspecting the
|
||||
/// free-text status line.
|
||||
///
|
||||
/// State machine:
|
||||
///
|
||||
/// - ``empty`` → editing non-blank text → ``dirty``
|
||||
/// - ``dirty`` → run starts → ``compiling``
|
||||
/// - ``compiling`` → success → ``clean`` (or ``dirty`` if the buffer was edited
|
||||
/// mid-compile; or ``queued(untilBeat:)`` if the run scheduled a quantized
|
||||
/// slot swap that has not yet fired) / failure → ``failed(diagnosticCount:)``
|
||||
/// - ``queued(untilBeat:)`` → the scheduled swap fires → ``clean`` (or
|
||||
/// ``dirty`` if the buffer was edited while queued)
|
||||
/// - ``clean`` / ``queued(untilBeat:)`` / ``failed(diagnosticCount:)`` →
|
||||
/// editing → ``dirty`` (or ``empty`` if the buffer is cleared to whitespace)
|
||||
public enum ReevalState: Equatable, Sendable {
|
||||
|
||||
/// Buffer is empty or whitespace-only. Nothing to evaluate.
|
||||
case empty
|
||||
|
||||
/// Buffer matches the text of the last successful run — re-evaluating would
|
||||
/// re-run the same source. Re-evaluation is still permitted (e.g. additive).
|
||||
case clean
|
||||
|
||||
/// Buffer has been edited since the last successful run (or has never been
|
||||
/// run) and holds non-blank content. A re-evaluation is available and would
|
||||
/// change what is playing.
|
||||
case dirty
|
||||
|
||||
/// A compile + run is in flight. Run controls should be disabled.
|
||||
case compiling
|
||||
|
||||
/// The run compiled and its slot swap is scheduled but has not yet fired —
|
||||
/// the change becomes audible on `untilBeat` (a `LyrebirdClock` beat). Only
|
||||
/// reached when swaps are quantized (see `SwapQuantize`); the state settles
|
||||
/// to ``clean`` once the clock passes the boundary.
|
||||
case queued(untilBeat: Double)
|
||||
|
||||
/// The last run failed to compile. `diagnosticCount` is the number of
|
||||
/// parsed diagnostics (0 when the failure produced no line-mapped
|
||||
/// diagnostics, e.g. a toolchain error).
|
||||
case failed(diagnosticCount: Int)
|
||||
|
||||
/// `true` when a re-evaluation can be triggered right now — i.e. the buffer
|
||||
/// holds runnable content and no compile is already in flight. A pending
|
||||
/// quantized swap (``queued``) does not block a further edit + re-run.
|
||||
public var canEvaluate: Bool {
|
||||
switch self {
|
||||
case .empty, .compiling:
|
||||
return false
|
||||
case .clean, .dirty, .queued, .failed:
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,31 @@
|
||||
// ScratchEvalMode.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Which evaluator the scratch editor runs the buffer through.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// The evaluation path for a `LyrebirdScratchModel`'s buffer.
|
||||
public enum ScratchEvalMode: String, CaseIterable, Sendable {
|
||||
/// Full Swift snippet compiled with swiftc into a dylib and run — the whole
|
||||
/// language, `SynthesizerBase` subclasses, arbitrary code. Costs a compile.
|
||||
case swift
|
||||
/// Interpreted graph-DSL — instant, no swiftc, but only generator-graph
|
||||
/// expressions (`OscSin.Audio(freq: 440) * 0.1`, `bass = …`).
|
||||
case graphDSL
|
||||
|
||||
/// Human-readable label for a mode toggle.
|
||||
public var title: String {
|
||||
switch self {
|
||||
case .swift: return "Swift"
|
||||
case .graphDSL: return "Graph DSL"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,199 @@
|
||||
// ScratchSwiftTokenizer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// A small, dependency-free lexer that classifies the colorable spans of Swift
|
||||
// source — comments, string literals, numbers, keywords, and Capitalized type
|
||||
// names — for the scratch editor's syntax highlighting. It is intentionally
|
||||
// approximate (a highlighter, not a parser): good enough to read code at a
|
||||
// glance, and re-run whole on every keystroke — a full grapheme walk of the
|
||||
// buffer, fine for typical snippet sizes (not tuned or validated for very large
|
||||
// documents). Pure (no AppKit) so it is unit-testable. Ranges are `NSRange`
|
||||
// (UTF-16), matching `NSTextView`.
|
||||
//
|
||||
// macOS only — consumed by the macOS-only scratch editor.
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
|
||||
/// Classifies Swift source into colorable token spans for syntax highlighting.
|
||||
enum ScratchSwiftTokenizer {
|
||||
|
||||
/// A colorable category. Uncategorized text (identifiers, punctuation,
|
||||
/// whitespace) produces no token and renders in the default text color.
|
||||
enum Kind: Equatable {
|
||||
case keyword
|
||||
case type
|
||||
case string
|
||||
case number
|
||||
case comment
|
||||
}
|
||||
|
||||
/// One colorable span. `range` is a UTF-16 `NSRange` into the source.
|
||||
struct Token: Equatable {
|
||||
let range: NSRange
|
||||
let kind: Kind
|
||||
}
|
||||
|
||||
/// Swift keywords (plus a few common contextual ones) colored as keywords.
|
||||
private static let keywords: Set<String> = [
|
||||
"associatedtype", "class", "deinit", "enum", "extension", "fileprivate",
|
||||
"func", "import", "init", "inout", "internal", "let", "open", "operator",
|
||||
"private", "precedencegroup", "protocol", "public", "rethrows", "static",
|
||||
"struct", "subscript", "typealias", "var",
|
||||
"break", "case", "continue", "default", "defer", "do", "else",
|
||||
"fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch",
|
||||
"where", "while",
|
||||
"as", "await", "catch", "false", "is", "nil", "self", "Self", "super",
|
||||
"throw", "throws", "true", "try", "Any",
|
||||
"async", "some", "any", "mutating", "nonmutating", "weak", "unowned",
|
||||
"final", "lazy", "indirect", "convenience", "required", "optional",
|
||||
"override", "dynamic", "willSet", "didSet", "get", "set",
|
||||
"actor", "nonisolated", "isolated", "distributed", "consuming",
|
||||
"borrowing", "sending", "each",
|
||||
]
|
||||
|
||||
/// UTF-16 length of the `"""` multiline-string delimiter.
|
||||
private static let tripleQuoteDelimiterLength: Int = 3
|
||||
|
||||
/// Classify `text` into colorable token spans, left to right.
|
||||
static func tokens(in text: String) -> [Token] {
|
||||
let chars: [Character] = Array(text)
|
||||
let count: Int = chars.count
|
||||
// Prefix table of UTF-16 offsets so `[a, b)` maps to an exact NSRange
|
||||
// even with multi-unit characters (emoji in a comment, etc.).
|
||||
var utf16Starts: [Int] = [Int](repeating: 0, count: count + 1)
|
||||
var acc: Int = 0
|
||||
for k: Int in 0..<count {
|
||||
utf16Starts[k] = acc
|
||||
acc += chars[k].utf16.count
|
||||
}
|
||||
utf16Starts[count] = acc
|
||||
|
||||
func makeRange(_ start: Int, _ end: Int) -> NSRange {
|
||||
NSRange(location: utf16Starts[start], length: utf16Starts[end] - utf16Starts[start])
|
||||
}
|
||||
|
||||
var tokens: [Token] = []
|
||||
var i: Int = 0
|
||||
while i < count {
|
||||
let c: Character = chars[i]
|
||||
|
||||
// Line comment: // … end of line
|
||||
if c == "/", i + 1 < count, chars[i + 1] == "/" {
|
||||
let start: Int = i
|
||||
i += 2
|
||||
while i < count, chars[i] != "\n" { i += 1 }
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .comment))
|
||||
continue
|
||||
}
|
||||
|
||||
// Block comment: /* … */ with Swift's nesting.
|
||||
if c == "/", i + 1 < count, chars[i + 1] == "*" {
|
||||
let start: Int = i
|
||||
i += 2
|
||||
var depth: Int = 1
|
||||
while i < count, depth > 0 {
|
||||
if chars[i] == "/", i + 1 < count, chars[i + 1] == "*" {
|
||||
depth += 1
|
||||
i += 2
|
||||
} else if chars[i] == "*", i + 1 < count, chars[i + 1] == "/" {
|
||||
depth -= 1
|
||||
i += 2
|
||||
} else {
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .comment))
|
||||
continue
|
||||
}
|
||||
|
||||
// String literal: triple-quoted (multiline) or single-line.
|
||||
if c == "\"" {
|
||||
let start: Int = i
|
||||
if i + 2 < count, chars[i + 1] == "\"", chars[i + 2] == "\"" {
|
||||
i += tripleQuoteDelimiterLength
|
||||
while i < count {
|
||||
if chars[i] == "\\" { i = min(i + 2, count); continue }
|
||||
if chars[i] == "\"", i + 2 < count,
|
||||
chars[i + 1] == "\"", chars[i + 2] == "\"" {
|
||||
i += tripleQuoteDelimiterLength
|
||||
break
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
} else {
|
||||
i += 1
|
||||
while i < count {
|
||||
if chars[i] == "\\" { i = min(i + 2, count); continue } // escape
|
||||
if chars[i] == "\"" { i += 1; break }
|
||||
if chars[i] == "\n" { break } // unterminated
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .string))
|
||||
continue
|
||||
}
|
||||
|
||||
// Number literal (must start with a digit here).
|
||||
if c.isNumber {
|
||||
let start: Int = i
|
||||
i += 1
|
||||
while i < count {
|
||||
let d: Character = chars[i]
|
||||
if (d == "e" || d == "E" || d == "p" || d == "P"),
|
||||
i + 1 < count, chars[i + 1] == "+" || chars[i + 1] == "-" {
|
||||
i += 2 // signed exponent, e.g. 1e-10
|
||||
} else if d.isHexDigit || d == "_"
|
||||
|| d == "x" || d == "X" || d == "o" || d == "O"
|
||||
|| d == "b" || d == "B" || d == "e" || d == "E"
|
||||
|| d == "p" || d == "P" {
|
||||
i += 1
|
||||
} else if d == ".", i + 1 < count, chars[i + 1].isNumber {
|
||||
i += 1 // decimal point (not a range/member `.`)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .number))
|
||||
continue
|
||||
}
|
||||
|
||||
// Attribute: @escaping, @MainActor, …
|
||||
if c == "@" {
|
||||
let start: Int = i
|
||||
i += 1
|
||||
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
|
||||
i += 1
|
||||
}
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
|
||||
continue
|
||||
}
|
||||
|
||||
// Identifier: keyword, Capitalized type, or plain (no token).
|
||||
if c.isLetter || c == "_" {
|
||||
let start: Int = i
|
||||
i += 1
|
||||
while i < count, chars[i].isLetter || chars[i].isNumber || chars[i] == "_" {
|
||||
i += 1
|
||||
}
|
||||
let word: String = String(chars[start..<i])
|
||||
if keywords.contains(word) {
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .keyword))
|
||||
} else if let first: Character = word.first, first.isUppercase {
|
||||
tokens.append(Token(range: makeRange(start, i), kind: .type))
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
i += 1
|
||||
}
|
||||
return tokens
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
// ScratchSyntaxHighlighter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Paints ``ScratchSwiftTokenizer`` token colors onto an `NSTextStorage`. Split
|
||||
// out of the SwiftUI `NSViewRepresentable` so the tokenizer→color→storage wiring
|
||||
// is unit-testable against a plain `NSTextStorage` (no window / view needed).
|
||||
//
|
||||
// macOS only.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
enum ScratchSyntaxHighlighter {
|
||||
|
||||
/// Foreground color for a token kind. `NSColor.system*` are dynamic, so they
|
||||
/// adapt to the editor's light/dark appearance automatically.
|
||||
static func color(for kind: ScratchSwiftTokenizer.Kind) -> NSColor {
|
||||
switch kind {
|
||||
case .keyword: return .systemPink
|
||||
case .type: return .systemPurple
|
||||
case .string: return .systemRed
|
||||
case .number: return .systemBlue
|
||||
case .comment: return .systemGreen
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize `baseAttributes` (font / paragraph / label color) over the whole
|
||||
/// storage — so a paste or font change can't leave stray styling — then
|
||||
/// overlay per-token foreground colors. Attribute-only: the string is not
|
||||
/// changed, so the caller's selection is preserved.
|
||||
static func apply(to storage: NSTextStorage, baseAttributes: [NSAttributedString.Key: Any]) {
|
||||
let full: NSRange = NSRange(location: 0, length: storage.length)
|
||||
storage.beginEditing()
|
||||
storage.setAttributes(baseAttributes, range: full)
|
||||
for token: ScratchSwiftTokenizer.Token in ScratchSwiftTokenizer.tokens(in: storage.string) {
|
||||
// Ranges come from the same string, but guard against any bounds
|
||||
// drift before touching the storage.
|
||||
let end: Int = token.range.location + token.range.length
|
||||
if token.range.location >= 0, end <= storage.length {
|
||||
storage.addAttribute(.foregroundColor,
|
||||
value: color(for: token.kind),
|
||||
range: token.range)
|
||||
}
|
||||
}
|
||||
storage.endEditing()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user