Compare commits
20 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9f244b1939 | |||
| 24ea32e47c | |||
| c14efe998a | |||
| 63b630b317 | |||
| 3668739d20 | |||
| 6e7f4c0076 | |||
| f8878324fd | |||
| 844dc4d9cd | |||
| 2c20b02e59 | |||
| b6fdee8bfc | |||
| 77580ee98e | |||
| ea0aa84ca7 | |||
| 3e33f09e07 | |||
| d6875da2cb | |||
| 5e6534a615 | |||
| 9ec92277de | |||
| 90dc00f323 | |||
| 8eb64f883f | |||
| 62b2f5dbec | |||
| 8519cabe42 |
@@ -1,4 +1,8 @@
|
||||
.build/
|
||||
.build-linux/
|
||||
.build-glibc/
|
||||
.build-docker*/
|
||||
build/
|
||||
.claude/settings.local.json
|
||||
.claude/worktrees/
|
||||
*.o
|
||||
@@ -8,3 +12,17 @@
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
xcuserdata/
|
||||
*.xcuserstate
|
||||
|
||||
# Linux container scratch build trees (docker runs with the repo mounted).
|
||||
.build-alsa/
|
||||
.build-alsa-amd64/
|
||||
.build-noalsa/
|
||||
|
||||
# Spike sub-packages build their own .build when run from their directory.
|
||||
spikes/**/.build/
|
||||
|
||||
# Local SwiftOpenUI fork clone for the @Observable GUI spike (patched, user-local).
|
||||
spikes/SwiftOpenUI/
|
||||
|
||||
# All local Docker/scratch build trees.
|
||||
.build-*/
|
||||
|
||||
@@ -12,7 +12,7 @@ Eight agents live in `~/.claude/agents/` (maintainer's source of truth) and are
|
||||
| `lyrebird_generator_agent` | **Any new Generator** — oscillator, filter, effect, noise, math operator, bus I/O. |
|
||||
| `lyrebird_engine_agent` | Engine internals — SynthesisEngine, CoreAudioDriver/iOSAudioDriver, AUHAL, SPSCQueue, ScheduledEvent, Group/ParallelGroup, RT thread architecture. |
|
||||
| `lyrebird_language_agent` | Non-RT language side — SynthesizerBase, @LiveParam, ParameterNode, LyrebirdRoutine/Task/Clock, Pattern, MIDI, OSC, NRT, Score, demand pattern usage. |
|
||||
| `lyrebird_swiftui_agent` | LyrebirdUI module — @UIParam, ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. |
|
||||
| `lyrebird_swiftui_agent` | LyrebirdUI module — ParameterKnob/Slider/XY/Button/Label, scope/envelope views, platform-conditional code. (@UIParam/UIParamNode themselves live in core `Lyrebird`.) |
|
||||
| `lyrebird_architect_agent` | Cross-cutting analysis — duplicate patterns, API consistency, SC naming alignment, refactor planning. **No implementation.** |
|
||||
| `lyrebird_review_agent` | Pre-merge review (via `/lyrebird_review`) — RT safety, bus rules, protocol correctness, helper usage, test coverage. |
|
||||
| `pr_review_agent` | General pre-PR review — bugs, security, code smells. Broader scope than `lyrebird_review`. |
|
||||
@@ -52,6 +52,8 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
|
||||
**Engine / RT core**
|
||||
- Engine init, audio driver, render pass → `docs/engine/synthesis-engine.md`, `docs/engine/core-audio-driver.md`, `docs/signal-flow/signal-flow.md`
|
||||
- Linux live audio (`ALSAAudioDriver`, `makeDefaultAudioDriver()`, libasound build requirement) → `docs/engine/alsa-audio-driver.md`
|
||||
- Portable WAV read/write off Apple (`WavFileWriter` / `WavFileReader`, header layout, `WavFileError`) → `docs/engine/portable-wav-codec.md`
|
||||
- Bus memory / In / Out → `docs/engine/bus-system.md`
|
||||
- Sample-accurate scheduling → `docs/engine/scheduling.md`
|
||||
- ParallelGroup / multi-core → `docs/engine/multi-core.md`
|
||||
@@ -75,6 +77,8 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
- Routines / tasks / clock / MIDI / OSC → `docs/tooling/routine-task.md`
|
||||
- `Pattern<T>` factory catalog (sequence, series, geometric, uniformRandom, brownian, gaussian, cauchy, beta, shuffle, nonRepeatingRandom, weightedRandom, closure, repeating, limit, drop, stutter, switching, concatenate, roundRobin, tuple, interleave, map, filter, reject, accumulate, difference, wrap, clip, round, smooth) → `docs/tooling/routine-task.md` (§ Pattern Factory Reference) + `Sources/Lyrebird/Lyrebird.docc/RoutineTask.md`
|
||||
- MIDI clock sync (`MIDIClockFollower`) → `docs/tooling/midi-clock-sync.md`
|
||||
- Linux MIDI (`MIDI` via ALSA sequencer — `MIDI/ALSAMIDI.swift`, `ALSASeqMIDIEvent` mapping; needs CALSA/libasound) → `Sources/Lyrebird/MIDI/ALSAMIDI.swift`
|
||||
- Linux OSC (`OSCClient` / `OSCServer` POSIX-UDP transport off Apple, `OSCServerError`; codec unchanged) → `Sources/Lyrebird/OSC/OSCServer.swift`
|
||||
- Non-RT parameter value sources / `ValueComputable` / `ValueComputableClosure` (consumed by `LyrebirdProcess` parameters) → `Sources/Lyrebird/Lyrebird.docc/ValueComputable.md`
|
||||
- TemporalStream / language-side value generation → `Sources/Lyrebird/Lyrebird.docc/TemporalDemand.md`
|
||||
- Polyphonic voice pool / step sequencer → `docs/tooling/routine-task.md`
|
||||
@@ -87,6 +91,7 @@ These guards catch classes of regression that **`swift build` / `swift test` str
|
||||
- CLI / REPL / hot-swap → `docs/tooling/cli-guide.md`, `docs/tooling/repl.md`
|
||||
- Project scaffolding / package targets → `docs/tooling/project-system.md`, `docs/tooling/targets.md`
|
||||
- Dev workflow / phase branches / build → `docs/tooling/workflow.md`
|
||||
- Linux user setup (toolchain, VS Code, build/test, run a sample) → `docs/linux-getting-started.md`
|
||||
- Xcode project templates → `docs/tooling/xcode-templates.md`
|
||||
- AUv3 plugin internals (`LyrebirdAudioUnit`, `LyrebirdAUVoicePoolBinding`, `AUInput`, preset codable, parameter slots) → `Sources/Lyrebird/Lyrebird.docc/AUv3.md`
|
||||
|
||||
@@ -109,7 +114,8 @@ One-liners. Detail and rationale lives in linked docs.
|
||||
|
||||
**Platform / build**
|
||||
- macOS 15+ / iOS 18+ / swift-tools 6.0 — `Synchronization.Atomic` requires macOS 15.
|
||||
- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS.
|
||||
- No AVAudioEngine. Use `kAudioUnitSubType_HALOutput` (full duplex AUHAL) on macOS, RemoteIO on iOS, blocking `snd_pcm_writei` on a dedicated thread (ALSA) on Linux.
|
||||
- Never name a concrete driver in code that is meant to build on more than one platform — call `makeDefaultAudioDriver()`. Which drivers exist depends on how Lyrebird itself was built (a Linux build without libasound, or one cross-compiled from macOS, has no `ALSAAudioDriver`), so a consumer-side `#if` is a guess. Code already locked to one platform is exempt and should name its driver directly — e.g. the AppKit-only `ui-demo` scaffold template emits `CoreAudioDriver()`.
|
||||
- No Xcode Playgrounds. All tests use Swift Testing (`@Test`, `#expect`, `@Suite`).
|
||||
|
||||
**RT thread (render callback)** — `docs/engine/synthesis-engine.md`, `docs/protocols/writing-generators.md`
|
||||
@@ -129,9 +135,9 @@ One-liners. Detail and rationale lives in linked docs.
|
||||
- Open every `_computeSamples` with `_checkCount(count)` — the inherited helper that traps if `count > _result[0].count`. Replaces the long-form `precondition(...)` boilerplate.
|
||||
- `floatValue` is provided by the `AudioGenerator` protocol extension (returns `calculatedSamples(...).first?.first ?? 0`). Do not redeclare in `AudioGenerator` conformers unless you need different scalar semantics (e.g. `ConstantGeneratorInput`). `ControlGenerator` conformers must provide their own `floatValue` returning the block target.
|
||||
- Buffer factories `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` (in `ResultBuffer.swift`) replace `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals when a generator owns a separately-allocated scratch buffer.
|
||||
- Every `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread.
|
||||
- Every sub-blocking `ControlGenerator.Control.init` calls `_setupSubBlockBuffer()` (or `_setupSubBlockBuffer(channels: N)`) after `super.init()`. Never call on the RT thread. **Exception:** `BlockRateControlGenerator` conformers never sub-block and omit the call (see the bypass bullet below).
|
||||
- `Control._computeSamples` uses `count` (not `graph.engine.blockSize`) for phase/state advancement — `_computeSamples` may run N times per audio block in sub-block mode.
|
||||
- Generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop. Canonical pattern: `Out.Control`. See `docs/protocols/writing-generators.md` §15 for the bypass list and decision rule.
|
||||
- Control generators with per-audio-block state (bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers) must advance once per audio block, bypassing the sub-block loop. Conform to `BlockRateControlGenerator` (marker protocol in `GeneratorCore/BlockRateControlGenerator.swift`) — its `calculatedSamples` default routes to the block-rate gateway and the conformer skips `_setupSubBlockBuffer()`. This replaced the old per-generator `calculatedSamples { _calculatedSamplesBlockRate(...) }` forwarder. A true sub-blocking Control must NOT conform. See `docs/protocols/writing-generators.md` §15 for the decision rule.
|
||||
- Multi-row generators (any with `_result.count > 1`) override `var outputChannelCount: Int { get }` to return the fixed channel count set at `init`. `GeneratorBase` defaults to `1`. Missing override silently mono-izes the generator under `+ - * /` operators. Channel count must be derivable from a `let` at init — never runtime-mutable. Detail + cases: `docs/stdlib/multichannel.md`.
|
||||
- `mul:` / `add:` parameters are channel-aware: mono input broadcasts; equal-N applies element-wise; mismatched multi-row precondition-traps. Same policy as `BinaryOpGenerator`. Detail: `docs/stdlib/multichannel.md`.
|
||||
|
||||
@@ -193,6 +199,8 @@ Throws `EngineAddError`: `.boundToOtherEngine(current:prior:)` (cross-engine), `
|
||||
|
||||
`engine.remove(_:)` and `engine.remove(_:at:)` still return `Bool` — they unbind synchronously on successful enqueue. Documented constraint: allow one `processBlock` between `remove` and re-add of the same instance.
|
||||
|
||||
`engine.stop()` also unbinds every non-persistent synth it was hosting (including ones nested inside drained `Group` subtrees) as part of its node-tree teardown, so a stop-then-re-add of the same instance — to the same engine or a different one — needs no such wait; the RT thread is already halted before `stop()`'s unbind pass runs. See `docs/engine/synthesis-engine.md` § `stop()` node-tree teardown contract.
|
||||
|
||||
Call-site pattern: every `engine.add` invocation needs `try`. In non-throwing contexts (closures dispatched to `DispatchQueue.main.async`, non-throwing methods), wrap in `do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }` — the existing `LyrebirdRoutineContext` / `LyrebirdMessageContext` / `LyrebirdProcessContext` adapters use this pattern.
|
||||
|
||||
## Swift Code Style Rules
|
||||
@@ -323,9 +331,12 @@ Tool: `Tools/AnnotateBindings/annotate_bindings.py` drives `sourcekit-lsp` to fi
|
||||
Module-level helpers exist to eliminate repeated boilerplate; inlining any of them in a new generator is a review violation:
|
||||
|
||||
- `_checkCount(_:)` — `GeneratorBase` method; first line of every `_computeSamples`
|
||||
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; canonical body of any `calculatedSamples` override that bypasses the `ControlGenerator` sub-block path (IIR filters, bus writers, buffer-position advancers, trigger detectors, random drawers)
|
||||
- `BlockRateControlGenerator` — `GeneratorCore/BlockRateControlGenerator.swift`; marker protocol a `ControlGenerator` conforms to when its state must advance once per audio block (IIR filters, bus writers, buffer-position advancers, gain smoothers, trigger detectors, random drawers, analysers). Supplies the block-rate `calculatedSamples` gateway for free and lets the conformer skip `_setupSubBlockBuffer()`. The standard way to bypass sub-blocking — superseded the per-generator `_calculatedSamplesBlockRate` forwarder. A true sub-blocker must NOT conform.
|
||||
- `_calculatedSamplesBlockRate(graph:count:)` — `Generator` extension; the block-rate gateway the `BlockRateControlGenerator` default calls. Call it directly only in the rare case a generator needs the bypass but cannot conform to the marker
|
||||
- `OscillatorBase` — `Generators/Oscillators/OscillatorBase.swift`; extend instead of declaring `_freqInput` / `_freqIsGenerator` / `_phase` / `_mulAdd` inline. Designated `init(freq:phase:mul:add:)` performs canonical phase normalisation. Used by LF / band-limited oscillators (LFSawtooth, LFSquare, LFTriangle, LFDutyCycle, OscSawtooth, OscSquare, OscTriangle, OscDutyCycle) and `Impulse` (post-super-init writes `_phase = 1.0 - initPhase` so `initPhase == 0` fires at sample 0). Table-lookup oscillators (`OscSin`, `OscTable`) intentionally excluded — they store `_phase` in table-index units to avoid a per-sample multiply in the inner loop.
|
||||
- `NoiseBase` — `Generators/Noise/NoiseBase.swift`; extend instead of declaring `rngState: UInt64` + `_mulAdd: MulAddSpec` inline. Designated `init(initialRngState:mul:add:)`. Used by 23 noise generators across 3 tiers (parameterless, extra-state, distribution-parameterised). LF noise variants and Crackle intentionally excluded.
|
||||
- `UnaryMathBase` — `Generators/Math/UnaryMathBase.swift`; extend instead of declaring `inputSource` + `_mulAdd` inline. Designated `init(_:mul:add:)`. The shared `_Base` for the single-input math operators — each is `public class _Base: UnaryMathBase {}`, with `Audio`/`Control` supplying only the per-operator kernel. Used by 14 operators (Abs, Ceil, Floor, Round, Sign, Sqrt, Log, Exp, Sin, Cos, Tan, Tanh, Reciprocal, DbAmp). Multi-input math (Max, Min, Ring1–4, ExpExp, ExpLin, …) keeps its own `_Base`.
|
||||
- `SpectralFeatureControlBase` — `Generators/Spectral/SpectralFeatureControlBase.swift`; shared base for the control-rate spectral feature analysers (SpectralCentroid, SpectralSpread, SpectralFlatness, SpectralEntropy, SpectralFlux, SpectralRolloff). Owns the analysis handle, spectral buffer, MulAddSpec, ramp state, sub-block bypass, and the drive-analysis → `computeFeature` → ramp body; each `Control` subclass adds only its own params/state and overrides `computeFeature(graph:count:) -> Double`.
|
||||
- `runRBJBiquadBlock(...)` — `Generators/Filters/RBJBiquadHelpers.swift`; module-internal helper holding the shared `_computeSamples` body for `(freq, q)` RBJ biquad filters (LP / HP / AP / Notch). Concrete filters pass the coefficient formula as a closure.
|
||||
- `runTwoPoleResonatorScalarBlock(input:into:y1:y2:b0:na1:na2:count:)` / `runTwoPoleResonatorInterpolatedBlock(input:into:y1:y2:start:end:count:)` — `Generators/Filters/FilterHelpers.swift`; shared per-sample loop body for two-pole resonator filters (`y[n] = b0·x[n] − na1·y[n−1] − na2·y[n−2]`). Consumed by `RingingFilter` + `ResonatingFilter` — concrete filter passes its coefficient-computation function and one-line helper calls.
|
||||
- `sampleOrFallback(_:scalar:at:)` — `Generators/Filters/FilterHelpers.swift`; per-sample coefficient lookup with zero-fallback past block end. Replaces the `xxxSamples.map { i < $0.count ? $0[i] : 0 } ?? scalarX` pattern. Used by `SecondOrderSection` (5 coefficient slots) + `FirstOrderSection` (3 slots). `Lag`/`Decay` family use a different end-clamp + `lagCoeff` wrapping convention; helper doesn't apply there.
|
||||
@@ -333,7 +344,7 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
|
||||
- `leakyIntegratorStep(state:x:b1:)` — `Generators/Filters/FilterHelpers.swift`; `y = x + b1·state`, mutates state, returns y. SC `Decay`/`Decay2` convention (input not attenuated by `1 − b1`). Used by `Decay.Audio` + `Decay2.Audio` (cascade two for attack/decay difference).
|
||||
- `attackReleaseSmoother(state:target:attackCoeff:attackComp:releaseCoeff:releaseComp:direction:)` — `Generators/Dynamics/DynamicsHelpers.swift`; asymmetric attack/release smoother step with direction selector (`.rising` for envelope followers; `.falling` for compressor/expander gain-target smoothing). Used by `AmplitudeFollower.Audio` (`.rising`) + `Compressor.Audio` / `Expander.Audio` (`.falling`).
|
||||
- `sampleOrZero(_ p: UnsafePointer<Double>, _ i: Int, _ n: Int) -> Double` — `GeneratorCore/HotLoopHelpers.swift`; `i < n ? p[i] : 0`. Replaces the per-sample `(i < n) ? srcP[i] : 0` boilerplate inside hot loops that read an input row via raw pointer. Module-internal helper used across Filters (Lag / Lag2 / LagUpDown / Lag2UpDown / LeakDC / Decay / Decay2 / SecondOrderSection / FirstOrderSection / RBJBiquad / CombFilter / AllpassFilter) and Delays (DelayLine / DelayLineFeedback). `@_spi(LyrebirdExtensions) public` so out-of-tree generators can adopt the same helper.
|
||||
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used by `Flute` (6 params), `Clarinet` (4 params), `PanXYDistance` (4 params), `PanAzDistance` (4 params). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
|
||||
- `resolveGeneratorOrScalar(_:isGenerator:graph:count:) -> (samples: [Double]?, scalar: Double)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate input resolution. Replaces the 8-line `if _xxxIsGenerator { xxxSamples = ...; scalarXxx = 0 } else { xxxSamples = nil; scalarXxx = ... }` boilerplate at the top of any `_computeSamples` that pulls multiple `ValidGeneratorInput` parameters. Used across many multi-input generators (`Flute`, `Clarinet`, `KarplusStrong`/`GatedKarplusStrong`, `BowedString`, `PlayBuffer`, `SpatialDistance`, `MuTronIII`, `Hilbert`, the spatial panners, and more). Tuple destructure at the call site is the CLAUDE.md-documented exception to the explicit-type-annotation rule. `@inline(__always) @_spi(LyrebirdExtensions) public`.
|
||||
- `applySpatialDistanceFiltering(...)` — `Generators/Panning/SpatialDistanceHelpers.swift`; module-internal shared per-sample pipeline for `PanXYDistance` (Cartesian) and `PanAzDistance` (polar). Both callers pre-compute `(panX, panY)` and the Chebyshev distance metric `posD` from their respective coordinate frames; the rest of the pipeline (amplitude attenuation, cutoff-coefficient caching, Doppler read-rate, delay-line write/read/wrap/clamp, one-pole lowpass, equal-power 4-corner pan) is identical and lives here. Mutates delay-line + one-pole state in place via `inout`. `@inline(__always) internal`.
|
||||
- `plateReverbInputDiffusion(...)` / `plateReverbTankHalf(...)` — `Generators/Reverb/PlateReverbHelpers.swift`; PlateReverb-specific per-sample sub-blocks. `plateReverbInputDiffusion` runs the 4-stage cascaded Schroeder allpass network on a single sample. `plateReverbTankHalf` runs one half of the figure-of-eight tank (modulated allpass → delay 1 → damping LP → decay scale → allpass 2 → delay 2 write). Consumed twice per sample by `PlateReverb._computeSamples` (left and right halves). All state mutated `inout`. `@inline(__always) internal`.
|
||||
- `gverbReadEarlyTaps(...)` / `gverbFDNDamperCascade(...)` — `Generators/Reverb/GVerbHelpers.swift`; GVerb-specific per-sample sub-blocks. `gverbReadEarlyTaps` reads four pre-FDN early-reflection taps with branchless wrap + per-tap gains and returns a 4-tuple. `gverbFDNDamperCascade` applies the FDN one-pole LP damper cascade `y = x*(1-damp) + prev*damp` to four raw FDN reads, mutates `fdnDampState[0..3]` with denormal flush, returns 4-tuple. Both `@inline(__always) internal`.
|
||||
@@ -341,11 +352,15 @@ Module-level helpers exist to eliminate repeated boilerplate; inlining any of th
|
||||
- `_mulAdd.applyIfNeeded(to:graph:count:)`
|
||||
- `fillRampedResult(into:from:to:mulAdd:graph:count:)`
|
||||
- `fillScalarRampedResult(into:previousOutputValue:target:count:)` — `MulAdd.swift`; canonical body of every `Math.Control` `_computeSamples` ramp (28 generators). Distinct from `fillRampedResult` because the caller has pre-folded `mul`/`add` into the scalar `target` — the helper writes the ramp without re-applying `MulAddSpec.apply`.
|
||||
- `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)`
|
||||
- `fillHeldResult(into:value:previousOutputValue:mulAdd:graph:count:)` — `MulAdd.swift`; held-constant counterpart of `fillScalarRampedResult` — fills a block with one value, applies mul/add, sets `previousOutputValue` to the last sample. For block-rate `Control` paths whose output holds one value (one-pole smoothers `Lag`/`Decay`/`LeakDC`/`Slew`/`Formlet`, block-constant analysis `ZeroCrossing`/`Slope`/`RunningMin`/`Max`, trigger/counter latches `Trig`/`Schmidt`/`PulseCount`/`Stepper`; 20 sites). No-op at `count == 0`. NOT for per-sample-varying output.
|
||||
- `MulAddSpec.applyScalar(_:graph:)` — `MulAdd.swift`; folds scalar `mul`/`add` into one block-constant `target` (returns it unchanged on identity). The scalar counterpart of `applyIfNeeded`; used by the 36 scalar-fold paths (Math.Control plus Routing/Waveshaping crossfades and shapers) before `fillScalarRampedResult`.
|
||||
- `firstGeneratorSampleOrFloat(_:isGenerator:graph:count:)` / `lastGeneratorSampleOrFloat(_:isGenerator:graph:count:)` — `GeneratorCore/InputResolutionHelpers.swift`; block-rate read of a generator-or-scalar input. `first…` reads the block's first sample (`0` if empty) — oscillator/LF/noise `Control` paths; `last…` reads the final sample (ramp endpoint) — dynamics + delay-time paths. Both fall back to `floatValue` for non-generators
|
||||
- `xorshift64Next(_:)`
|
||||
- `lyrebirdSeedXorshift64(from:mixConstant:)` / `lyrebirdSeedXorshift64(from:)` — `Math/LyrebirdConstants.swift`; init-time xorshift64 seed helper. Two-arg form decorrelates Audio/Control pairs via `mixConstant`; one-arg form is the convenience for stand-alone single-state owners (e.g. `DemandTemporalTendency` / `DemandTemporalBrownian`)
|
||||
- `catmullRomCubic(_:_:_:_:t:)` — `Math/CubicInterpolation.swift`; the single shared 4-point Catmull-Rom cubic kernel. Pass `(pM1, p0, p1, p2, t:)` — the sample before the segment, the two bracketing it, the one after, and `t ∈ [0, 1]`. Use instead of inlining the `t²`/`t³` expanded form. `@inline(__always) @_spi(LyrebirdExtensions) public`. Consumers: oscillator table reads (`OscSin` / `oscillatorTableReadCubic`), `PlayBuffer`, `chaoticInterpolate`, and the fractional-delay lines (`DelayLine` / `DelayLineFeedback` / `CombFilter` / `AllpassFilter`).
|
||||
|
||||
- `RTScratchBuffer<Element>` — `Buffers/RTScratchBuffer.swift`; a `~Copyable` single-owner heap scratch buffer that replaces hand-paired `allocate`/`deinitialize`/`deallocate` in scratch-owning generators (the Spectral/FFT family). `init(count:)` zero-fills (`Element: Numeric`); `init(count:repeating:)` fills any value. `@inline(__always)` `baseAddress`/`count`/`subscript` (`nonmutating set`) so the hot loop matches the raw pointer. Store as a `let` assigned in `init` — never a per-call local. Not for `[UnsafeMutablePointer]` per-channel arrays (a `~Copyable` cannot be `Array`-stored) or capacity-1 scalar boxes used via `.pointee`. `@_spi(LyrebirdExtensions) public`.
|
||||
|
||||
Full table, signatures, examples, and the per-generator exceptions (notably `MathGenerators.Control` and the non-standard ControlGenerator ramp paths) live in `docs/protocols/writing-generators.md` §13. That document is the single source of truth — when adding or removing a helper, update §13 and reference it from here.
|
||||
|
||||
## Code Review
|
||||
|
||||
@@ -50,7 +50,7 @@ If a unit is useful at both rates, implement both via the **enum namespace patte
|
||||
- **First line of every `_computeSamples` is `_checkCount(count)`.** It traps if `count` exceeds the pre-allocated buffer. No grow path exists.
|
||||
- **Pre-allocate everything in `init`.** Bus memory, scratch buffers, vDSP setup objects. `init` runs off the RT thread; `_computeSamples` must only read/write existing storage. Use `makeResultBuffer(channels:)` / `makeSampleBuffer(_:)` instead of `[Double](repeating: 0, count: lyrebirdDefaultResultBufferSize)` literals.
|
||||
- **Use `count`, never `engine.blockSize`,** for phase/state advancement — a `Control._computeSamples` may run several times per audio block in sub-block mode.
|
||||
- **Generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers) override `calculatedSamples` to bypass the sub-block loop via `_calculatedSamplesBlockRate(graph:count:)`. See §15 for the bypass list.
|
||||
- **Control generators with per-audio-block state** (bus writers, position advancers, gain smoothers, trigger detectors, random drawers, analysers) conform the `Control` to `BlockRateControlGenerator` to bypass the sub-block loop (no `calculatedSamples` override, no `_setupSubBlockBuffer()`). See writing-generators.md §15.
|
||||
- **Multi-row generators** (`_result.count > 1`) call `super.init(channels: N)` and override `outputChannelCount`. Missing the override silently mono-izes the generator under `+ - * /`. Channel count must be a `let` fixed at init.
|
||||
- **Extend the right base** where one exists: `OscillatorBase`, `NoiseBase`. Don't re-declare `_phase` / `_mulAdd` / `rngState` inline.
|
||||
- **Denormal hygiene** — flush denormals to zero in feedback paths (filters, delays, reverbs).
|
||||
|
||||
@@ -11,30 +11,11 @@
|
||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000040 /* Assets.xcassets */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8D00000000000000000012 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
@@ -50,11 +31,32 @@
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C8D00000000000000000004 /* LyrebirdScratch.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratch.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratch.entitlements; sourceTree = "<group>"; };
|
||||
C8D00000000000000000040 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8D00000000000000000012 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C8D00000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000005 /* LyrebirdScratchDemo */,
|
||||
C8D00000000000000000005 /* LyrebirdScratch */,
|
||||
C8D00000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
@@ -62,45 +64,47 @@
|
||||
C8D00000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */,
|
||||
C8D00000000000000000004 /* LyrebirdScratch.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C8D00000000000000000005 /* LyrebirdScratchDemo */ = {
|
||||
C8D00000000000000000005 /* LyrebirdScratch */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000007 /* main.swift */,
|
||||
C8D00000000000000000008 /* AppDelegate.swift */,
|
||||
C8D00000000000000000006 /* Info.plist */,
|
||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */,
|
||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
|
||||
C8D00000000000000000040 /* Assets.xcassets */,
|
||||
);
|
||||
path = LyrebirdScratchDemo;
|
||||
path = LyrebirdScratch;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
C8D00000000000000000014 /* LyrebirdScratchDemo */ = {
|
||||
C8D00000000000000000014 /* LyrebirdScratch */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */;
|
||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */;
|
||||
buildPhases = (
|
||||
C8D00000000000000000011 /* Sources */,
|
||||
C8D00000000000000000012 /* Frameworks */,
|
||||
C8D00000000000000000013 /* Resources */,
|
||||
C8D00000000000000000035 /* Embed Frameworks */,
|
||||
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdScratchDemo;
|
||||
name = LyrebirdScratch;
|
||||
packageProductDependencies = (
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||
);
|
||||
productName = LyrebirdScratchDemo;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
||||
productName = LyrebirdScratch;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratch.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
@@ -111,14 +115,14 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2620;
|
||||
LastUpgradeCheck = 2660;
|
||||
TargetAttributes = {
|
||||
C8D00000000000000000014 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */;
|
||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
@@ -135,7 +139,7 @@
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
C8D00000000000000000014 /* LyrebirdScratchDemo */,
|
||||
C8D00000000000000000014 /* LyrebirdScratch */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -145,11 +149,30 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "Bundle Lyrebird swiftmodules";
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "# Bundle the Lyrebird module artifacts into the app so the live-compile scratchpad\n# can `import LyrebirdSynth` / `import LyrebirdLiveCompile` on any machine — they\n# otherwise resolve only from BUILT_PRODUCTS_DIR / the dev source tree, both absent\n# once the .app is exported. LiveSession stages Contents/Resources/LyrebirdArtifacts\n# at launch; artifactSourceDir() / discoverSPMModuleMaps() then find them.\nset -e\nART=\"${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Resources/LyrebirdArtifacts\"\nDEST=\"${ART}/Modules\"\n/bin/rm -rf \"${ART}\"\n/bin/mkdir -p \"${DEST}\"\n# 1. Swift module interfaces the snippet imports (+ their transitive deps).\nfor m in LyrebirdSynth LyrebirdLiveCompile LyrebirdLiveCompileUI LyrebirdGraphDSLEmbedded; do\n SRC=\"${BUILT_PRODUCTS_DIR}/${m}.swiftmodule\"\n if [ -e \"${SRC}\" ]; then /bin/cp -R \"${SRC}\" \"${DEST}/\"; fi\ndone\n# 2. LyrebirdC C-shim Clang module (LyrebirdSynth depends on it; a snippet importing\n# LyrebirdSynth needs its module map + header). The SPM source map uses a header path\n# relative to the map dir, so map + include/ copied together stay self-contained and\n# relocatable — placed at LyrebirdArtifacts/LyrebirdC.build so discoverSPMModuleMaps()\n# finds it once staged.\nCSRC=\"${SRCROOT}/../../Sources/LyrebirdC\"\nif [ -f \"${CSRC}/module.modulemap\" ]; then\n CDEST=\"${ART}/LyrebirdC.build\"\n /bin/mkdir -p \"${CDEST}\"\n /bin/cp \"${CSRC}/module.modulemap\" \"${CDEST}/\"\n [ -d \"${CSRC}/include\" ] && /bin/cp -R \"${CSRC}/include\" \"${CDEST}/\"\nfi\necho \"Bundled Lyrebird modules + LyrebirdC shim into ${ART}\"\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
C8D00000000000000000011 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
@@ -166,19 +189,40 @@
|
||||
C8D00000000000000000016 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -187,18 +231,39 @@
|
||||
C8D00000000000000000017 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -239,6 +304,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -263,9 +329,6 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Debug;
|
||||
@@ -305,6 +368,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -322,7 +386,6 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Release;
|
||||
@@ -330,7 +393,7 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = {
|
||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C8D00000000000000000016 /* Debug */,
|
||||
@@ -339,7 +402,7 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = {
|
||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C8D00000000000000000019 /* Debug */,
|
||||
@@ -16,9 +16,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -31,7 +31,7 @@
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
@@ -45,9 +45,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
@@ -62,9 +62,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
@@ -20,6 +20,21 @@ import LyrebirdLiveCompileUI
|
||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||
|
||||
// Entitlements / signing posture (rationale kept here because Xcode strips
|
||||
// comments from `LyrebirdScratch.entitlements` on every project resave):
|
||||
//
|
||||
// • App Sandbox is intentionally OFF. Live-compile shells out to `swiftc`
|
||||
// (`posix_spawn`, disallowed under the sandbox) and `dlopen`s the resulting
|
||||
// UNSIGNED snippet dylib (rejected by the sandbox). This is a direct-
|
||||
// distribution developer tool, not a Mac App Store app; sandbox-off is the
|
||||
// only viable configuration. (An XPC-worker split could revisit this.)
|
||||
// • Hardened Runtime is ON, so the entitlement
|
||||
// `com.apple.security.cs.disable-library-validation = true` is REQUIRED —
|
||||
// without it dyld rejects `dlopen` of the unsigned, non-team-signed snippet
|
||||
// dylib ("code signing blocked mmap()").
|
||||
//
|
||||
// Do not remove that entitlement or the app can't load compiled snippets.
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
@@ -31,6 +46,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
// Stage the Lyrebird compile artifacts into ~/Library/Application Support
|
||||
// (ungated) before the session reads its default -I/-L/rpath. Without
|
||||
// this the snippet compiler points swiftc at the SPM build dir under
|
||||
// ~/Documents, tripping the macOS Documents-folder permission gate.
|
||||
// Best-effort: if staging fails the session falls back to the build dir.
|
||||
LiveSession.stageArtifacts()
|
||||
self.session = LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@@ -39,7 +60,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
||||
print("[LyrebirdScratch] Engine failed to start: \(error)")
|
||||
}
|
||||
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||
@@ -48,13 +69,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
menuController.installMainMenu()
|
||||
self.menuController = menuController
|
||||
|
||||
let windowWidth: CGFloat = 720
|
||||
let windowHeight: CGFloat = 560
|
||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
contentRect: NSRect(origin: .zero, size: CGSize(width: 720, height: 560)),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
@@ -63,7 +81,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = "Lyrebird — Live Scratch"
|
||||
win.contentViewController = hosting
|
||||
win.center()
|
||||
// Base geometry: three-quarters of the screen wide, three-quarters tall,
|
||||
// anchored to the left edge and vertically centered in the visible area
|
||||
// (below the menu bar, above the Dock).
|
||||
let visible: NSRect = (win.screen ?? NSScreen.main)?.visibleFrame
|
||||
?? NSRect(x: 0, y: 0, width: 1440, height: 900)
|
||||
let width: CGFloat = visible.width * 0.75
|
||||
let height: CGFloat = visible.height * 0.75
|
||||
let originX: CGFloat = visible.minX
|
||||
let originY: CGFloat = visible.minY + (visible.height - height) / 2
|
||||
win.setFrame(NSRect(x: originX, y: originY, width: width, height: height), display: true)
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
self.window = win
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "16x16", "filename" : "icon_16.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "16x16", "filename" : "icon_32.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "32x32", "filename" : "icon_32.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "32x32", "filename" : "icon_64.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "128x128", "filename" : "icon_128.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "128x128", "filename" : "icon_256.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "256x256", "filename" : "icon_256.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "256x256", "filename" : "icon_512.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "512x512", "filename" : "icon_512.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "512x512", "filename" : "icon_1024.png" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
|
After Width: | Height: | Size: 338 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 720 B |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -13,14 +13,14 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<string>1.6.3</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<string>3</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,45 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!--
|
||||
App Sandbox is intentionally OFF.
|
||||
|
||||
LyrebirdScratchDemo shells out to `swiftc` at runtime to compile user-
|
||||
typed Swift snippets, then calls `dlopen` on the resulting unsigned dylib.
|
||||
Both operations are blocked by the macOS App Sandbox:
|
||||
|
||||
- `posix_spawn` / `fork` for the swiftc subprocess is disallowed in a
|
||||
sandboxed process (com.apple.security.temporary-exception.mach-lookup
|
||||
grants exist for specific Apple tools only, not arbitrary executables).
|
||||
- `dlopen` of a dylib that was not shipped with the app bundle and is
|
||||
not code-signed with a matching team ID is rejected by the sandbox.
|
||||
|
||||
This app is a direct-distribution developer tool, not a Mac App Store
|
||||
submission. Sandbox OFF is the only viable configuration for v1.
|
||||
This could be revisited if an XPC-worker approach is adopted.
|
||||
|
||||
com.apple.security.app-sandbox key is absent (defaults false).
|
||||
-->
|
||||
|
||||
<!--
|
||||
Hardened Runtime — Disable Library Validation.
|
||||
|
||||
With Hardened Runtime enabled (ENABLE_HARDENED_RUNTIME = YES in the
|
||||
Xcode project), `dlopen` of a dylib that was not signed with the same
|
||||
Team ID as the host app is rejected by the dynamic linker.
|
||||
|
||||
LyrebirdScratchDemo writes snippet dylibs to a per-session temp dir
|
||||
via `swiftc -emit-library`; those dylibs are unsigned (swiftc does not
|
||||
sign them). The `CS_ALLOW_UNSIGNED_EXECUTABLE_MEMORY` (library-
|
||||
validation disable) entitlement tells the kernel to skip the
|
||||
code-signing check for loaded libraries, allowing `dlopen` to succeed.
|
||||
|
||||
Without this entitlement the app would crash with DYLD_PRINT_LIBRARIES
|
||||
reporting: "Library not loaded: ... Reason: tried: ... no suitable image
|
||||
found. Did find: ... code signing blocked mmap() of '...'"
|
||||
-->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -368,6 +368,6 @@ The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | live-coding scratchpad |
|
||||
|
||||
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
|
||||
|
||||
@@ -0,0 +1,781 @@
|
||||
<!--
|
||||
LINUX_PLAN.md
|
||||
Lyrebird
|
||||
Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
SPDX-License-Identifier: MIT
|
||||
-->
|
||||
|
||||
# Lyrebird — Linux Support Plan
|
||||
|
||||
Hand-off plan for finishing Linux support. Branch:
|
||||
`feasibility/cross-platform-linux-windows`. Companion docs:
|
||||
`docs/cross-platform-feasibility.md` (how the port was done) and
|
||||
`docs/windows-support-plan.md` (Windows, deferred).
|
||||
|
||||
**A next agent can pick this up cold from this file.** Every item lists what,
|
||||
why, where (paths), first steps, and an acceptance check.
|
||||
|
||||
---
|
||||
|
||||
## 1. Current state (what already works)
|
||||
|
||||
The whole non-UI toolchain **cross-compiles to Linux**, verified from macOS:
|
||||
|
||||
| Target | musl SDK | glibc SDK |
|
||||
|---|---|---|
|
||||
| `LyrebirdSynth` (core engine + generators) | ✅ | ✅ |
|
||||
| `LyrebirdGraphDSL` | ✅ | ✅ |
|
||||
| `LyrebirdCLI` | ✗ (LineNoise `import Glibc`) | ✅ |
|
||||
|
||||
macOS/iOS builds are **byte-identical** to before the port (all Apple-only code
|
||||
is behind `#if canImport(...)` or re-exported by `LyrebirdDSP`). Full macOS
|
||||
suite (5644 tests) passes; the branch passed `/lyrebird_review` twice.
|
||||
|
||||
**Architecture that made this work** (do not undo):
|
||||
- `Sources/LyrebirdDSP/` — a target that `@_exported import`s Accelerate + the
|
||||
platform C-lib on Apple, and supplies portable scalar/FFT/biquad/vForce
|
||||
fallbacks off Apple. Generator/synth code writes `import LyrebirdDSP` (never
|
||||
`import Accelerate`/`import Darwin`) and carries **zero** platform `#if`.
|
||||
- Portable WAV codec (`Sources/Lyrebird/Buffers/Wav*.swift`) replaces
|
||||
`ExtAudioFile` off Apple.
|
||||
- Platform-abstraction files keep their own local `#if`: `MonotonicClock.swift`,
|
||||
`RTThreadIdentity.swift`, `PlatformCompat.swift` (OSStatus shim),
|
||||
`AudioFileFormat+AudioToolbox.swift`.
|
||||
|
||||
### How to build / verify Linux locally (from a Mac)
|
||||
|
||||
Two cross-compile SDKs are installed (reusable):
|
||||
|
||||
```bash
|
||||
# musl (static single binary; best for the core library)
|
||||
TC=~/Library/Developer/Toolchains/swift-6.3.3-RELEASE.xctoolchain/usr/bin/swift
|
||||
$TC build --swift-sdk aarch64-swift-linux-musl --target LyrebirdSynth --scratch-path .build-linux
|
||||
|
||||
# glibc / Ubuntu 24.04 (the target for CLI + real distros)
|
||||
$TC build --swift-sdk 6.3.3-RELEASE_ubuntu_noble_aarch64 --target LyrebirdCLI --scratch-path .build-glibc
|
||||
```
|
||||
|
||||
**Critical:** use the **swift.org** toolchain (path above), NOT Xcode's — the
|
||||
Static Linux SDK's `Foundation.swiftmodule` was built by swift.org's compiler and
|
||||
a mismatch buries the real errors under ~1244 bogus "Foundation compiled by older
|
||||
compiler" errors.
|
||||
|
||||
The glibc SDK was generated with `swift-sdk-generator` (swift.org ships no
|
||||
prebuilt glibc bundle). To regenerate:
|
||||
`swift run swift-sdk-generator make-linux-sdk --distribution-name ubuntu --distribution-version 24.04 --swift-version 6.3.3-RELEASE`.
|
||||
|
||||
### Standing maintenance — after every `git merge main`
|
||||
|
||||
New generators land on main importing `Darwin`/`Accelerate` directly, which
|
||||
breaks Linux. Every merge:
|
||||
|
||||
```bash
|
||||
# 1. migrate any new unguarded imports to LyrebirdDSP:
|
||||
grep -rlnE "^import Accelerate|^import Darwin" Sources/Lyrebird --include='*.swift'
|
||||
# (skip RTThreadIdentity / MonotonicClock / DiskOutError — their Darwin is guarded)
|
||||
# 2. new direct `stderr` / `fputs` usage breaks Linux — Swift 6 flags the imported
|
||||
# C `stderr` global as "not concurrency-safe". Use the portable helper instead:
|
||||
# core -> lyrebirdPrintError(_:) (Sources/Lyrebird/Utilities/StandardError.swift)
|
||||
# LyrebirdCLI -> printError(_:) (Sources/LyrebirdCLI/StandardError.swift)
|
||||
grep -rnE "\bfputs\b|\bstderr\b" Sources/Lyrebird Sources/LyrebirdCLI --include='*.swift'
|
||||
# 3. delete Finder sync cruft that appears during merges:
|
||||
find Sources Tests -regex '.* [0-9]+\.swift' -delete
|
||||
# 4. rebuild Linux to confirm — cross-compile (both SDKs) AND, when Docker is
|
||||
# available, run the suite natively (matches CI exactly). The stock swift
|
||||
# image has no ALSA headers, so either add them (needed to compile
|
||||
# ALSAAudioDriver) or opt out:
|
||||
# docker build -t lyrebird-alsa - <<'DOCKERFILE'
|
||||
# FROM swift:6.3.3
|
||||
# RUN apt-get update && apt-get install -y --no-install-recommends libasound2-dev pkg-config
|
||||
# DOCKERFILE
|
||||
# docker run --rm -v "$PWD":/pkg -w /pkg lyrebird-alsa swift test
|
||||
# # …or, without the ALSA package:
|
||||
# docker run --rm -e LYREBIRD_DISABLE_ALSA=1 -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test
|
||||
```
|
||||
|
||||
**Scaffolded projects need their own check.** `swift test` never compiles the
|
||||
source the CLI *emits*, so template regressions are invisible to it — that is
|
||||
how the `nrt`/`score` templates came to reference a `LyrebirdCLI`-internal
|
||||
symbol, and how they kept rendering to CAF (an Apple-only container that throws
|
||||
off Apple) while still compiling. The gated suite builds **and runs** every SPM
|
||||
template against this checkout:
|
||||
|
||||
```bash
|
||||
LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild
|
||||
# …and inside the Linux container, where it matters most:
|
||||
# docker run --rm -v "$PWD":/pkg -w /pkg lyrebird-alsa \
|
||||
# bash -c 'LYREBIRD_RUN_BUILD_TESTS=1 swift test --no-parallel --filter ProjectScaffolderBuild'
|
||||
```
|
||||
|
||||
Run it after touching `ProjectScaffolder` or any public API a template uses.
|
||||
|
||||
**Two arch/build gotchas the CI bring-up already paid for:**
|
||||
|
||||
- **BitBucket runners are x86_64; the Mac + its local Docker are arm64.** Some
|
||||
breakage is x86-only and invisible on an arm64 box — e.g. C code that uses a
|
||||
Darwin-only `<fenv.h>` macro under an `#if defined(__x86_64__)` branch compiles
|
||||
on arm64 Linux (wrong branch, and note Linux arm64 predefines `__aarch64__`,
|
||||
**not** Apple's `__arm64__`) but breaks on x86 glibc. To reproduce CI exactly,
|
||||
emulate the runner arch locally:
|
||||
`docker run --rm --platform linux/amd64 -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test`.
|
||||
- **A library-only build does not compile C target sources — only headers.**
|
||||
`swift build --target LyrebirdSynth` (a library) will not surface a bad
|
||||
`Sources/LyrebirdC/*.c`; the `.c` is compiled only when an executable/test
|
||||
links it. So the build *gate* can be green while `swift test` fails. Always
|
||||
verify with `swift test` (which links), not just the build gate.
|
||||
|
||||
### Verifying on macOS: always `swift test --no-parallel`
|
||||
|
||||
Plain `swift test` on macOS reports **~45 failures** on a clean tree. They are
|
||||
**not real** — `--no-parallel` is the project's canonical command
|
||||
(`docs/00-working-order.md` step 1) and the full suite passes under it.
|
||||
|
||||
The flakes are main-thread starvation, concentrated in `LyrebirdProcess`,
|
||||
`LyrebirdEventList*`, `RoutineTests` and `ActorIsolationGuardTests`: those tests
|
||||
dispatch to the main queue and then wait on a wall-clock timeout, while the
|
||||
parallel runner has `@MainActor` suites saturating main. Recognisable by the
|
||||
message shape — `got 0 of 3`, `.timedOut`, `Body should have entered`,
|
||||
`Expected ~0.2s between events, got 2.3s` — never a wrong numeric result.
|
||||
Parallel is also *slower* here (≈286 s vs ≈94 s), so there is no reason to use
|
||||
it. Phase 148 fixed an earlier batch in these same suites; residual
|
||||
parallel-only flakes are recorded in `docs/01-completed-working-order.md`.
|
||||
|
||||
**Do not debug these before re-running serially.** If a failure is suspected to
|
||||
be real, the cheap discriminator is a clean-tree baseline: `git worktree add
|
||||
<tmp> HEAD` and run the same command there — a failure present at HEAD is not
|
||||
yours.
|
||||
|
||||
Linux in-container runs (`docker run … swift test`) have not shown this; the
|
||||
affected suites are macOS-host-only, so CI is unaffected.
|
||||
|
||||
### IDE for Linux
|
||||
**VS Code + the official Swift extension** (`swiftlang.swift-vscode`) —
|
||||
SourceKit-LSP, LLDB, test explorer, SPM. Best-maintained non-Xcode path.
|
||||
|
||||
---
|
||||
|
||||
## 2. Remaining work — prioritized
|
||||
|
||||
Ordered by value for a *usable* Linux Lyrebird. Items 1–3 make it real; 4–8 are
|
||||
capability/coverage.
|
||||
|
||||
**Status board** (update the box when an item lands; each item's own heading
|
||||
carries the same marker):
|
||||
|
||||
| # | Item | Priority | Status |
|
||||
|---|---|---|---|
|
||||
| 3 | Linux CI lane | HIGH | ✅ done — green on BitBucket |
|
||||
| 2 | Golden DSP tests on Linux | HIGH | ✅ done — 6 goldens green in CI |
|
||||
| 1 | `ALSAAudioDriver` (live audio) | HIGH | ◑ plays on hardware; deeper checks pending |
|
||||
| 6 | DiskIn + buffer file I/O | MEDIUM | ✅ done — WavFileReader backend |
|
||||
| 4 | MIDI on Linux | MEDIUM | ⚠️ built, untested on hardware |
|
||||
| 5 | OSC on Linux | MEDIUM | ✅ done — POSIX UDP, loopback-verified |
|
||||
| 8 | SwiftOpenUI GUI spike | EXPLORATION | ✅ drag works on hardware (@State + @Observable patch); patch PR-ready |
|
||||
| 7 | CLI on musl (LineNoise) | LOW | ☐ decision |
|
||||
|
||||
### Item 1 — `ALSAAudioDriver` (live audio) — HIGH — ⚠️ BUILT, NOT YET HEARD
|
||||
**What:** A driver conforming to `AudioDriver` that opens a Linux audio device
|
||||
and calls `engine.processBlock(inputSamples:)` from a render thread.
|
||||
**Why:** Without it, Linux only does offline NRT-to-WAV. This is the capability
|
||||
that makes Linux usable.
|
||||
**Delivered:** `Sources/Lyrebird/AudioDrivers/ALSAAudioDriver.swift` — a
|
||||
blocking `snd_pcm_writei` loop on a dedicated thread, the shape the plan
|
||||
recommended (no callback re-entrancy, no ALSA async-handler restrictions,
|
||||
back-pressure straight from the device). **Full reference:
|
||||
`docs/engine/alsa-audio-driver.md`** — transport, duplex, xrun policy,
|
||||
lifecycle, and the build requirement; that document is canonical, this section
|
||||
is the plan-level summary.
|
||||
|
||||
**Do not name a driver in portable code** — call `makeDefaultAudioDriver()`
|
||||
(`AudioDrivers/DefaultAudioDriver.swift`), which resolves to `iOSAudioDriver` /
|
||||
`CoreAudioDriver` / `ALSAAudioDriver` / `OfflineDriver` from *inside* the
|
||||
module. Which drivers exist is not a function of the OS alone (a Linux build
|
||||
without libasound, or one cross-compiled from macOS, has no ALSA), so a
|
||||
consumer-side `#if` is guessing. `isLiveAudioAvailable` reports whether the
|
||||
build has any live backend at all.
|
||||
|
||||
- **Format** `SND_PCM_FORMAT_FLOAT_LE`, matching the engine's `Float` buses, so
|
||||
nothing in the path converts or dithers.
|
||||
- **Setup** via `snd_pcm_set_params` (ALSA's own convenience over the
|
||||
hw/sw-params dance), latency = `blockSize × periodsPerBuffer / sampleRate`.
|
||||
- **Duplex** when the engine asks for input channels: a capture PCM is opened
|
||||
and `snd_pcm_link`ed to playback so the two cannot drift; `linkedStreams`
|
||||
reports whether the kernel accepted the link.
|
||||
- **RT thread** marks itself via `RTThreadIdentity.markCurrentThreadAsRT()`,
|
||||
calls `enableFlushToZero()`, and requests `SCHED_FIFO` at 75 % of the policy
|
||||
range — denial is normal for an unprivileged process and is reported through
|
||||
`hasRealtimePriority` rather than failing the start.
|
||||
- **No allocation in the loop**: interleave/deinterleave staging buffers are
|
||||
raw pointers allocated in `setup(engine:)`.
|
||||
- **Xrun policy** is factored out into `ALSARecoveryAction.classify(_:)` —
|
||||
`-EINTR`/`-EAGAIN` retry, `-EPIPE`/`-ESTRPIPE` recover via `snd_pcm_recover`,
|
||||
anything else stops the loop and lands in `lastError`. The errno values are
|
||||
spelled out as Linux constants rather than taken from the host's `errno.h`,
|
||||
so the classification cannot differ per platform (`EAGAIN` is 11 on Linux, 35
|
||||
on Darwin) and the tests mean the same thing everywhere.
|
||||
|
||||
**Build requirement — libasound2-dev.** The `CALSA` system-library target
|
||||
(`Sources/CALSA/`) needs ALSA's headers. `Package.swift` adds that target only
|
||||
when the manifest is evaluated **on a Linux host**, so:
|
||||
- macOS/iOS builds never see it (verified: `swift build`/`swift test` unchanged).
|
||||
- **Cross-compiling to Linux from a Mac produces a binary with no live-audio
|
||||
driver** — the host is macOS, so `CALSA` is absent and the driver compiles
|
||||
away. Build natively on Linux to get audio out; cross-compiles remain
|
||||
offline-only.
|
||||
- A native Linux build without the package fails with
|
||||
`error: 'alsa/asoundlib.h' file not found` → `could not build C module 'CALSA'`.
|
||||
Fix: `apt-get install libasound2-dev pkg-config`, which the CI lane now does.
|
||||
Escape hatch for a box that deliberately has no audio stack:
|
||||
`LYREBIRD_DISABLE_ALSA=1 swift build` (verified — everything but the driver
|
||||
builds).
|
||||
|
||||
**Verified (headless):** 11 new tests in `LyrebirdPortableTests`, green on
|
||||
macOS and on Linux arm64 + x86_64:
|
||||
- interleave/deinterleave: frame order, missing channel → silence, short bus →
|
||||
padded, round-trip identity, extra channel dropped (all platforms — a
|
||||
transposed index here yields channel-swapped audio, not an error, which is
|
||||
exactly what nobody notices on a headless box);
|
||||
- `ALSARecoveryAction` classification of every branch (all platforms);
|
||||
- Linux-only: `start()` before `setup` throws `.notConfigured`; an unopenable
|
||||
device throws `.playbackDeviceOpenFailed` and leaves `lastError` clear;
|
||||
repeated/early `stop()` is safe; defaults and `suggestedControlBlockSize`.
|
||||
These also serve as the guard that the driver is actually *in* the build — if
|
||||
the `CALSA` dependency ever stops resolving, the whole file compiles away to
|
||||
nothing and every other test would still pass.
|
||||
|
||||
**Acceptance — basic playback CONFIRMED on hardware.** On an Ubuntu 24.04 arm64
|
||||
Parallels VM (2026-08-21), the `quickstart` template played its 10-second sine to
|
||||
the speakers via `makeDefaultAudioDriver()` → `ALSAAudioDriver`. The driver moves
|
||||
a real speaker — the headline capability is proven. Still to exercise on hardware:
|
||||
1. ~~sine to speakers~~ ✅ (confirmed at the template default rate; still worth a
|
||||
pass at both 44.1 and 48 kHz and a couple of block sizes);
|
||||
2. xrun recovery under load (the `-EPIPE` path is written but never taken);
|
||||
3. duplex: confirm `snd_pcm_link` succeeds on a real duplex device and that
|
||||
input reaches the engine;
|
||||
4. `SCHED_FIFO` grant under a `limits.conf`-configured user;
|
||||
5. latency sanity vs `periodsPerBuffer`.
|
||||
Basic output is no longer unproven; the robustness checks (2–5) remain open.
|
||||
|
||||
**Follow-ups, deliberately not done here:**
|
||||
- **PipeWire backend.** ALSA-through-PipeWire's compat layer works, but a native
|
||||
PipeWire driver is the better long-term desktop path. `AudioDriver` is the
|
||||
seam; nothing in this driver blocks it.
|
||||
- ~~**Scaffolder templates emit `CoreAudioDriver()`**~~ ✅ **done** — the CLI
|
||||
templates (`quickstart`, `basic`, `demo`) now emit
|
||||
`makeDefaultAudioDriver()`. The first attempt emitted the
|
||||
`#if canImport(AudioToolbox)` switch in the *generated* source; review caught
|
||||
that this breaks exactly where it matters — Windows, a cross-compiled Linux
|
||||
build, and `LYREBIRD_DISABLE_ALSA=1` all lack `ALSAAudioDriver`, so the
|
||||
emitted `#else` would not compile. Hence the library-side factory. The
|
||||
`ui-demo` and Xcode templates keep `CoreAudioDriver` deliberately: they import
|
||||
AppKit / are Xcode projects, so they are Apple-only by construction.
|
||||
Also fixed here: the `nrt` and `score` templates emitted `printError(...)`, a
|
||||
helper that exists only inside the `LyrebirdCLI` target, so **every
|
||||
scaffolded `nrt`/`score` project failed to compile** — a regression from the
|
||||
earlier stderr port on this branch. They now emit a self-contained
|
||||
`FileHandle`-based helper. All five CLI templates are verified by scaffolding
|
||||
and **building** them in the Linux container, not by string inspection.
|
||||
|
||||
### Item 2 — Golden-value DSP tests that run on Linux — HIGH — ✅ DONE
|
||||
**What:** Tests asserting concrete numeric output of the portable FFT/biquad
|
||||
**through the real generators**, runnable off Apple.
|
||||
**Why:** `Tests/LyrebirdDSPTests/ScalarDSPParityTests.swift` compares to *real
|
||||
vDSP* and is therefore `#if canImport(Accelerate)` — **Apple-only**. Nothing
|
||||
verified that the portable DSP produces correct *audio* on Linux; a packing or
|
||||
scaling bug in the portable FFT would have shipped silently.
|
||||
**Delivered:** a new platform-neutral test target `LyrebirdPortableTests`
|
||||
(`Tests/LyrebirdPortableTests/`, in the main `targets:` array so a Linux host
|
||||
sees it) holding **6 golden-value tests**, no `#if` guards anywhere:
|
||||
|
||||
| Test | Portable code it pins |
|
||||
|---|---|
|
||||
| `butterworthLowPassOrder4ImpulseResponse` | `vDSP_biquadD` opaque-setup cascade (`PortableBiquad.swift`) |
|
||||
| `butterworthHighPassOrder2ImpulseResponse` | same, different coefficient path |
|
||||
| `klankImpulseResponse` | vector kernel — `vsmulD` / `vmulD` / **`vsubD`** / `sveD` |
|
||||
| `resonatorBankImpulseResponse` | same kernel, `(freq, decay, amp)` spec order |
|
||||
| `analysisMagnitudeSpectrumOfBinCentredSine` | forward `vDSP_fft_zrip` + `ctoz` packing and real-FFT scaling |
|
||||
| `resynthesisReconstructsInputSine` | inverse FFT + windowed overlap-add round trip |
|
||||
|
||||
Goldens were captured on macOS (arm64, vDSP-backed) and are compared with a
|
||||
`absolute + relative × |golden|` tolerance — `1e-9` for the double-precision
|
||||
filter responses, `1e-5` for the `Float`-internal spectral paths.
|
||||
`Tests/LyrebirdPortableTests/PortableTestSupport.swift` holds the local
|
||||
engine/collect helpers (test targets cannot share sources) and deliberately uses
|
||||
only the public + `@_spi(LyrebirdExtensions)` surface.
|
||||
|
||||
**Both directions of the check were verified** (a golden test that cannot fail is
|
||||
worse than none):
|
||||
- swapping `vDSP_vsubD`'s operands in `AccelerateShim.swift` → Klank and
|
||||
ResonatorBank fail on Linux with diffs of `1e7`+ (the classic vDSP
|
||||
reversed-operand bug, caught).
|
||||
- swapping real/imag in `vDSP_ctoz` (`PortableFFT.swift`) → both spectral tests
|
||||
fail with diffs of ~0.29 on a unit-amplitude sine.
|
||||
Each sabotage was reverted immediately after the run.
|
||||
|
||||
**Verified green:** macOS (`swift test --no-parallel`, vDSP path — see the
|
||||
serial-run note above) and Linux in-container on
|
||||
both architectures — `docker run --rm [--platform linux/amd64] -v "$PWD":/pkg
|
||||
-w /pkg swift:6.3.3 swift test` — so the CI lane (Item 3, x86_64 runners) runs
|
||||
them on every push with no config change; only the explanatory comment in
|
||||
`bitbucket-pipelines.yml` was updated.
|
||||
|
||||
**Regenerating a golden** (only after establishing the change was intended —
|
||||
unexplained drift is the bug this target exists to catch): run the same graph on
|
||||
macOS and print each sample with `String(format: "%+.15e")`.
|
||||
|
||||
**Not done here (deliberate):** the ~165 files of `LyrebirdTests` are still
|
||||
macOS-host-only. Most are platform-neutral and could migrate to
|
||||
`LyrebirdPortableTests` over time, which would widen Linux coverage well beyond
|
||||
DSP; that is bulk mechanical work, independent of this item, and best done in
|
||||
slices rather than as one move.
|
||||
|
||||
### Item 3 — Linux CI lane — HIGH — ✅ DONE
|
||||
**What:** CI building + testing on Linux.
|
||||
**Why:** Locks in the port so a main-merge can't silently regress it (see the
|
||||
standing-maintenance hazard). CI is also the only place tests actually *run* on
|
||||
Linux without a local Linux box.
|
||||
**Delivered:** `bitbucket-pipelines.yml` (the repo remote is BitBucket, not
|
||||
GitHub) using the official `swift:6.3.3` image. `size: 2x` (8 GB). Builds
|
||||
`LyrebirdSynth` / `LyrebirdGraphDSL` / `LyrebirdCLI`, then `swift test` runs
|
||||
every target the Linux manifest exposes: **LyrebirdDSPTests, LyrebirdGraphDSLTests,
|
||||
LyrebirdCLITests — 239 tests, all green** natively in-container.
|
||||
**Verified locally** in the same image via Docker Desktop (arm64):
|
||||
`docker run --rm -v "$PWD":/pkg -w /pkg swift:6.3.3 swift test`.
|
||||
|
||||
Supporting changes made to get here:
|
||||
- **Manifest split** (`Package.swift`): the Apple-only targets — `LyrebirdUI`,
|
||||
`LyrebirdUITests`, `LyrebirdTests` (imports `AudioToolbox` directly in some
|
||||
files), and `LyrebirdBenchmark` (micro-benchmarks vDSP) — are appended under
|
||||
`#if os(macOS)` *after* the `Package(...)` initializer (an `#if` cannot be an
|
||||
array element in a manifest). On a Linux/Windows host they are simply absent,
|
||||
so `swift test` compiles only the portable surface. macOS/iOS builds see every
|
||||
target unchanged; the two remaining test targets' `AudioToolbox`/`Accelerate`
|
||||
links are now `.when(platforms: [.macOS, .iOS])`.
|
||||
- **Core `stderr` fix**: a `git merge main` had landed
|
||||
`fputs(..., stderr)` in `Score/ScoreElementDSL.swift`, which fails Swift 6
|
||||
concurrency checking on Linux — the exact standing-maintenance hazard. Added
|
||||
`Utilities/StandardError.swift` (`lyrebirdPrintError(_:)`, `FileHandle`-based)
|
||||
and routed the call through it. Grep guard added to the maintenance list above.
|
||||
|
||||
**Registry compile-memory (resolved):** the generated
|
||||
`Sources/LyrebirdGraphDSL/Generated/GeneratedDSLRegistry.swift` used to be one
|
||||
~300-element array literal; the type-checker checked it as a single expression and
|
||||
needed several GB, so two concurrent heavy compiles OOM-killed the compiler on an
|
||||
8 GB runner. Fixed in `Tools/DSLRegistryGen`: `emitRegistry` now emits the entries
|
||||
as fixed-size (`registryChunkSize = 32`) `private static let _chunkN` arrays
|
||||
concatenated into `generated`, so each chunk type-checks independently. Verified
|
||||
building at full parallelism on Linux from a clean scratch — no OOM — so CI runs
|
||||
default `-j` (no cap). Regenerate with `bash scripts/generate-dsl-registry.sh`
|
||||
after changing a public generator init; the `--check` drift guard stays green.
|
||||
|
||||
**Acceptance:** green CI on push to the branch — Pipelines is enabled on the
|
||||
BitBucket repo.
|
||||
|
||||
### Item 4 — MIDI on Linux — MEDIUM — ⚠️ BUILT, NOT YET RECEIVED FROM HARDWARE
|
||||
**What:** `Sources/Lyrebird/MIDI/` was `#if canImport(CoreMIDI)`-guarded out, so
|
||||
there was no MIDI in/out on Linux.
|
||||
**Delivered:** an ALSA-sequencer backend behind the same `MIDI` public API as the
|
||||
CoreMIDI one.
|
||||
- **Shared, tested mapping.** `MIDI/ALSASeqMIDIEvent.swift` — a pure enum +
|
||||
`midiMessage(for:)` that turns a decoded seq event into a `MIDIMessage`,
|
||||
routing channel-voice events through the existing
|
||||
`MIDIMessage.from(status:data1:data2:)` so Linux applies the identical parsing
|
||||
(note-on velocity 0 → note-off, the pitch-bend offset) the CoreMIDI path does.
|
||||
Pure Swift, no ALSA import, so it is unit-tested on **both** platforms
|
||||
(`ALSASeqMIDIEventTests`, 8 tests).
|
||||
- **The backend.** `MIDI/ALSAMIDI.swift`, guarded
|
||||
`#if !canImport(CoreMIDI) && canImport(CALSA)`, defines `MIDI` for native
|
||||
Linux: `snd_seq_open`, in/out simple ports, source enumeration
|
||||
(`snd_seq_query_next_client/port`), auto-subscribe to readable sources, a
|
||||
`poll()`-based input thread (200 ms cadence so `stop()` is responsive) that
|
||||
decodes events via the shared mapping and dispatches on the `lyrebird.midi`
|
||||
queue, and `send` / `sendVirtual` building seq events from `MIDIMessage`.
|
||||
The handler registry, dispatch contract, and lifecycle discipline mirror the
|
||||
CoreMIDI class; the two definitions are mutually exclusive so exactly one
|
||||
`MIDI` compiles per platform.
|
||||
- `MIDISource` / `MIDIDestination` are now cross-platform: `endpointRef` on
|
||||
Apple, ALSA `client:port` off Apple. `MIDIError` gained `Equatable` and its
|
||||
`OSStatus`-carrying cases double as ALSA return-code carriers (`OSStatus` is
|
||||
`Int32` off Apple). `MIDIMessage` / `+UMP` / `MIDIHandlerToken` were already
|
||||
neutral.
|
||||
|
||||
**Availability:** like `ALSAAudioDriver`, `MIDI` exists on Linux only where
|
||||
CALSA is linked — absent under `LYREBIRD_DISABLE_ALSA=1` or a cross-compile from
|
||||
macOS. Consumers that need MIDI everywhere must guard accordingly.
|
||||
|
||||
**Verified (headless):** `ALSAMIDITests` (Linux-only) — handler registry, the
|
||||
not-started send/create guards, safe repeated stop, empty pre-start
|
||||
enumeration, and a tolerant start/stop that accepts either a real open or a
|
||||
clean `clientCreateFailed` when `/dev/snd/seq` is absent (the container case),
|
||||
checking a failed start does not latch `isStarted`. macOS
|
||||
`swift test --no-parallel` 5714/5714; Linux arm64 302 / x86_64 302;
|
||||
`LYREBIRD_DISABLE_ALSA=1` 289.
|
||||
|
||||
**Acceptance NOT met — no controller has been received from.** The container has
|
||||
no sequencer device, so the poll loop, event decode from a live controller,
|
||||
subscription, and `send` to real hardware have never run. Outstanding on a Linux
|
||||
box with ALSA + a connected controller:
|
||||
1. receive note-on / note-off / CC / pitch-bend / program-change from a
|
||||
controller and confirm the decoded `MIDIMessage`;
|
||||
2. `send` to a hardware synth and hear it;
|
||||
3. `createVirtualInput` / `createVirtualOutput` visible to other clients
|
||||
(`aconnect -l`) and round-trip;
|
||||
4. hot-plug: a controller connected after `start()` appears (the poll loop does
|
||||
not currently re-enumerate — see below).
|
||||
|
||||
**Known limitations / follow-ups:**
|
||||
- **No hot-plug re-enumeration.** CoreMIDI's `MIDIClientCreateWithBlock`
|
||||
notification re-runs `_refreshEndpoints` / `_connectAllSources`; the ALSA
|
||||
backend enumerates and subscribes once at `start()`. A device connected later
|
||||
is not auto-subscribed. ALSA exposes this via the System announce port
|
||||
(subscribe to client 0 port 1 and handle `SND_SEQ_EVENT_PORT_START`); left as
|
||||
a follow-up.
|
||||
- **UMP / MIDI 2.0.** The CoreMIDI path sends MIDI 1.0 over the UMP API; the
|
||||
ALSA path is MIDI 1.0 via legacy seq events. Functionally equivalent for the
|
||||
`MIDIMessage` set; a native UMP seq path is not implemented.
|
||||
|
||||
### Item 5 — OSC on Linux — MEDIUM — ✅ DONE
|
||||
**What:** `OSCClient` / `OSCServer` used Apple's `Network.framework`
|
||||
(`NWConnection` / `NWListener`), guarded out on Linux.
|
||||
**Delivered:** POSIX BSD-socket transports under `#else`, no dependencies. The
|
||||
OSC 1.0 codec (`OSCArgument` / `OSCCodec` / `OSCMessage`) was already portable;
|
||||
only the transport was swapped, and the handler registry / decode+dispatch is
|
||||
now shared code rather than living inside the `Network` guard.
|
||||
- `OSCClient`: a connected UDP socket (`getaddrinfo` → `socket` → `connect`),
|
||||
opened lazily on the first send on the serial `sendQueue`, reused after. A
|
||||
resolution/connect failure is latched so a bad host does not re-resolve every
|
||||
send. `sendto` with a nil destination avoids the name clash with the class's
|
||||
own `send`.
|
||||
- `OSCServer`: `socket` + `SO_REUSEADDR` + `bind` to `INADDR_ANY:port`, then a
|
||||
dedicated receive thread running a `poll()` loop (200 ms cadence) that
|
||||
`recv`s datagrams and hands them to the shared decode+dispatch. `stop()`
|
||||
shuts the socket down (unblocking any wait), clears the run flag, joins, and
|
||||
closes — the same discipline as the ALSA backends. New `OSCServerError`
|
||||
(`socketFailed` / `bindFailed`, carrying `errno`) is thrown off Apple; on
|
||||
Apple `NWListener` throws its own error. `OSCHandlerToken` moved out of the
|
||||
`Network` guard so it exists on both platforms.
|
||||
|
||||
**Acceptance MET — verified over real loopback, on both platforms.** Unlike the
|
||||
ALSA MIDI and audio backends, OSC needs no hardware: `OSCLoopbackTests`
|
||||
(`Tests/LyrebirdPortableTests`) binds an `OSCServer` on 127.0.0.1 and sends to it
|
||||
with `OSCClient`, asserting a full argument round trip, glob-pattern address
|
||||
matching, that a removed handler stops receiving, and safe idempotent stop. It
|
||||
exercises `Network.framework` on macOS and the POSIX transport on Linux, and
|
||||
passes on both — including **Linux without ALSA** (OSC is pure POSIX, so it does
|
||||
not depend on CALSA and runs under `LYREBIRD_DISABLE_ALSA=1`). macOS
|
||||
`swift test --no-parallel` 5718/5718; Linux arm64 306 / x86_64 306;
|
||||
`LYREBIRD_DISABLE_ALSA=1` 293.
|
||||
|
||||
### Item 6 — DiskIn + LyrebirdBuffer file I/O on Linux — MEDIUM — ✅ DONE
|
||||
**What:** `Generators/BufferIO/DiskIn.swift` and `Buffers/LyrebirdBufferFileIO.swift`
|
||||
were fully `#if canImport(AudioToolbox)`-guarded (no portable fallback), so
|
||||
soundfile-into-buffer loads and disk streaming did not exist off Apple.
|
||||
**Delivered:** portable `#else` branches on the `WavFileReader` /
|
||||
`WavFileWriter` backend, mirroring `DiskOut` / `NRTDriver`:
|
||||
- `LyrebirdBuffer.load` / `loadAllChannels` / `fill` read WAV via
|
||||
`WavFileReader`; the chunked read + channel-extract + optional peak
|
||||
normalisation is replicated in two portable helpers
|
||||
(`portableReadMono` / `portableReadAllChannels`). `channelOutOfRange` /
|
||||
`invalidChannelCount` stay cross-platform; open/read failures surface as
|
||||
`WavFileError` (matching the documented `NRTDriver` decision, rather than
|
||||
wrapping).
|
||||
- `LyrebirdBuffer.write` gains a `WavFileWriter` branch (RF64 already went
|
||||
through the portable `RF64Writer` on both platforms); the Apple-only
|
||||
containers throw a new `LyrebirdBufferIOError.unsupportedFormatOnPlatform`.
|
||||
- `DiskIn.Audio` streams via `WavFileReader`, reopening the file to loop (the
|
||||
reader is forward-only). **Sample-rate handling:** `ExtAudioFile` resamples
|
||||
to the engine rate transparently; the portable reader hands back the file's
|
||||
native frames, so `DiskIn` folds `fileSampleRate / engineSampleRate` into the
|
||||
read-position advance (`_readRateScale`, `1.0` on Apple) — a 44.1 kHz file on
|
||||
a 48 kHz engine plays at the right speed and pitch via the existing linear
|
||||
interpolation. The buffer-load paths do **not** resample on either platform
|
||||
(they keep the file's own rate), so no scale is needed there.
|
||||
- `LyrebirdBufferIOError` split: the `OSStatus` cases are Apple-only; the
|
||||
semantic cases (`channelOutOfRange`, `invalidChannelCount`,
|
||||
`fileTooLargeForContainer`) are cross-platform; `unsupportedFormatOnPlatform`
|
||||
is added off Apple. `DiskInError` stays Apple-only — the portable `DiskIn`
|
||||
throws `WavFileError`.
|
||||
|
||||
**Verified:** new `Tests/LyrebirdPortableTests/PortableFileIOTests.swift` —
|
||||
mono/stereo load round trips, channel select, `channelOutOfRange`, fill
|
||||
truncate + zero-pad, peak normalisation, int16 write→load round trip, DiskIn
|
||||
sample-accurate streaming at matching rate, and (off-Apple only) DiskIn
|
||||
sample-rate-ratio folding + `write` to a CAF throwing
|
||||
`unsupportedFormatOnPlatform`. Fixtures are written with `WavFileWriter`, so the
|
||||
suite runs on both platforms; on Apple the same paths exercise `ExtAudioFile`
|
||||
and a round trip that agrees on both is the guarantee. macOS
|
||||
`swift test --no-parallel` 5706/5706; Linux arm64 + x86_64 289/289;
|
||||
`LYREBIRD_DISABLE_ALSA=1` 281/281.
|
||||
|
||||
**One test is portable-only by nature:** the SR-ratio DiskIn test is
|
||||
`#if !canImport(AudioToolbox)`, because on Apple `ExtAudioFile` does the
|
||||
conversion inside `DiskIn` (advancing at rate 1) and the exact file-frame
|
||||
mapping the test asserts only holds for the portable read-position scaling.
|
||||
|
||||
### Item 7 — CLI on musl (LineNoise) — LOW / decision
|
||||
**What:** `LyrebirdCLI` builds on glibc but not musl — the `LineNoise`
|
||||
dependency does `import Glibc` with no `Musl` support.
|
||||
**Why / decision:** glibc is the standard Linux target, so this is optional.
|
||||
Options: (a) accept CLI = glibc-only (recommended); (b) fork/patch LineNoise for
|
||||
`Musl`; (c) swap the line-editing dependency. Document the choice; don't spend
|
||||
effort unless a static-musl CLI binary is specifically wanted.
|
||||
|
||||
### Item 8 — GUI spike: **SwiftOpenUI** for `LyrebirdUI` on Linux — EXPLORATION
|
||||
**What:** Evaluate `codelynx/SwiftOpenUI` (MIT) as the path to run `LyrebirdUI`
|
||||
on Linux. It is a SwiftUI-API reimplementation: **on macOS it imports real
|
||||
SwiftUI**; on Linux it renders via **GTK4** (needs `libgtk-4-dev`) — the same
|
||||
"real API on Apple / portable backend elsewhere" pattern Lyrebird already uses
|
||||
for `LyrebirdDSP`.
|
||||
**Why it looks reasonable:** its coverage matches what `LyrebirdUI` actually
|
||||
needs — `Canvas`/`Path`/`Circle`/`Rectangle` (the knobs, scope, and envelope
|
||||
views are custom-drawn), drag/tap gestures (the XY pad), and the
|
||||
`@State`/`@Binding` wrappers that `@UIParam` builds on. MIT-licensed.
|
||||
**Risks / unknowns (why it's a spike, not a commitment):**
|
||||
- Maturity is modest (~31 stars, effectively one author) — bus-factor risk; the
|
||||
"Stable" self-label is optimistic. SwiftUI reimplementations always have edge
|
||||
gaps.
|
||||
- Lyrebird's AppKit `NSEvent` mouse monitor (`MouseInputBridge`, installed via
|
||||
`MouseInput.install(_:)`) is Apple-only — a GTK input path is needed for the
|
||||
mouse-driven generators.
|
||||
- `@UIParam` (`Sources/LyrebirdUI/`) + `ParameterKnob`/`Slider`/`XY`/scope/
|
||||
envelope views must actually compile + render against SwiftOpenUI's surface.
|
||||
**Compile-probe done (container, no display) — the hard 20% answered.**
|
||||
`codelynx/SwiftOpenUI` (`develop` @ 8100d9c, MIT). Modules `SwiftOpenUI` +
|
||||
`BackendGTK4` (a `.systemLibrary` on `libgtk-4-dev`). Built the framework **and a
|
||||
LyrebirdUI-style Canvas knob** in a GTK4 container (`swift:6.3.3` + `libgtk-4-dev`):
|
||||
SwiftOpenUI + BackendGTK4 compile on Linux, and the knob (custom drawing +
|
||||
`@Observable` model + drag) compiles. What the probe found:
|
||||
|
||||
- **`GraphicsContext` is NOT provided — this is the shim.** SwiftOpenUI's
|
||||
`Canvas(renderer: { ctx, size in … })` hands back a **Cairo-backed
|
||||
`DrawingContext`** (`setColor` / `moveTo` / `lineTo` / `arc` / `stroke()` /
|
||||
`fill()`), not SwiftUI's `GraphicsContext`. So every LyrebirdUI custom-drawn
|
||||
view — `ParameterKnob`, `LyrebirdScopeView`, `LyrebirdEnvelopeView`,
|
||||
`LyrebirdSpectrumView`, `LyrebirdScatterView` (the 9 `Canvas` + 6
|
||||
`GraphicsContext` call sites) — needs its drawing body **rewritten** from
|
||||
`GraphicsContext.fill/stroke/draw` to `DrawingContext`. The rewrite is
|
||||
mechanical (both are imperative 2-D drawing) and was proven to compile, but it
|
||||
is per-view work, not a drop-in.
|
||||
- **`@Observable` works on Linux (stdlib `Observation`), but SwiftOpenUI does not
|
||||
re-export it** — a consumer must add `import Observation` explicitly (real
|
||||
SwiftUI re-exports it). SwiftOpenUI's `DependencyTracking` claims
|
||||
`@Observable`-driven rebuilds, so `@UIParam`'s backing model should drive
|
||||
re-renders — but that is runtime behavior still to confirm on a display.
|
||||
- **Gestures fit.** `.onDrag { (d: DragGestureValue) in … }` carries
|
||||
`translation`, which is what the knob/XY drags need; the closure shape differs
|
||||
from SwiftUI's `DragGesture().onChanged`, so a light rewrite.
|
||||
- Declarative controls (`Slider`, `Button`, `Text`, `VStack`/`HStack`) and the
|
||||
`@State`/`@Observable` binding port with light friction.
|
||||
|
||||
**Update 10 — RESUME with fork patches (2026-09-05).** Re-verified upstream
|
||||
`develop @ 8100d9c` still has the observation→full-rebuild→gesture-teardown
|
||||
(`GTKViewHost.rebuild()` still gates the narrow path on `!fromObservation`); no
|
||||
`@GestureState`, no gesture-identity reconciliation. Confirmed the blocker lives
|
||||
in the GTK4 render/gesture layer, **below** the state wrappers — so no
|
||||
`@State`/`@Binding`/`@Observable` choice routes around it (the single-control
|
||||
`@State` "success" is an artifact of Problem 1's idle-starvation masking Problem
|
||||
2). Decision: **keep the SwiftUI path for the Linux pre-release** and fix it in
|
||||
the fork. Two patches planned (B: live redraw via high-priority `queue_draw`
|
||||
during drag; C: reuse the existing `beginInteractiveUpdate`/`endInteractiveUpdate`
|
||||
deferral so no rebuild recreates the gesture mid-drag). Full plan, fork-commit
|
||||
strategy, and validation: **`spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md`**.
|
||||
Patches are the next work session.
|
||||
|
||||
**Update 9 — INTERACTIVE-UI BLOCKER (hardware, 2026-08-22). All 8 views build
|
||||
and the timer-driven ones work; live drag interaction does NOT.** On-hardware
|
||||
testing of the full demo found two distinct SwiftOpenUI GTK4-backend problems,
|
||||
both root-caused from the pinned fork source. Both are BEYOND the drag-observable
|
||||
patch already submitted upstream (that patch fixed single-control gesture
|
||||
*streaming*, which does work — see below).
|
||||
|
||||
What works on hardware: the scope animates, the CPU meters update, audio tracks
|
||||
live (dragging a knob changes the sound continuously). What fails: the *visual*
|
||||
of interactive controls.
|
||||
|
||||
Bisected with `LYREBIRD_DEMO={knob,controls,full}` (diagnostic scaffolding in
|
||||
`Sources/LyrebirdUILinuxDemo/`, commit 22dd5b6a — kept until this is resolved):
|
||||
- `knob` (one knob): gesture STREAMS (sound tracks continuously), but the knob
|
||||
Canvas only redraws on mouse-UP.
|
||||
- `controls` (all controls, no animated views): knob/XY drop back to one tick per
|
||||
gesture; native slider moves but its sound update only lands on mouse-up.
|
||||
- `full`: scope animates; every interactive control is one-tick.
|
||||
|
||||
Root causes (in `.build-*/checkouts/SwiftOpenUI/Sources/Backend/GTK4/Rendering/`):
|
||||
1. **Idle-starved redraw (Problem 1).** `GTKViewHost.scheduleRebuild` schedules
|
||||
the redraw with plain `g_idle_add` (default idle priority). During a continuous
|
||||
drag, higher-priority pointer-motion events saturate the GLib loop and starve
|
||||
the idle rebuild, so the Canvas only redraws when motion stops (release). Audio
|
||||
is unaffected because `node.update(_:)` runs directly in the `onChanged`
|
||||
closure, not via a rebuild. Fix direction: high-priority `gtk_widget_queue_draw`
|
||||
on the Canvas during drag, not an idle-scheduled full-tree rebuild.
|
||||
2. **Drag-gesture teardown under sibling rebuilds (Problem 2).** With several
|
||||
controls bound to one node, a drag triggers a mid-drag rebuild that recreates
|
||||
the dragged Canvas widget → the `GtkGestureDrag` detaches → one tick. The
|
||||
single-control case only survives because its rebuild is idle-starved (so the
|
||||
widget is never recreated during the drag). Fix direction: reconcile the drag-
|
||||
gesture widget by IDENTITY so it survives rebuilds — exactly the preferred fix
|
||||
in `spikes/SwiftOpenUIKnob/UPSTREAM_ISSUE.md`, and the drop-target code
|
||||
(`GTKDropState` widget-pinning) is the in-repo precedent.
|
||||
|
||||
Decision (2026-08-22): PAUSE the interactive-UI push and gauge the SwiftOpenUI
|
||||
maintainer's responsiveness on the submitted PR first. If it is accepted → dig
|
||||
into Problems 1 & 2 (extend the issue/PR). If rejected with rationale → iterate.
|
||||
If it goes stale → reconsider the Linux UI approach (swift-cross-ui, or a thinner
|
||||
GTK layer). Not blocking anything else on the branch — the headless core, audio,
|
||||
scope/CPU readouts, and static views are all fine; only live *dragging* is
|
||||
affected. Investigation cost is already paid and captured here, so resuming does
|
||||
not require re-bisecting.
|
||||
|
||||
**Update 8 — control + visualization set ported.** All eight `LyrebirdUI`
|
||||
controls/views now have `Linux*` counterparts in `LyrebirdUILinux`:
|
||||
`LinuxParameterKnob` / `Slider` / `Label` / `Button` / `XY` (controls) and
|
||||
`LinuxScopeView` / `LinuxEnvelopeView` / `LinuxStatusView` (visualization). The
|
||||
animated views (scope, CPU status) use an `@Observable` model polled by a
|
||||
Foundation `Timer` on `RunLoop.main` (pumped by the GTK4 backend), NOT
|
||||
SwiftOpenUI's off-main `.task`. See Update 9 for the interaction blocker found
|
||||
when these were tested together on hardware.
|
||||
|
||||
**Update 7 — symmetric import shape + runnable demo.** Two ergonomics changes
|
||||
so friends can clone and run:
|
||||
- **Re-export shims** give both platforms one import shape. `LyrebirdUILinux`
|
||||
gets `LinuxUIExports.swift` (`@_exported import SwiftOpenUI` +
|
||||
`@_exported import BackendGTK4`); the macOS `LyrebirdUI` gets
|
||||
`LyrebirdUIExports.swift` (`@_exported import SwiftUI`). Downstream code is
|
||||
then `import LyrebirdSynth` + one `#if canImport(LyrebirdUI)` selecting
|
||||
`LyrebirdUI` (Apple) vs `LyrebirdUILinux` (Linux); body code beneath is
|
||||
identical because both bind the same core `@UIParam`/`UIParamNode`. In-repo
|
||||
precedent for `@_exported`: `Sources/LyrebirdDSP/AccelerateShim.swift`.
|
||||
- **Runnable demo** — new `LyrebirdUILinuxDemo` executable target (opt-in, same
|
||||
`LYREBIRD_ENABLE_LINUX_UI=1` gate): `KnobDemoSynth` (`@UIParam`
|
||||
frequency/amplitude sine → `Pan2`), `KnobDemoView` (two `LinuxParameterKnob`s),
|
||||
and a `main.swift` that starts the engine on `makeDefaultAudioDriver()` (ALSA
|
||||
if present, else silent Offline) then runs the GTK4 loop. Run with
|
||||
`LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo`. Turn the freq knob,
|
||||
hear the pitch track (needs a live ALSA device; GUI works regardless).
|
||||
|
||||
**Next steps (full cross-platform `LyrebirdUI` merge — deferred).** The symmetric
|
||||
shape above still keeps two module names. A *true* single unconditional
|
||||
`import LyrebirdUI` on both platforms needs the modules merged:
|
||||
1. Make the `LyrebirdUI` target cross-platform: build on Linux too, with internal
|
||||
`#if canImport(SwiftUI)` (Apple) / `#else` SwiftOpenUI (Linux) branches per
|
||||
control, and depend on SwiftOpenUI + BackendGTK4 on Linux only.
|
||||
2. Port the *remaining* controls. Done so far: `ParameterKnob`, `ParameterSlider`,
|
||||
`ParameterButton`, `ParameterLabel`, `ParameterXY`, `LyrebirdScopeView`,
|
||||
`LyrebirdEnvelopeView`, and `LyrebirdStatusView` (CPU meters) — all as `Linux*`
|
||||
in `LyrebirdUILinux`. The core control + visualization set is now ported.
|
||||
Deferred by choice: the large `LyrebirdEngineStatusView` (601 lines — a
|
||||
composite of start/stop + counts + a gain slider + a mute toggle + CPU, mostly
|
||||
duplicating already-ported controls) and the node-tree / message-banner /
|
||||
running-processes diagnostic views; port those only if the friends round wants
|
||||
them. NOTES: (a) the scope introduced the periodic-redraw
|
||||
pattern for animated viz views — an `@Observable` model polled by a Foundation
|
||||
`Timer` on `RunLoop.main` (which the GTK4 backend pumps ~every 5 ms), NOT
|
||||
SwiftOpenUI's `.task` (whose closure runs off-main and would race the
|
||||
observation registrar); its 30 Hz redraw is compile-verified but still needs
|
||||
on-hardware confirmation. (b) The envelope is static (draws once, no timer).
|
||||
`DrawingContext` has no text drawing, so the envelope's "L"/"R" marker letters
|
||||
are omitted (dashed green/orange lines still mark loop/release) — the status
|
||||
views likely need text, so plan on real `Text` views over/around a `Canvas`
|
||||
rather than text inside it.
|
||||
3. Fold `LyrebirdUILinux` + `LyrebirdUILinuxDemo` back into `LyrebirdUI` /
|
||||
a shared demo; retire the separate module.
|
||||
4. Gate the whole thing on the SwiftOpenUI dep being available (fork now,
|
||||
upstream + tag later). Larger review surface — its own branch.
|
||||
Do this only after the fork→upstream switch settles, so the merged module isn't
|
||||
pinned to a personal fork.
|
||||
|
||||
**Update 6 — shared parameter model moved to core.** The SwiftUI-free
|
||||
`@UIParam` property wrapper and its `@Observable` `UIParamNode` backing object
|
||||
moved from the macOS-only `LyrebirdUI` module into core `LyrebirdSynth`
|
||||
(`Sources/Lyrebird/Parameters/`). Neither imports SwiftUI — only `Observation`
|
||||
(stdlib, Linux-OK) — so nothing platform-gates them. `LinuxParameterKnob` now
|
||||
binds a real `UIParamNode` (via a synthesizer's `@UIParam` projected value
|
||||
`synth.$paramName`) with a value `range`, exactly as the macOS `ParameterKnob`
|
||||
does — one parameter model drives both platforms. Because `UIParamNode` is
|
||||
`@Observable`, `node.update(_:)` from a drag takes the GTK4 backend's narrow
|
||||
redraw path (the fork fix), so the gesture survives. The `UIParamTests` suite
|
||||
moved to `LyrebirdPortableTests` so Linux exercises it too. The placeholder
|
||||
`LinuxKnobModel` is gone. No macOS API broke: every real `@UIParam` consumer
|
||||
already imports `LyrebirdSynth`. Remaining: switch the SwiftOpenUI dep to
|
||||
upstream `codelynx/SwiftOpenUI` + a tagged release once the PR lands.
|
||||
|
||||
**Update 5 — `LyrebirdUILinux` target scaffolded (depends on the fork).** An
|
||||
opt-in Linux UI target now lives in the main package: build with
|
||||
`LYREBIRD_ENABLE_LINUX_UI=1` on a Linux host with `libgtk-4-dev`. It depends on
|
||||
the personal fork `github.com/joshpar/SwiftOpenUI` pinned to commit `1ac66079`
|
||||
(the drag fix), plus `BackendGTK4`, and holds the first ported control —
|
||||
`LinuxParameterKnob` (Canvas/`DrawingContext` + `.onDrag`, `@Observable`-backed).
|
||||
Gated so the **default** Linux build/CI stays lean and fork-free (verified: a
|
||||
flag-off resolve fetches no fork). macOS/iOS builds never see the target.
|
||||
Caveats: (1) SwiftPM writes `Package.resolved` at the package root regardless of
|
||||
`--scratch-path`, so a flagged build adds the fork pin locally — **do not commit
|
||||
a fork-polluted `Package.resolved`** (the committed one stays fork-free). (2) The
|
||||
control binds to a local `@Observable`; the shared-model step — moving the
|
||||
SwiftUI-free `@UIParam` / `UIParamNode` from the macOS-only `LyrebirdUI` module
|
||||
into core `LyrebirdSynth` so macOS and Linux UIs share one parameter model — is
|
||||
the next reviewed change. Switch the dep to upstream `codelynx/SwiftOpenUI` + a
|
||||
tagged release once the PR lands.
|
||||
|
||||
**Update 4 — `@Observable` PATCH CONFIRMED on hardware (2026-08-21).** With
|
||||
`swiftopenui-drag-observable.patch` applied to a fork, the `@Observable` knob
|
||||
(`spikes/SwiftOpenUIKnobObservable/`) tracks the drag continuously — so
|
||||
`@UIParam` (which is `@Observable`-backed) can drive a `Canvas` control on Linux
|
||||
**directly, no `@State` shim**. The patch is display-validated and PR-ready
|
||||
(`spikes/SwiftOpenUIKnob/PR_DESCRIPTION.md`, `UPSTREAM_ISSUE.md`). **Verdict:
|
||||
GO** — SwiftOpenUI is a viable single-codebase UI path for Linux, pending (a)
|
||||
the patch landing upstream or being vendored, and (b) the per-view
|
||||
`GraphicsContext → DrawingContext` drawing rewrite (mechanical, already shown to
|
||||
compile). The remaining LyrebirdUI port work is now ordinary, not blocked.
|
||||
|
||||
**Update 3 — `@State` drag CONFIRMED on hardware (2026-08-21).** On the Ubuntu
|
||||
24.04 arm64 VM the `@State` knob tracks the drag continuously — the narrow
|
||||
mutation path preserves the `GtkGestureDrag`, so the core question ("can a
|
||||
Canvas control take live drag input on GTK4?") is answered **yes**. The no-fork
|
||||
`@State` usage pattern is a viable single-codebase path today; LyrebirdUI's
|
||||
`@UIParam` (which is `@Observable`-backed) would draw from a local `@State` and
|
||||
sync to the param. The `@Observable` framework patch
|
||||
(`swiftopenui-drag-observable.patch`) — which would let `@UIParam` drive the
|
||||
Canvas directly, no `@State` shim — remains **compile-only**; validate it against
|
||||
a fork (`PATCH_TESTING.md`) before filing the PR.
|
||||
|
||||
**Update 2 — drag fix identified (compile-verified), pending display
|
||||
validation.** Root cause is narrow: SwiftOpenUI's GTK4 backend has a narrow
|
||||
mutation path that redraws a `Canvas` in place and preserves the drag gesture,
|
||||
but it is skipped for `@Observable`-driven changes (it falls through to a full
|
||||
rebuild to re-register observation, and the rebuild destroys the gesture). Two
|
||||
fixes, both in `spikes/SwiftOpenUIKnob/` (`PATCH_TESTING.md`): a **no-fork
|
||||
`@State` usage pattern** (the narrow path already covers `@State` Canvas
|
||||
redraws), and a **framework patch** (`swiftopenui-drag-observable.patch`) that
|
||||
runs the describe pass under `withObservationTracking` so `@Observable` takes
|
||||
the narrow path too. Both need the user's GTK4 display to confirm; if they hold,
|
||||
SwiftOpenUI remains the single-codebase path.
|
||||
|
||||
**Update 1 (hardware run, Ubuntu 24.04 arm64): renders + `@Observable`
|
||||
re-renders, but continuous drag is broken.** A drag handler that writes the
|
||||
bound value triggers a body rebuild that replaces the GTK drag-gesture widget
|
||||
(SwiftOpenUI defers that only for *drop*, not drag), so a knob moves one step
|
||||
per press instead of tracking the drag — the exact interaction every LyrebirdUI
|
||||
knob/slider/XY needs. See `spikes/SwiftOpenUIKnob/README.md` for the confirmed
|
||||
root cause and diagnostic. This is now the gating unknown, ahead of the
|
||||
GraphicsContext rewrite. Resolving it needs an upstream fix (defer the rebuild
|
||||
for drag gestures, or reuse the gesture widget) or a UI structure that keeps the
|
||||
gesture widget stable across value redraws.
|
||||
|
||||
**Verdict: conditional GO.** The framework builds on Linux and the hard 20%
|
||||
(custom drawing) is portable via a mechanical per-view `GraphicsContext →
|
||||
DrawingContext` rewrite that compiles — not a drop-in, but not a wall either.
|
||||
Still gated on a **display run** (Parallels) to confirm the knob actually
|
||||
renders, `@Observable` drives re-render, and drag behaves — the container has no
|
||||
X/Wayland. Risks unchanged: 32 stars / one author, "Stable" self-label
|
||||
optimistic. Alternative if the display run disappoints: `swift-cross-ui`
|
||||
(stackotter — own API, bigger rewrite) or stay headless on Linux.
|
||||
|
||||
**Reproduce the display run on Parallels:** `apt install libgtk-4-dev`; a
|
||||
minimal SwiftPM app depending on `SwiftOpenUI` + `BackendGTK4` (Linux) with an
|
||||
`App`/`WindowGroup`, `import Observation`, a `Canvas(renderer:)` knob drawn via
|
||||
`DrawingContext`, and `.onDrag`; entry `GTK4Backend().run(App.self)`; then
|
||||
`swift run`. The exact ~60-line spike is available on request.
|
||||
|
||||
---
|
||||
|
||||
Windows is planned separatelyWindows is planned separately and on hold (`docs/windows-support-plan.md`).
|
||||
@@ -0,0 +1,282 @@
|
||||
# Lyrebird on Linux
|
||||
|
||||
Lyrebird is a native audio-synthesis framework in Swift. You implement `Generator`
|
||||
and `Synthesizer` types; the engine handles audio I/O and signal-graph evaluation.
|
||||
As of **2.0**, Lyrebird runs on Linux with full parity across the engine, the
|
||||
standard generator library, offline render, live audio (ALSA), MIDI, OSC, the
|
||||
GTK4 GUI, and the live-coding scratchpad.
|
||||
|
||||
This is the Linux guide: install, build, run, scaffold a project, and the feature
|
||||
map. For the macOS/iOS story and the framework internals, see the top-level docs.
|
||||
|
||||
---
|
||||
|
||||
## 1. Requirements
|
||||
|
||||
**Distribution.** Ubuntu 24.04 LTS is the tested target — it matches the CI image
|
||||
(`swift:6.3.3`). Other modern glibc distributions work but are untested. (An ARM64
|
||||
Ubuntu VM — e.g. Parallels on Apple silicon — is a supported dev setup.)
|
||||
|
||||
**Swift toolchain.** Use the **swift.org** toolchain (6.0+), *not* a distro
|
||||
package. [swiftly](https://www.swift.org/install/linux/) is the easiest installer:
|
||||
|
||||
```bash
|
||||
curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz
|
||||
tar zxf swiftly-$(uname -m).tar.gz && ./swiftly init
|
||||
# in a new shell:
|
||||
swiftly install latest
|
||||
swift --version
|
||||
```
|
||||
|
||||
If a new shell can't find `swift`/`swiftc`/`sourcekit-lsp`, add swiftly's bin
|
||||
directory to `PATH` (Lyrebird's tools search `PATH`, so this is all that's needed):
|
||||
|
||||
```bash
|
||||
echo 'export PATH="$HOME/.local/share/swiftly/bin:$PATH"' >> ~/.bashrc
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
**System packages.** Install what you need for the features you want:
|
||||
|
||||
```bash
|
||||
# Build/link the core + tests:
|
||||
sudo apt install build-essential pkg-config
|
||||
|
||||
# Live audio + MIDI (ALSA backends). Without this, build with
|
||||
# LYREBIRD_DISABLE_ALSA=1 — everything compiles, but there is no sound or MIDI:
|
||||
sudo apt install libasound2-dev
|
||||
|
||||
# The GTK4 GUI and the live-coding scratchpad:
|
||||
sudo apt install libgtk-4-dev libgtksourceview-5-dev libfontconfig-dev
|
||||
```
|
||||
|
||||
**IDE.** There is no Xcode on Linux. The maintained path is **VS Code + the
|
||||
official Swift extension** (`swiftlang.swift-vscode`) — SourceKit-LSP completion,
|
||||
diagnostics, LLDB debugging, and a test explorer:
|
||||
|
||||
```bash
|
||||
code --install-extension swiftlang.swift-vscode
|
||||
```
|
||||
|
||||
Open the repository folder; the extension reads `Package.swift` automatically.
|
||||
Neovim/Emacs with `sourcekit-lsp` also work.
|
||||
|
||||
---
|
||||
|
||||
## 2. Build and test
|
||||
|
||||
```bash
|
||||
git clone git@bitbucket.org:realizedsound/lyrebird.git
|
||||
cd lyrebird
|
||||
swift build
|
||||
swift test --no-parallel # --no-parallel avoids a known parallel-runner teardown flake
|
||||
```
|
||||
|
||||
On a Linux host the manifest omits the Apple-only targets, so `swift build` /
|
||||
`swift test` compile the portable surface: the core engine + generators
|
||||
(`LyrebirdSynth`), the interpreted graph DSL (`LyrebirdGraphDSL`), the CLI
|
||||
(`LyrebirdCLI`), the GTK4 UI (`LyrebirdUI` + backend), and the Linux demos.
|
||||
|
||||
No sound stack on the box? Build and test everything except the ALSA driver:
|
||||
|
||||
```bash
|
||||
LYREBIRD_DISABLE_ALSA=1 swift test --no-parallel
|
||||
```
|
||||
|
||||
The **LiveCompile** live-coding subsystem is a separate SwiftPM package under
|
||||
`LiveCompile/` (it dynamically links the engine, so it builds on its own):
|
||||
|
||||
```bash
|
||||
cd LiveCompile
|
||||
swift build
|
||||
swift test --no-parallel
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Set up a project
|
||||
|
||||
Scaffold a new Swift package wired to Lyrebird with the CLI:
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI new MyProject --template quickstart
|
||||
cd MyProject
|
||||
swift run
|
||||
```
|
||||
|
||||
Templates:
|
||||
|
||||
| `--template` | What you get |
|
||||
|---|---|
|
||||
| `quickstart` | Fastest sound — a 440 Hz sine to the speakers. |
|
||||
| `basic` | Default starter synth + engine setup. |
|
||||
| `demo` | A richer multi-generator example. |
|
||||
| `nrt` | Offline render to a WAV (`output.wav`) — no audio device needed. |
|
||||
| `score` | Render from notation (MusicXML in, WAV out). |
|
||||
| `ui-demo` | A GUI scaffold (AppKit on macOS; see the GTK4 demos below on Linux). |
|
||||
|
||||
The generated project calls `makeDefaultAudioDriver()`, which resolves to
|
||||
`ALSAAudioDriver` on Linux (or a silent `OfflineDriver` when there is no live
|
||||
backend — check `isLiveAudioAvailable`). Never name a concrete driver directly in
|
||||
portable code; `makeDefaultAudioDriver()` picks the right one for how the package
|
||||
was built.
|
||||
|
||||
---
|
||||
|
||||
## 4. Run the built-in samples
|
||||
|
||||
### Offline render — works with no audio device
|
||||
|
||||
The surest first run. Renders a WAV end-to-end, no hardware involved:
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI new MyRender --template nrt
|
||||
cd MyRender && swift run # writes output.wav
|
||||
```
|
||||
|
||||
### Live audio — needs a working sound device
|
||||
|
||||
In a VM, make sure the guest has audio (`aplay -l` should list a device):
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI new MyTone --template quickstart
|
||||
cd MyTone && swift run # a sine tone for a few seconds
|
||||
```
|
||||
|
||||
### REPL
|
||||
|
||||
```bash
|
||||
swift run LyrebirdCLI repl
|
||||
```
|
||||
|
||||
Drops into a Swift REPL with `import LyrebirdSynth` wired up — define generators
|
||||
and synthesizers and add them to a running engine live.
|
||||
|
||||
### GTK4 GUI demo
|
||||
|
||||
A live parameter-control window (needs `libgtk-4-dev` + a display; sound needs
|
||||
`libasound2-dev` + a device):
|
||||
|
||||
```bash
|
||||
swift run LyrebirdUILinuxDemo
|
||||
```
|
||||
|
||||
The default window shows live CPU-load meters, a live oscilloscope of the stereo
|
||||
output, an example envelope plot, and controls for two parameters (frequency and
|
||||
amplitude): an XY pad, a knob, a slider, and a readout each, plus a gate toggle
|
||||
and reset. Every control bound to a parameter observes the same `@UIParam` node,
|
||||
so moving one (say the freq knob) updates the others live — the same parameter
|
||||
model the macOS SwiftUI controls use.
|
||||
|
||||
Pick a focused demo with `LYREBIRD_DEMO`:
|
||||
|
||||
| `LYREBIRD_DEMO` | Demo |
|
||||
|---|---|
|
||||
| `full` (default) | The full control panel described above. |
|
||||
| `knob` | A single knob driving a sine tone. |
|
||||
| `mouse` | `Mouse.X` / `Mouse.Y` / `Mouse.Click` driving synthesis from pointer position. |
|
||||
| `events` | The process / event-list performance views. |
|
||||
| `narrowtest` | A narrow-path redraw isolation harness (development aid). |
|
||||
|
||||
```bash
|
||||
LYREBIRD_DEMO=mouse swift run LyrebirdUILinuxDemo
|
||||
```
|
||||
|
||||
### Live-coding scratchpad
|
||||
|
||||
A GTK4 window with a real code editor that compiles and runs Swift snippets into
|
||||
the live engine — Lyrebird's answer to a live-coding environment. It lives in the
|
||||
`LiveCompile` package and needs `libgtksourceview-5-dev`:
|
||||
|
||||
```bash
|
||||
cd LiveCompile
|
||||
swift build # build first: the snippet links the engine's dynamic libs
|
||||
swift run LyrebirdScratchLinuxDemo
|
||||
```
|
||||
|
||||
> The `swift build` step is required before `swift run`: a snippet links against
|
||||
> `libLyrebirdDynamic` / `libLyrebirdLiveCompileDynamic`, which `swift build`
|
||||
> produces but `swift run` alone does not.
|
||||
|
||||
Type Swift, evaluate, hear it. `context` is your live session:
|
||||
|
||||
```swift
|
||||
context.play { OscSin.Audio(freq: 330, mul: 0.15) }
|
||||
context.reportMessage("playing 330 Hz")
|
||||
```
|
||||
|
||||
Scratchpad features:
|
||||
|
||||
- **Swift editor** — GtkSourceView with syntax highlighting, a line-number gutter,
|
||||
and auto-indent.
|
||||
- **Code completion** — `Ctrl+Space` at the caret shows sourcekit-lsp completions
|
||||
(types, members, parameters), filtered by what you've typed.
|
||||
- **Run (fresh)** — clears the previous snippet's synths and runs the buffer.
|
||||
- **Run (additive)** — layers the new snippet on top of what's already playing.
|
||||
- **Line evaluation** — select one or more lines and Run evaluates just those.
|
||||
- **Stop audio** — a panic button that clears all snippet audio without tearing
|
||||
down the engine.
|
||||
- **Live oscilloscope** — shows the session's stereo output in real time.
|
||||
- **Save / load** — a File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
||||
`Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators and native file
|
||||
dialogs. Snippets are plain `.swift` files; the title shows a `●` when there are
|
||||
unsaved edits.
|
||||
|
||||
---
|
||||
|
||||
## 5. Feature map
|
||||
|
||||
| Capability | Linux | Notes |
|
||||
|---|---|---|
|
||||
| Core engine + generators | ✅ | `LyrebirdSynth` |
|
||||
| Interpreted graph DSL | ✅ | `LyrebirdGraphDSL` |
|
||||
| CLI / REPL / scaffolding | ✅ | glibc; not built under musl |
|
||||
| Offline render (NRT → WAV) | ✅ | portable WAV codec; CAF/AIFF/AAC are Apple-only |
|
||||
| Soundfile load / DiskIn | ✅ | WAV only off Apple |
|
||||
| Live audio | ✅ | ALSA; needs `libasound2-dev` + a device |
|
||||
| MIDI in/out | ✅ | ALSA sequencer |
|
||||
| OSC | ✅ | POSIX UDP |
|
||||
| GTK4 GUI (`LyrebirdUI`) | ✅ | knob / slider / label / button / XY pad + scope + envelope + CPU status; standalone windows; mouse input; on the [SwiftOpenUI](https://github.com/joshpar/SwiftOpenUI) GTK4 backend |
|
||||
| Live-coding scratchpad | ✅ | `LiveCompile`; editor + completion + save/load + live scope |
|
||||
| SwiftUI UI | ❌ | macOS/iOS only (Lyrebird uses GTK4 on Linux) |
|
||||
| AUv3 plugin | ❌ | Apple-only |
|
||||
|
||||
The GTK4 UI builds on a pinned release of the
|
||||
[joshpar/SwiftOpenUI](https://github.com/joshpar/SwiftOpenUI) fork (see
|
||||
`Package.swift`). To develop against a local checkout of the fork, point
|
||||
`LYREBIRD_SWIFTOPENUI_LOCAL` at it:
|
||||
|
||||
```bash
|
||||
LYREBIRD_SWIFTOPENUI_LOCAL=/path/to/SwiftOpenUI swift build
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Troubleshooting
|
||||
|
||||
- **No sound / `isLiveAudioAvailable` is false.** Confirm ALSA sees a device with
|
||||
`aplay -l`. In a VM, enable guest audio. To work without any sound stack, build
|
||||
with `LYREBIRD_DISABLE_ALSA=1`.
|
||||
- **`swiftc` / `sourcekit-lsp` not found** (common with swiftly). Add
|
||||
`~/.local/share/swiftly/bin` to `PATH` (see §1). Lyrebird searches `PATH`, so
|
||||
no further configuration is needed.
|
||||
- **`gtk/gtk.h` or `gtksourceview/gtksource.h` not found.** Install the dev
|
||||
packages: `libgtk-4-dev`, `libgtksourceview-5-dev`, `libfontconfig-dev`.
|
||||
- **Scratchpad snippet fails to link** (`cannot find -lLyrebirdLiveCompileDynamic`).
|
||||
Run `swift build` in `LiveCompile/` before `swift run` (see §4).
|
||||
- **`Package.resolved` shows up as modified after a Linux build.** The Linux
|
||||
dependency resolve records the SwiftOpenUI pin; run `git checkout Package.resolved`
|
||||
before committing to keep the tree clean.
|
||||
|
||||
---
|
||||
|
||||
## 7. Reference
|
||||
|
||||
- `docs/linux-getting-started.md` — the original getting-started walkthrough.
|
||||
- `docs/cross-platform-feasibility.md` — the porting approach.
|
||||
- `docs/engine/alsa-audio-driver.md` — the Linux audio driver.
|
||||
- `docs/engine/portable-wav-codec.md` — the off-Apple WAV read/write path.
|
||||
- `Sources/Lyrebird/MIDI/ALSAMIDI.swift`, `Sources/Lyrebird/OSC/OSCServer.swift` —
|
||||
the Linux MIDI and OSC backends.
|
||||
- `LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md`
|
||||
— the live-coding subsystem.
|
||||
@@ -141,7 +141,7 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdScratchDemo — Live-Coding Scratchpad
|
||||
### LyrebirdScratch — Live-Coding Scratchpad
|
||||
|
||||
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
|
||||
|
||||
@@ -157,7 +157,7 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
|
||||
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
|
||||
|
||||
**Why this app cannot be sandboxed:**
|
||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratchDemo.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||
|
||||
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
||||
|
||||
|
||||
@@ -106,3 +106,36 @@ let package = Package(
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
#if os(Linux)
|
||||
// On Linux the editor UI is SwiftOpenUI/GTK4 (the macOS AppKit surface is
|
||||
// #if os(macOS)-gated out). Wire the cross-platform LyrebirdUI product — which
|
||||
// @_exported re-exports SwiftOpenUI + BackendGTK4 and provides LyrebirdWindow /
|
||||
// LyrebirdScopeView — into the UI target, plus a runnable minimal scratch demo:
|
||||
// LYREBIRD_ENABLE_LINUX_UI is not needed; `swift run LyrebirdScratchLinuxDemo`.
|
||||
if let uiIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdLiveCompileUI" }) {
|
||||
package.targets[uiIndex].dependencies.append(
|
||||
.product(name: "LyrebirdUI", package: "Lyrebird")
|
||||
)
|
||||
}
|
||||
package.targets.append(
|
||||
.executableTarget(
|
||||
name: "LyrebirdScratchLinuxDemo",
|
||||
dependencies: [
|
||||
"LyrebirdLiveCompile",
|
||||
"LyrebirdLiveCompileUI",
|
||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||
.product(name: "LyrebirdUI", package: "Lyrebird"),
|
||||
],
|
||||
path: "Sources/LyrebirdScratchLinuxDemo"
|
||||
// NOTE: a live-compiled snippet links `-lLyrebirdDynamic
|
||||
// -lLyrebirdLiveCompileDynamic`, so those shared libraries must exist in
|
||||
// the build dir before you Run. A same-package target can't depend on a
|
||||
// same-package product to force them, so build the whole package first —
|
||||
// `swift build` (builds all products, incl. the …Dynamic .so's) — then
|
||||
// `swift run LyrebirdScratchLinuxDemo`. `swift run` alone only builds the
|
||||
// executable's own graph and would leave the snippet link unable to find
|
||||
// libLyrebirdLiveCompileDynamic.so.
|
||||
)
|
||||
)
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// ArtifactStagingError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Errors raised while staging compile artifacts into Application Support.
|
||||
enum ArtifactStagingError: Error {
|
||||
/// The staging destination already exists, is non-empty, and does not look
|
||||
/// like a prior staging root — refused rather than clobbered.
|
||||
case destinationNotAStagingRoot(String)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Handle to one successfully compiled and loaded snippet.
|
||||
///
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
// The editor (`LyrebirdScratchView`) renders diagnostics in its
|
||||
// margin gutter using `(line, column)` directly.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public struct Diagnostic: Equatable, Sendable {
|
||||
/// 1-based line number in the **user's** snippet body. May be `nil` when the
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum DiagnosticParser {
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//
|
||||
// Severity classifier for a parsed swiftc diagnostic line.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum DiagnosticSeverity: String, Equatable, Sendable {
|
||||
case error
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// (line, column); build errors carry no span → `line: nil` with the message
|
||||
// alone.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
/// Maps interpreted-graph-DSL errors to editor diagnostics.
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// One parsed code-completion candidate from `sourcekit-lsp`. macOS only.
|
||||
// One parsed code-completion candidate from `sourcekit-lsp`. macOS/Linux only.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// One code-completion candidate returned by sourcekit-lsp.
|
||||
public struct LSPCompletionItem: Sendable, Equatable {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
|
||||
/// `xcrun -f swiftc` and the fallback paths all failed.
|
||||
|
||||
@@ -9,14 +9,16 @@
|
||||
// `LiveCompiler.compile(source:)` shells out to `swiftc -emit-library`, then
|
||||
// `dlopen`s the resulting dylib and resolves the snippet entry symbol. No UI,
|
||||
// no `SynthesisEngine` binding (those are handled by the harness and session
|
||||
// layers). macOS only — iOS cannot exec swiftc.
|
||||
// layers). macOS/Linux only — iOS cannot exec swiftc.
|
||||
|
||||
import Foundation
|
||||
#if os(macOS)
|
||||
import Darwin
|
||||
#if canImport(Darwin)
|
||||
import Darwin // dlopen / dlsym / dlerror
|
||||
#elseif canImport(Glibc)
|
||||
import Glibc // dlopen / dlsym / dlerror on Linux
|
||||
#endif
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Symbol the snippet preamble must export. Snippets declare:
|
||||
///
|
||||
@@ -26,10 +28,37 @@ import Darwin
|
||||
/// ```
|
||||
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
|
||||
|
||||
/// Platform shared-library extension: `dylib` (Mach-O) on macOS, `so` (ELF) on
|
||||
/// Linux. A snippet is `swiftc -emit-library`'d to `lib<name>.<ext>`, and the
|
||||
/// resident Lyrebird library is `libLyrebirdDynamic.<ext>`.
|
||||
#if os(macOS)
|
||||
let livecompileSharedLibraryExtension: String = "dylib"
|
||||
#else
|
||||
let livecompileSharedLibraryExtension: String = "so"
|
||||
#endif
|
||||
|
||||
/// Search `$PATH` for an executable named `name`, returning the first hit or
|
||||
/// `nil`. Covers toolchains installed outside the hard-coded locations — most
|
||||
/// notably a swiftly install (`~/.local/share/swiftly/bin`) on Linux, which puts
|
||||
/// both `swiftc` and `sourcekit-lsp` on `$PATH` but not in `/usr/bin`.
|
||||
func livecompileExecutableOnPath(_ name: String) -> String? {
|
||||
guard let pathEnv: String = ProcessInfo.processInfo.environment["PATH"] else { return nil }
|
||||
for dir: Substring in pathEnv.split(separator: ":") where !dir.isEmpty {
|
||||
let base: String = String(dir)
|
||||
let candidate: String = base.hasSuffix("/") ? base + name : base + "/" + name
|
||||
if FileManager.default.isExecutableFile(atPath: candidate) {
|
||||
return candidate
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
|
||||
/// fresh temp dir, dylib name, and `dlopen` handle.
|
||||
/// fresh temp dir, shared-library name, and `dlopen` handle.
|
||||
public enum LiveCompiler {
|
||||
|
||||
static var sharedLibraryExtension: String { livecompileSharedLibraryExtension }
|
||||
|
||||
/// Compile `source` to a dylib and resolve the snippet entry symbol.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -52,7 +81,7 @@ public enum LiveCompiler {
|
||||
let workDir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LyrebirdLiveCompile-\(snippetID)", isDirectory: true)
|
||||
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
||||
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).dylib").path
|
||||
let dylibPath: String = workDir.appendingPathComponent("lib\(moduleName).\(sharedLibraryExtension)").path
|
||||
|
||||
do {
|
||||
try FileManager.default.createDirectory(
|
||||
@@ -112,11 +141,17 @@ public enum LiveCompiler {
|
||||
|
||||
/// First-success search:
|
||||
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
|
||||
/// 2. Hard-coded toolchain paths.
|
||||
/// 2. An executable `swiftc` on `$PATH` — covers a swiftly install
|
||||
/// (`~/.local/share/swiftly/bin`) and any Linux toolchain layout that
|
||||
/// isn't in the hard-coded list.
|
||||
/// 3. Hard-coded toolchain paths.
|
||||
static func findSwiftc() throws -> String {
|
||||
if let xcrun: String = swiftcViaXcrun() {
|
||||
return xcrun
|
||||
}
|
||||
if let onPath: String = swiftcOnPath() {
|
||||
return onPath
|
||||
}
|
||||
let candidates: [String] = [
|
||||
"/usr/bin/swiftc",
|
||||
"/usr/local/bin/swiftc",
|
||||
@@ -128,6 +163,11 @@ public enum LiveCompiler {
|
||||
throw LiveCompileError.swiftcNotFound
|
||||
}
|
||||
|
||||
/// Search `$PATH` for an executable `swiftc`. Returns the first hit, or `nil`.
|
||||
static func swiftcOnPath() -> String? {
|
||||
livecompileExecutableOnPath("swiftc")
|
||||
}
|
||||
|
||||
/// `xcrun --show-sdk-path` — returns the macOS SDK path used by the user's
|
||||
/// active Xcode. `nil` when xcrun is missing or returns non-zero.
|
||||
static func sdkPathViaXcrun() -> String? {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
|
||||
// `CompiledSnippet.swift`.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -40,6 +40,14 @@ public final class LiveSession: @unchecked Sendable {
|
||||
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// Output-tapping oscilloscope capture for the editor's scope view. When a
|
||||
/// fresh tap is installed at init (the engine is not yet running and has no
|
||||
/// tap), this is that capture; if the engine already had a `scopeTap`, this
|
||||
/// reuses it; it is `nil` only when no tap is present (attachment declined,
|
||||
/// or the engine was already running with no tap). Must be installed before
|
||||
/// `start()`.
|
||||
public let scope: ScopeCapture?
|
||||
|
||||
/// `-I` paths threaded to `swiftc` for module discovery.
|
||||
public let importPaths: [URL]
|
||||
|
||||
@@ -64,9 +72,27 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var reportedSampleRate: Double?
|
||||
|
||||
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var lastSnippetMessage: String?
|
||||
/// Most recent snippet `context.reportMessage(_:)` value (tests read this via
|
||||
/// `@testable import`). Backed by the internal message log (`_messageLog`).
|
||||
internal var lastSnippetMessage: String? { _messageLog.last }
|
||||
|
||||
/// Accumulated `context.reportMessage(_:)` output (and host-side notices like
|
||||
/// a dropped slot swap) since the last drain. Main-thread only — appended
|
||||
/// during the synchronous snippet entry, drained by the host after each run.
|
||||
private var _messageLog: [String] = []
|
||||
|
||||
/// Append a snippet/host message to the log. Main-thread only.
|
||||
internal func appendMessage(_ message: String) {
|
||||
_messageLog.append(message)
|
||||
}
|
||||
|
||||
/// Return and clear the accumulated messages. Called by the host after a run
|
||||
/// to move them into its console.
|
||||
public func drainMessages() -> [String] {
|
||||
let out: [String] = _messageLog
|
||||
_messageLog.removeAll()
|
||||
return out
|
||||
}
|
||||
|
||||
// Tracked state — all access guarded by `trackingLock`.
|
||||
private let trackingLock: NSLock = NSLock()
|
||||
@@ -100,14 +126,31 @@ public final class LiveSession: @unchecked Sendable {
|
||||
private var _swapQuantize: SwapQuantize = .immediate
|
||||
private var _pendingSwapBeat: Double?
|
||||
|
||||
/// Samples per channel the scope captures per display frame.
|
||||
private static let scopeBufferSize: Int = 1024
|
||||
|
||||
/// - Parameter attachScope: When `true` (default) and the engine is not yet
|
||||
/// running and has no existing tap, install a ``ScopeCapture`` on the first
|
||||
/// one or two output buses for the editor's scope view.
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
attachScope: Bool = true,
|
||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [URL] = LiveSession.defaultRpaths()
|
||||
) {
|
||||
self.engine = engine
|
||||
// Install the scope tap before the host calls `start()` (the RT thread
|
||||
// caches `scopeTap` at start; setting it afterwards is a no-op).
|
||||
if attachScope, !engine.isRunning, engine.scopeTap == nil, engine.numOutputChannels >= 1 {
|
||||
let buses: [Int] = Array(0..<min(2, engine.numOutputChannels))
|
||||
let capture: ScopeCapture = ScopeCapture(buses: buses, bufferSize: LiveSession.scopeBufferSize)
|
||||
engine.scopeTap = capture
|
||||
self.scope = capture
|
||||
} else {
|
||||
self.scope = engine.scopeTap
|
||||
}
|
||||
self.importPaths = importPaths
|
||||
self.librarySearchPaths = librarySearchPaths
|
||||
self.libraries = libraries
|
||||
@@ -313,6 +356,59 @@ public final class LiveSession: @unchecked Sendable {
|
||||
return false
|
||||
}
|
||||
|
||||
/// **Gracefully release** the synth in the named `slot` (trigger its
|
||||
/// envelope release phase) and drop the slot handle, so the voice tails out
|
||||
/// and then frees itself via its own done-action — rather than being hard-cut
|
||||
/// like ``clearSlot(_:)``. This is the live-coding "let go of this voice"
|
||||
/// gesture: pair it with ``SnippetContext/play(slot:_:)-…`` to start a
|
||||
/// persistent voice under a name and release it later from a separate
|
||||
/// evaluation.
|
||||
///
|
||||
/// The handle is dropped **only if the release succeeds**, so a voice with no
|
||||
/// gate to release (its `release(engine:)` throws) stays in the slot and can
|
||||
/// still be stopped with ``clearSlot(_:)`` — it is never orphaned.
|
||||
///
|
||||
/// On success the voice is moved from the slot map into the anonymous
|
||||
/// tracked list, so it remains reachable by ``clearTracked()`` / ``resetAll()``
|
||||
/// (the toolbar "Clear Synths"). A well-behaved voice self-frees via its
|
||||
/// done-action before then; a mis-configured one that never self-frees is
|
||||
/// still reclaimable rather than leaked until a process restart. (A later
|
||||
/// hard `engine.remove` on an already-self-freed synth is a harmless no-op.)
|
||||
///
|
||||
/// - Parameter name: Slot to release.
|
||||
/// - Returns: `true` if a gated voice was released; `false` if the slot was
|
||||
/// empty or its occupant had no gate (reported via `lastSnippetMessage`).
|
||||
///
|
||||
/// The identity guard below (`… === entry.synth`) is load-bearing, not
|
||||
/// defensive dead code: `clearSlot` / `clearSlots` / `resetAll` are
|
||||
/// nonisolated and may run on another thread while this `release(engine:)`
|
||||
/// call is in flight on the main actor.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public func releaseSlot(_ name: String) -> Bool {
|
||||
let entry: SlotEntry?
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
entry = slottedSynths[name]
|
||||
}
|
||||
guard let entry: SlotEntry = entry else { return false }
|
||||
do {
|
||||
try entry.synth.release(engine: engine)
|
||||
// Released — free the name for reuse and keep the voice reachable by
|
||||
// the tracked-synth sweep (its safety net until it self-frees).
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
if slottedSynths[name]?.synth === entry.synth {
|
||||
slottedSynths[name] = nil
|
||||
trackedSynths.append(entry.synth)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
appendMessage(
|
||||
"slot '\(name)': release failed (\(error)) — use clearSlot() to stop it")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a slot occupant, scheduling the removal no earlier than the
|
||||
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
|
||||
/// scheduled add is never orphaned. `desired` is the caller's intended
|
||||
@@ -474,8 +570,8 @@ public final class LiveSession: @unchecked Sendable {
|
||||
if let previous: SlotEntry = previous {
|
||||
let removed: Bool = removeSlotOccupant(previous, desired: time)
|
||||
if !removed {
|
||||
lastSnippetMessage =
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap"
|
||||
appendMessage(
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -569,6 +665,13 @@ public final class LiveSession: @unchecked Sendable {
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#if os(Linux)
|
||||
// Source-only system-library module maps (CALSA, LyrebirdC) — see the
|
||||
// helper. Without CALSA's, a Linux `import LyrebirdSynth` fails to resolve.
|
||||
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#endif
|
||||
return args
|
||||
}
|
||||
|
||||
@@ -594,7 +697,15 @@ public final class LiveSession: @unchecked Sendable {
|
||||
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
|
||||
}
|
||||
} else {
|
||||
#if os(macOS)
|
||||
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
|
||||
#else
|
||||
// ELF has no Mach-O flat-namespace deferred lookup: a snippet resolves
|
||||
// Lyrebird symbols by NEEDED-linking libLyrebirdDynamic.so, which needs
|
||||
// it present in a -L path (i.e. hasDylib == true). Reaching here on
|
||||
// Linux means no such library was found; emit no link flag so the link
|
||||
// fails loudly rather than adding a macOS-only one.
|
||||
#endif
|
||||
}
|
||||
return args
|
||||
}
|
||||
@@ -658,6 +769,44 @@ public final class LiveSession: @unchecked Sendable {
|
||||
return found
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
/// Linux only: locate the `CALSA` **system-library** module map, which lives
|
||||
/// only in the package *source* tree (`Sources/CALSA/module.modulemap`),
|
||||
/// never in the build dir — a `.systemLibrary` target emits no
|
||||
/// `<CTarget>.build/module.modulemap`. `LyrebirdSynth` transitively imports
|
||||
/// `CALSA` on Linux (the ALSA driver), so a snippet's `import LyrebirdSynth`
|
||||
/// fails with `missing required module 'CALSA'` unless the map is surfaced.
|
||||
/// macOS never hits this (Core Audio, no CALSA import). `LyrebirdC` is a
|
||||
/// regular C target and IS covered by `discoverSPMModuleMaps` (build-tree
|
||||
/// map) — adding its source map too would `redefinition of module 'LyrebirdC'`.
|
||||
/// Walks up from each import path (bounded) to the package root.
|
||||
static func discoverSourceSystemModuleMaps(in importPaths: [URL]) -> [URL] {
|
||||
let maxWalk: Int = 8
|
||||
let relativeMaps: [String] = [
|
||||
"Sources/CALSA/module.modulemap",
|
||||
]
|
||||
var found: [URL] = []
|
||||
var visited: Set<String> = Set<String>()
|
||||
for start: URL in importPaths {
|
||||
var cur: URL = start
|
||||
for _ in 0..<maxWalk {
|
||||
for rel: String in relativeMaps {
|
||||
let probe: URL = cur.appendingPathComponent(rel)
|
||||
if FileManager.default.fileExists(atPath: probe.path),
|
||||
!visited.contains(probe.path) {
|
||||
visited.insert(probe.path)
|
||||
found.append(probe)
|
||||
}
|
||||
}
|
||||
let parent: URL = cur.deletingLastPathComponent()
|
||||
if parent == cur { break }
|
||||
cur = parent
|
||||
}
|
||||
}
|
||||
return found
|
||||
}
|
||||
#endif
|
||||
|
||||
// MARK: - Build-dir discovery
|
||||
|
||||
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
|
||||
@@ -685,7 +834,10 @@ public final class LiveSession: @unchecked Sendable {
|
||||
// (→ libLyrebirdDynamic.dylib); the module/target is `LyrebirdSynth`
|
||||
// (LyrebirdSynth.swiftmodule). The consumer-facing `Lyrebird` product
|
||||
// is static and produces no dylib, so it is not a marker here.
|
||||
let markers: [String] = ["libLyrebirdDynamic.dylib", "LyrebirdSynth.swiftmodule"]
|
||||
let markers: [String] = [
|
||||
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)",
|
||||
"LyrebirdSynth.swiftmodule",
|
||||
]
|
||||
for start: URL in candidates {
|
||||
var cur: URL = start
|
||||
for _ in 0..<maxWalk {
|
||||
@@ -709,23 +861,42 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// already resolved in the running process.
|
||||
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
|
||||
FileManager.default.fileExists(
|
||||
atPath: buildDir.appendingPathComponent("libLyrebirdDynamic.dylib").path
|
||||
atPath: buildDir.appendingPathComponent(
|
||||
"libLyrebirdDynamic.\(livecompileSharedLibraryExtension)"
|
||||
).path
|
||||
)
|
||||
}
|
||||
|
||||
/// Prefer a populated staged artifacts dir (App Support, ungated) over the
|
||||
/// SPM build dir (which lives under `~/Documents` in a dev checkout). Hosts
|
||||
/// that want staging call ``stageArtifacts(from:to:)`` before constructing
|
||||
/// the session; these defaults then resolve to the staged copy.
|
||||
private static func resolvedArtifactsDir() -> URL? {
|
||||
// Prefer the staged dir only when it is populated AND current relative to
|
||||
// the live build dir — so a stale copy left by a different build (or a
|
||||
// partial stage) never masquerades as the resolved artifacts for a host
|
||||
// that did not itself stage.
|
||||
if let staged: URL = stagedArtifactsDir(),
|
||||
isArtifactsDirPopulated(staged),
|
||||
stagedDirIsCurrent(staged) {
|
||||
return staged
|
||||
}
|
||||
return currentBuildDir()
|
||||
}
|
||||
|
||||
public static func defaultImportPaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir, buildDir.appendingPathComponent("Modules")]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir, dir.appendingPathComponent("Modules")]
|
||||
}
|
||||
|
||||
public static func defaultLibrarySearchPaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir]
|
||||
}
|
||||
|
||||
public static func defaultRpaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
// LiveSessionArtifactStaging.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Snippet compilation needs the Lyrebird module artifacts (swiftmodules, the
|
||||
// Lyrebird dylibs, and the C-shim Clang module map + its umbrella header). In a
|
||||
// dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||
// non-sandboxed host reading them — and the `swiftc` it spawns reading them —
|
||||
// trips the macOS "wants to access your Documents folder" TCC gate.
|
||||
//
|
||||
// Staging copies the minimal artifact set into
|
||||
// `~/Library/Application Support/LyrebirdScratch/LiveCompile/`, an ungated
|
||||
// location, and rewrites the C module map's absolute umbrella-header path to the
|
||||
// staged copy. The default `-I` / `-L` / rpath resolution then prefers the
|
||||
// staged dir, so a shipped app compiles snippets without ever touching a
|
||||
// permission-gated folder.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
extension LiveSession {
|
||||
|
||||
/// Name of the artifacts subdirectory a host may ship inside its app bundle
|
||||
/// (`<App>.app/Contents/Resources/<name>`). Staging prefers this over the
|
||||
/// dev build dir when present, so a shipped app never reads outside its
|
||||
/// bundle or App Support.
|
||||
public static let bundledArtifactsDirName: String = "LyrebirdArtifacts"
|
||||
|
||||
/// `~/Library/Application Support/LyrebirdScratch/LiveCompile` — the ungated
|
||||
/// destination for staged compile artifacts. `nil` only if the Application
|
||||
/// Support directory can't be resolved.
|
||||
public static func stagedArtifactsDir() -> URL? {
|
||||
guard let base: URL = FileManager.default.urls(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask
|
||||
).first else { return nil }
|
||||
return base
|
||||
.appendingPathComponent("LyrebirdScratch", isDirectory: true)
|
||||
.appendingPathComponent("LiveCompile", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Whether `dir` is a usable compile root: it has a `Modules/` directory
|
||||
/// holding at least one `.swiftmodule`.
|
||||
public static func isArtifactsDirPopulated(_ dir: URL) -> Bool {
|
||||
let modules: URL = dir.appendingPathComponent("Modules", isDirectory: true)
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: modules,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return false }
|
||||
return entries.contains { $0.pathExtension == "swiftmodule" }
|
||||
}
|
||||
|
||||
/// Where to stage FROM. Prefers a `LyrebirdArtifacts` directory shipped in
|
||||
/// the app bundle's `Resources` (self-contained, never under a gated
|
||||
/// folder); falls back to the dev SPM build dir.
|
||||
public static func artifactSourceDir() -> URL? {
|
||||
if let resources: URL = Bundle.main.resourceURL {
|
||||
let bundled: URL = resources.appendingPathComponent(
|
||||
bundledArtifactsDirName,
|
||||
isDirectory: true
|
||||
)
|
||||
if isArtifactsDirPopulated(bundled) { return bundled }
|
||||
}
|
||||
return currentBuildDir()
|
||||
}
|
||||
|
||||
/// Copy the minimal artifact set from `source` (default: ``artifactSourceDir()``)
|
||||
/// into `destination` (default: ``stagedArtifactsDir()``), rewriting the C
|
||||
/// module map to point at a staged copy of its umbrella header. Idempotent:
|
||||
/// skips the copy when the destination is already newer than the source.
|
||||
/// Best-effort — returns the staged dir on success, `nil` on any failure or
|
||||
/// when no source/destination could be resolved.
|
||||
///
|
||||
/// - Note: In a dev checkout the source is the build dir under `~/Documents`,
|
||||
/// so the one-time copy still reads that gated folder; every subsequent
|
||||
/// launch reuses the staged copy and reads only App Support. A shipped app
|
||||
/// whose `Resources/LyrebirdArtifacts` is populated never reads a gated
|
||||
/// folder at all.
|
||||
@discardableResult
|
||||
public static func stageArtifacts(
|
||||
from source: URL? = nil,
|
||||
to destination: URL? = nil
|
||||
) -> URL? {
|
||||
guard let dest: URL = destination ?? stagedArtifactsDir() else { return nil }
|
||||
guard let src: URL = source ?? artifactSourceDir() else { return nil }
|
||||
do {
|
||||
try stageArtifactsThrowing(from: src, to: dest)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
return isArtifactsDirPopulated(dest) ? dest : nil
|
||||
}
|
||||
|
||||
// MARK: - Implementation
|
||||
|
||||
static let stageReceiptName: String = ".stage-receipt"
|
||||
|
||||
/// Slack in the receipt-vs-source stamp comparison. A `Date` stores seconds
|
||||
/// since 2001; the receipt records `timeIntervalSince1970`, so reconstructing
|
||||
/// it adds then subtracts the ~978-million-second epoch offset — floating-
|
||||
/// point arithmetic at that magnitude perturbs the sub-second fraction, so a
|
||||
/// bit-exact `>=` can spuriously read "stale" (the string encoding itself is
|
||||
/// exact; the loss is in the epoch conversion, not the receipt). mtime
|
||||
/// staleness needs no sub-second resolution — a rebuild moves mtimes by far
|
||||
/// more than a second.
|
||||
private static let stageStampToleranceSeconds: TimeInterval = 1.0
|
||||
|
||||
/// Whether a staged dir at `dest` is current relative to the artifact source
|
||||
/// it would stage from. When no source is discoverable (a shipped app with no
|
||||
/// build dir and no bundled artifacts), any populated staged dir is trusted.
|
||||
/// Otherwise the receipt must be at or after the source's newest artifact —
|
||||
/// so a staged copy left by a *different* build (or a partial stage that never
|
||||
/// wrote a receipt) is ignored and the resolver falls back to the build dir.
|
||||
/// Compared against ``artifactSourceDir()`` (not the build dir directly) so
|
||||
/// the base matches what ``stageArtifacts(from:to:)`` actually copies from.
|
||||
static func stagedDirIsCurrent(_ dest: URL) -> Bool {
|
||||
guard let source: URL = artifactSourceDir() else { return true }
|
||||
guard let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false))
|
||||
else { return false }
|
||||
return prior.timeIntervalSince1970 >= sourceArtifactStamp(source).timeIntervalSince1970 - stageStampToleranceSeconds
|
||||
}
|
||||
|
||||
private static func stageArtifactsThrowing(from src: URL, to dest: URL) throws {
|
||||
let fm: FileManager = FileManager.default
|
||||
let srcStamp: Date = sourceArtifactStamp(src)
|
||||
|
||||
// Up to date? A populated dest whose receipt is at or after the source's
|
||||
// newest artifact mtime needs no re-copy.
|
||||
if isArtifactsDirPopulated(dest),
|
||||
let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false)),
|
||||
prior.timeIntervalSince1970 >= srcStamp.timeIntervalSince1970 - stageStampToleranceSeconds {
|
||||
return
|
||||
}
|
||||
|
||||
// Refuse to clobber a directory we did not create: an existing, non-empty
|
||||
// `dest` must look like a prior staging root (a receipt or a `Modules/`
|
||||
// dir) before we replace it. Guards a typo'd `to:` from wiping real data.
|
||||
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||
}
|
||||
|
||||
// Build everything in a private sibling temp dir, then atomically swap it
|
||||
// over `dest`. `dest` is therefore only ever fully-complete or absent — a
|
||||
// failed/partial stage never leaves a dir that *looks* valid, and two
|
||||
// stagers racing the same `dest` can't observe a half-written tree.
|
||||
let staging: URL = dest.deletingLastPathComponent()
|
||||
.appendingPathComponent(".\(dest.lastPathComponent).staging-\(UUID().uuidString)", isDirectory: true)
|
||||
try fm.createDirectory(at: staging, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: staging) }
|
||||
|
||||
// 1. Swift modules.
|
||||
let srcModules: URL = src.appendingPathComponent("Modules", isDirectory: true)
|
||||
if fm.fileExists(atPath: srcModules.path) {
|
||||
try fm.copyItem(at: srcModules, to: staging.appendingPathComponent("Modules", isDirectory: true))
|
||||
}
|
||||
|
||||
// 2. Lyrebird dylibs (the snippet links these and bakes an rpath here;
|
||||
// at dlopen dyld matches the already-loaded install name, so the copy is
|
||||
// a link-time search target, not a second loaded image).
|
||||
for dylib: URL in lyrebirdDylibs(in: src) {
|
||||
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
|
||||
}
|
||||
|
||||
// 2.5. Self-contained C-shim module dirs (`<Module>.build/` holding a
|
||||
// `module.modulemap` whose header path is relative to the map — as shipped
|
||||
// in the app bundle's LyrebirdArtifacts). Copy the whole dir verbatim so the
|
||||
// relative header resolves at the staged location; no path rewrite needed.
|
||||
// (The absolute-`umbrella header` dev-build maps are handled separately in
|
||||
// step 3 — a relative-header map is skipped there, so no double-write.)
|
||||
copySelfContainedModuleMapDirs(from: src, writeInto: staging)
|
||||
|
||||
// 3. C module maps + their umbrella headers. Files are written under the
|
||||
// temp `staging` dir, but the umbrella path baked into each map must
|
||||
// reference the FINAL `dest` (where they land after the atomic swap) —
|
||||
// the temp dir is deleted.
|
||||
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
|
||||
|
||||
#if os(Linux)
|
||||
// 3.5. CALSA (the ALSA system library) has no `<Module>.build/` map in the
|
||||
// build dir — its module map lives only in the package source — so the
|
||||
// steps above miss it and a snippet's `import LyrebirdSynth` can't resolve
|
||||
// CALSA from the staged root. Copy the source module dir (map + relative
|
||||
// include/) into a self-contained `CALSA.build/` that `discoverSPMModuleMaps`
|
||||
// then finds at the staged location. macOS never imports CALSA.
|
||||
stageCALSAModuleMap(from: src, writeInto: staging)
|
||||
#endif
|
||||
|
||||
// Receipt: store the source stamp so the next call can skip an unchanged
|
||||
// source.
|
||||
let stampText: String = String(srcStamp.timeIntervalSince1970)
|
||||
try stampText.write(
|
||||
to: staging.appendingPathComponent(stageReceiptName, isDirectory: false),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
|
||||
// Re-check the clobber guard immediately before the swap: the copy phase
|
||||
// above is a window in which something could have materialized a
|
||||
// non-staging directory at `dest`. Holding the guard across the whole
|
||||
// operation, not just at entry, keeps `replaceItemAt` from silently
|
||||
// wiping a dir we would have refused.
|
||||
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||
}
|
||||
|
||||
// Atomic swap into place.
|
||||
if fm.fileExists(atPath: dest.path) {
|
||||
_ = try fm.replaceItemAt(dest, withItemAt: staging)
|
||||
} else {
|
||||
try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
do {
|
||||
try fm.moveItem(at: staging, to: dest)
|
||||
} catch {
|
||||
// A concurrent stager may have created `dest` between the check
|
||||
// and the move; if it is now a valid root, treat as success.
|
||||
guard isArtifactsDirPopulated(dest) else { throw error }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Lyrebird dylibs present at the top level of `src`.
|
||||
private static func lyrebirdDylibs(in src: URL) -> [URL] {
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return [] }
|
||||
return entries.filter {
|
||||
$0.pathExtension == livecompileSharedLibraryExtension
|
||||
&& $0.lastPathComponent.hasPrefix("libLyrebird")
|
||||
}
|
||||
}
|
||||
|
||||
#if os(Linux)
|
||||
/// Copy the CALSA source module dir (`Sources/CALSA/`: `module.modulemap` +
|
||||
/// `include/calsa-shim.h`) into `staging/CALSA.build/`, so the staged root is a
|
||||
/// self-contained compile root for a snippet that transitively imports CALSA.
|
||||
/// The map's header path is relative, so it resolves verbatim at the staged
|
||||
/// location. Best-effort: if the source map isn't found (e.g. a detached build
|
||||
/// dir), staging proceeds without it and the snippet compile surfaces the gap.
|
||||
private static func stageCALSAModuleMap(from src: URL, writeInto staging: URL) {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard let calsaMap: URL = LiveSession.discoverSourceSystemModuleMaps(in: [src]).first else {
|
||||
return
|
||||
}
|
||||
let calsaSrcDir: URL = calsaMap.deletingLastPathComponent()
|
||||
let stagedDir: URL = staging.appendingPathComponent("CALSA.build", isDirectory: true)
|
||||
try? fm.copyItem(at: calsaSrcDir, to: stagedDir)
|
||||
}
|
||||
#endif
|
||||
|
||||
/// A `dest` is safe to replace when it doesn't exist, is empty, or looks like
|
||||
/// a prior staging root (has a receipt or a `Modules/` dir).
|
||||
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.fileExists(atPath: dest.path) else { return true }
|
||||
if fm.fileExists(atPath: dest.appendingPathComponent(stageReceiptName).path) { return true }
|
||||
if fm.fileExists(atPath: dest.appendingPathComponent("Modules").path) { return true }
|
||||
let contents: [URL] = (try? fm.contentsOfDirectory(at: dest, includingPropertiesForKeys: nil)) ?? []
|
||||
return contents.isEmpty
|
||||
}
|
||||
|
||||
/// For each `<Module>.build/module.modulemap` under `src` whose umbrella
|
||||
/// header exists, copy the header's `include` directory into
|
||||
/// `writeInto/<Module>.headers` and write a staged map whose umbrella path
|
||||
/// points at `finalRoot/<Module>.headers/<header>` — the location those files
|
||||
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
|
||||
/// Best-effort per map: a map with no resolvable umbrella header, or one that
|
||||
/// fails to copy, is skipped without aborting the rest.
|
||||
/// Copy each `<Module>.build/` directory under `src` that holds a
|
||||
/// `module.modulemap` **without** an `umbrella header` directive — i.e. a
|
||||
/// self-contained map whose `header "…"` path is relative to the map's own
|
||||
/// directory (as bundled in the app's `LyrebirdArtifacts`). The whole dir is
|
||||
/// copied verbatim (map + adjacent headers), so the relative path resolves at
|
||||
/// the staged location and `discoverSPMModuleMaps` finds the copied map. Maps
|
||||
/// with an absolute `umbrella header` are left for ``stageClangModuleMaps``.
|
||||
private static func copySelfContainedModuleMapDirs(from src: URL, writeInto staging: URL) {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return }
|
||||
|
||||
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
guard fm.fileExists(atPath: map.path),
|
||||
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||
umbrellaHeaderPath(in: text) == nil // self-contained (relative header) only
|
||||
else { continue }
|
||||
let stagedDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||
try? fm.removeItem(at: stagedDir)
|
||||
try? fm.copyItem(at: buildDir, to: stagedDir)
|
||||
}
|
||||
}
|
||||
|
||||
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return }
|
||||
|
||||
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
guard fm.fileExists(atPath: map.path),
|
||||
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||
let umbrella: String = umbrellaHeaderPath(in: text)
|
||||
else { continue }
|
||||
|
||||
let headerURL: URL = URL(fileURLWithPath: umbrella)
|
||||
guard fm.fileExists(atPath: headerURL.path) else { continue }
|
||||
|
||||
let includeDir: URL = headerURL.deletingLastPathComponent()
|
||||
let moduleName: String = buildDir.deletingPathExtension().lastPathComponent
|
||||
let headerName: String = headerURL.lastPathComponent
|
||||
// Files go under the temp staging dir…
|
||||
let stagedHeaders: URL = staging.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||
let stagedMapDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||
// …but the baked umbrella path names their final resting place.
|
||||
let finalHeader: URL = dest
|
||||
.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||
.appendingPathComponent(headerName, isDirectory: false)
|
||||
let rewritten: String = text.replacingOccurrences(of: umbrella, with: finalHeader.path)
|
||||
do {
|
||||
try? fm.removeItem(at: stagedHeaders)
|
||||
try fm.copyItem(at: includeDir, to: stagedHeaders)
|
||||
try fm.createDirectory(at: stagedMapDir, withIntermediateDirectories: true)
|
||||
try rewritten.write(
|
||||
to: stagedMapDir.appendingPathComponent("module.modulemap", isDirectory: false),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the path inside `umbrella header "..."` from a Clang module map.
|
||||
static func umbrellaHeaderPath(in modulemap: String) -> String? {
|
||||
guard let marker: Range<String.Index> = modulemap.range(of: "umbrella header") else { return nil }
|
||||
let after: Substring = modulemap[marker.upperBound...]
|
||||
guard let open: String.Index = after.firstIndex(of: "\"") else { return nil }
|
||||
let afterOpen: Substring = after[after.index(after: open)...]
|
||||
guard let close: String.Index = afterOpen.firstIndex(of: "\"") else { return nil }
|
||||
return String(afterOpen[..<close])
|
||||
}
|
||||
|
||||
/// Newest modification date among the artifacts we actually copy — a cheap
|
||||
/// staleness proxy that avoids walking the whole build tree. Derives the
|
||||
/// dylib set from the same wildcard scan the copy step uses, so a new/renamed
|
||||
/// Lyrebird dylib can't slip past the freshness check.
|
||||
///
|
||||
/// It does not probe the C module map or its umbrella header directly: a
|
||||
/// header edit forces `swift build` to rebuild the downstream swiftmodules
|
||||
/// too, which moves `Modules/`'s mtime — so a header change is caught
|
||||
/// transitively. (A hand-edited header with no rebuild would not re-stage,
|
||||
/// but that state never occurs from a normal build.)
|
||||
private static func sourceArtifactStamp(_ src: URL) -> Date {
|
||||
let fm: FileManager = FileManager.default
|
||||
var newest: Date = Date.distantPast
|
||||
var probes: [URL] = [src.appendingPathComponent("Modules", isDirectory: true)]
|
||||
probes += lyrebirdDylibs(in: src)
|
||||
for probe: URL in probes {
|
||||
if let attrs: [FileAttributeKey: Any] = try? fm.attributesOfItem(atPath: probe.path),
|
||||
let date: Date = attrs[.modificationDate] as? Date,
|
||||
date > newest {
|
||||
newest = date
|
||||
}
|
||||
}
|
||||
return newest
|
||||
}
|
||||
|
||||
private static func stageReceiptDate(_ receipt: URL) -> Date? {
|
||||
guard let text: String = try? String(contentsOf: receipt, encoding: .utf8),
|
||||
let interval: TimeInterval = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
else { return nil }
|
||||
return Date(timeIntervalSince1970: interval)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -11,7 +11,7 @@
|
||||
// cases (toolchain missing, dlopen failure, etc.) pass through under
|
||||
// `.compilerError`.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
|
||||
/// Snippet failed to compile. `diagnostics` are already line-mapped via the
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
// across the Swift and DSL paths. The only difference is speed: a graph edit
|
||||
// re-evaluates in microseconds instead of a swiftc round-trip.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import LyrebirdSynth
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
|
||||
@@ -17,9 +17,9 @@
|
||||
// that file, which is what lets `import LyrebirdSynth` and the injected
|
||||
// `context: SnippetContext` resolve for an otherwise free-standing file.
|
||||
//
|
||||
// macOS only.
|
||||
// macOS/Linux only.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Provides code completion for a live-coding editor buffer.
|
||||
@@ -92,6 +92,13 @@ public actor SnippetCompletionService {
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: session.importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#if os(Linux)
|
||||
// CALSA's system-library module map is source-only (see LiveSession);
|
||||
// completion needs it too, or `import LyrebirdSynth` fails to resolve.
|
||||
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: session.importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#endif
|
||||
for path: URL in session.librarySearchPaths {
|
||||
args += ["-L", path.path]
|
||||
}
|
||||
@@ -106,8 +113,16 @@ public actor SnippetCompletionService {
|
||||
}
|
||||
|
||||
private static func sdkPath() -> String? {
|
||||
// Linux needs no `-sdk`, and `xcrun` does not exist there. Crucially,
|
||||
// guard the spawn: on Linux, `Process.run()` throws when the launch path
|
||||
// is missing, and a subsequent `waitUntilExit()` on a process that never
|
||||
// started BLOCKS FOREVER (it is a no-op on macOS) — the completion hang.
|
||||
// The macOS xcrun helpers in LiveCompiler avoid this by checking
|
||||
// `isExecutableFile(atPath:)` first; do the same here.
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
||||
let p: Process = Process()
|
||||
p.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||
p.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
p.arguments = ["--show-sdk-path", "--sdk", "macosx"]
|
||||
let out: Pipe = Pipe()
|
||||
p.standardOutput = out
|
||||
@@ -123,12 +138,20 @@ public actor SnippetCompletionService {
|
||||
/// Minimum-deployment target triple. Arch matches the running process;
|
||||
/// the OS floor matches the package's `macOS 15` minimum.
|
||||
private static func targetTriple() -> String {
|
||||
#if os(macOS)
|
||||
#if arch(arm64)
|
||||
let arch: String = "arm64"
|
||||
return "arm64-apple-macosx15.0"
|
||||
#else
|
||||
let arch: String = "x86_64"
|
||||
return "x86_64-apple-macosx15.0"
|
||||
#endif
|
||||
#else
|
||||
// Linux GNU triple; the Swift/LLVM spelling of arm64 is `aarch64`.
|
||||
#if arch(arm64)
|
||||
return "aarch64-unknown-linux-gnu"
|
||||
#else
|
||||
return "x86_64-unknown-linux-gnu"
|
||||
#endif
|
||||
#endif
|
||||
return "\(arch)-apple-macosx15.0"
|
||||
}
|
||||
|
||||
/// Launch sourcekit-lsp and open the (empty) document. Call once before the
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
// synth that the host will track for re-evaluation cleanup, and report back via
|
||||
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import LyrebirdSynth
|
||||
|
||||
public final class SnippetContext {
|
||||
@@ -43,7 +43,7 @@ public final class SnippetContext {
|
||||
session.track(synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "engine.add failed: \(error)"
|
||||
session.appendMessage("engine.add failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public final class SnippetContext {
|
||||
try session.swapSlot(name, synth: synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "play(slot: \"\(name)\") failed: \(error)"
|
||||
session.appendMessage("play(slot: \"\(name)\") failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,41 @@ public final class SnippetContext {
|
||||
play(ClosureSynthesizer(bus: bus, make))
|
||||
}
|
||||
|
||||
/// **Gracefully release** the voice in a named slot — trigger its envelope
|
||||
/// release phase and let it tail out and free itself — then drop the slot.
|
||||
///
|
||||
/// The live-coding "start a voice, let go of it later" gesture: name a slot
|
||||
/// with ``play(slot:_:)``, then release it from a *separate* evaluation (e.g.
|
||||
/// select the line and hit ⌘E):
|
||||
///
|
||||
/// ```swift
|
||||
/// context.play(slot: "pad") { EnvGen(gate: 1, ...) * OscSaw.Audio(freq: 110) }
|
||||
/// // …later, in another evaluation:
|
||||
/// context.release(slot: "pad")
|
||||
/// ```
|
||||
///
|
||||
/// The released voice must free itself (an `EnvGen`/gate with a free-on-done
|
||||
/// action) to leave the engine. For an immediate hard stop instead, use
|
||||
/// ``free(slot:)``.
|
||||
///
|
||||
/// - Parameter name: Slot to release.
|
||||
/// - Returns: `true` if a gated voice was released; `false` if the slot was
|
||||
/// empty or its occupant has no gate.
|
||||
@discardableResult
|
||||
@MainActor public func release(slot name: String) -> Bool {
|
||||
session.releaseSlot(name)
|
||||
}
|
||||
|
||||
/// **Immediately** stop and remove the voice in a named slot — a hard cut,
|
||||
/// no release tail. The counterpart to ``release(slot:)``.
|
||||
///
|
||||
/// - Parameter name: Slot to free.
|
||||
/// - Returns: `true` if a voice was removed; `false` if the slot was empty.
|
||||
@discardableResult
|
||||
@MainActor public func free(slot name: String) -> Bool {
|
||||
session.clearSlot(name)
|
||||
}
|
||||
|
||||
/// Snippet-side hook for test verification: report the engine's sample rate
|
||||
/// back through the session so tests can confirm the `context.engine`
|
||||
/// linkage compiled and called correctly.
|
||||
@@ -146,7 +181,7 @@ public final class SnippetContext {
|
||||
/// Snippet-side hook for test verification: record an arbitrary message
|
||||
/// back on the session. Lets tests confirm the snippet body executed.
|
||||
public func reportMessage(_ message: String) {
|
||||
session.lastSnippetMessage = message
|
||||
session.appendMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//
|
||||
// C ABI signature of the snippet's exported entry point.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. The host
|
||||
/// passes a pointer to a `LiveSession` (or harness context) here; snippets need
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// from the opaque pointer the host hands in. The user's body is dropped in as
|
||||
// the function body.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public enum SnippetHarness {
|
||||
|
||||
@@ -27,6 +27,7 @@ public enum SnippetHarness {
|
||||
/// `compileAndRun` is `@MainActor`).
|
||||
public static func wrap(userBody: String) -> WrappedSnippet {
|
||||
let preamble: String = """
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
|
||||
@@ -12,9 +12,9 @@
|
||||
// `initialize` / `initialized`, `textDocument/didOpen` / `didChange`, and
|
||||
// `textDocument/completion`.
|
||||
//
|
||||
// macOS only — the whole live-compile surface shells out to the toolchain.
|
||||
// macOS/Linux only — the whole live-compile surface shells out to the toolchain.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Nanoseconds in one second — for `Task.sleep`.
|
||||
@@ -80,8 +80,22 @@ public final class SourceKitLSPClient: @unchecked Sendable {
|
||||
/// Resolve `sourcekit-lsp` from the active toolchain via `xcrun`, falling
|
||||
/// back to the conventional Xcode path.
|
||||
private static func resolveExecutable() -> URL {
|
||||
// Guard the xcrun spawn: `xcrun` is macOS-only, and on Linux
|
||||
// `Process.run()` throws for a missing launch path while a following
|
||||
// `waitUntilExit()` on the never-started process BLOCKS FOREVER (a no-op
|
||||
// on macOS). Skip straight to the conventional path there, where the
|
||||
// toolchain ships `/usr/bin/sourcekit-lsp`.
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else {
|
||||
// No xcrun (Linux): prefer a `sourcekit-lsp` on $PATH (swiftly, a
|
||||
// custom toolchain, …) over the conventional /usr/bin location.
|
||||
if let onPath: String = livecompileExecutableOnPath("sourcekit-lsp") {
|
||||
return URL(fileURLWithPath: onPath)
|
||||
}
|
||||
return URL(fileURLWithPath: "/usr/bin/sourcekit-lsp")
|
||||
}
|
||||
let xcrun: Process = Process()
|
||||
xcrun.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun")
|
||||
xcrun.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
xcrun.arguments = ["--find", "sourcekit-lsp"]
|
||||
let out: Pipe = Pipe()
|
||||
xcrun.standardOutput = out
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
// LyrebirdLiveCompile
|
||||
//
|
||||
// Errors surfaced by ``SourceKitLSPClient``. macOS only.
|
||||
// Errors surfaced by ``SourceKitLSPClient``. macOS/Linux only.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// A failure from the `sourcekit-lsp` client.
|
||||
public enum SourceKitLSPError: Error, CustomStringConvertible {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// few hundred ms after ⌘↩, then the swap lands exactly on the downbeat rather
|
||||
// than whenever the compile happened to finish.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// SwiftFormatter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — snippet source formatting.
|
||||
//
|
||||
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
|
||||
// shells to `swiftc`) to pretty-print a snippet. macOS/Linux only — iOS cannot
|
||||
// exec subprocesses. Writes the source to a temp file and runs `swift-format format
|
||||
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
|
||||
// a streaming approach risks on large output.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Stateless `swift-format` wrapper.
|
||||
public enum SwiftFormatter {
|
||||
|
||||
/// Format `source` and return the pretty-printed result. Runs synchronously
|
||||
/// (spawns `swift-format`); call off the main thread.
|
||||
///
|
||||
/// - Parameter source: Swift source to format. Top-level snippet code is
|
||||
/// accepted — `swift-format` formats whatever parses.
|
||||
/// - Returns: The formatted source.
|
||||
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
|
||||
/// (typically a parse error), or an I/O failure.
|
||||
public static func format(source: String) throws -> String {
|
||||
let tool: String = try findSwiftFormat()
|
||||
|
||||
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||||
let workDir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
|
||||
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("\(error)")
|
||||
}
|
||||
// Register cleanup as soon as the dir exists, so a later write failure
|
||||
// doesn't leak it.
|
||||
defer { try? FileManager.default.removeItem(at: workDir) }
|
||||
do {
|
||||
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("\(error)")
|
||||
}
|
||||
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: tool)
|
||||
process.arguments = ["format", sourcePath]
|
||||
let stdoutPipe: Pipe = Pipe()
|
||||
let stderrPipe: Pipe = Pipe()
|
||||
process.standardOutput = stdoutPipe
|
||||
process.standardError = stderrPipe
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
|
||||
}
|
||||
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
|
||||
// emit both a large formatted buffer and (on a broken snippet) a large
|
||||
// diagnostic stream; reading them sequentially would deadlock if the
|
||||
// stream we aren't reading yet fills its OS pipe buffer while the child
|
||||
// blocks writing to it.
|
||||
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
|
||||
let errHandle: FileHandle = stderrPipe.fileHandleForReading
|
||||
let group: DispatchGroup = DispatchGroup()
|
||||
let drainQueue: DispatchQueue = DispatchQueue(
|
||||
label: "net.realizedsound.lyrebird.swift-format-drain",
|
||||
attributes: .concurrent
|
||||
)
|
||||
// Box the drained bytes in reference cells: on Linux the `DispatchQueue`
|
||||
// closures are `@Sendable` and cannot mutate a captured `var`. Each
|
||||
// closure writes its own box (no shared mutation), and `group.wait()`
|
||||
// fences before the reads below.
|
||||
let outBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
|
||||
let errBox: SwiftFormatterDataBox = SwiftFormatterDataBox()
|
||||
group.enter()
|
||||
drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.enter()
|
||||
drainQueue.async { errBox.data = errHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.wait()
|
||||
process.waitUntilExit()
|
||||
let outData: Data = outBox.data
|
||||
let errData: Data = errBox.data
|
||||
|
||||
guard process.terminationStatus == 0 else {
|
||||
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
|
||||
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
|
||||
}
|
||||
guard let formatted: String = String(data: outData, encoding: .utf8) else {
|
||||
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
|
||||
}
|
||||
return formatted
|
||||
}
|
||||
|
||||
/// Whether a `swift-format` executable is available on this machine.
|
||||
public static var isAvailable: Bool {
|
||||
(try? findSwiftFormat()) != nil
|
||||
}
|
||||
|
||||
// MARK: - Tool resolution
|
||||
|
||||
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
|
||||
static func findSwiftFormat() throws -> String {
|
||||
if let viaXcrun: String = swiftFormatViaXcrun() {
|
||||
return viaXcrun
|
||||
}
|
||||
let candidates: [String] = [
|
||||
"/usr/bin/swift-format",
|
||||
"/usr/local/bin/swift-format",
|
||||
"/opt/homebrew/bin/swift-format",
|
||||
]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw SwiftFormatterError.toolNotFound
|
||||
}
|
||||
|
||||
private static func swiftFormatViaXcrun() -> String? {
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
process.arguments = ["-f", "swift-format"]
|
||||
let stdout: Pipe = Pipe()
|
||||
process.standardOutput = stdout
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
guard process.terminationStatus == 0 else { return nil }
|
||||
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference cell for one drained pipe's bytes, so the concurrent drain closures
|
||||
/// write through a reference instead of mutating a captured `var` (which the
|
||||
/// Linux `@Sendable` `DispatchQueue` closures forbid). `@unchecked Sendable`:
|
||||
/// each instance is written by exactly one closure and read only after
|
||||
/// `DispatchGroup.wait()`.
|
||||
private final class SwiftFormatterDataBox: @unchecked Sendable {
|
||||
var data: Data = Data()
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
// SwiftFormatterError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Errors raised while formatting snippet source with `swift-format`.
|
||||
public enum SwiftFormatterError: Error {
|
||||
/// No `swift-format` executable could be located (no Xcode / toolchain, or
|
||||
/// an older toolchain that predates the bundled formatter).
|
||||
case toolNotFound
|
||||
/// `swift-format` exited non-zero — usually a parse error in the source.
|
||||
case formatFailed(exitCode: Int32, stderr: String)
|
||||
/// A filesystem or process I/O failure.
|
||||
case ioFailed(String)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
// SwiftToolchainStatus.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Result of probing for a usable Swift toolchain (the Swift scratchpad compiles
|
||||
/// snippets by shelling out to `swiftc`, which requires Xcode or the Command Line
|
||||
/// Tools). The Graph DSL mode does not need a toolchain, so a `.missing*` status is
|
||||
/// a soft condition — it gates only the Swift-compile path. Produced by ``ToolchainProbe``.
|
||||
public enum SwiftToolchainStatus: Equatable, Sendable {
|
||||
/// `swiftc` and the macOS SDK both resolve — the Swift scratchpad can compile.
|
||||
case available
|
||||
/// No developer tools at all (`xcode-select -p` fails and `swiftc` is unresolved).
|
||||
/// Fix: install the Command Line Tools (`xcode-select --install`) or Xcode.
|
||||
case missingDeveloperTools
|
||||
/// A developer directory is selected but `swiftc` could not be resolved.
|
||||
/// Fix: install/repair Xcode or the Command Line Tools.
|
||||
case missingSwiftc
|
||||
/// `swiftc` resolves but the macOS SDK does not — usually an incomplete Xcode.
|
||||
/// Fix: install a full Xcode.
|
||||
case missingSDK
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
// ToolchainProbe.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Detects whether a usable Swift toolchain is present, so the app can warn the user
|
||||
/// (with install guidance) instead of only failing into the console on the first Run.
|
||||
///
|
||||
/// The resolvers are injectable so the `.missing*` branches can be unit-tested without
|
||||
/// actually uninstalling the toolchain; the defaults wrap the real `LiveCompiler`
|
||||
/// resolution (`xcrun -f swiftc`, `xcrun --show-sdk-path`) plus `xcode-select -p`.
|
||||
///
|
||||
/// **Not RT-related.** Runs `xcrun` / `xcode-select` subprocesses — call off the main
|
||||
/// thread (a couple of fast execs).
|
||||
public struct ToolchainProbe: Sendable {
|
||||
|
||||
private let swiftcResolver: @Sendable () -> String?
|
||||
private let sdkResolver: @Sendable () -> String?
|
||||
private let developerDirResolver: @Sendable () -> String?
|
||||
|
||||
/// - Parameters:
|
||||
/// - swiftcResolver: Returns the `swiftc` path, or `nil` when unresolved.
|
||||
/// - sdkResolver: Returns the macOS SDK path, or `nil` when unresolved.
|
||||
/// - developerDirResolver: Returns the active developer dir (`xcode-select -p`),
|
||||
/// or `nil` when no developer directory is configured.
|
||||
public init(
|
||||
swiftcResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSwiftcResolver,
|
||||
sdkResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSDKResolver,
|
||||
developerDirResolver: @escaping @Sendable () -> String? = ToolchainProbe.developerDirViaXcodeSelect
|
||||
) {
|
||||
self.swiftcResolver = swiftcResolver
|
||||
self.sdkResolver = sdkResolver
|
||||
self.developerDirResolver = developerDirResolver
|
||||
}
|
||||
|
||||
/// Default `swiftc` resolver — wraps the internal `LiveCompiler.findSwiftc()` so the
|
||||
/// public `init` default argument does not reference internal API.
|
||||
public static func defaultSwiftcResolver() -> String? { try? LiveCompiler.findSwiftc() }
|
||||
|
||||
/// Default macOS SDK resolver — wraps the internal `LiveCompiler.sdkPathViaXcrun()`.
|
||||
public static func defaultSDKResolver() -> String? { LiveCompiler.sdkPathViaXcrun() }
|
||||
|
||||
/// Classify the current toolchain state.
|
||||
public func status() -> SwiftToolchainStatus {
|
||||
let swiftc: String? = swiftcResolver()
|
||||
let sdk: String? = sdkResolver()
|
||||
if swiftc != nil && sdk != nil { return .available }
|
||||
if swiftc == nil {
|
||||
// No swiftc: distinguish "no developer tools at all" from "tools present
|
||||
// but swiftc unresolved" by whether a developer dir is configured.
|
||||
return developerDirResolver() == nil ? .missingDeveloperTools : .missingSwiftc
|
||||
}
|
||||
// swiftc resolves but the SDK does not.
|
||||
return .missingSDK
|
||||
}
|
||||
|
||||
/// Active developer directory via `xcode-select -p`, or `nil` when unset / xcode-select
|
||||
/// is missing / returns non-zero.
|
||||
public static func developerDirViaXcodeSelect() -> String? {
|
||||
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else { return nil }
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||
process.arguments = ["-p"]
|
||||
let stdout: Pipe = Pipe()
|
||||
process.standardOutput = stdout
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
guard process.terminationStatus == 0 else { return nil }
|
||||
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -12,7 +12,7 @@
|
||||
// from each swiftc-reported line so error rows point back at the row the user
|
||||
// typed.
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
public struct WrappedSnippet: Equatable {
|
||||
public let source: String
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
// LinuxScratchView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Minimal Linux/GTK4 live-coding scratch surface. The macOS editor
|
||||
// (LyrebirdScratchView / NSTextView) is `#if os(macOS)`-gated elsewhere; this is
|
||||
// the SwiftOpenUI counterpart: a plain code editor + Run/Clear + a console,
|
||||
// driving a `LiveSession` (compile the snippet to a .so, dlopen it, run it). No
|
||||
// syntax highlighting / gutter / completion — that is the full-parity
|
||||
// GtkSourceView editor (a later step). `import LyrebirdUI` re-exports the
|
||||
// SwiftOpenUI View DSL + the GTK4 backend and provides `LyrebirdScopeView`.
|
||||
#if os(Linux)
|
||||
import Foundation
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile // LiveSession
|
||||
import LyrebirdUI
|
||||
|
||||
/// A seed snippet: the fastest path to sound — a bare generator graph via
|
||||
/// `context.play { … }` — plus a console line.
|
||||
public let lyrebirdLinuxScratchSeed: String = """
|
||||
// Edit, then Run. `context` is your live LiveSession. Ctrl+Space for completions.
|
||||
context.play { OscSin.Audio(freq: 330, mul: 0.15) }
|
||||
context.reportMessage("playing 330 Hz")
|
||||
"""
|
||||
|
||||
/// Observable state for the Linux scratch view: the running flag and the console
|
||||
/// log. The `LiveSession` compiles/runs off the main thread; results are folded
|
||||
/// back onto the main actor (== the GTK main loop) so the `@Observable` reads
|
||||
/// refresh the view.
|
||||
///
|
||||
/// `@unchecked Sendable`: main-thread-confined UI state plus an
|
||||
/// `@unchecked Sendable` `LiveSession`; the run closure hops to the main actor
|
||||
/// before touching `console` / `isRunning`.
|
||||
@Observable
|
||||
public final class LinuxScratchModel: @unchecked Sendable {
|
||||
|
||||
public var console: String = ""
|
||||
public var isRunning: Bool = false
|
||||
|
||||
/// The editor's document text and current selection. Owned by the model (not
|
||||
/// the view) so file open/save and the dirty flag have one source of truth.
|
||||
public var source: String
|
||||
public var selection: String = ""
|
||||
|
||||
/// Path of the file backing the document, or `nil` for an unsaved buffer.
|
||||
public var currentPath: String? = nil
|
||||
/// Set when the buffer has unsaved edits; drives the title's `●` marker.
|
||||
public var isDirty: Bool = false
|
||||
/// Suppresses dirty-marking while the model itself replaces the text (new /
|
||||
/// open), so a load doesn't immediately look unsaved.
|
||||
@ObservationIgnored private var suppressDirty: Bool = false
|
||||
|
||||
@ObservationIgnored public let session: LiveSession
|
||||
@ObservationIgnored public let completionService: SnippetCompletionService
|
||||
/// Imperative handle to push loaded text into the reused editor widget.
|
||||
@ObservationIgnored public let editor: CodeEditorController = CodeEditorController()
|
||||
|
||||
public init(session: LiveSession, initialSource: String = lyrebirdLinuxScratchSeed) {
|
||||
self.session = session
|
||||
self.source = initialSource
|
||||
self.completionService = SnippetCompletionService(session: session)
|
||||
}
|
||||
|
||||
/// The editor's two-way binding calls this; marks the buffer dirty unless the
|
||||
/// change came from a programmatic load. Ignores an unchanged value so a
|
||||
/// widget echo of the same text never flips the dirty flag — which also makes
|
||||
/// a load robust whether or not GtkSourceView delivers its change signal
|
||||
/// synchronously: `replaceDocument` has already set `source`, so the echoed
|
||||
/// value compares equal and returns here before touching `isDirty`.
|
||||
public func setSource(_ newValue: String) {
|
||||
guard newValue != source else { return }
|
||||
source = newValue
|
||||
if !suppressDirty { isDirty = true }
|
||||
}
|
||||
|
||||
/// A short title for the window/header: the filename (or `untitled.swift`)
|
||||
/// with a leading `●` when there are unsaved edits.
|
||||
public var displayTitle: String {
|
||||
let name: String = currentPath.map(Self.lastComponent) ?? "untitled.swift"
|
||||
return (isDirty ? "● " : "") + name
|
||||
}
|
||||
|
||||
/// Ctrl+Space completion source for the editor: the buffer text + caret
|
||||
/// (line, column) → sourcekit-lsp completions mapped to editor candidates.
|
||||
/// Errors (server hiccups) yield no candidates rather than surfacing.
|
||||
public var completionProvider: @Sendable (String, Int, Int) async -> [CodeCompletionItem] {
|
||||
let service: SnippetCompletionService = completionService
|
||||
return { (text: String, line: Int, column: Int) in
|
||||
let items: [LSPCompletionItem] = (try? await service.completions(
|
||||
userBody: text, line: line, character: column)) ?? []
|
||||
return items.map { (item: LSPCompletionItem) in
|
||||
CodeCompletionItem(label: item.label, insertText: item.insertText)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compile + run `source`. `additive` keeps the previous run's synths;
|
||||
/// otherwise they are cleared first. Non-blocking: swiftc runs off-main.
|
||||
public func run(source: String, additive: Bool) {
|
||||
guard !isRunning else { return }
|
||||
isRunning = true
|
||||
append(additive ? "▶ running (additive)…" : "▶ running…")
|
||||
let sess: LiveSession = session
|
||||
Task { [weak self] in
|
||||
do {
|
||||
_ = try await sess.compileAndRunAsync(source, additive: additive)
|
||||
let messages: [String] = sess.drainMessages()
|
||||
await self?.finish(ok: true, messages: messages, error: nil)
|
||||
} catch {
|
||||
let messages: [String] = sess.drainMessages()
|
||||
await self?.finish(ok: false, messages: messages, error: "\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public func clear() {
|
||||
console = ""
|
||||
}
|
||||
|
||||
/// Panic valve: stop and remove all snippet audio without tearing down the
|
||||
/// engine (``LiveSession/resetAll()``). Leaves the editor and session intact
|
||||
/// so the next Run starts clean.
|
||||
///
|
||||
/// Guarded by `isRunning` for the same reason the macOS host's
|
||||
/// `resetSession()` guards on `isCompiling`: `resetAll()`'s documented
|
||||
/// precondition forbids running it concurrently with an in-flight
|
||||
/// `compileAndRunAsync`, whose `clearTracked()`/`runEntry` interleave can
|
||||
/// leak a just-added synth. A no-op while a compile is running is the safe
|
||||
/// choice — the audio it starts is cleared by the next Stop.
|
||||
public func killAudio() {
|
||||
guard !isRunning else { return }
|
||||
session.resetAll()
|
||||
append("■ audio stopped")
|
||||
}
|
||||
|
||||
// MARK: - File open / save
|
||||
//
|
||||
// Snippets are plain Swift source, so a document is just a `.swift` text
|
||||
// file. The native `GtkFileDialog` (via `GTK4FileDialog`) picks the path;
|
||||
// its completion runs on the GTK main thread, same as these methods (they
|
||||
// are invoked from button actions), so the `@Observable` writes are safe.
|
||||
|
||||
/// Reset to a fresh unsaved buffer seeded with the starter snippet.
|
||||
public func newDocument() {
|
||||
replaceDocument(text: lyrebirdLinuxScratchSeed, path: nil)
|
||||
append("✎ new document")
|
||||
}
|
||||
|
||||
/// Present an Open dialog, then load the chosen file.
|
||||
public func openDocument() {
|
||||
GTK4FileDialog.open(title: "Open Lyrebird snippet") { [weak self] (path: String?) in
|
||||
guard let self, let path: String = path else { return }
|
||||
self.loadFile(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load `path` into the editor (replacing the buffer).
|
||||
public func loadFile(_ path: String) {
|
||||
do {
|
||||
let text: String = try String(contentsOfFile: path, encoding: .utf8)
|
||||
replaceDocument(text: text, path: path)
|
||||
append("📂 opened " + Self.lastComponent(path))
|
||||
} catch {
|
||||
append("✗ open failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Save to the current path, or fall through to Save As when there is none.
|
||||
public func save() {
|
||||
if let path: String = currentPath {
|
||||
writeFile(path)
|
||||
} else {
|
||||
saveAs()
|
||||
}
|
||||
}
|
||||
|
||||
/// Present a Save dialog (pre-filled with the current name), then write.
|
||||
public func saveAs() {
|
||||
let suggested: String = currentPath.map(Self.lastComponent) ?? "untitled.swift"
|
||||
GTK4FileDialog.save(title: "Save Lyrebird snippet", suggestedName: suggested) { [weak self] (path: String?) in
|
||||
guard let self, let path: String = path else { return }
|
||||
self.writeFile(path)
|
||||
}
|
||||
}
|
||||
|
||||
private func writeFile(_ path: String) {
|
||||
do {
|
||||
try source.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
currentPath = path
|
||||
isDirty = false
|
||||
append("💾 saved " + Self.lastComponent(path))
|
||||
} catch {
|
||||
append("✗ save failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace the buffer with `text` and adopt `path`, without marking dirty.
|
||||
/// Pushes into the live widget too — the reused editor doesn't otherwise
|
||||
/// mirror an external text change (see `CodeEditorController`).
|
||||
private func replaceDocument(text: String, path: String?) {
|
||||
suppressDirty = true
|
||||
source = text
|
||||
editor.setText(text)
|
||||
currentPath = path
|
||||
isDirty = false
|
||||
suppressDirty = false
|
||||
}
|
||||
|
||||
private static func lastComponent(_ path: String) -> String {
|
||||
(path as NSString).lastPathComponent
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private func finish(ok: Bool, messages: [String], error: String?) {
|
||||
for message: String in messages {
|
||||
append(message)
|
||||
}
|
||||
if let error: String = error {
|
||||
append("✗ " + error)
|
||||
} else {
|
||||
append("✓ done")
|
||||
}
|
||||
isRunning = false
|
||||
}
|
||||
|
||||
private func append(_ line: String) {
|
||||
console += (console.isEmpty ? "" : "\n") + line
|
||||
}
|
||||
}
|
||||
|
||||
/// The minimal Linux scratch editor: a `TextEditor` over the snippet source,
|
||||
/// Run (fresh / additive) + Clear buttons, a live oscilloscope of the session's
|
||||
/// output, and a console. Host it in a `LyrebirdWindow` or a `WindowGroup`.
|
||||
public struct LyrebirdScratchLinuxView: View {
|
||||
|
||||
@State private var model: LinuxScratchModel
|
||||
|
||||
/// - Parameters:
|
||||
/// - session: The `LiveSession` that compiles + runs snippets.
|
||||
/// - initialSource: Seed editor text. Defaults to a play-a-tone snippet.
|
||||
public init(session: LiveSession, initialSource: String = lyrebirdLinuxScratchSeed) {
|
||||
_model = State(wrappedValue: LinuxScratchModel(session: session, initialSource: initialSource))
|
||||
}
|
||||
|
||||
/// Host an externally-owned model — used when the app also wires the model's
|
||||
/// file actions into the menu bar (`.commands`), which needs the same
|
||||
/// instance the view renders.
|
||||
public init(model: LinuxScratchModel) {
|
||||
_model = State(wrappedValue: model)
|
||||
}
|
||||
|
||||
/// What Run evaluates: the selection if the user has selected something
|
||||
/// (non-whitespace), otherwise the whole document.
|
||||
private var evaluationSource: String {
|
||||
model.selection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? model.source : model.selection
|
||||
}
|
||||
|
||||
/// Append a hint to the Run buttons when a selection is what will run.
|
||||
private func runLabel(base: String) -> String {
|
||||
model.selection.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
? base
|
||||
: base + " — selection"
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
Text("Lyrebird — Linux scratch — " + model.displayTitle)
|
||||
|
||||
// File actions (New / Open… / Save / Save As…) live in the menu bar
|
||||
// with Ctrl+N/O/S accelerators — see `lyrebirdScratchFileCommands`,
|
||||
// wired via `.commands` on the demo's WindowGroup. A snippet is plain
|
||||
// Swift source, so a document is just a `.swift` text file, saved and
|
||||
// loaded through the native GtkFileDialog.
|
||||
|
||||
// GtkSourceView-backed editor: Swift syntax highlighting + gutter.
|
||||
// The selection is mirrored out so Run can evaluate just the selected
|
||||
// lines (like the macOS editor); with nothing selected it runs the
|
||||
// whole buffer. The controller lets a file open replace the buffer.
|
||||
CodeEditor(
|
||||
text: Binding(get: { model.source }, set: { model.setSource($0) }),
|
||||
selection: Binding(get: { model.selection }, set: { model.selection = $0 }),
|
||||
controller: model.editor,
|
||||
completionProvider: model.completionProvider
|
||||
)
|
||||
.frame(height: 260)
|
||||
|
||||
HStack(spacing: 8) {
|
||||
Button {
|
||||
model.run(source: evaluationSource, additive: false)
|
||||
} label: {
|
||||
Text(model.isRunning ? "Running…" : runLabel(base: "Run (fresh)"))
|
||||
}
|
||||
Button {
|
||||
model.run(source: evaluationSource, additive: true)
|
||||
} label: {
|
||||
Text(runLabel(base: "Run (additive)"))
|
||||
}
|
||||
Button {
|
||||
model.killAudio()
|
||||
} label: {
|
||||
Text("Stop audio")
|
||||
}
|
||||
Button {
|
||||
model.clear()
|
||||
} label: {
|
||||
Text("Clear")
|
||||
}
|
||||
}
|
||||
|
||||
if let scope: ScopeCapture = model.session.scope {
|
||||
LyrebirdScopeView(capture: scope)
|
||||
}
|
||||
|
||||
Text("Console")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Text(model.console)
|
||||
.font(.caption)
|
||||
.monospacedDigit()
|
||||
.frame(height: 140)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
}
|
||||
|
||||
/// The scratchpad's File menu commands — New / Open… / Save / Save As… — with
|
||||
/// Ctrl+N / Ctrl+O / Ctrl+S / Ctrl+Shift+S accelerators (SwiftOpenUI maps the
|
||||
/// `.command` modifier to Ctrl on Linux). Attach to the hosting `WindowGroup`
|
||||
/// with `.commands { lyrebirdScratchFileCommands(model: model) }`; SwiftOpenUI
|
||||
/// declares commands on the Scene, not inside a View, so the app must own the
|
||||
/// model and pass the same instance to `LyrebirdScratchLinuxView(model:)`.
|
||||
@CommandsBuilder
|
||||
public func lyrebirdScratchFileCommands(model: LinuxScratchModel) -> some Commands {
|
||||
CommandGroup(replacing: .newItem) {
|
||||
CommandMenuItem("New", shortcut: KeyboardShortcut("n")) { model.newDocument() }
|
||||
CommandMenuItem("Open…", shortcut: KeyboardShortcut("o")) { model.openDocument() }
|
||||
}
|
||||
CommandGroup(replacing: .saveItem) {
|
||||
CommandMenuItem("Save", shortcut: KeyboardShortcut("s")) { model.save() }
|
||||
CommandMenuItem("Save As…", shortcut: KeyboardShortcut("s", modifiers: [.command, .shift])) { model.saveAs() }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -15,9 +15,19 @@ Compile diagnostics from a failing snippet are parsed by `DiagnosticParser`
|
||||
and rendered beneath the editor with line numbers already remapped from the wrapped
|
||||
source back to the user's snippet coordinates.
|
||||
|
||||
The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which is
|
||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||
`LyrebirdScratchView` (the `NSTextView` editor described here) is macOS-only, but
|
||||
the scratchpad itself runs on **Linux** too, through a GTK4 counterpart —
|
||||
`LyrebirdScratchLinuxView` / `LinuxScratchModel` on the SwiftOpenUI backend. Both
|
||||
drive the same `LyrebirdLiveCompile` engine; only the editor UI differs. See
|
||||
[Linux (GTK4)](#linux-gtk4) below. What is genuinely unavailable is **iOS**:
|
||||
`LyrebirdLiveCompile` shells out to `swiftc`, which iOS does not provide.
|
||||
|
||||
> Note: **Swift mode needs a Swift toolchain** (Xcode or the Command Line Tools) —
|
||||
> it compiles snippets with `swiftc`. At launch the app probes for one
|
||||
> (`ToolchainProbe`) and, if none is found, shows an alert (once per launch) with
|
||||
> install guidance (Install Command Line Tools / Get Xcode). **Graph DSL mode needs no
|
||||
> toolchain** — it interprets generator-graph expressions in-process — so it's the
|
||||
> zero-install fallback.
|
||||
|
||||
## Hosting
|
||||
|
||||
@@ -41,19 +51,43 @@ window.open {
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
|
||||
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
|
||||
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
|
||||
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
|
||||
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
||||
anonymous tracked synths and every named slot.
|
||||
|
||||
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
|
||||
running graph, without touching the rest of the buffer or the whole-buffer
|
||||
re-evaluation baseline (the buffer's clean/dirty status still reflects the last
|
||||
whole run). This is the live-coding "evaluate this line/region" gesture: audition
|
||||
a single voice or tweak, layer it in, keep going. It reads the editor selection
|
||||
via ``LyrebirdScratchModel/updateSelection(_:)`` and runs it through
|
||||
``LyrebirdScratchModel/runSelection()``; disabled when nothing is selected.
|
||||
|
||||
The engine status pill at the top-left is also a **Start/Stop** button
|
||||
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
|
||||
red "▶ start engine" when stopped. A snippet is only audible while the engine
|
||||
is running; the host normally starts it at launch, but this lets the user
|
||||
recover from a failed start (e.g. no output device) without relaunching.
|
||||
|
||||
## Engine panel (scope + status)
|
||||
|
||||
The panel at the bottom of the window is a small always-on view of the running
|
||||
engine:
|
||||
|
||||
- A live dual-channel **oscilloscope** of the output (``ScratchScopeView``),
|
||||
fed by a ``ScopeCapture`` that ``LiveSession`` attaches to the first one or two
|
||||
output buses at init (it must be installed before `start()`). Pass
|
||||
`attachScope: false` to `LiveSession.init` to opt out.
|
||||
- **CPU average / peak** meter bars and the **synth / group / snippet** counts,
|
||||
so overrun and node growth are visible at a glance.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
A snippet has one local in scope:
|
||||
@@ -71,8 +105,152 @@ context: SnippetContext
|
||||
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).
|
||||
- `context.reportMessage(_:)` — print a line to the **Console** panel (see
|
||||
below); the live-coding equivalent of `print`.
|
||||
|
||||
## Console
|
||||
|
||||
An always-open panel down the right side of the window is the log:
|
||||
|
||||
- **Report messages** — every `context.reportMessage(_:)` line (and host notices
|
||||
like a failed `engine.add` or a dropped slot swap).
|
||||
- **Errors** — compile and Graph DSL diagnostics, with their `line:col`, shown
|
||||
here rather than in a transient bottom strip so they stay visible while you
|
||||
fix them.
|
||||
- **Run notices** — a one-line result for each run.
|
||||
|
||||
Oldest first, auto-scrolled to the newest, capped at
|
||||
``LyrebirdScratchModel/maxConsoleEntries`` lines. **Clear** empties it; a
|
||||
**Reset Session** clears it too. The model exposes the log as
|
||||
``LyrebirdScratchModel/consoleEntries``.
|
||||
|
||||
## Functional snippets & scheduling
|
||||
|
||||
A Swift-mode snippet is **real Swift**, not just a graph expression — loops,
|
||||
`let` bindings, functions, arrays all work. The harness preamble imports
|
||||
**Foundation**, `LyrebirdSynth`, and `LyrebirdLiveCompile`, so `pow`, `sin`,
|
||||
`sqrt`, `Date`, and the whole generator library are in scope without any
|
||||
`import` — which is good, because a snippet **can't** declare one (its body is
|
||||
wrapped inside the entry function, and `import` is only legal at file scope). The
|
||||
one rule for anything time-based: **schedule** events, don't `Thread.sleep`. The snippet body runs
|
||||
once, synchronously, on the main thread; sleeping in a loop would freeze the UI
|
||||
(the audio thread is separate, but the editor isn't). Use
|
||||
`engine.schedule(_:after:)` for sample-accurate timing instead.
|
||||
|
||||
For example, a `for` loop that plays ten short sine tones a third of a second
|
||||
apart — a C-major run — each a decaying `Line` envelope times a sine that frees
|
||||
itself when done (`doneAction: .freeNode`), so the voices never pile up:
|
||||
|
||||
```swift
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||
for i in 0..<10 {
|
||||
let freq: Double = scale[i]
|
||||
let tone = ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
}
|
||||
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||
catch { context.reportMessage("schedule \(i) failed: \(error)") }
|
||||
}
|
||||
context.reportMessage("scheduled 10 tones")
|
||||
```
|
||||
|
||||
The loop returns immediately after scheduling all ten adds; the engine fires
|
||||
each at its time (`0, 0.35, 0.70 … s`). A 0.2 s tone with 0.35 s spacing leaves a
|
||||
short gap between each. This is *fire-and-forget* scheduling for a fixed sequence.
|
||||
|
||||
### The one rule: retention
|
||||
|
||||
The snippet body runs **once, synchronously, then returns**. Anything that fires
|
||||
*later* must be held by something that outlives the snippet — the snippet itself
|
||||
is transient. Three things self-sustain, and everything below builds on them:
|
||||
|
||||
- **`engine.schedule(…)`** — the engine holds the pending event.
|
||||
- **`LyrebirdRoutine` / `LyrebirdTask`** — the routine runs on a dedicated
|
||||
background thread that retains it until the body finishes or `stop()` is called.
|
||||
- **`context.play(…)` synths** — the session tracks them (and named slots).
|
||||
|
||||
A `Thread.sleep` or busy `while` loop in the snippet *body* is the anti-pattern:
|
||||
it runs on the **main thread**, so it freezes the editor UI (the RT audio thread
|
||||
keeps going, but you can't type). Anything that *waits* belongs on a routine's
|
||||
background thread, not in the body.
|
||||
|
||||
### Mechanisms
|
||||
|
||||
| Mechanism | Use for | Timing API |
|
||||
|---|---|---|
|
||||
| `context.engine.schedule(_:after:)` / `schedule(_:at:)` | One-shot "play this at time T" | Seconds, or a `SampleTime` |
|
||||
| `LyrebirdRoutine` | A sequence with pauses; open-ended loops | `ctx.wait(seconds:)` / `wait(beats:)` / `waitUntil(sampleTime:)` |
|
||||
| `LyrebirdTask` | Same as a routine but **pausable** (`pause()` / `resume()`) | same as routine |
|
||||
| `LyrebirdClock` | Beat → sample-time reference | `clock.sampleTime(beat:)`, `nextBeat(after:)` → feed `schedule(_:at:)` or `ctx.waitUntil(sampleTime:)` |
|
||||
| Trigger generators (`Impulse` → `Demand` / `TriggeredRandom` / gate) | Timing *inside* the audio graph — arps, gated LFOs, step patterns | Sample-accurate, in the running synth |
|
||||
| `LyrebirdProcess` / `LyrebirdEventList`, `Score` / `ScorePlayer` | Structured / pre-composed timelines | Event lists |
|
||||
|
||||
All of these are reachable from a snippet through `context.engine` and the public
|
||||
`LyrebirdSynth` types — nothing extra is injected.
|
||||
|
||||
### Waiting: `LyrebirdRoutine`
|
||||
|
||||
For "play N things with a pause between each" — the reactive counterpart to the
|
||||
fire-and-forget loop above — use a routine. Its body runs on a background thread
|
||||
(so `wait` never freezes the UI), and `routine.start(engine:)` keeps it alive
|
||||
after the snippet returns:
|
||||
|
||||
```swift
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0]
|
||||
let routine = LyrebirdRoutine { ctx in
|
||||
for freq in scale {
|
||||
ctx.add(ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
})
|
||||
try ctx.wait(seconds: 0.3) // background-thread wait — UI stays live
|
||||
}
|
||||
}
|
||||
routine.start(engine: context.engine) // self-sustaining; survives the snippet
|
||||
```
|
||||
|
||||
`ctx.add(_:)` hops to the main-actor `engine.add` for you. `ctx.wait(beats:)`
|
||||
waits at `ctx.tempo` (default 120 BPM; set `ctx.tempo = …` in the body to change
|
||||
it); `ctx.waitUntil(sampleTime:)` waits to an absolute engine time, which is where
|
||||
`LyrebirdClock.sampleTime(beat:)` comes in for on-grid spacing. Call
|
||||
`routine.stop()` (e.g. from a later ⌘E) to cancel — the body exits at its next
|
||||
`wait`.
|
||||
|
||||
### Caveats
|
||||
|
||||
- **Never block the main thread** — no `Thread.sleep` / busy loops in the snippet
|
||||
body. Wait on a routine instead.
|
||||
- `Task { }` / `DispatchQueue.main.asyncAfter` *technically* work (they fire later
|
||||
on main and the session keeps `context` alive), but prefer `engine.schedule`
|
||||
(sample-accurate) or a routine (proper timed waits) over ad-hoc dispatch.
|
||||
- A `LyrebirdClock` used only to compute schedule times is fine to let go; if
|
||||
you need it *driving* something over time, a routine's thread keeps it alive.
|
||||
|
||||
### NRT: sample-clock timing only
|
||||
|
||||
**Render to File (⌥⌘R) is offline.** The `NRTDriver` renders faster than real
|
||||
time in a tight **synchronous burst** — 10 s of audio in a fraction of a second —
|
||||
and it does **not** wait for anything on the wall clock. So only timing expressed
|
||||
in **engine / sample time** survives a render; wall-clock timing silently drops out.
|
||||
|
||||
| Mechanism | Live | Render to File |
|
||||
|---|---|---|
|
||||
| `engine.schedule(_:after:/at:)` | ✅ | ✅ — fires at its sample time as blocks render |
|
||||
| In-graph triggers (`Impulse` → `Demand` / gates) | ✅ | ✅ — per-sample, driven by the render itself (best for NRT) |
|
||||
| `LyrebirdClock.sampleTime(beat:)` → `schedule(_:at:)` | ✅ | ✅ — pure beat→sample math |
|
||||
| `LyrebirdRoutine` / `LyrebirdTask` (`wait(seconds:/beats:)`) | ✅ | ❌ — **wall-clock sleeps on a background thread; the render finishes before they fire, so their `ctx.add`s never make the file** |
|
||||
| Real-time playback (`playTimeline`, live `ScorePlayer`) | ✅ | ❌ — the sample-accurate scheduling underneath is fine; the wall-clock playback driver isn't |
|
||||
|
||||
Rule of thumb: if the timing is a routine's `wait`, it's for **live** play; to make
|
||||
the same idea render, re-express it as `engine.schedule(_:after:)` (fixed
|
||||
sequence) or an `Impulse`-driven graph (periodic / patterned). This is a real
|
||||
footgun — routine timing works when you play it and silently produces an empty or
|
||||
truncated bounce when you render it.
|
||||
|
||||
> Note: **Graph DSL mode** evaluates only generator-graph expressions — no loops
|
||||
> or scheduling. Functional code like the above needs **Swift mode**.
|
||||
|
||||
## Named slots (hot-swap)
|
||||
|
||||
@@ -95,11 +273,35 @@ voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
|
||||
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
|
||||
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
|
||||
|
||||
Clear a slot with `context.session.clearSlot("bass")`, all slots with
|
||||
`context.session.clearSlots()`. The toolbar **Clear Synths** button is a full
|
||||
reset — anonymous synths *and* every slot. A slot definition you delete from the
|
||||
buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear
|
||||
it explicitly or hit Clear Synths.
|
||||
### Start a voice, release it later
|
||||
|
||||
The slot **name is the handle** — the persistent reference you keep across
|
||||
evaluations. (Swift `let`/`var` bindings do not carry from one snippet to the
|
||||
next: each ⌘↩ / ⌘E is a separately-compiled unit, so a variable declared in one
|
||||
run is invisible to the next.) So the "start something, let go of it later"
|
||||
gesture is: name a slot in one evaluation, then release it by name from another —
|
||||
a natural pairing with **Run Selection** (⌘E):
|
||||
|
||||
```swift
|
||||
// Select this line, ⌘E — starts a persistent, gated voice named "pad":
|
||||
context.play(slot: "pad") { EnvGen(gate: 1, /* … release-on-done */) * OscSaw.Audio(freq: 110) }
|
||||
|
||||
// …later, select this line, ⌘E — graceful release: the envelope tails out,
|
||||
// then the voice frees itself:
|
||||
context.release(slot: "pad")
|
||||
```
|
||||
|
||||
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||
drops the handle; the voice must free itself (an `EnvGen`/gate with a
|
||||
free-on-done action) to leave the engine.
|
||||
- `context.free(slot:)` is the **immediate** hard stop (no tail) — the
|
||||
counterpart to `release`.
|
||||
|
||||
Clear a slot with `context.free(slot: "bass")` (or `context.session.clearSlot`),
|
||||
all slots with `context.session.clearSlots()`. The toolbar **Clear Synths**
|
||||
button is a full reset — anonymous synths *and* every slot. A slot definition you
|
||||
delete from the buffer and stop re-running is *not* auto-removed (a `Pdef`-style
|
||||
gotcha) — release/free it explicitly or hit Clear Synths.
|
||||
|
||||
## Threading
|
||||
|
||||
@@ -190,15 +392,48 @@ through its own diagnostics.
|
||||
> which turns a benign ObjC class-duplication warning into a hard cast crash when
|
||||
> a snippet is `dlopen`'d.
|
||||
|
||||
## Compile artifacts & Application Support
|
||||
|
||||
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts: the
|
||||
swiftmodules, the Lyrebird dylibs, and the C-shim (`LyrebirdC`) Clang module map.
|
||||
In a dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||
non-sandboxed host — and the `swiftc` subprocess it spawns — trips the macOS
|
||||
"wants to access your Documents folder" permission gate. (The scratch/compile
|
||||
temp dirs use `/var/folders/…` and are never the cause.)
|
||||
|
||||
``LiveSession/stageArtifacts(from:to:)`` copies the minimal set into
|
||||
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` — an ungated
|
||||
location — and **rewrites the C module map's absolute umbrella-header path** to a
|
||||
staged copy of the header, so the staged directory is a fully self-contained
|
||||
compile root. ``LiveSession/defaultImportPaths()`` / `defaultLibrarySearchPaths()`
|
||||
/ `defaultRpaths()` then prefer the staged dir when it is populated. Staging is
|
||||
idempotent (a receipt file skips an unchanged source) and best-effort (falls back
|
||||
to the build dir on any failure). A host calls it once before constructing the
|
||||
session:
|
||||
|
||||
```swift
|
||||
LiveSession.stageArtifacts() // stage into App Support
|
||||
let session = LiveSession(engine: engine) // defaults resolve to the staged dir
|
||||
```
|
||||
|
||||
For a **standalone** app, ship the artifacts inside the bundle at
|
||||
`Contents/Resources/LyrebirdArtifacts` (name = ``LiveSession/bundledArtifactsDirName``);
|
||||
``LiveSession/artifactSourceDir()`` prefers that over the build dir, so a shipped
|
||||
`LyrebirdScratch.app` in `/Applications` stages without ever reading a
|
||||
permission-gated folder. In a dev checkout the one-time stage copy still reads
|
||||
the build dir under `~/Documents`; every later launch reuses the staged copy.
|
||||
|
||||
## 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.
|
||||
``SnippetCompletionService``. Press **Esc** (or **F5** — the standard macOS
|
||||
completion keys) to complete at the caret; the candidates are the real symbols the snippet would
|
||||
see at compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`,
|
||||
…), the injected `context` (`context.` → `play`, `engine`, …), and the Swift
|
||||
standard library. Completion is **manual, never auto-triggered on `.`** — an
|
||||
unrequested popup ambushes typing and the built-in completion window is awkward
|
||||
to dismiss mid-edit.
|
||||
|
||||
How it resolves those symbols for an otherwise free-standing file: the service
|
||||
maintains a small temp workspace holding the snippet **wrapped** in the same
|
||||
@@ -210,14 +445,44 @@ 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.
|
||||
|
||||
## Linux (GTK4)
|
||||
|
||||
On Linux the scratchpad is `LyrebirdScratchLinuxView`, driven by
|
||||
`LinuxScratchModel`, on the GTK4 SwiftOpenUI backend (re-exported through
|
||||
`LyrebirdUI`). It runs the same `LiveSession` compile→`dlopen`→run path as the
|
||||
macOS view; the difference is the editor and its chrome:
|
||||
|
||||
- **Editor** — a `GtkSourceView` with Swift syntax highlighting, a line-number
|
||||
gutter, and auto-indent (needs `libgtksourceview-5-dev`).
|
||||
- **Completion** — **Ctrl+Space** at the caret shows sourcekit-lsp completions,
|
||||
filtered by the identifier prefix already typed.
|
||||
- **Run** — a *Run (fresh)* button clears the previous snippet's synths; *Run
|
||||
(additive)* layers on top. Selecting one or more lines evaluates just those
|
||||
(the selection is mirrored out of the editor).
|
||||
- **Stop audio** — a panic button calling ``LiveSession/resetAll()``.
|
||||
- **Live scope** — a `LyrebirdScopeView` of the session's output.
|
||||
- **Save / load** — a native File menu (`New`, `Open…`, `Save`, `Save As…`) with
|
||||
`Ctrl+N` / `Ctrl+O` / `Ctrl+S` / `Ctrl+Shift+S` accelerators, backed by
|
||||
`GtkFileDialog`. Snippets are plain `.swift` files; `LinuxScratchModel` tracks
|
||||
`currentPath` / `isDirty` and surfaces a `●` marker in the title. The File menu
|
||||
commands are provided by `lyrebirdScratchFileCommands(model:)`, attached to the
|
||||
hosting `WindowGroup` with `.commands` (SwiftOpenUI declares commands on the
|
||||
Scene, so the app owns the model and shares it with
|
||||
`LyrebirdScratchLinuxView(model:)`).
|
||||
|
||||
`LyrebirdScratchLinuxDemo` is the runnable entry point. Because a snippet links
|
||||
the engine's dynamic libraries, run `swift build` in `LiveCompile/` before
|
||||
`swift run LyrebirdScratchLinuxDemo`. See `LINUX_README.md` for the full setup.
|
||||
|
||||
## Limitations
|
||||
|
||||
- macOS only.
|
||||
- Snippet compilation shells out to `swiftc`, so the scratchpad is desktop-only
|
||||
(macOS and Linux); it is unavailable on iOS.
|
||||
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
|
||||
approximate by design, not a full parser. Completion (above) uses the real
|
||||
compiler via sourcekit-lsp; the two are independent.
|
||||
- Completion currently triggers on `.`; a manual-invoke shortcut is a possible
|
||||
follow-up.
|
||||
- Completion is invoked manually with **Esc** (or **F5**); there is no
|
||||
auto-trigger on `.`.
|
||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||
dylib is `dlopen`'d.
|
||||
@@ -251,6 +516,17 @@ orange and a warning banner appears — nudging the user to restart to reclaim t
|
||||
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
|
||||
a hard stop: the choice stays with the user.
|
||||
|
||||
Two Run-menu commands act on this:
|
||||
|
||||
- **Reset Session** (``LyrebirdScratchModel/resetSession()``) — an *in-process*
|
||||
reset: stops all snippet audio, shuts down the code-completion server (freeing
|
||||
its subprocess and temp workspace), and clears diagnostics and the run
|
||||
baseline. **Non-destructive** — your buffer is left untouched, so it needs no
|
||||
confirmation. It does **not** unload the mapped snippet dylibs.
|
||||
- **Restart to Reclaim Memory…** — relaunches the app (after a confirmation,
|
||||
since unsaved buffer edits are lost), the only way to actually free the mapped
|
||||
dylibs. The fresh process starts at zero.
|
||||
|
||||
## Graph DSL mode (instant, no compile)
|
||||
|
||||
The status-bar toggle switches the editor between two evaluators:
|
||||
|
||||
@@ -28,7 +28,7 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
|
||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
||||
public func installMainMenu(appName: String = "LyrebirdScratch") {
|
||||
let mainMenu: NSMenu = NSMenu()
|
||||
|
||||
mainMenu.addItem(appMenuItem(appName: appName))
|
||||
@@ -39,6 +39,11 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
mainMenu.addItem(windowMenuItem())
|
||||
|
||||
NSApplication.shared.mainMenu = mainMenu
|
||||
|
||||
// Launch check: if the Swift toolchain is missing, warn with install guidance
|
||||
// (the Swift scratchpad needs swiftc). Fires once per launch — the probe runs
|
||||
// off-main and the alert (if any) is dispatched back to the main thread.
|
||||
warnIfSwiftToolchainMissing()
|
||||
}
|
||||
|
||||
// MARK: App menu
|
||||
@@ -135,6 +140,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
keyEquivalent: "f")
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
||||
action: #selector(formatCode(_:)),
|
||||
keyEquivalent: "f"))
|
||||
format.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(format)
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
@@ -152,10 +163,26 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
keyEquivalent: "\r")
|
||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(runAdd))
|
||||
menu.addItem(target(NSMenuItem(title: "Run Selection",
|
||||
action: #selector(runSelection(_:)),
|
||||
keyEquivalent: "e")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let render: NSMenuItem = target(NSMenuItem(title: "Render to File…",
|
||||
action: #selector(renderToFile(_:)),
|
||||
keyEquivalent: "r"))
|
||||
render.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(render)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Reset Session",
|
||||
action: #selector(resetSession(_:)),
|
||||
keyEquivalent: "")))
|
||||
menu.addItem(target(NSMenuItem(title: "Restart to Reclaim Memory…",
|
||||
action: #selector(restartApp(_:)),
|
||||
keyEquivalent: "")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
@@ -215,6 +242,18 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
switch menuItem.action {
|
||||
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
|
||||
return model.reevalState.canEvaluate
|
||||
case #selector(runSelection(_:)):
|
||||
// Needs a selection to run and an evaluator that isn't mid-compile.
|
||||
return model.hasSelection && model.reevalState.canEvaluate
|
||||
case #selector(resetSession(_:)):
|
||||
// Don't tear the session down mid-compile.
|
||||
return !model.isCompiling
|
||||
case #selector(formatCode(_:)):
|
||||
// Not mid-compile; the model's formatter no-ops on a blank buffer.
|
||||
return !model.isCompiling
|
||||
case #selector(renderToFile(_:)):
|
||||
// Needs an evaluatable buffer and no compile/render in flight.
|
||||
return model.reevalState.canEvaluate
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -280,6 +319,90 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
Task { @MainActor in _ = await model.run(additive: true) }
|
||||
}
|
||||
|
||||
@objc private func runSelection(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.runSelection() }
|
||||
}
|
||||
|
||||
@objc private func formatCode(_ sender: Any?) {
|
||||
Task { @MainActor in await model.formatBuffer() }
|
||||
}
|
||||
|
||||
@objc private func renderToFile(_ sender: Any?) {
|
||||
// Single save dialog: an accessory view carries the format popup + duration,
|
||||
// and keeps the filename extension in sync with the chosen container.
|
||||
let defaultRenderDuration: Double = 5.0
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.message = "Render the snippet (or selection) to an audio file"
|
||||
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||
baseName: "render", initialDuration: defaultRenderDuration, savePanel: panel
|
||||
)
|
||||
panel.accessoryView = accessory
|
||||
|
||||
guard panel.runModal() == .OK, let chosenURL: URL = panel.url else { return }
|
||||
|
||||
guard let duration: Double = accessory.durationSeconds else {
|
||||
let invalid: NSAlert = NSAlert()
|
||||
invalid.messageText = "Invalid duration"
|
||||
invalid.informativeText = "Enter a positive number of seconds (e.g. 5.0)."
|
||||
invalid.runModal()
|
||||
return
|
||||
}
|
||||
|
||||
let format: AudioFileFormat = accessory.selectedFormat
|
||||
// This is the source of truth for the final extension: force it to match the
|
||||
// chosen format so a hand-typed name with the wrong (or no) extension still
|
||||
// produces a correctly-named file. (The accessory's own panel-name sync is a
|
||||
// live-preview convenience; enforcement happens here.)
|
||||
let url: URL = chosenURL.deletingPathExtension().appendingPathExtension(format.fileExtension)
|
||||
|
||||
Task { @MainActor in
|
||||
let ok: Bool = await model.renderToFile(url: url, format: format, duration: duration)
|
||||
if ok { NSWorkspace.shared.activateFileViewerSelecting([url]) }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func resetSession(_ sender: Any?) {
|
||||
model.resetSession()
|
||||
}
|
||||
|
||||
@objc private func restartApp(_ sender: Any?) {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = "Restart to reclaim memory?"
|
||||
alert.informativeText =
|
||||
"Relaunches the app to free the \(model.loadedSnippetCount) mapped snippet "
|
||||
+ "dylibs (compiled snippets can't be unloaded any other way). Unsaved changes "
|
||||
+ "in the buffer will be lost."
|
||||
alert.addButton(withTitle: "Restart")
|
||||
alert.addButton(withTitle: "Cancel")
|
||||
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
||||
LyrebirdScratchMenuController.relaunchApp()
|
||||
}
|
||||
|
||||
/// Relaunch the host `.app`: open a fresh instance, then terminate this one
|
||||
/// once it is confirmed on its way. The new process starts with zero mapped
|
||||
/// snippet dylibs — the only way to reclaim that memory. On a launch failure
|
||||
/// the current process is **kept** (and the user informed) rather than
|
||||
/// terminated into oblivion.
|
||||
private static func relaunchApp() {
|
||||
let url: URL = Bundle.main.bundleURL
|
||||
let config: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
|
||||
config.createsNewApplicationInstance = true
|
||||
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
|
||||
DispatchQueue.main.async {
|
||||
if let error: Error = error {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = "Restart failed"
|
||||
alert.informativeText =
|
||||
"Could not relaunch the app (\(error.localizedDescription)). "
|
||||
+ "The current session is unchanged."
|
||||
alert.runModal()
|
||||
} else if app != nil {
|
||||
NSApp.terminate(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func clearSynths(_ sender: Any?) {
|
||||
model.clearTracked()
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ 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
|
||||
// (e.g. the LyrebirdScratch app) get the `LyrebirdLiveCompile` API
|
||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
||||
// dynamic product — which clashes in Xcode with the static target embed.
|
||||
@_exported import LyrebirdLiveCompile
|
||||
@@ -99,6 +99,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||
@Published public private(set) var statusMessage: String = ""
|
||||
|
||||
/// Accumulated console log shown in the always-open right panel: snippet
|
||||
/// `context.reportMessage(_:)` output, compile/DSL errors, and run notices,
|
||||
/// oldest first. Capped at ``maxConsoleEntries``.
|
||||
@Published public private(set) var consoleEntries: [ScratchConsoleEntry] = []
|
||||
|
||||
/// Upper bound on retained console lines; the oldest are dropped past it.
|
||||
public nonisolated static let maxConsoleEntries: Int = 500
|
||||
|
||||
private var _consoleSeq: Int = 0
|
||||
|
||||
/// Append one console line, trimming the log to ``maxConsoleEntries``.
|
||||
private func appendConsole(_ kind: ScratchConsoleEntry.Kind, _ text: String, location: String? = nil) {
|
||||
_consoleSeq += 1
|
||||
consoleEntries.append(ScratchConsoleEntry(id: _consoleSeq, kind: kind, text: text, location: location))
|
||||
let overflow: Int = consoleEntries.count - LyrebirdScratchModel.maxConsoleEntries
|
||||
if overflow > 0 { consoleEntries.removeFirst(overflow) }
|
||||
}
|
||||
|
||||
/// Empty the console.
|
||||
public func clearConsole() {
|
||||
consoleEntries.removeAll()
|
||||
}
|
||||
|
||||
/// After a run resolves, move the snippet's report messages into the console
|
||||
/// (they arrive in order during the run), then the run outcome: on failure,
|
||||
/// each diagnostic as an error line; on success, a one-line notice.
|
||||
private func recordRunConsole(succeeded: Bool) {
|
||||
for message: String in session.drainMessages() {
|
||||
appendConsole(.message, message)
|
||||
}
|
||||
if succeeded {
|
||||
appendConsole(.info, statusMessage)
|
||||
} else if diagnostics.isEmpty {
|
||||
appendConsole(.error, statusMessage)
|
||||
} else {
|
||||
for diagnostic: Diagnostic in diagnostics {
|
||||
let location: String? = diagnostic.line.map { "\($0):\(diagnostic.column)" }
|
||||
appendConsole(.error, diagnostic.message, location: location)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||
@Published public private(set) var trackedSynthCount: Int
|
||||
@@ -151,6 +193,23 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// horizontally.
|
||||
@Published public var wrapsLines: Bool = true
|
||||
|
||||
/// The current editor selection text (empty when nothing is selected).
|
||||
/// Pushed by the editor on selection change; drives ``hasSelection`` and
|
||||
/// ``runSelection()``.
|
||||
@Published public private(set) var selectionText: String = ""
|
||||
|
||||
/// `true` when the editor has a non-whitespace selection available to run.
|
||||
public var hasSelection: Bool {
|
||||
!selectionText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
}
|
||||
|
||||
/// Record the editor's current selection. Called by the editor's
|
||||
/// selection-change delegate; empty string clears it.
|
||||
public func updateSelection(_ text: String) {
|
||||
guard text != selectionText else { return } // avoid redundant republish
|
||||
selectionText = text
|
||||
}
|
||||
|
||||
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
||||
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
||||
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
|
||||
@@ -229,7 +288,11 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// resolves (edits made mid-compile are re-evaluated once it finishes).
|
||||
private func recomputeReevalStateAfterEdit() {
|
||||
guard !isCompiling else { return }
|
||||
reevalState = derivedIdleState()
|
||||
// Assign only on a real change: after the first edit dirties the buffer,
|
||||
// every later keystroke re-derives `.dirty` — republishing an unchanged
|
||||
// value would re-render the whole view for nothing.
|
||||
let next: ReevalState = derivedIdleState()
|
||||
if next != reevalState { reevalState = next }
|
||||
}
|
||||
|
||||
/// Settle a `.queued` state once its scheduled swap has become audible.
|
||||
@@ -268,29 +331,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
@discardableResult
|
||||
public func run(additive: Bool) async -> Bool {
|
||||
switch evalMode {
|
||||
case .swift: return await runSwiftSnippet(additive: additive)
|
||||
case .graphDSL: return runGraphDSLBuffer(additive: additive)
|
||||
case .swift: return await runSwiftSnippet(body: text, additive: additive, recordBaseline: true)
|
||||
case .graphDSL: return runGraphDSLBuffer(body: text, additive: additive, recordBaseline: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift path: compile the buffer to a dylib off-main and run it.
|
||||
private func runSwiftSnippet(additive: Bool) async -> Bool {
|
||||
/// Evaluate just the current editor selection as an **additive** run: the
|
||||
/// selected text is compiled/interpreted and added to whatever is already
|
||||
/// playing (never a non-additive replace), and it does not disturb the
|
||||
/// whole-buffer re-evaluation baseline — the buffer's `.clean`/`.dirty`
|
||||
/// status still reflects the last *whole* run. No-op when nothing is
|
||||
/// selected. Works in both Swift and Graph DSL modes.
|
||||
@discardableResult
|
||||
public func runSelection() async -> Bool {
|
||||
guard hasSelection else { return false }
|
||||
let body: String = selectionText
|
||||
switch evalMode {
|
||||
case .swift: return await runSwiftSnippet(body: body, additive: true, recordBaseline: false)
|
||||
case .graphDSL: return runGraphDSLBuffer(body: body, additive: true, recordBaseline: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift path: compile `body` to a dylib off-main and run it.
|
||||
/// `recordBaseline` distinguishes a whole-buffer run (updates the `.clean`
|
||||
/// baseline) from a selection run (leaves it untouched).
|
||||
private func runSwiftSnippet(body: String, additive: Bool, recordBaseline: Bool) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
statusMessage = "Compiling…"
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
var runSucceeded: Bool = false
|
||||
defer {
|
||||
isCompiling = false
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
recordRunConsole(succeeded: runSucceeded)
|
||||
}
|
||||
do {
|
||||
try await session.compileAndRunAsync(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
settleReevalAfterSuccess(body: body)
|
||||
statusMessage = "Ran \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||
runSucceeded = true
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
switch sessionError {
|
||||
@@ -303,7 +385,7 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
message: "\(underlying)",
|
||||
rawLine: 0
|
||||
)]
|
||||
statusMessage = "Compile failed — see diagnostics below."
|
||||
statusMessage = "Compile failed — see console."
|
||||
} else {
|
||||
diagnostics = diags
|
||||
let plural: String = diags.count == 1 ? "" : "s"
|
||||
@@ -316,31 +398,32 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
diagnostics = diags
|
||||
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
|
||||
}
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Graph-DSL path: interpret the buffer in-process — instant, no swiftc, so
|
||||
/// no `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||
/// Graph-DSL path: interpret `body` in-process — instant, no swiftc, so no
|
||||
/// `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||
/// currently-playing graph untouched (the session builds before it mutates).
|
||||
private func runGraphDSLBuffer(additive: Bool) -> Bool {
|
||||
private func runGraphDSLBuffer(body: String, additive: Bool, recordBaseline: Bool) -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
var runSucceeded: Bool = false
|
||||
defer {
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
recordRunConsole(succeeded: runSucceeded)
|
||||
}
|
||||
do {
|
||||
try session.runGraphDSL(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
settleReevalAfterSuccess(body: body)
|
||||
statusMessage = "Ran DSL \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||
runSucceeded = true
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
if case .graphDSLFailed(let diags, _) = sessionError {
|
||||
@@ -350,21 +433,23 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
} else {
|
||||
statusMessage = "Error: \(sessionError)"
|
||||
}
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the just-run text as the baseline and settle the readiness state:
|
||||
/// `.queued` when the buffer is unchanged and a quantized slot swap is
|
||||
/// scheduled but not yet audible, otherwise the derived idle state (`.clean`,
|
||||
/// or `.dirty` if the buffer was edited while the run was in flight).
|
||||
private func settleReevalAfterSuccess(body: String) {
|
||||
lastEvaluatedText = body
|
||||
/// Settle the readiness state after a successful run. For a whole-buffer run
|
||||
/// (`recordBaseline`), record the run text as the `.clean` baseline; for a
|
||||
/// selection run, leave the baseline untouched (the buffer's status still
|
||||
/// reflects the last whole run). Either way resolve to `.queued` when the
|
||||
/// buffer is unchanged and a quantized swap is pending, else the derived
|
||||
/// idle state.
|
||||
private func settleReeval(body: String, recordBaseline: Bool) {
|
||||
if recordBaseline { lastEvaluatedText = body }
|
||||
let idle: ReevalState = derivedIdleState()
|
||||
if idle == .clean, let beat: Double = session.pendingSwapBeat {
|
||||
reevalState = .queued(untilBeat: beat)
|
||||
@@ -373,6 +458,33 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle the readiness state after a *failed* run. A whole-buffer failure
|
||||
/// sets `.failed` (the badge should reflect that the buffer doesn't run). A
|
||||
/// selection failure must NOT touch the whole-buffer badge — the buffer and
|
||||
/// its last whole-run baseline are unaffected — so it recomputes the derived
|
||||
/// idle state and marks the status line as a selection failure. Diagnostics
|
||||
/// (already set by the caller) still surface the error either way.
|
||||
private func settleReevalAfterFailure(recordBaseline: Bool) {
|
||||
if recordBaseline {
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
} else {
|
||||
statusMessage = "Selection — " + statusMessage
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
}
|
||||
|
||||
/// Status-line phrase for a run: distinguishes a whole-buffer replace/add
|
||||
/// from a selection add, and includes the live tracked-synth count.
|
||||
private func runDescription(additive: Bool, recordBaseline: Bool) -> String {
|
||||
let what: String
|
||||
if !recordBaseline {
|
||||
what = "selection (added)"
|
||||
} else {
|
||||
what = additive ? "additive" : "replaced"
|
||||
}
|
||||
return "(\(what)). Tracked synths: \(session.trackedSynthCount)"
|
||||
}
|
||||
|
||||
/// Switch evaluation mode. When the buffer still holds the *current* mode's
|
||||
/// untouched placeholder, swap in the target mode's placeholder so the seed
|
||||
/// example matches the mode; any edited buffer is left as-is.
|
||||
@@ -392,6 +504,141 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
/// In-process session reset: stop all snippet audio, shut down the code-
|
||||
/// completion server (freeing its subprocess + temp workspace), and clear
|
||||
/// diagnostics and the run baseline. **Non-destructive** — the editor buffer
|
||||
/// (the user's code) is left untouched, so this needs no confirmation.
|
||||
///
|
||||
/// It reclaims everything it *can* in-process — but **not** the compiled
|
||||
/// snippet dylibs (`loadedSnippetCount`), which cannot be unloaded safely
|
||||
/// (`dlclose` is unsafe for Swift dylibs). Only relaunching the process frees
|
||||
/// those; the status line says so, and the "Restart" command does it.
|
||||
///
|
||||
/// No-op while a compile is in flight (matching the run methods' guard) — a
|
||||
/// reset must not tear the session down under an active `compileAndRunAsync`.
|
||||
/// Pretty-print the buffer with `swift-format` (off the main thread),
|
||||
/// replacing the text on success. Logs the outcome to the console; on a
|
||||
/// parse error or missing toolchain the buffer is left untouched.
|
||||
public func formatBuffer() async {
|
||||
guard !isCompiling else { return }
|
||||
let source: String = text
|
||||
guard !LyrebirdScratchModel.isBlank(source) else { return }
|
||||
// Hold the busy flag across the subprocess round-trip so a second Format
|
||||
// (or a Run) can't overlap, and re-check the buffer before applying: the
|
||||
// user may keep typing while `swift-format` runs, and a result computed
|
||||
// from the now-stale `source` must not clobber those edits. `reevalState`
|
||||
// goes `.compiling` too so the Run/Render menu items (validated on
|
||||
// `reevalState.canEvaluate`) actually disable during the format.
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
defer {
|
||||
isCompiling = false
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
do {
|
||||
let formatted: String = try await Task.detached(priority: .userInitiated) {
|
||||
try SwiftFormatter.format(source: source)
|
||||
}.value
|
||||
guard text == source else {
|
||||
appendConsole(.error, "Buffer changed during formatting — result discarded.")
|
||||
return
|
||||
}
|
||||
if formatted != source {
|
||||
text = formatted
|
||||
}
|
||||
appendConsole(.info, "Formatted.")
|
||||
} catch {
|
||||
appendConsole(.error, "Format failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the current selection (or the whole buffer when nothing is
|
||||
/// selected) to an audio file, offline. Builds the snippet graph on a
|
||||
/// throwaway engine driven by an `NRTDriver` — matching the live engine's
|
||||
/// sample rate / channel count / bus layout — then renders `duration`
|
||||
/// seconds off the main thread (`NRTDriver.start()` blocks). Logs the
|
||||
/// outcome to the console.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - url: Destination file. Its extension should match `format`.
|
||||
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to
|
||||
/// `.cafFloat32`. RF64/CAF are uncapped; plain WAV/AIFF throw past 4 GB.
|
||||
/// - duration: Render length in seconds. Must be finite and > 0.
|
||||
/// - Returns: `true` when the file was rendered (so the caller can reveal it).
|
||||
@discardableResult
|
||||
public func renderToFile(
|
||||
url: URL,
|
||||
format: AudioFileFormat = .cafFloat32,
|
||||
duration: Double
|
||||
) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
guard duration > 0, duration.isFinite else {
|
||||
appendConsole(.error, "Render duration must be a positive number of seconds.")
|
||||
return false
|
||||
}
|
||||
let code: String = hasSelection ? selectionText : text
|
||||
guard !LyrebirdScratchModel.isBlank(code) else {
|
||||
appendConsole(.error, "Nothing to render.")
|
||||
return false
|
||||
}
|
||||
// Gate the Run/Render menu items (validated on `reevalState.canEvaluate`)
|
||||
// and any re-entrancy for the render's duration.
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
defer {
|
||||
isCompiling = false
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
let live: SynthesisEngine = session.engine
|
||||
let offline: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: live.blockSize,
|
||||
controlBlockSize: live.controlBlockSize,
|
||||
sampleRate: live.sampleRate,
|
||||
numOutputChannels: live.numOutputChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: live.numAudioBuses,
|
||||
numControlBuses: live.numControlBuses,
|
||||
driver: NRTDriver(outputURL: url, duration: duration, format: format)
|
||||
)
|
||||
let offlineSession: LiveSession = LiveSession(engine: offline, attachScope: false)
|
||||
do {
|
||||
// Build the graph on the offline engine (compile off-main, add on main).
|
||||
try await offlineSession.compileAndRunAsync(code, additive: true)
|
||||
// Render synchronously, off the main thread; NRTDriver writes the CAF.
|
||||
// `stop()` runs inside the detached task (where `offline` lives): the
|
||||
// driver returns with the engine still `isRunning`, and only `stop()`
|
||||
// drains the node tree — without it every rendered graph leaks
|
||||
// (matches EngineHost's NRT job teardown). Keeping it here also avoids
|
||||
// a cross-actor use of the non-Sendable engine after the detached run.
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
defer { offline.stop() }
|
||||
try offline.start()
|
||||
}.value
|
||||
appendConsole(.info, "Rendered \(String(format: "%.2f", duration)) s → \(url.lastPathComponent)")
|
||||
return true
|
||||
} catch {
|
||||
appendConsole(.error, "Render failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func resetSession() {
|
||||
guard !isCompiling else { return }
|
||||
session.resetAll()
|
||||
_completion?.shutdownSynchronously()
|
||||
_completion = nil // recreated lazily on next completion
|
||||
diagnostics = []
|
||||
consoleEntries.removeAll()
|
||||
lastEvaluatedText = nil
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
reevalState = derivedIdleState()
|
||||
statusMessage = loadedSnippetCount > 0
|
||||
? "Session reset. \(loadedSnippetCount) snippet dylibs still mapped — Restart to reclaim that memory."
|
||||
: "Session reset."
|
||||
}
|
||||
|
||||
/// Start the audio engine if stopped, or stop it if running. Surfaces the
|
||||
/// outcome (including a start failure — e.g. no audio device) on the status
|
||||
/// line. The host normally starts the engine at launch; this lets the user
|
||||
|
||||
@@ -58,9 +58,35 @@ import LyrebirdLiveCompile
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@StateObject private var model: LyrebirdScratchModel
|
||||
@State private var engineTick: Int = 0
|
||||
/// Snapshot of the engine's non-`@Published` live stats, refreshed on the
|
||||
/// heartbeat. Bound in place by the status rows — deliberately NOT via
|
||||
/// `.id(tick)`, which forces a subview teardown/rebuild every tick and churns
|
||||
/// the surrounding layout, nudging the editor's scroll position ("screen
|
||||
/// jumping" while scrolled down). Updating an `@State` value re-renders the
|
||||
/// labels in place with stable identity, so the layout stays put.
|
||||
@State private var stats: EngineStats = EngineStats()
|
||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||
|
||||
/// Non-`@Published` engine values polled on the heartbeat.
|
||||
private struct EngineStats: Equatable {
|
||||
var isRunning: Bool = false
|
||||
var averageCPU: Double = 0
|
||||
var peakCPU: Double = 0
|
||||
var synthesizerCount: Int = 0
|
||||
var groupCount: Int = 0
|
||||
}
|
||||
|
||||
private func snapshotStats() -> EngineStats {
|
||||
let e: SynthesisEngine = model.session.engine
|
||||
return EngineStats(
|
||||
isRunning: e.isRunning,
|
||||
averageCPU: e.averageCPU,
|
||||
peakCPU: e.peakCPU,
|
||||
synthesizerCount: e.synthesizerCount,
|
||||
groupCount: e.groupCount
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -85,6 +111,29 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
mainColumn
|
||||
Divider()
|
||||
consolePanel
|
||||
.frame(width: consoleWidth)
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight)
|
||||
.onAppear {
|
||||
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||
// Idempotent — safe if `onAppear` fires again.
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
let next: EngineStats = snapshotStats()
|
||||
if next != stats { stats = next }
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
}
|
||||
|
||||
/// The editor column: engine controls, editor, status, engine panel.
|
||||
private var mainColumn: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
if let hint: String = model.snippetMemoryHint {
|
||||
@@ -101,27 +150,50 @@ public struct LyrebirdScratchView: View {
|
||||
wrapsLines: model.wrapsLines,
|
||||
requestCompletions: { line, character in
|
||||
await model.completionItems(line: line, character: character)
|
||||
}
|
||||
},
|
||||
onSelectionChanged: { selected in model.updateSelection(selected) }
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
statusBar
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
diagnosticsList
|
||||
Divider()
|
||||
enginePanel
|
||||
}
|
||||
}
|
||||
|
||||
/// Always-open right-side console: report messages, errors, and run notices,
|
||||
/// oldest first, auto-scrolled to the newest.
|
||||
private var consolePanel: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text("Console")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Button("Clear") { model.clearConsole() }
|
||||
.buttonStyle(.plain)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.disabled(model.consoleEntries.isEmpty)
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
Divider()
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 2) {
|
||||
ForEach(model.consoleEntries) { entry in
|
||||
ConsoleRow(entry: entry)
|
||||
}
|
||||
Color.clear.frame(height: 1).id(consoleBottomID)
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.onChange(of: model.consoleEntries.count) { _, _ in
|
||||
proxy.scrollTo(consoleBottomID, anchor: .bottom)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onAppear {
|
||||
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||
// Idempotent — safe if `onAppear` fires again.
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
engineTick &+= 1
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,21 +202,21 @@ public struct LyrebirdScratchView: View {
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Button {
|
||||
model.toggleEngine()
|
||||
engineTick &+= 1
|
||||
stats = snapshotStats()
|
||||
} label: {
|
||||
HStack(spacing: reevalBadgeSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.fill(stats.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "▶ start engine")
|
||||
Text(stats.isRunning ? "engine running" : "▶ start engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
|
||||
.foregroundStyle(stats.isRunning ? Color.secondary : Color.primary)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
.help(stats.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(stats.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
@@ -160,7 +232,6 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
/// Warning strip shown once mapped snippet dylibs cross the restart
|
||||
@@ -180,6 +251,70 @@ public struct LyrebirdScratchView: View {
|
||||
.background(Color.orange.opacity(0.12))
|
||||
}
|
||||
|
||||
/// Bottom engine panel: a live output oscilloscope plus a compact status
|
||||
/// readout (sample rate, CPU average/peak meters, node counts). The status
|
||||
/// text refreshes in place off the ``stats`` snapshot — no `.id(tick)`
|
||||
/// teardown, so the surrounding layout (and the editor's scroll) stays put.
|
||||
private var enginePanel: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
if let scope: ScopeCapture = model.session.scope {
|
||||
ScratchScopeView(capture: scope)
|
||||
.frame(height: scopeHeight)
|
||||
}
|
||||
engineStatusRow
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
|
||||
/// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts.
|
||||
private var engineStatusRow: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Text("Engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
cpuMeter(label: "CPU avg", value: stats.averageCPU)
|
||||
cpuMeter(label: "CPU peak", value: stats.peakCPU)
|
||||
Text("synths \(stats.synthesizerCount) · groups \(stats.groupCount) · snippets \(model.loadedSnippetCount)")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
/// One labelled CPU meter bar. `value` is a fraction of one block period
|
||||
/// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun.
|
||||
private func cpuMeter(label: String, value: Double) -> some View {
|
||||
let clamped: CGFloat = CGFloat(min(max(value, 0), 1))
|
||||
let fill: Color = value > cpuMeterCriticalThreshold
|
||||
? .red
|
||||
: (value > cpuMeterWarningThreshold ? .orange : .green)
|
||||
return HStack(spacing: 6) {
|
||||
Text(label)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: cpuLabelWidth, alignment: .leading)
|
||||
GeometryReader { geo in
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15))
|
||||
RoundedRectangle(cornerRadius: 2).fill(fill)
|
||||
.frame(width: geo.size.width * clamped)
|
||||
}
|
||||
}
|
||||
.frame(height: meterHeight)
|
||||
Text(formatCPU(value))
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: cpuValueWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
@@ -190,6 +325,14 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate just the current selection, additively. No-op when nothing is
|
||||
/// selected.
|
||||
public func runSelection() {
|
||||
Task { @MainActor in
|
||||
_ = await model.runSelection()
|
||||
}
|
||||
}
|
||||
|
||||
public func presentOpenPanel() {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
@@ -322,18 +465,6 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
||||
DiagnosticRow(diagnostic: diag)
|
||||
}
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
}
|
||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
||||
}
|
||||
|
||||
// Layout constants — all in points. Kept private; tuned to match
|
||||
// LyrebirdEngineStatusView's visual density.
|
||||
private let scratchMinWidth: CGFloat = 520
|
||||
@@ -350,26 +481,38 @@ public struct LyrebirdScratchView: View {
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
private let reevalBadgeSpacing: CGFloat = 4
|
||||
private let scopeHeight: CGFloat = 88
|
||||
private let meterHeight: CGFloat = 6
|
||||
private let consoleWidth: CGFloat = 300
|
||||
private let consoleBottomID: String = "scratch.console.bottom"
|
||||
private let cpuLabelWidth: CGFloat = 58
|
||||
private let cpuValueWidth: CGFloat = 40
|
||||
/// CPU-meter fill turns orange above this fraction of one block period, red
|
||||
/// above ``cpuMeterCriticalThreshold``.
|
||||
private let cpuMeterWarningThreshold: Double = 0.5
|
||||
private let cpuMeterCriticalThreshold: Double = 0.8
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
/// message in a compact monospaced row.
|
||||
private struct DiagnosticRow: View {
|
||||
private struct ConsoleRow: View {
|
||||
|
||||
let diagnostic: Diagnostic
|
||||
let entry: ScratchConsoleEntry
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
||||
Text(locationString)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.severity.rawValue)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(color(for: diagnostic.severity))
|
||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.message)
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Text(glyph)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(color)
|
||||
.frame(width: 14, alignment: .leading)
|
||||
if let location: String = entry.location {
|
||||
Text(location)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Text(entry.text)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(entry.kind == .error ? Color.primary : color)
|
||||
.textSelection(.enabled)
|
||||
.multilineTextAlignment(.leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
@@ -377,59 +520,94 @@ private struct DiagnosticRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var locationString: String {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
/// Leading glyph per kind: an X for errors, an arrow for messages, a dot for
|
||||
/// info notices.
|
||||
private var glyph: String {
|
||||
switch entry.kind {
|
||||
case .error: return "✗"
|
||||
case .message: return "›"
|
||||
case .info: return "·"
|
||||
}
|
||||
// No user-body line. A swiftc preamble hit carries a real (1-based)
|
||||
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
|
||||
// harness/preamble at all), so label the two cases distinctly.
|
||||
return diagnostic.rawLine >= 1
|
||||
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
: "(file)"
|
||||
}
|
||||
|
||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
||||
switch severity {
|
||||
private var color: Color {
|
||||
switch entry.kind {
|
||||
case .error: return .red
|
||||
case .warning: return .orange
|
||||
case .note: return .secondary
|
||||
case .message: return .cyan
|
||||
case .info: return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private let rowGutter: CGFloat = 8
|
||||
private let locationColumnWidth: CGFloat = 80
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSTextView` subclass that fixes member-completion behavior.
|
||||
///
|
||||
/// The default `rangeForUserCompletion` scans back over the whole dotted
|
||||
/// expression, so completing a member right after a `.` (e.g. `context.` →
|
||||
/// `engine`) would *replace* the receiver (`context`) with the chosen member
|
||||
/// instead of inserting after the dot. When the character before the insertion
|
||||
/// point is a `.`, this override returns an empty range at the caret, so the
|
||||
/// completion is a pure insertion and `context.engine` is produced.
|
||||
/// UTF-16 code unit for `.` (the member-access operator that triggers and
|
||||
/// shapes completion).
|
||||
private let dotCharacterCode: unichar = 46
|
||||
/// expression, so a candidate would *replace* the receiver rather than the
|
||||
/// partial word being typed. Completing a member after `context.` → `engine`
|
||||
/// would replace `context`; accepting an argument label after `OscSin.Audio(`
|
||||
/// → `freq:` would replace `OscSin.Audio`. The correct replace range is just
|
||||
/// the run of identifier characters immediately before the caret (empty after
|
||||
/// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there.
|
||||
|
||||
/// Whether `selection` is a bare insertion point sitting immediately after a
|
||||
/// `.` in `text` — the member-completion trigger condition.
|
||||
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
|
||||
guard selection.length == 0, selection.location > 0, selection.location <= text.length
|
||||
else { return false }
|
||||
return text.character(at: selection.location - 1) == dotCharacterCode
|
||||
/// Whether `c` (a UTF-16 code unit) is a Swift identifier character —
|
||||
/// ASCII letter, digit, or underscore. Sufficient for completion-range
|
||||
/// scanning; identifiers with non-ASCII scalars are not a concern here.
|
||||
private func isIdentifierCodeUnit(_ c: unichar) -> Bool {
|
||||
let underscore: unichar = 95
|
||||
let zero: unichar = 48, nine: unichar = 57
|
||||
let upperA: unichar = 65, upperZ: unichar = 90
|
||||
let lowerA: unichar = 97, lowerZ: unichar = 122
|
||||
return c == underscore
|
||||
|| (c >= zero && c <= nine)
|
||||
|| (c >= upperA && c <= upperZ)
|
||||
|| (c >= lowerA && c <= lowerZ)
|
||||
}
|
||||
|
||||
final class ScratchTextView: NSTextView {
|
||||
/// Invoked when the user asks for completion (the standard completion key —
|
||||
/// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then
|
||||
/// shows the completion window. Completion is manual only.
|
||||
var onManualComplete: (() -> Void)?
|
||||
|
||||
override var rangeForUserCompletion: NSRange {
|
||||
let sel: NSRange = selectedRange()
|
||||
if caretFollowsDot(in: string as NSString, selection: sel) {
|
||||
return NSRange(location: sel.location, length: 0)
|
||||
// Never replace across an actual selection — defer to the default.
|
||||
guard sel.length == 0, sel.location <= (string as NSString).length else {
|
||||
return super.rangeForUserCompletion
|
||||
}
|
||||
return super.rangeForUserCompletion
|
||||
let ns: NSString = string as NSString
|
||||
var start: Int = sel.location
|
||||
while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) {
|
||||
start -= 1
|
||||
}
|
||||
return NSRange(location: start, length: sel.location - start)
|
||||
}
|
||||
|
||||
/// Intercept the built-in `complete:` command (bound to Esc / F5) so the
|
||||
/// candidates are fetched asynchronously first, then shown. Without this,
|
||||
/// pressing Esc would call the delegate with an empty (never-fetched) list.
|
||||
/// Everything else falls through to the normal editor commands.
|
||||
override func doCommand(by selector: Selector) {
|
||||
if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) {
|
||||
onManualComplete?()
|
||||
return
|
||||
}
|
||||
super.doCommand(by: selector)
|
||||
}
|
||||
|
||||
/// Esc is delivered as `cancelOperation:` (not `complete:`) by the default
|
||||
/// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm —
|
||||
/// only F5 does. Route it here too so Esc invokes completion as documented.
|
||||
/// The completion window, once open, consumes Esc itself to dismiss, so this
|
||||
/// only fires when the window is closed.
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
onManualComplete?()
|
||||
}
|
||||
|
||||
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
|
||||
/// `ScratchEditor.configure` reserves this as the text view's left inset so
|
||||
/// the gutter overlay doesn't cover the text.
|
||||
static let lineNumberGutterWidth: CGFloat = 40
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
|
||||
@@ -444,6 +622,9 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
/// Async source of code-completion candidates for a zero-based user-space
|
||||
/// (line, UTF-16 character). Supplied by the view from the model.
|
||||
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
|
||||
/// Called with the current selected substring whenever the selection
|
||||
/// changes (empty when nothing is selected). Drives "Run Selection".
|
||||
let onSelectionChanged: @MainActor (String) -> Void
|
||||
|
||||
@MainActor
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
@@ -455,17 +636,67 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
/// applies its results if it is still the newest (so a slow older request
|
||||
/// can't clobber a fresher one that landed first).
|
||||
private var _completionGeneration: Int = 0
|
||||
/// Pending debounced re-highlight; cancelled and rescheduled on each edit
|
||||
/// so a burst of keystrokes re-tokenizes the buffer once, not per key.
|
||||
private var _highlightWork: DispatchWorkItem?
|
||||
/// Last selection substring pushed to the model, so an unchanged selection
|
||||
/// (the common case while typing — caret moves, selection stays empty)
|
||||
/// doesn't republish `@Published` state and re-render the whole view.
|
||||
private var _lastSelectionPushed: String = ""
|
||||
/// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying
|
||||
/// wrap/paragraph settings on a pure text republish (every keystroke).
|
||||
var lastWraps: Bool?
|
||||
|
||||
/// Idle delay before re-highlighting after an edit. Short enough to feel
|
||||
/// instant once typing pauses; long enough to coalesce a fast burst.
|
||||
private static let highlightDebounce: TimeInterval = 0.045
|
||||
|
||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
parent.text = tv.string
|
||||
parent.applyHighlight(to: tv)
|
||||
// Auto-trigger member completion right after a `.` is typed.
|
||||
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
|
||||
triggerCompletion(tv)
|
||||
scheduleHighlight(tv)
|
||||
// Completion is manual (Esc), never auto-triggered on `.`: an
|
||||
// unrequested popup ambushes typing and the built-in completion
|
||||
// window is awkward to dismiss mid-edit.
|
||||
}
|
||||
|
||||
/// Coalesce full-buffer re-highlighting: cancel any pending pass and run
|
||||
/// one shortly after the edits stop. Newly typed characters render in the
|
||||
/// base color immediately (via `typingAttributes`); syntax colors catch
|
||||
/// up a beat later, avoiding an O(n) tokenize on every keystroke.
|
||||
private func scheduleHighlight(_ tv: NSTextView) {
|
||||
_highlightWork?.cancel()
|
||||
let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in
|
||||
guard let self: Coordinator = self, let tv: NSTextView = tv else { return }
|
||||
self.parent.applyHighlight(to: tv)
|
||||
}
|
||||
_highlightWork = work
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work)
|
||||
}
|
||||
|
||||
/// Push the current selected substring up to the model so "Run Selection"
|
||||
/// knows what (if anything) is selected — but only when it actually
|
||||
/// changed, to avoid a per-caret-move `@Published` republish.
|
||||
func textViewDidChangeSelection(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
let sel: NSRange = tv.selectedRange()
|
||||
let selected: String
|
||||
if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length {
|
||||
selected = (tv.string as NSString).substring(with: sel)
|
||||
} else {
|
||||
selected = ""
|
||||
}
|
||||
guard selected != _lastSelectionPushed else { return }
|
||||
_lastSelectionPushed = selected
|
||||
// Defer the @Published mutation: a programmatic text change (via
|
||||
// `updateNSView` → `replaceText`) can clamp the selection and re-post
|
||||
// this notification from inside a SwiftUI update pass. Scheduling on
|
||||
// the next main-actor tick keeps that off the render pass ("Publishing
|
||||
// changes from within view updates is not allowed").
|
||||
let notify: @MainActor (String) -> Void = parent.onSelectionChanged
|
||||
Task { @MainActor in notify(selected) }
|
||||
}
|
||||
|
||||
/// The text view calls this synchronously from `complete(_:)`; return the
|
||||
@@ -515,6 +746,10 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
scroll.autoresizingMask = [.width, .height]
|
||||
|
||||
let tv: ScratchTextView = ScratchTextView(frame: .zero)
|
||||
// Opt into TextKit 1: accessing `layoutManager` permanently switches the
|
||||
// text view off TextKit 2, where `self.layoutManager` is nil — the gutter
|
||||
// drawing needs it to place numbers against laid-out line rects.
|
||||
_ = tv.layoutManager
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
@@ -525,6 +760,16 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
scroll.documentView = tv
|
||||
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
// Manual completion (Esc): fetch candidates, then show the window.
|
||||
let coordinator: Coordinator = context.coordinator
|
||||
tv.onManualComplete = { [weak coordinator, weak tv] in
|
||||
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
|
||||
coordinator.triggerCompletion(tv)
|
||||
}
|
||||
// Line-number gutter: a floating overlay pinned to the left of the visible
|
||||
// area (see `ScratchLineNumberGutter` for why not an `NSRulerView`).
|
||||
let gutter: ScratchLineNumberGutter = ScratchLineNumberGutter(scrollView: scroll, textView: tv)
|
||||
scroll.addFloatingSubview(gutter, for: .vertical)
|
||||
return scroll
|
||||
}
|
||||
|
||||
@@ -533,14 +778,23 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||
if fontChanged {
|
||||
tv.font = font
|
||||
}
|
||||
let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines
|
||||
context.coordinator.lastWraps = wrapsLines
|
||||
let textChanged: Bool = tv.string != text
|
||||
|
||||
// Fast path: a pure text republish (the per-keystroke case) needs no work
|
||||
// here — the `NSTextView` already holds the text (it's the editor of
|
||||
// record), highlighting is debounced in the Coordinator, and font/wrap
|
||||
// are unchanged. Skip the paragraph-style measure + attribute churn.
|
||||
guard textChanged || fontChanged || wrapChanged else { return }
|
||||
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||
if fontChanged { tv.font = font }
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
if tv.string != text {
|
||||
if textChanged {
|
||||
// External change (load, reset, mode switch) — replace + re-highlight.
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
|
||||
@@ -573,6 +827,15 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraph)
|
||||
// A direct `setAttributedString` bypasses `NSTextView`'s edit path, so the
|
||||
// gutter (which redraws on `NSText.didChangeNotification`) isn't told to
|
||||
// refresh. Nudge it explicitly after a programmatic replace (format /
|
||||
// load / reset) so the line count doesn't go stale.
|
||||
if let scroll: NSScrollView = tv.enclosingScrollView {
|
||||
for sub: NSView in scroll.subviews {
|
||||
(sub as? ScratchLineNumberGutter)?.refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Syntax highlighting
|
||||
@@ -638,7 +901,11 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.smartInsertDeleteEnabled = false
|
||||
tv.allowsUndo = true
|
||||
tv.usesFindBar = true
|
||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
||||
// Left inset reserves the column the `ScratchLineNumberGutter` overlay
|
||||
// draws line numbers into (see `ScratchLineNumberGutter.draw(_:)`).
|
||||
// `textContainerInset` is symmetric, so the right margin matches —
|
||||
// harmless whitespace.
|
||||
tv.textContainerInset = NSSize(width: ScratchTextView.lineNumberGutterWidth, height: editorInset)
|
||||
tv.drawsBackground = true
|
||||
tv.backgroundColor = .textBackgroundColor
|
||||
tv.textColor = .labelColor
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// RenderOptionsAccessory.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Accessory view embedded in the "Render to File" `NSSavePanel`: a container/encoding
|
||||
/// popup and a duration field. Selecting a format rewrites the panel's filename
|
||||
/// extension and remembers the choice (`UserDefaults`) so the next render defaults to it.
|
||||
///
|
||||
/// The sample rate and channel count are intentionally **not** exposed here — the
|
||||
/// offline render mirrors the live engine (WYSIWYG with what was just heard).
|
||||
@MainActor
|
||||
final class RenderOptionsAccessory: NSView {
|
||||
|
||||
// MARK: - Format catalogue
|
||||
|
||||
/// One selectable output format. `token` is the persistence key (stable across
|
||||
/// reordering / re-titling of the list, unlike a raw index or the display title).
|
||||
private struct Option {
|
||||
let title: String
|
||||
let format: AudioFileFormat
|
||||
let token: String
|
||||
}
|
||||
|
||||
private static let options: [Option] = [
|
||||
Option(title: "WAV — 32-bit float", format: .wavFloat32, token: "wavF32"),
|
||||
Option(title: "WAV — 16-bit integer", format: .wavInt16, token: "wavI16"),
|
||||
Option(title: "WAV — 24-bit integer", format: .wavInt24, token: "wavI24"),
|
||||
Option(title: "AIFF — 32-bit float", format: .aiffFloat32, token: "aiffF32"),
|
||||
Option(title: "CAF — 32-bit float (uncapped)", format: .cafFloat32, token: "cafF32"),
|
||||
Option(title: "RF64 WAV — 32-bit float (>4 GB)", format: .rf64Float32, token: "rf64F32"),
|
||||
Option(title: "RF64 WAV — 24-bit integer (>4 GB)", format: .rf64Int24, token: "rf64I24"),
|
||||
Option(title: "AAC — 256 kbps (M4A)", format: .aacHigh, token: "aacHigh"),
|
||||
Option(title: "AAC — 128 kbps (M4A)", format: .aacMedium, token: "aacMedium"),
|
||||
Option(title: "Apple Lossless (M4A)", format: .alac, token: "alac"),
|
||||
]
|
||||
|
||||
/// Persisted last-used format token. Defaults to CAF (the pre-accessory behaviour).
|
||||
private static let defaultsKey: String = "com.lyrebird.scratch.renderFormatToken"
|
||||
private static let fallbackToken: String = "cafF32"
|
||||
|
||||
// MARK: - Layout metrics
|
||||
|
||||
private static let accessoryWidth: CGFloat = 380
|
||||
private static let accessoryHeight: CGFloat = 96
|
||||
private static let contentMargin: CGFloat = 16
|
||||
private static let gridSpacing: CGFloat = 8
|
||||
private static let minDurationFieldWidth: CGFloat = 80
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private let formatPopup: NSPopUpButton = NSPopUpButton(frame: .zero, pullsDown: false)
|
||||
private let durationField: NSTextField = NSTextField(frame: .zero)
|
||||
|
||||
private let baseName: String
|
||||
private weak var savePanel: NSSavePanel?
|
||||
|
||||
// MARK: - Public read-out
|
||||
|
||||
/// The format for the currently selected popup item.
|
||||
var selectedFormat: AudioFileFormat {
|
||||
let index: Int = formatPopup.indexOfSelectedItem
|
||||
guard index >= 0 && index < RenderOptionsAccessory.options.count else {
|
||||
return .cafFloat32
|
||||
}
|
||||
return RenderOptionsAccessory.options[index].format
|
||||
}
|
||||
|
||||
/// Parsed duration in seconds, or `nil` when the field is not a positive number.
|
||||
var durationSeconds: Double? { RenderOptionsAccessory.parseDuration(durationField.stringValue) }
|
||||
|
||||
/// Parse a duration string to a positive, finite seconds value (or `nil`). Pure —
|
||||
/// extracted so it can be unit-tested without the modal panel.
|
||||
static func parseDuration(_ raw: String) -> Double? {
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespaces)
|
||||
guard let value: Double = Double(trimmed), value > 0, value.isFinite else { return nil }
|
||||
return value
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - baseName: Filename stem (no extension); the format's extension is appended.
|
||||
/// - initialDuration: Seconds pre-filled in the duration field.
|
||||
/// - savePanel: The panel to keep the filename extension in sync with.
|
||||
init(baseName: String, initialDuration: Double, savePanel: NSSavePanel) {
|
||||
self.baseName = baseName
|
||||
self.savePanel = savePanel
|
||||
super.init(frame: NSRect(x: 0, y: 0,
|
||||
width: RenderOptionsAccessory.accessoryWidth,
|
||||
height: RenderOptionsAccessory.accessoryHeight))
|
||||
|
||||
let startIndex: Int = RenderOptionsAccessory.persistedIndex()
|
||||
|
||||
formatPopup.addItems(withTitles: RenderOptionsAccessory.options.map(\.title))
|
||||
formatPopup.selectItem(at: startIndex)
|
||||
formatPopup.target = self
|
||||
formatPopup.action = #selector(formatChanged)
|
||||
formatPopup.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
durationField.stringValue = String(format: "%.2f", initialDuration)
|
||||
durationField.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
let formatLabel: NSTextField = RenderOptionsAccessory.makeLabel("Format:")
|
||||
let durationLabel: NSTextField = RenderOptionsAccessory.makeLabel("Duration (s):")
|
||||
|
||||
let grid: NSGridView = NSGridView(views: [
|
||||
[formatLabel, formatPopup],
|
||||
[durationLabel, durationField],
|
||||
])
|
||||
grid.translatesAutoresizingMaskIntoConstraints = false
|
||||
grid.rowSpacing = RenderOptionsAccessory.gridSpacing
|
||||
grid.columnSpacing = RenderOptionsAccessory.gridSpacing
|
||||
grid.column(at: 0).xPlacement = .trailing
|
||||
addSubview(grid)
|
||||
|
||||
let margin: CGFloat = RenderOptionsAccessory.contentMargin
|
||||
NSLayoutConstraint.activate([
|
||||
grid.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
|
||||
grid.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
|
||||
grid.topAnchor.constraint(equalTo: topAnchor, constant: margin),
|
||||
grid.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin),
|
||||
durationField.widthAnchor.constraint(
|
||||
greaterThanOrEqualToConstant: RenderOptionsAccessory.minDurationFieldWidth),
|
||||
])
|
||||
|
||||
// Seed the panel filename once from baseName + the initial format's extension.
|
||||
savePanel.nameFieldStringValue = baseName + "." + selectedFormat.fileExtension
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
@objc private func formatChanged() {
|
||||
syncPanelExtension()
|
||||
let index: Int = formatPopup.indexOfSelectedItem
|
||||
if index >= 0 && index < RenderOptionsAccessory.options.count {
|
||||
UserDefaults.standard.set(RenderOptionsAccessory.options[index].token,
|
||||
forKey: RenderOptionsAccessory.defaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-extension the panel's current filename to match the selected format,
|
||||
/// **preserving any stem the user typed** — only the extension is replaced.
|
||||
private func syncPanelExtension() {
|
||||
guard let panel: NSSavePanel = savePanel else { return }
|
||||
let currentStem: String = (panel.nameFieldStringValue as NSString).deletingPathExtension
|
||||
let stem: String = currentStem.isEmpty ? baseName : currentStem
|
||||
panel.nameFieldStringValue = stem + "." + selectedFormat.fileExtension
|
||||
}
|
||||
|
||||
/// Test seam: select a format by index as if the user picked it from the popup
|
||||
/// (fires the same `formatChanged` side effects — panel re-extension + persistence).
|
||||
func selectFormatForTesting(at index: Int) {
|
||||
formatPopup.selectItem(at: index)
|
||||
formatChanged()
|
||||
}
|
||||
|
||||
/// Test seam: clear the persisted last-format so a test can start from the
|
||||
/// default and not leak state into other tests or the real app.
|
||||
static func clearPersistedFormatForTesting() {
|
||||
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private static func persistedIndex() -> Int {
|
||||
let token: String = UserDefaults.standard.string(forKey: defaultsKey) ?? fallbackToken
|
||||
if let index: Int = options.firstIndex(where: { $0.token == token }) { return index }
|
||||
return options.firstIndex(where: { $0.token == fallbackToken }) ?? 0
|
||||
}
|
||||
|
||||
private static func makeLabel(_ text: String) -> NSTextField {
|
||||
let label: NSTextField = NSTextField(labelWithString: text)
|
||||
label.translatesAutoresizingMaskIntoConstraints = false
|
||||
return label
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,42 @@
|
||||
// ScratchConsoleEntry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// One line in the scratch editor's console panel — a report message, an error,
|
||||
// or a run notice.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// A single entry in the always-open console.
|
||||
public struct ScratchConsoleEntry: Identifiable, Equatable {
|
||||
|
||||
/// What kind of line this is, for coloring.
|
||||
public enum Kind: Equatable {
|
||||
/// `context.reportMessage(_:)` output (and host notices).
|
||||
case message
|
||||
/// A compile / DSL error.
|
||||
case error
|
||||
/// A run outcome / informational notice.
|
||||
case info
|
||||
}
|
||||
|
||||
/// Monotonic id (also the display order).
|
||||
public let id: Int
|
||||
public let kind: Kind
|
||||
public let text: String
|
||||
/// `"line:col"` for an error with a known source position, else `nil`.
|
||||
public let location: String?
|
||||
|
||||
public init(id: Int, kind: Kind, text: String, location: String? = nil) {
|
||||
self.id = id
|
||||
self.kind = kind
|
||||
self.text = text
|
||||
self.location = location
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,164 @@
|
||||
// ScratchLineNumberGutter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Line-number gutter for `ScratchEditor`'s text view, implemented as a plain
|
||||
// floating overlay `NSView` rather than an `NSRulerView`. Enabling
|
||||
// `NSScrollView.rulersVisible` in this SwiftUI `NSViewRepresentable` mis-tiles
|
||||
// the document view (text goes invisible and stops taking input), and drawing
|
||||
// inside a layer-backed `NSTextView` never reaches `draw(_:)`. A floating
|
||||
// subview draws normally and leaves the text view untouched. It reads the text
|
||||
// view's layout manager and the clip view's scroll offset to place one
|
||||
// right-aligned number per source line in the visible region.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
final class ScratchLineNumberGutter: NSView {
|
||||
|
||||
private weak var textView: NSTextView?
|
||||
private weak var scrollView: NSScrollView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.scrollView = scrollView
|
||||
self.textView = textView
|
||||
let height: CGFloat = scrollView.contentView.bounds.height
|
||||
super.init(frame: NSRect(x: 0, y: 0, width: ScratchTextView.lineNumberGutterWidth, height: height))
|
||||
self.autoresizingMask = [.height]
|
||||
|
||||
let clip: NSClipView = scrollView.contentView
|
||||
clip.postsBoundsChangedNotifications = true
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSView.boundsDidChangeNotification, object: clip)
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSText.didChangeNotification, object: textView)
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSView.frameDidChangeNotification, object: textView)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberGutter does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
/// Redraw the whole gutter after an edit / scroll / relayout. A programmatic
|
||||
/// text replace (format / load / reset) can happen without an
|
||||
/// `NSText.didChangeNotification`, so the host also nudges this directly.
|
||||
@objc func refresh() { needsDisplay = true }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
gutterFillColor.setFill()
|
||||
bounds.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let divider: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
divider.move(to: NSPoint(x: dividerX, y: bounds.minY))
|
||||
divider.line(to: NSPoint(x: dividerX, y: bounds.maxY))
|
||||
divider.lineWidth = 1
|
||||
divider.stroke()
|
||||
|
||||
guard let textView: NSTextView = textView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let container: NSTextContainer = textView.textContainer,
|
||||
let clip: NSClipView = scrollView?.contentView else { return }
|
||||
|
||||
let visibleRect: NSRect = clip.documentVisibleRect
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let ns: NSString = textView.string as NSString
|
||||
let total: Int = ns.length
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: gutterFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
// Glyphs visible in the clip, then the source-line walk over that range.
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: container)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
|
||||
// Snap to the START of the first visible source line before counting: when
|
||||
// word-wrap puts a wrapped continuation fragment at the top of the visible
|
||||
// area, `charRange.location` lands mid-line, and `lineNumber(at:)` would
|
||||
// over-count by one (throwing off every number below it).
|
||||
let firstLineStart: Int = ns.lineRange(for: NSRange(location: min(charRange.location, total), length: 0)).location
|
||||
var lineIndex: Int = lineNumber(at: firstLineStart, in: ns)
|
||||
var cursor: Int = firstLineStart
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor < total {
|
||||
let lineRange: NSRange = ns.lineRange(for: NSRange(location: cursor, length: 0))
|
||||
// Position from the line *fragment* rect (the row's box), not the glyph
|
||||
// bounding rect. `boundingRect` is inconsistent across a trailing
|
||||
// newline and blank lines — it's what left the last number cramped
|
||||
// against the trailing empty line. The fragment rect is one clean,
|
||||
// uniform-height box per row.
|
||||
let firstGlyph: Int = layoutManager.glyphIndexForCharacter(at: lineRange.location)
|
||||
let fragment: NSRect = layoutManager.lineFragmentRect(
|
||||
forGlyphAt: firstGlyph,
|
||||
effectiveRange: nil,
|
||||
withoutAdditionalLayout: true
|
||||
)
|
||||
drawNumber(lineIndex, docY: fragment.minY + inset, lineHeight: fragment.height,
|
||||
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break }
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
|
||||
// Trailing empty line (empty doc, or one ending in a newline): drawn from
|
||||
// the layout manager's extra fragment, which `boundingRect` on a
|
||||
// zero-length range does not cover.
|
||||
let endsWithNewline: Bool = total > 0 && CharacterSet.newlines.contains(
|
||||
Unicode.Scalar(ns.character(at: total - 1)) ?? Unicode.Scalar(0)
|
||||
)
|
||||
if total == 0 || endsWithNewline {
|
||||
let extra: NSRect = layoutManager.extraLineFragmentRect
|
||||
if extra.height > 0 {
|
||||
drawNumber(lineIndex, docY: extra.minY + inset, lineHeight: extra.height,
|
||||
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func drawNumber(_ n: Int, docY: CGFloat, lineHeight: CGFloat, visibleMinY: CGFloat,
|
||||
attrs: [NSAttributedString.Key: Any]) {
|
||||
// Document Y → gutter-local Y (the gutter floats over the visible area).
|
||||
let y: CGFloat = docY - visibleMinY
|
||||
let label: NSString = "\(n)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let point: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: y + (lineHeight - size.height) * verticalCenterFraction
|
||||
)
|
||||
label.draw(at: point, withAttributes: attrs)
|
||||
}
|
||||
|
||||
/// 1-based source line number of the character at `loc`. Counts CR/LF/CRLF.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
text.enumerateSubstrings(in: NSRange(location: 0, length: loc),
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5
|
||||
private let gutterFontSize: CGFloat = 11
|
||||
private let verticalCenterFraction: CGFloat = 0.5
|
||||
private let gutterFillColor: NSColor = .controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = .separatorColor
|
||||
private let gutterTextColor: NSColor = .tertiaryLabelColor
|
||||
private var gutterFont: NSFont { NSFont.monospacedSystemFont(ofSize: gutterFontSize, weight: .regular) }
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,145 +0,0 @@
|
||||
// ScratchLineNumberRuler.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
||||
// 1-based line label per visible line into the ruler's bounds.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
||||
/// invalidates itself on every text edit and frame change.
|
||||
final class ScratchLineNumberRuler: NSRulerView {
|
||||
|
||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
||||
/// swaps the text view performs after attachment.
|
||||
private weak var textView: NSTextView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.textView = textView
|
||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
||||
self.clientView = textView
|
||||
self.ruleThickness = gutterWidth
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSText.didChangeNotification,
|
||||
object: textView)
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.frameDidChangeNotification,
|
||||
object: textView)
|
||||
let clipView: NSClipView = scrollView.contentView
|
||||
clipView.postsBoundsChangedNotifications = true
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.boundsDidChangeNotification,
|
||||
object: clipView)
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func invalidateForChange(_ note: Notification) {
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
guard let textView: NSTextView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let textContainer: NSTextContainer = textView.textContainer else {
|
||||
return
|
||||
}
|
||||
|
||||
gutterFillColor.setFill()
|
||||
rect.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let dividerPath: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
||||
dividerPath.lineWidth = 1
|
||||
dividerPath.stroke()
|
||||
|
||||
let nsText: NSString = textView.string as NSString
|
||||
let totalLength: Int = nsText.length
|
||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: rulerFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
||||
var cursor: Int = charRange.location
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor <= totalLength {
|
||||
// `lineRange(for:)` advances cursor by the full line including its
|
||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
||||
// handled by Foundation.
|
||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
||||
actualCharacterRange: nil)
|
||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
||||
in: textContainer)
|
||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
||||
let label: NSString = "\(lineIndex)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let drawPoint: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
||||
)
|
||||
label.draw(at: drawPoint, withAttributes: attrs)
|
||||
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break } // defensive — empty trailing line
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based line number of the character at `loc`. Delegates to
|
||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
||||
// that precedes the first visible line.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
||||
text.enumerateSubstrings(in: prefixRange,
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let gutterWidth: CGFloat = 40
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
||||
private let rulerFontSize: CGFloat = 11
|
||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
||||
private var rulerFont: NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
// ScratchScopeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// A compact real-time oscilloscope for the scratch editor's engine panel.
|
||||
// Reimplemented here (rather than reusing `LyrebirdUI.LyrebirdScopeView`) because
|
||||
// the LiveCompile stack must not link `LyrebirdUI` — that would static-fold a
|
||||
// second copy of `LyrebirdSynth`'s ObjC classes. It reads the same core
|
||||
// `ScopeCapture` the engine writes to.
|
||||
|
||||
#if os(macOS)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Polls a ``ScopeCapture`` at ~30 Hz and draws each captured channel's waveform
|
||||
/// with `Canvas`. Channels stack vertically; channel 0 cyan, channel 1 orange.
|
||||
struct ScratchScopeView: View {
|
||||
|
||||
let capture: ScopeCapture
|
||||
|
||||
@State private var channels: [[Float]] = []
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
|
||||
private static let channelColors: [Color] = [.cyan, .orange, .green, .yellow]
|
||||
private static let backgroundColor: Color = Color(white: 0.08)
|
||||
private static let zeroLineOpacity: Double = 0.25
|
||||
private static let separatorOpacity: Double = 0.3
|
||||
private static let waveformHeightFraction: CGFloat = 0.44
|
||||
|
||||
var body: some View {
|
||||
Canvas { ctx, size in
|
||||
ctx.fill(Path(CGRect(origin: .zero, size: size)),
|
||||
with: .color(ScratchScopeView.backgroundColor))
|
||||
guard !channels.isEmpty else { return }
|
||||
let count: Int = channels.count
|
||||
let rowH: CGFloat = size.height / CGFloat(count)
|
||||
|
||||
for (ch, samples): (Int, [Float]) in channels.enumerated() {
|
||||
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
|
||||
let halfH: CGFloat = rowH * ScratchScopeView.waveformHeightFraction
|
||||
|
||||
var guide: Path = Path()
|
||||
guide.move(to: CGPoint(x: 0, y: midY))
|
||||
guide.addLine(to: CGPoint(x: size.width, y: midY))
|
||||
ctx.stroke(guide, with: .color(.white.opacity(ScratchScopeView.zeroLineOpacity)),
|
||||
lineWidth: 0.5)
|
||||
|
||||
if ch < count - 1 {
|
||||
let sepY: CGFloat = rowH * CGFloat(ch + 1)
|
||||
var sep: Path = Path()
|
||||
sep.move(to: CGPoint(x: 0, y: sepY))
|
||||
sep.addLine(to: CGPoint(x: size.width, y: sepY))
|
||||
ctx.stroke(sep, with: .color(.white.opacity(ScratchScopeView.separatorOpacity)),
|
||||
lineWidth: 0.5)
|
||||
}
|
||||
|
||||
guard samples.count > 1 else { continue }
|
||||
let color: Color = ScratchScopeView.channelColors[ch % ScratchScopeView.channelColors.count]
|
||||
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
|
||||
var path: Path = Path()
|
||||
for (i, sample): (Int, Float) in samples.enumerated() {
|
||||
let x: CGFloat = CGFloat(i) * xStep
|
||||
let y: CGFloat = midY - CGFloat(sample) * halfH
|
||||
if i == 0 { path.move(to: CGPoint(x: x, y: y)) }
|
||||
else { path.addLine(to: CGPoint(x: x, y: y)) }
|
||||
}
|
||||
ctx.stroke(path, with: .color(color), lineWidth: 1.0)
|
||||
}
|
||||
}
|
||||
.background(ScratchScopeView.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
channels = capture.snapshot()
|
||||
try? await Task.sleep(nanoseconds: ScratchScopeView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,141 @@
|
||||
// ToolchainAlert.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// User-facing text for a missing-toolchain warning. Pure/value type so the
|
||||
/// status → message mapping is unit-testable without presenting a modal.
|
||||
public struct ToolchainAlertContent: Equatable {
|
||||
/// Alert title (the `NSAlert.messageText`).
|
||||
public let title: String
|
||||
/// Alert body explaining the problem and the fix (the `NSAlert.informativeText`).
|
||||
public let message: String
|
||||
/// Whether "Install Command Line Tools" is an appropriate remedy (it is for a
|
||||
/// missing toolchain, but not for a present-but-incomplete SDK).
|
||||
public let offersCommandLineToolsInstall: Bool
|
||||
}
|
||||
|
||||
/// Map a toolchain status to alert content, or `nil` when nothing needs saying
|
||||
/// (`.available`). Pure — no side effects.
|
||||
public func toolchainAlertContent(for status: SwiftToolchainStatus) -> ToolchainAlertContent? {
|
||||
let dslNote: String = " The Graph DSL mode works without a toolchain if you'd rather not install one."
|
||||
switch status {
|
||||
case .available:
|
||||
return nil
|
||||
case .missingDeveloperTools:
|
||||
return ToolchainAlertContent(
|
||||
title: "Swift toolchain not found",
|
||||
message: "The Swift scratchpad compiles snippets with swiftc, which needs "
|
||||
+ "Xcode or the Command Line Tools." + dslNote,
|
||||
offersCommandLineToolsInstall: true
|
||||
)
|
||||
case .missingSwiftc:
|
||||
return ToolchainAlertContent(
|
||||
title: "Swift compiler not found",
|
||||
message: "A developer directory is selected, but swiftc could not be resolved. "
|
||||
+ "Install or repair Xcode or the Command Line Tools." + dslNote,
|
||||
offersCommandLineToolsInstall: true
|
||||
)
|
||||
case .missingSDK:
|
||||
return ToolchainAlertContent(
|
||||
title: "macOS SDK not found",
|
||||
message: "swiftc was found but the macOS SDK is missing — your Xcode may be "
|
||||
+ "incomplete. Install a full Xcode." + dslNote,
|
||||
offersCommandLineToolsInstall: false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// App Store product page for Xcode.
|
||||
private let xcodeAppStoreURL: String = "macappstore://apps.apple.com/app/xcode/id497799835"
|
||||
|
||||
@MainActor
|
||||
extension LyrebirdScratchMenuController {
|
||||
|
||||
/// Probe for a Swift toolchain off the main thread and, if missing, present a
|
||||
/// one-time warning alert with install guidance. Safe no-op when the toolchain is
|
||||
/// available. Called once at launch from `installMainMenu`.
|
||||
public func warnIfSwiftToolchainMissing(probe: ToolchainProbe = ToolchainProbe()) {
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
let status: SwiftToolchainStatus = probe.status()
|
||||
guard let content: ToolchainAlertContent = toolchainAlertContent(for: status) else { return }
|
||||
DispatchQueue.main.async {
|
||||
LyrebirdScratchMenuController.presentToolchainAlert(content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Present the toolchain warning as a modal `NSAlert` with install actions.
|
||||
static func presentToolchainAlert(_ content: ToolchainAlertContent) {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = content.title
|
||||
alert.informativeText = content.message
|
||||
alert.alertStyle = .warning
|
||||
|
||||
// Buttons are added in first→last order; NSAlert returns .alertFirstButtonReturn
|
||||
// for the first, +1 for the next, etc.
|
||||
let installButton: NSButton? = content.offersCommandLineToolsInstall
|
||||
? alert.addButton(withTitle: "Install Command Line Tools")
|
||||
: nil
|
||||
let xcodeButton: NSButton = alert.addButton(withTitle: "Get Xcode")
|
||||
let okButton: NSButton = alert.addButton(withTitle: "OK")
|
||||
|
||||
// Make OK the default (Return) so an accidental Return dismisses rather than
|
||||
// launching the installer / App Store. Clearing the other buttons' key
|
||||
// equivalents removes their default-button status.
|
||||
installButton?.keyEquivalent = ""
|
||||
xcodeButton.keyEquivalent = ""
|
||||
okButton.keyEquivalent = "\r"
|
||||
|
||||
let response: NSApplication.ModalResponse = alert.runModal()
|
||||
let firstButton: NSApplication.ModalResponse = .alertFirstButtonReturn
|
||||
let secondButton: NSApplication.ModalResponse =
|
||||
NSApplication.ModalResponse(rawValue: firstButton.rawValue + 1)
|
||||
|
||||
if content.offersCommandLineToolsInstall {
|
||||
if response == firstButton {
|
||||
launchCommandLineToolsInstaller()
|
||||
} else if response == secondButton {
|
||||
openXcodeInAppStore()
|
||||
}
|
||||
// third button = OK: dismiss.
|
||||
} else {
|
||||
if response == firstButton {
|
||||
openXcodeInAppStore()
|
||||
}
|
||||
// second button = OK: dismiss.
|
||||
}
|
||||
}
|
||||
|
||||
/// Launch Apple's Command Line Tools installer (`xcode-select --install`). This
|
||||
/// opens Apple's own GUI installer dialog — the app never installs silently.
|
||||
private static func launchCommandLineToolsInstaller() {
|
||||
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||
// Mirror the executable-file pre-check used by the other subprocess helpers.
|
||||
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else {
|
||||
openXcodeInAppStore()
|
||||
return
|
||||
}
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||
process.arguments = ["--install"]
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
// If we can't launch it, fall back to the App Store (Xcode includes the tools).
|
||||
openXcodeInAppStore()
|
||||
}
|
||||
}
|
||||
|
||||
/// Open Xcode's App Store product page.
|
||||
private static func openXcodeInAppStore() {
|
||||
guard let url: URL = URL(string: xcodeAppStoreURL) else { return }
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
// main.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Runnable Linux live-coding scratchpad:
|
||||
//
|
||||
// swift run LyrebirdScratchLinuxDemo
|
||||
//
|
||||
// Opens a GTK4 window with a code editor + Run/Clear + a live scope + a console.
|
||||
// Type Swift, press Run: the snippet is compiled to a .so, dlopen'd, and run
|
||||
// against the shared libLyrebirdDynamic, playing into the running engine. Needs
|
||||
// libgtk-4-dev to build and (for sound) a live ALSA device; without ALSA the
|
||||
// editor still compiles + runs snippets, just silently.
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
import LyrebirdLiveCompileUI
|
||||
import LyrebirdUI // GTK4Backend / App / WindowGroup, via @_exported re-exports
|
||||
|
||||
private let scratchBlockSize: Int = 512
|
||||
private let scratchSampleRate: Double = 44_100.0
|
||||
private let scratchOutputChannels: Int = 2
|
||||
private let scratchInputChannels: Int = 0
|
||||
|
||||
let scratchDriver: any AudioDriver = makeDefaultAudioDriver()
|
||||
let scratchEngine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: scratchBlockSize,
|
||||
sampleRate: scratchSampleRate,
|
||||
numOutputChannels: scratchOutputChannels,
|
||||
numInputChannels: scratchInputChannels,
|
||||
driver: scratchDriver
|
||||
)
|
||||
|
||||
// Construct the session BEFORE start() so it can install its scope tap (the RT
|
||||
// thread caches the tap at start()).
|
||||
let scratchSession: LiveSession = LiveSession(engine: scratchEngine)
|
||||
|
||||
do {
|
||||
try scratchEngine.start()
|
||||
} catch {
|
||||
print("[Lyrebird] scratch engine start failed: \(error)")
|
||||
}
|
||||
|
||||
if !isLiveAudioAvailable {
|
||||
print("[Lyrebird] no live audio backend — snippets still compile + run, but there is no sound.")
|
||||
}
|
||||
|
||||
// Register the GTK pointer sink so a snippet's `Mouse.X.Control()` /
|
||||
// `Mouse.Y.Control()` / `Mouse.Click.Control()` read live values. Without this
|
||||
// the shared `MouseInput` bridge is never installed and `Mouse.X` sits at its
|
||||
// default, so e.g. `OscSin.Audio(freq: Mouse.X.Control() * 100)` never
|
||||
// modulates. Install timing is not sensitive on Linux (SwiftOpenUI attaches the
|
||||
// pointer controllers to every window it opens); the snippet reads the same
|
||||
// process-global singleton in the shared libLyrebird.
|
||||
MouseTracker.installShared()
|
||||
|
||||
// The app owns the model so the File menu commands (New / Open… / Save /
|
||||
// Save As…, with Ctrl+N/O/S accelerators) can bind to the same instance the
|
||||
// view renders — SwiftOpenUI declares `.commands` on the Scene, not the View.
|
||||
let scratchModel: LinuxScratchModel = LinuxScratchModel(session: scratchSession)
|
||||
|
||||
// `LiveSession` / `LinuxScratchModel` are `@unchecked Sendable`, so they cross
|
||||
// into SwiftOpenUI's nonisolated scene closure directly.
|
||||
struct LyrebirdScratchApp: App {
|
||||
var body: some Scene {
|
||||
WindowGroup("Lyrebird Scratch") {
|
||||
LyrebirdScratchLinuxView(model: scratchModel)
|
||||
}
|
||||
.commands {
|
||||
lyrebirdScratchFileCommands(model: scratchModel)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
GTK4Backend().run(LyrebirdScratchApp.self)
|
||||
@@ -0,0 +1,134 @@
|
||||
// ArtifactStagingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Verifies that a staged artifacts directory is a self-contained, working
|
||||
/// compile root: a snippet compiled against the staged `-I` / `-L` / rpath
|
||||
/// succeeds without reaching back into the original build tree.
|
||||
@Suite("LiveSession artifact staging")
|
||||
struct ArtifactStagingTests {
|
||||
|
||||
/// The dev SPM build dir the tests run from — the staging source.
|
||||
private func buildDir() -> URL? {
|
||||
LiveSession.currentBuildDir()
|
||||
}
|
||||
|
||||
@Test func umbrellaHeaderPathParses() {
|
||||
let map: String = """
|
||||
module LyrebirdC {
|
||||
umbrella header "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h"
|
||||
export *
|
||||
}
|
||||
"""
|
||||
#expect(LiveSession.umbrellaHeaderPath(in: map) == "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h")
|
||||
}
|
||||
|
||||
@Test func umbrellaHeaderPathNilWhenAbsent() {
|
||||
#expect(LiveSession.umbrellaHeaderPath(in: "module Foo { export * }") == nil)
|
||||
}
|
||||
|
||||
@Test func stageProducesPopulatedRootWithStagedModuleMap() throws {
|
||||
guard let src: URL = buildDir() else {
|
||||
// No build dir discoverable (unusual for a test run) — nothing to stage.
|
||||
return
|
||||
}
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||
#expect(staged == dest)
|
||||
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||
|
||||
// The staged C module map must point at the staged header copy, not the
|
||||
// original absolute path under the source tree.
|
||||
let stagedMap: URL = dest
|
||||
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
|
||||
.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
if FileManager.default.fileExists(atPath: stagedMap.path) {
|
||||
let text: String = try String(contentsOf: stagedMap, encoding: .utf8)
|
||||
#expect(text.contains("\(dest.path)/LyrebirdC.headers"))
|
||||
#expect(!text.contains("/Sources/LyrebirdC/include"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func refusesToClobberNonStagingDir() throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
// A pre-existing file that does NOT look like a staging root.
|
||||
let precious: URL = dest.appendingPathComponent("precious.txt", isDirectory: false)
|
||||
try "keep me".write(to: precious, atomically: true, encoding: .utf8)
|
||||
|
||||
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||
#expect(staged == nil) // refused
|
||||
#expect(FileManager.default.fileExists(atPath: precious.path)) // untouched
|
||||
}
|
||||
|
||||
@Test func idempotentSecondStageKeepsRoot() throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||
// Second call with an unchanged source: still a valid, current root.
|
||||
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||
#expect(LiveSession.stagedDirIsCurrent(dest))
|
||||
}
|
||||
|
||||
@Test func snippetCompilesFromStagedRoot() async throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
guard LiveSession.hasLyrebirdDylib(in: src) else {
|
||||
// Xcode-SPM layout (no dylib) — the staged-link path under test needs
|
||||
// the bare-SPM dylib present; skip when absent.
|
||||
return
|
||||
}
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
guard let staged: URL = LiveSession.stageArtifacts(from: src, to: dest) else {
|
||||
Issue.record("staging produced no root")
|
||||
return
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
// Point the session ONLY at the staged root — no original build dir.
|
||||
let session: LiveSession = await LiveSession(
|
||||
engine: engine,
|
||||
attachScope: false,
|
||||
importPaths: [staged, staged.appendingPathComponent("Modules")],
|
||||
librarySearchPaths: [staged],
|
||||
libraries: ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [staged]
|
||||
)
|
||||
// A trivial snippet that touches the LyrebirdSynth API proves the module
|
||||
// resolves from the staged root.
|
||||
try await session.compileAndRunAsync("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
await session.clearTracked()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -8,15 +8,18 @@ import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@Suite("DiagnosticParser")
|
||||
struct DiagnosticParserTests {
|
||||
|
||||
@Test
|
||||
func parsesSingleErrorAtUserBodyLine() throws {
|
||||
// Wrapped snippet preamble is 8 lines; user body starts at line 9.
|
||||
// swiftc reports an error on wrapped line 10 → maps to user line 2.
|
||||
// Representative offset: for a preamble whose user body starts at line 9,
|
||||
// a swiftc error on wrapped line 10 maps to user line 2. (This tests the
|
||||
// parser's arithmetic directly; the actual harness offset — which shifts
|
||||
// when the preamble changes — is exercised by
|
||||
// `endToEndOffsetMatchesSnippetHarness` below.)
|
||||
let stderr: String = "/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope"
|
||||
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
|
||||
try #require(diagnostics.count == 1)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -8,7 +8,7 @@ import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@Suite("LiveCompiler")
|
||||
struct LiveCompilerTests {
|
||||
@@ -30,7 +30,11 @@ struct LiveCompilerTests {
|
||||
|
||||
let snippet: CompiledSnippet = try LiveCompiler.compile(source: source)
|
||||
#expect(snippet.moduleName.hasPrefix("LBSnippet_"))
|
||||
#if os(macOS)
|
||||
#expect(snippet.dylibPath.hasSuffix(".dylib"))
|
||||
#else
|
||||
#expect(snippet.dylibPath.hasSuffix(".so"))
|
||||
#endif
|
||||
|
||||
var marker: Int32 = 0
|
||||
withUnsafeMutablePointer(to: &marker) { ptr in
|
||||
@@ -103,6 +107,11 @@ struct LiveCompilerTests {
|
||||
for url: URL in LiveSession.discoverSPMModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#if os(Linux)
|
||||
for url: URL in LiveSession.discoverSourceSystemModuleMaps(in: importPaths) {
|
||||
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
|
||||
}
|
||||
#endif
|
||||
return args
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession diagnostics")
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
import LyrebirdGraphDSLEmbedded
|
||||
|
||||
@@ -9,7 +9,7 @@ import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession")
|
||||
@@ -34,7 +34,12 @@ struct LiveSessionTests {
|
||||
@Test
|
||||
func buildDirDiscoveryFindsLyrebirdDylib() throws {
|
||||
let buildDir: URL = try #require(LiveSession.currentBuildDir())
|
||||
let dylib: URL = buildDir.appendingPathComponent("libLyrebirdDynamic.dylib")
|
||||
#if os(macOS)
|
||||
let libName: String = "libLyrebirdDynamic.dylib"
|
||||
#else
|
||||
let libName: String = "libLyrebirdDynamic.so"
|
||||
#endif
|
||||
let dylib: URL = buildDir.appendingPathComponent(libName)
|
||||
#expect(FileManager.default.fileExists(atPath: dylib.path))
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// MessageLogTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession message log")
|
||||
struct MessageLogTests {
|
||||
|
||||
private func makeSession() -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@Test func accumulatesAndDrains() {
|
||||
let session: LiveSession = makeSession()
|
||||
session.appendMessage("a")
|
||||
session.appendMessage("b")
|
||||
#expect(session.lastSnippetMessage == "b") // last value, for tests
|
||||
#expect(session.drainMessages() == ["a", "b"])
|
||||
// Drained → empty.
|
||||
#expect(session.lastSnippetMessage == nil)
|
||||
#expect(session.drainMessages().isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,63 @@
|
||||
// ScopeAttachTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession scope attach")
|
||||
struct ScopeAttachTests {
|
||||
|
||||
private func makeEngine(outChannels: Int = 2) -> SynthesisEngine {
|
||||
SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: outChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
@Test func attachesStereoScopeByDefault() {
|
||||
let engine: SynthesisEngine = makeEngine(outChannels: 2)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
let scope: ScopeCapture? = session.scope
|
||||
#expect(scope != nil)
|
||||
#expect(scope?.buses == [0, 1])
|
||||
// Installed on the engine so the RT thread writes to it.
|
||||
#expect(engine.scopeTap === scope)
|
||||
}
|
||||
|
||||
@Test func attachScopeFalseInstallsNothing() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||
#expect(session.scope == nil)
|
||||
#expect(engine.scopeTap == nil)
|
||||
}
|
||||
|
||||
@Test func monoEngineTapsOneBus() {
|
||||
let engine: SynthesisEngine = makeEngine(outChannels: 1)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
#expect(session.scope?.buses == [0])
|
||||
}
|
||||
|
||||
@Test func reusesExistingTapRatherThanReplacing() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let existing: ScopeCapture = ScopeCapture(buses: [0], bufferSize: 256)
|
||||
engine.scopeTap = existing
|
||||
let session: LiveSession = LiveSession(engine: engine) // attach on, but a tap exists
|
||||
#expect(session.scope === existing)
|
||||
#expect(engine.scopeTap === existing)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,94 @@
|
||||
// SlotReleaseTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession slot release")
|
||||
struct SlotReleaseTests {
|
||||
|
||||
/// A synth whose graceful `release` succeeds (records the call) — stands in
|
||||
/// for a gated `EnvGen` voice.
|
||||
private final class GatedSynth: SynthesizerBase, @unchecked Sendable {
|
||||
var released: Bool = false
|
||||
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||
override func release(engine: SynthesisEngine) throws { released = true }
|
||||
}
|
||||
|
||||
/// A synth with no gate — inherits the default `release` that throws `.noGate`.
|
||||
private final class GatelessSynth: SynthesizerBase, @unchecked Sendable {
|
||||
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||
}
|
||||
|
||||
private func makeStartedSession() throws -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
try engine.start()
|
||||
return session
|
||||
}
|
||||
|
||||
@Test func releaseGatedSlotTriggersReleaseAndDropsHandle() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
let voice: GatedSynth = GatedSynth()
|
||||
try session.swapSlot("pad", synth: voice)
|
||||
#expect(session.slotNames.contains("pad"))
|
||||
|
||||
let released: Bool = session.releaseSlot("pad")
|
||||
#expect(released)
|
||||
#expect(voice.released) // graceful release fired
|
||||
#expect(session.slotNames.contains("pad") == false) // handle dropped, name free
|
||||
// Safety net: the released voice moves to the tracked list so it stays
|
||||
// reclaimable by resetAll() / Clear Synths even if it never self-frees.
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
session.resetAll()
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func nameIsReusableAfterRelease() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
try session.swapSlot("pad", synth: GatedSynth())
|
||||
#expect(session.releaseSlot("pad"))
|
||||
// The name is free again — a fresh voice claims the slot cleanly.
|
||||
try session.swapSlot("pad", synth: GatedSynth())
|
||||
#expect(session.slotNames.contains("pad"))
|
||||
#expect(session.slotCount == 1)
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func releaseGatelessSlotFailsAndKeepsHandle() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
try session.swapSlot("bass", synth: GatelessSynth())
|
||||
|
||||
let released: Bool = session.releaseSlot("bass")
|
||||
#expect(released == false)
|
||||
// Not orphaned — still in the slot, still stoppable with a hard clear.
|
||||
#expect(session.slotNames.contains("bass"))
|
||||
#expect(session.clearSlot("bass"))
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func releaseEmptySlotReturnsFalse() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
#expect(session.releaseSlot("nothing-here") == false)
|
||||
session.engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
@@ -8,7 +8,7 @@ import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
@Suite("SnippetHarness")
|
||||
struct SnippetHarnessTests {
|
||||
@@ -16,6 +16,9 @@ struct SnippetHarnessTests {
|
||||
@Test
|
||||
func wrappedSourceContainsPreambleAndUserBody() {
|
||||
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
|
||||
// Foundation so snippets can use `pow`, `sin`, `Date`, … without an import
|
||||
// (a snippet can't declare one — its body is inside the entry function).
|
||||
#expect(wrapped.source.contains("import Foundation"))
|
||||
#expect(wrapped.source.contains("import LyrebirdSynth"))
|
||||
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
|
||||
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// SnippetScheduledLoopTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Proves the scratch editor runs *functional* Swift — a real `for` loop that
|
||||
/// schedules a timed sequence — not just single-graph expressions.
|
||||
@MainActor
|
||||
@Suite("Snippet scheduled loop")
|
||||
struct SnippetScheduledLoopTests {
|
||||
|
||||
@Test func snippetCanUseFoundationMath() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 44_100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||
try engine.start()
|
||||
// `pow` / `sin` come from Foundation, which the harness preamble imports —
|
||||
// a snippet can't add the import itself. This would fail to compile
|
||||
// ("cannot find 'pow' in scope") without it.
|
||||
let snippet: String = """
|
||||
let semitone: Double = pow(2.0, 1.0 / 12.0)
|
||||
let freq: Double = 440.0 * semitone
|
||||
context.play { OscSin.Audio(freq: freq) * (0.1 * sin(0.0) + 0.1) }
|
||||
context.reportMessage("math ok \\(freq)")
|
||||
"""
|
||||
try session.compileAndRun(snippet)
|
||||
#expect(session.lastSnippetMessage?.hasPrefix("math ok") == true)
|
||||
session.clearTracked()
|
||||
}
|
||||
|
||||
@Test func loopSchedulesTenSelfFreeingTones() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 44_100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
try engine.start()
|
||||
|
||||
// A `for` loop that schedules ten short sine tones, 0.35 s apart. Each is
|
||||
// a decaying amplitude envelope (`Line` with `doneAction: .freeNode`)
|
||||
// times a sine, so it plays ~0.2 s and then frees itself — no manual
|
||||
// cleanup, no blocking the main thread.
|
||||
let snippet: String = """
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||
for i in 0..<10 {
|
||||
let freq: Double = scale[i]
|
||||
let tone = ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
}
|
||||
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||
catch { context.reportMessage("schedule failed: \\(error)") }
|
||||
}
|
||||
context.reportMessage("scheduled 10 tones")
|
||||
"""
|
||||
|
||||
try session.compileAndRun(snippet)
|
||||
// The `for` loop and the scheduling calls compiled and ran.
|
||||
#expect(session.lastSnippetMessage == "scheduled 10 tones")
|
||||
|
||||
// Advance ~4.5 s of audio; the scheduled adds fire over time. (Each
|
||||
// tone's `.freeNode` self-frees via the engine's async auto-free watcher
|
||||
// in the running app — that background timer doesn't get a turn inside
|
||||
// this synchronous processBlock loop, so here the tones accumulate; the
|
||||
// auto-free path itself is covered by `AutoFreeOnDoneTests`.)
|
||||
let blocks: Int = Int(4.5 * 44_100 / 512)
|
||||
var peakActive: Int = 0
|
||||
var producedAudio: Bool = false
|
||||
for _ in 0..<blocks {
|
||||
engine.processBlock(inputSamples: [])
|
||||
peakActive = max(peakActive, engine.synthesizerCount)
|
||||
if engine.audioBuses[0].contains(where: { $0 != 0 }) { producedAudio = true }
|
||||
}
|
||||
|
||||
#expect(peakActive == 10, "all ten scheduled tones should have entered the tree over time")
|
||||
#expect(producedAudio, "the scheduled tones should have written audio to the bus")
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// SwiftFormatterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("SwiftFormatter")
|
||||
struct SwiftFormatterTests {
|
||||
|
||||
@Test func formatsMessySource() throws {
|
||||
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||
let messy: String = "let x=1\nstruct Foo{let a:Int}\n"
|
||||
let formatted: String = try SwiftFormatter.format(source: messy)
|
||||
// Canonical spacing appears; the mangled originals are gone.
|
||||
#expect(formatted.contains("let x = 1"))
|
||||
#expect(!formatted.contains("let x=1"))
|
||||
#expect(!formatted.contains("struct Foo"))
|
||||
}
|
||||
|
||||
@Test func alreadyFormattedIsStable() throws {
|
||||
guard SwiftFormatter.isAvailable else { return }
|
||||
let clean: String = "let x = 1\n"
|
||||
let once: String = try SwiftFormatter.format(source: clean)
|
||||
let twice: String = try SwiftFormatter.format(source: once)
|
||||
#expect(once == twice) // idempotent
|
||||
}
|
||||
|
||||
@Test func parseErrorThrowsFormatFailed() {
|
||||
guard SwiftFormatter.isAvailable else { return }
|
||||
// Unbalanced brace — swift-format should exit non-zero.
|
||||
let broken: String = "func f( {\n"
|
||||
var caught: SwiftFormatterError?
|
||||
do {
|
||||
_ = try SwiftFormatter.format(source: broken)
|
||||
} catch let error as SwiftFormatterError {
|
||||
caught = error
|
||||
} catch {
|
||||
Issue.record("unexpected error type: \(error)")
|
||||
}
|
||||
guard case .formatFailed = caught else {
|
||||
Issue.record("expected .formatFailed, got \(String(describing: caught))")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
// ToolchainProbeTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("ToolchainProbe")
|
||||
struct ToolchainProbeTests {
|
||||
|
||||
private func probe(swiftc: String?, sdk: String?, devDir: String?) -> ToolchainProbe {
|
||||
ToolchainProbe(
|
||||
swiftcResolver: { swiftc },
|
||||
sdkResolver: { sdk },
|
||||
developerDirResolver: { devDir }
|
||||
)
|
||||
}
|
||||
|
||||
@Test("swiftc + SDK both present → available")
|
||||
func availableWhenBothResolve() {
|
||||
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: "/SDK", devDir: "/Dev").status() == .available)
|
||||
}
|
||||
|
||||
@Test("no swiftc and no developer dir → missingDeveloperTools")
|
||||
func missingDeveloperTools() {
|
||||
#expect(probe(swiftc: nil, sdk: nil, devDir: nil).status() == .missingDeveloperTools)
|
||||
}
|
||||
|
||||
@Test("no swiftc but developer dir present → missingSwiftc")
|
||||
func missingSwiftc() {
|
||||
#expect(probe(swiftc: nil, sdk: nil, devDir: "/Dev").status() == .missingSwiftc)
|
||||
// SDK value is irrelevant when swiftc is unresolved.
|
||||
#expect(probe(swiftc: nil, sdk: "/SDK", devDir: "/Dev").status() == .missingSwiftc)
|
||||
}
|
||||
|
||||
@Test("swiftc present but SDK missing → missingSDK")
|
||||
func missingSDK() {
|
||||
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: nil, devDir: "/Dev").status() == .missingSDK)
|
||||
}
|
||||
|
||||
@Test("default probe on a build machine finds developer tools")
|
||||
func defaultProbeFindsDeveloperTools() {
|
||||
// Any machine that can build/test this package has a developer directory, so
|
||||
// the real (non-injected) resolvers must never report missingDeveloperTools —
|
||||
// this smoke-tests that the default xcode-select / xcrun probes actually run.
|
||||
// (Not asserting strict `.available`: a full-SDK requirement would couple the
|
||||
// suite to the host's exact toolchain completeness.)
|
||||
#expect(ToolchainProbe().status() != .missingDeveloperTools)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,155 @@
|
||||
// LinuxScratchModelTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Pure-logic tests for the Linux scratch model's document / file surface
|
||||
// (dirty-tracking, new/load/save, title). Deliberately avoids the paths that
|
||||
// open a native GtkFileDialog (`openDocument()`, `saveAs()`) — those need a
|
||||
// running GTK application and a display, so they are exercised by hand on the
|
||||
// VM, not here. The paths covered are headless-safe: `CodeEditorController`'s
|
||||
// `setText` is a no-op until a widget is attached, and `save()` with a
|
||||
// `currentPath` set writes the file directly without a dialog.
|
||||
#if os(Linux)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LinuxScratchModel document + file I/O")
|
||||
struct LinuxScratchModelTests {
|
||||
|
||||
private func makeModel(initialSource: String = lyrebirdLinuxScratchSeed) -> LinuxScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LinuxScratchModel(session: LiveSession(engine: engine), initialSource: initialSource)
|
||||
}
|
||||
|
||||
private func tempPath(_ ext: String = "swift") -> String {
|
||||
FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("lyrebird-scratch-\(UUID().uuidString).\(ext)")
|
||||
.path
|
||||
}
|
||||
|
||||
// MARK: - Dirty tracking
|
||||
|
||||
@Test func freshModelIsCleanWithSeed() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
#expect(model.source == lyrebirdLinuxScratchSeed)
|
||||
#expect(model.isDirty == false)
|
||||
#expect(model.currentPath == nil)
|
||||
}
|
||||
|
||||
@Test func setSourceMarksDirtyOnRealChange() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
model.setSource(model.source + "\n// edit")
|
||||
#expect(model.isDirty == true)
|
||||
}
|
||||
|
||||
@Test func setSourceIgnoresUnchangedEcho() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
// A widget echo of the identical value must not flip the dirty flag.
|
||||
model.setSource(model.source)
|
||||
#expect(model.isDirty == false)
|
||||
}
|
||||
|
||||
// MARK: - New
|
||||
|
||||
@Test func newDocumentResetsToSeedAndClean() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
model.setSource("context.play { OscSin.Audio(freq: 440) }")
|
||||
model.currentPath = "/tmp/whatever.swift"
|
||||
#expect(model.isDirty == true)
|
||||
|
||||
model.newDocument()
|
||||
#expect(model.source == lyrebirdLinuxScratchSeed)
|
||||
#expect(model.currentPath == nil)
|
||||
#expect(model.isDirty == false)
|
||||
}
|
||||
|
||||
// MARK: - Load
|
||||
|
||||
@Test func loadFileReplacesBufferAndAdoptsPathClean() throws {
|
||||
let path: String = tempPath()
|
||||
let body: String = "context.play { OscSin.Audio(freq: 220, mul: 0.2) }\n"
|
||||
try body.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
defer { try? FileManager.default.removeItem(atPath: path) }
|
||||
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
model.loadFile(path)
|
||||
#expect(model.source == body)
|
||||
#expect(model.currentPath == path)
|
||||
#expect(model.isDirty == false)
|
||||
}
|
||||
|
||||
@Test func loadFileMissingPathKeepsBuffer() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
let before: String = model.source
|
||||
model.loadFile("/nonexistent/does-not-exist.swift")
|
||||
// Failure is reported to the console; the buffer is untouched.
|
||||
#expect(model.source == before)
|
||||
#expect(model.currentPath == nil)
|
||||
}
|
||||
|
||||
// MARK: - Save
|
||||
|
||||
@Test func saveWritesToCurrentPathAndClears() throws {
|
||||
let path: String = tempPath()
|
||||
defer { try? FileManager.default.removeItem(atPath: path) }
|
||||
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
let code: String = "context.play { WhiteNoise.Audio(mul: 0.1) }"
|
||||
model.setSource(code)
|
||||
model.currentPath = path
|
||||
#expect(model.isDirty == true)
|
||||
|
||||
model.save() // currentPath is set -> writes directly, no dialog
|
||||
#expect(model.isDirty == false)
|
||||
let onDisk: String = try String(contentsOfFile: path, encoding: .utf8)
|
||||
#expect(onDisk == code)
|
||||
}
|
||||
|
||||
@Test func saveThenLoadRoundTrip() throws {
|
||||
let path: String = tempPath()
|
||||
defer { try? FileManager.default.removeItem(atPath: path) }
|
||||
|
||||
let writer: LinuxScratchModel = makeModel()
|
||||
let code: String = "context.play { OscSaw.Audio(freq: 110, mul: 0.15) }"
|
||||
writer.setSource(code)
|
||||
writer.currentPath = path
|
||||
writer.save()
|
||||
|
||||
let reader: LinuxScratchModel = makeModel()
|
||||
reader.loadFile(path)
|
||||
#expect(reader.source == code)
|
||||
#expect(reader.currentPath == path)
|
||||
#expect(reader.isDirty == false)
|
||||
}
|
||||
|
||||
// MARK: - Title
|
||||
|
||||
@Test func displayTitleUntitledWhenNoPath() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
#expect(model.displayTitle == "untitled.swift")
|
||||
}
|
||||
|
||||
@Test func displayTitleShowsFilenameAndDirtyMarker() {
|
||||
let model: LinuxScratchModel = makeModel()
|
||||
model.currentPath = "/home/user/tune.swift"
|
||||
#expect(model.displayTitle == "tune.swift")
|
||||
model.setSource(model.source + " ")
|
||||
#expect(model.displayTitle == "● tune.swift")
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -64,7 +64,9 @@ struct LyrebirdScratchModelTests {
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
#expect(model.statusMessage.contains("replaced"))
|
||||
#expect(model.statusMessage.contains("Tracked synths: 0"))
|
||||
#expect(session.lastSnippetMessage == "hello")
|
||||
// The report message is drained from the session into the console.
|
||||
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello" })
|
||||
#expect(session.lastSnippetMessage == nil) // drained
|
||||
#expect(model.isCompiling == false)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// RenderOptionsAccessoryTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
// Serialized: these tests mutate a shared `UserDefaults` key (the persisted
|
||||
// last-format), so they must not interleave.
|
||||
@Suite("RenderOptionsAccessory", .serialized)
|
||||
@MainActor
|
||||
struct RenderOptionsAccessoryTests {
|
||||
|
||||
// Popup order (see RenderOptionsAccessory.options).
|
||||
private let wavFloat32Index: Int = 0
|
||||
private let wavInt24Index: Int = 2
|
||||
private let rf64Float32Index: Int = 5
|
||||
|
||||
private func makeAccessory() -> (RenderOptionsAccessory, NSSavePanel) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||
baseName: "render", initialDuration: 5.0, savePanel: panel
|
||||
)
|
||||
return (accessory, panel)
|
||||
}
|
||||
|
||||
// MARK: - Duration parsing
|
||||
|
||||
@Test("parseDuration accepts positive finite numbers and rejects the rest")
|
||||
func durationParsing() {
|
||||
#expect(RenderOptionsAccessory.parseDuration("5.0") == 5.0)
|
||||
#expect(RenderOptionsAccessory.parseDuration(" 2.5 ") == 2.5)
|
||||
#expect(RenderOptionsAccessory.parseDuration("0") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("-1") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("abc") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("nan") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("inf") == nil)
|
||||
}
|
||||
|
||||
// MARK: - Format read-out
|
||||
|
||||
@Test("Selecting a format updates selectedFormat")
|
||||
func selectedFormatReflectsPopup() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
|
||||
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||
#expect(accessory.selectedFormat == .wavFloat32)
|
||||
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||
#expect(accessory.selectedFormat == .wavInt24)
|
||||
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||
#expect(accessory.selectedFormat == .rf64Float32)
|
||||
}
|
||||
|
||||
// MARK: - Panel filename sync
|
||||
|
||||
@Test("Changing format preserves a user-typed filename stem")
|
||||
func formatChangePreservesUserStem() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
|
||||
// User renames the target, then switches format.
|
||||
panel.nameFieldStringValue = "mySound.caf"
|
||||
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||
#expect(panel.nameFieldStringValue == "mySound.wav")
|
||||
|
||||
// Switching again keeps the stem, swaps only the extension.
|
||||
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||
#expect(panel.nameFieldStringValue == "mySound.wav") // RF64 keeps .wav
|
||||
}
|
||||
|
||||
@Test("Empty filename falls back to the base name")
|
||||
func emptyStemFallsBackToBaseName() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
panel.nameFieldStringValue = ""
|
||||
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||
#expect(panel.nameFieldStringValue == "render.wav")
|
||||
}
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
@Test("Last-selected format persists to a fresh accessory")
|
||||
func formatSelectionPersists() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
|
||||
let (first, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
first.selectFormatForTesting(at: rf64Float32Index) // persists "rf64F32"
|
||||
|
||||
// A brand-new accessory should open on the remembered format.
|
||||
let (second, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
#expect(second.selectedFormat == .rf64Float32)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,76 @@
|
||||
// ScratchModelConsoleTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel console")
|
||||
@MainActor
|
||||
struct ScratchModelConsoleTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||
}
|
||||
|
||||
@Test func successfulRunLogsInfo() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
}
|
||||
|
||||
@Test func failedRunLogsErrorEntries() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "NotAGenerator(freq: 1)")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||
#expect(model.consoleEntries.contains { $0.text.contains("NotAGenerator") })
|
||||
}
|
||||
|
||||
@Test func reportMessagesAppearAsMessages() async {
|
||||
// A DSL run pushes no messages; drive the log directly to prove the
|
||||
// message → console wiring (drainMessages → .message entries).
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
model.session.appendMessage("hello from snippet")
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello from snippet" })
|
||||
}
|
||||
|
||||
@Test func clearConsoleEmpties() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(!model.consoleEntries.isEmpty)
|
||||
model.clearConsole()
|
||||
#expect(model.consoleEntries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func resetSessionClearsConsole() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(!model.consoleEntries.isEmpty)
|
||||
model.resetSession()
|
||||
#expect(model.consoleEntries.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
// ScratchModelFormatTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel formatting")
|
||||
@MainActor
|
||||
struct ScratchModelFormatTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||
}
|
||||
|
||||
@Test func formatRewritesMessyBufferAndLogs() async {
|
||||
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||
let model: LyrebirdScratchModel = makeModel(text: "let x=1\n")
|
||||
await model.formatBuffer()
|
||||
#expect(model.text.contains("let x = 1"))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
}
|
||||
|
||||
@Test func formatBlankBufferIsNoOp() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||
let before: String = model.text
|
||||
await model.formatBuffer()
|
||||
#expect(model.text == before)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,125 @@
|
||||
// ScratchModelRenderTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel render-to-file")
|
||||
@MainActor
|
||||
struct ScratchModelRenderTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||
}
|
||||
|
||||
@Test func rendersWholeBufferToCAF() async throws {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let duration: Double = 0.25
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: duration)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
|
||||
// The CAF should hold roughly `duration` seconds at the engine's rate.
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
guard let fileRef: ExtAudioFileRef = fileRef else {
|
||||
Issue.record("could not open rendered CAF")
|
||||
return
|
||||
}
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
var frames: Int64 = 0
|
||||
var size: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||||
#expect(ExtAudioFileGetProperty(fileRef, kExtAudioFileProperty_FileLengthFrames, &size, &frames) == noErr)
|
||||
// Allow a block of slack either way.
|
||||
let expected: Double = duration * 48_000
|
||||
#expect(Double(frames) > expected - 128 && Double(frames) < expected + 512)
|
||||
}
|
||||
|
||||
@Test func rendersSelectionWhenPresent() async {
|
||||
// Whole buffer has two statements; select only the first and render it.
|
||||
let model: LyrebirdScratchModel = makeModel(
|
||||
text: "context.play { OscSin.Audio(freq: 440) * 0.1 }\ncontext.play { OscSin.Audio(freq: 880) * 0.1 }")
|
||||
model.updateSelection("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
#expect(model.hasSelection)
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
|
||||
@Test func nonPositiveDurationFails() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0)
|
||||
#expect(!ok)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||
}
|
||||
|
||||
@Test func blankBufferRendersNothing() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||
#expect(!ok)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
|
||||
/// The `format:` argument reaches the NRT driver: rendering to a WAV Int24 target
|
||||
/// and an RF64 target produces files with the requested on-disk encoding.
|
||||
@Test(arguments: [
|
||||
(AudioFileFormat.wavInt24, "wav", UInt32(24), false),
|
||||
(AudioFileFormat.rf64Float32, "wav", UInt32(32), true),
|
||||
])
|
||||
func rendersHonourFormat(format: AudioFileFormat, ext: String, bits: UInt32, isFloat: Bool) async throws {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString)").appendingPathExtension(ext)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let ok: Bool = await model.renderToFile(url: url, format: format, duration: 0.1)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||
#expect(asbd.mBitsPerChannel == bits)
|
||||
#expect((asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) == isFloat)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,58 @@
|
||||
// ScratchModelResetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel resetSession")
|
||||
@MainActor
|
||||
struct ScratchModelResetTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||
}
|
||||
|
||||
@Test func resetStopsAudioAndClearsDiagnosticsButKeepsBuffer() async {
|
||||
let source: String = "OscSin(freq: 440) * 0.1"
|
||||
let model: LyrebirdScratchModel = makeModel(text: source)
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // tracked 1
|
||||
#expect(model.trackedSynthCount == 1)
|
||||
|
||||
model.resetSession()
|
||||
|
||||
#expect(model.trackedSynthCount == 0) // audio stopped
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
// Non-destructive: the user's buffer is preserved.
|
||||
#expect(model.text == source)
|
||||
#expect(model.statusMessage.contains("reset"))
|
||||
}
|
||||
|
||||
@Test func resetLeavesAFreshDirtyBaseline() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // .clean
|
||||
model.resetSession()
|
||||
// The placeholder buffer was never run in this fresh session → .dirty.
|
||||
#expect(model.reevalState == .dirty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
// ScratchModelRunSelectionTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel run selection")
|
||||
@MainActor
|
||||
struct ScratchModelRunSelectionTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||
}
|
||||
|
||||
@Test func hasSelectionReflectsNonWhitespaceSelection() {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
#expect(model.hasSelection == false)
|
||||
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||
#expect(model.hasSelection)
|
||||
model.updateSelection(" \n ") // whitespace only
|
||||
#expect(model.hasSelection == false)
|
||||
model.updateSelection("")
|
||||
#expect(model.hasSelection == false)
|
||||
}
|
||||
|
||||
@Test func runSelectionWithNoSelectionIsNoOp() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok == false)
|
||||
#expect(model.trackedSynthCount == 0)
|
||||
}
|
||||
|
||||
@Test func runSelectionAddsToRunningWithoutDisturbingBaseline() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
|
||||
// Whole-buffer run establishes the baseline → clean, one synth.
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.reevalState == .clean)
|
||||
#expect(model.trackedSynthCount == 1)
|
||||
|
||||
// Run a selected fragment: additive (adds a second synth) and leaves the
|
||||
// whole-buffer baseline intact (buffer still matches the last whole run).
|
||||
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok)
|
||||
#expect(model.trackedSynthCount == 2)
|
||||
#expect(model.reevalState == .clean) // baseline untouched
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
}
|
||||
|
||||
@Test func selectionRunAddsEvenFromADirtyBuffer() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // tracked 1, .clean
|
||||
// Dirty the buffer (edited since the last whole run).
|
||||
model.text = "OscSin(freq: 440) * 0.1\n# edited"
|
||||
#expect(model.reevalState == .dirty)
|
||||
|
||||
model.updateSelection("OscSin(freq: 330) * 0.1")
|
||||
_ = await model.runSelection() // additive → tracked 2
|
||||
model.updateSelection("OscSin(freq: 110) * 0.1")
|
||||
_ = await model.runSelection() // additive → tracked 3
|
||||
#expect(model.trackedSynthCount == 3)
|
||||
// The selection runs never replaced, and the buffer stays dirty.
|
||||
#expect(model.reevalState == .dirty)
|
||||
}
|
||||
|
||||
@Test func failedSelectionRunLeavesWholeBufferBadgeUntouched() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // .clean
|
||||
#expect(model.reevalState == .clean)
|
||||
|
||||
// A selection with an unknown generator fails to build.
|
||||
model.updateSelection("NotAGenerator(freq: 1)")
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok == false)
|
||||
#expect(!model.diagnostics.isEmpty)
|
||||
// The whole-buffer badge must stay clean — the buffer itself is fine.
|
||||
#expect(model.reevalState == .clean)
|
||||
#expect(model.statusMessage.hasPrefix("Selection"))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -38,14 +38,49 @@ struct ScratchTextViewTests {
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// Mid-identifier (no preceding dot) falls through to the default behavior,
|
||||
/// which covers the whole partial word so it gets replaced on completion.
|
||||
@Test func partialIdentifierUsesDefaultWordRange() {
|
||||
/// Mid-identifier (no preceding dot): the range covers the run of identifier
|
||||
/// characters before the caret, so the partial word gets replaced.
|
||||
@Test func partialIdentifierCoversWordRange() {
|
||||
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
// Default range spans the partial word `OscSi` (length 5 from offset 0).
|
||||
#expect(range == NSRange(location: 0, length: 5))
|
||||
}
|
||||
|
||||
/// Right after an open paren, the range is EMPTY at the caret — an argument
|
||||
/// label (`freq:`) inserts there instead of replacing the receiver
|
||||
/// (`OscSin.Audio(` → erases `OscSin.Audio` bug).
|
||||
@Test func afterOpenParenRangeIsEmptyAtCaret() {
|
||||
let text: String = "OscSin.Audio("
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// After a comma + space (next argument position), the range is empty too.
|
||||
@Test func afterCommaSpaceRangeIsEmptyAtCaret() {
|
||||
let text: String = "OscSin.Audio(freq: 440, "
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// A partial argument label inside parens replaces just that partial word,
|
||||
/// not the receiver expression.
|
||||
@Test func partialArgLabelCoversOnlyThePartial() {
|
||||
let text: String = "OscSin.Audio(fr"
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
// `fr` starts at offset 13 (after `OscSin.Audio(`), length 2.
|
||||
#expect(range == NSRange(location: 13, length: 2))
|
||||
}
|
||||
|
||||
/// Underscore is an identifier character, so a leading-underscore partial is
|
||||
/// covered whole.
|
||||
@Test func underscoreIsIdentifierChar() {
|
||||
let tv: ScratchTextView = makeTextView("_foo", caret: 4)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: 0, length: 4))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// ToolchainAlertTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("ToolchainAlert content")
|
||||
struct ToolchainAlertTests {
|
||||
|
||||
@Test("available status produces no alert content")
|
||||
func availableIsNil() {
|
||||
#expect(toolchainAlertContent(for: .available) == nil)
|
||||
}
|
||||
|
||||
@Test("missing-toolchain statuses offer the Command Line Tools install")
|
||||
func missingOffersCLTInstall() {
|
||||
for status: SwiftToolchainStatus in [.missingDeveloperTools, .missingSwiftc] {
|
||||
let content: ToolchainAlertContent? = toolchainAlertContent(for: status)
|
||||
#expect(content != nil)
|
||||
#expect(content?.offersCommandLineToolsInstall == true)
|
||||
#expect(content?.title.isEmpty == false)
|
||||
// Steers the user to the dependency-free fallback.
|
||||
#expect(content?.message.contains("Graph DSL") == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("missing-SDK does not offer CLT install (needs a full Xcode)")
|
||||
func missingSDKNoCLT() {
|
||||
let content: ToolchainAlertContent? = toolchainAlertContent(for: .missingSDK)
|
||||
#expect(content != nil)
|
||||
#expect(content?.offersCommandLineToolsInstall == false)
|
||||
#expect(content?.message.contains("Xcode") == true)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -20,7 +20,7 @@
|
||||
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
||||
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
// ProcessInfo — read the LYREBIRD_DISABLE_ALSA opt-out below.
|
||||
import Foundation
|
||||
|
||||
let package = Package(
|
||||
name: "Lyrebird",
|
||||
@@ -21,7 +23,10 @@ let package = Package(
|
||||
// double-registration crash fixed in Phase 167). External consumers
|
||||
// never reference this product — they use `Lyrebird` (static) above.
|
||||
.library(name: "LyrebirdDynamic", type: .dynamic, targets: ["LyrebirdSynth"]),
|
||||
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"]),
|
||||
// LyrebirdUI (SwiftUI/AppKit) product + targets are appended after this
|
||||
// literal under `#if os(macOS)` — they are Apple-only and must be absent
|
||||
// from the manifest on a native Linux/Windows host. See the block below
|
||||
// the `Package(...)` initializer.
|
||||
.library(name: "LyrebirdGraphDSL", targets: ["LyrebirdGraphDSL"]),
|
||||
.executable(name: "LyrebirdCLI", targets: ["LyrebirdCLI"]),
|
||||
],
|
||||
@@ -58,19 +63,38 @@ let package = Package(
|
||||
name: "LyrebirdC",
|
||||
path: "Sources/LyrebirdC"
|
||||
),
|
||||
// Vector-math seam. On Apple this target re-exports Accelerate
|
||||
// (`@_exported import Accelerate`); on non-Apple platforms it supplies
|
||||
// API-compatible scalar replacements for the vDSP/vForce primitives the
|
||||
// synthesis core uses. Every core file writes `import LyrebirdDSP` in
|
||||
// place of `import Accelerate`. See Sources/LyrebirdDSP/AccelerateShim.swift.
|
||||
.target(
|
||||
name: "LyrebirdDSP",
|
||||
path: "Sources/LyrebirdDSP",
|
||||
linkerSettings: [
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.target(
|
||||
// Module/target renamed `Lyrebird` → `LyrebirdSynth` (the `Lyrebird`
|
||||
// product above still vends it). Folder path kept as `Sources/Lyrebird`
|
||||
// so the source tree and `Lyrebird.docc` catalog don't move.
|
||||
name: "LyrebirdSynth",
|
||||
dependencies: ["LyrebirdC"],
|
||||
// `CALSA` (libasound, for the Linux `ALSAAudioDriver`) is appended
|
||||
// to these dependencies on a Linux host — see the block below the
|
||||
// `Package(...)` initializer.
|
||||
dependencies: ["LyrebirdC", "LyrebirdDSP"],
|
||||
path: "Sources/Lyrebird",
|
||||
linkerSettings: [
|
||||
.linkedFramework("CoreAudio"),
|
||||
.linkedFramework("AudioToolbox"),
|
||||
.linkedFramework("Accelerate"),
|
||||
.linkedFramework("CoreMIDI"),
|
||||
.linkedFramework("AVFoundation"),
|
||||
// Apple-only frameworks. Guarded with `.when(platforms:)` so a
|
||||
// non-Apple target (Linux/Windows feasibility) does not fail at
|
||||
// link-configuration time before source-level errors surface.
|
||||
// macOS/iOS builds are unaffected.
|
||||
.linkedFramework("CoreAudio", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("CoreMIDI", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("AVFoundation", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.executableTarget(
|
||||
@@ -87,15 +111,9 @@ let package = Package(
|
||||
]
|
||||
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
|
||||
),
|
||||
.target(
|
||||
name: "LyrebirdUI",
|
||||
dependencies: [
|
||||
"LyrebirdSynth",
|
||||
],
|
||||
path: "Sources/LyrebirdUI"
|
||||
// SwiftUI + AppKit + Observation are system frameworks — no linkerSettings needed.
|
||||
// Swift 6 language mode (Phase 202): inherits the swift-tools 6.0 default.
|
||||
),
|
||||
// NOTE: LyrebirdUI, LyrebirdUITests, and LyrebirdTests are appended after
|
||||
// the `Package(...)` initializer under `#if os(macOS)` — they need Apple
|
||||
// frameworks and must be absent from a native Linux/Windows manifest.
|
||||
// Phase 167 — `LyrebirdLiveCompile` (and its SwiftUI host
|
||||
// `LyrebirdLiveCompileUI`) moved to the `LiveCompile/` nested SwiftPM
|
||||
// package. It depends on the internal `.product(name: "LyrebirdDynamic",
|
||||
@@ -105,12 +123,10 @@ let package = Package(
|
||||
// cause of an ObjC class double-registration crash during `swift test`
|
||||
// in the single-package layout. The consumer-facing `Lyrebird` product
|
||||
// stays static (see products list). See `LiveCompile/Package.swift`.
|
||||
.executableTarget(
|
||||
name: "LyrebirdBenchmark",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Sources/LyrebirdBenchmark",
|
||||
swiftSettings: [.unsafeFlags(["-O"])]
|
||||
),
|
||||
// LyrebirdBenchmark micro-benchmarks Accelerate/vDSP primitives directly
|
||||
// (`import Accelerate`), so it is Apple-only and appended under
|
||||
// `#if os(macOS)` below the initializer — otherwise `swift test` on Linux
|
||||
// would try to build it and fail on the missing Accelerate module.
|
||||
// Interpreted graph-DSL. Pure Swift over core `LyrebirdSynth` types —
|
||||
// no swiftc, no AppKit — so it is cross-platform (iOS included). The
|
||||
// `DSLBuiltin` registry it consumes is emitted by the separate
|
||||
@@ -122,22 +138,13 @@ let package = Package(
|
||||
path: "Sources/LyrebirdGraphDSL"
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdTests",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Tests/LyrebirdTests",
|
||||
name: "LyrebirdDSPTests",
|
||||
dependencies: ["LyrebirdDSP"],
|
||||
path: "Tests/LyrebirdDSPTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox"),
|
||||
.linkedFramework("Accelerate"),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdUITests",
|
||||
dependencies: [
|
||||
"LyrebirdUI",
|
||||
"LyrebirdSynth",
|
||||
],
|
||||
path: "Tests/LyrebirdUITests"
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdGraphDSLTests",
|
||||
dependencies: [
|
||||
@@ -146,8 +153,8 @@ let package = Package(
|
||||
],
|
||||
path: "Tests/LyrebirdGraphDSLTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox"),
|
||||
.linkedFramework("Accelerate"),
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
@@ -155,5 +162,180 @@ let package = Package(
|
||||
dependencies: ["LyrebirdCLI"],
|
||||
path: "Tests/LyrebirdCLITests"
|
||||
),
|
||||
// Platform-neutral core tests. Unlike `LyrebirdTests` (Apple-only —
|
||||
// some files import AudioToolbox/Accelerate directly), this target
|
||||
// compiles and runs on every supported platform, so the golden-value
|
||||
// DSP tests it holds actually execute on Linux in CI. That is the only
|
||||
// place the portable FFT/biquad/vector fallbacks in `LyrebirdDSP` are
|
||||
// verified through the real generators; `LyrebirdDSPTests` compares to
|
||||
// real vDSP and is therefore Apple-only by construction.
|
||||
.testTarget(
|
||||
name: "LyrebirdPortableTests",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Tests/LyrebirdPortableTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
// LyrebirdUI — the cross-platform UI module. Public control/view names are the
|
||||
// same on every platform; each file switches its body by backend
|
||||
// (`#if canImport(SwiftUI)` → real SwiftUI on Apple / `#else` → SwiftOpenUI on
|
||||
// Linux). Base dependency is `LyrebirdSynth` (the shared `@UIParam` model);
|
||||
// the Linux block below adds the SwiftOpenUI + BackendGTK4 backend deps. On
|
||||
// Apple, SwiftUI/AppKit are system frameworks so no package dep is needed.
|
||||
package.products.append(
|
||||
.library(name: "LyrebirdUI", targets: ["LyrebirdUI"])
|
||||
)
|
||||
package.targets.append(
|
||||
.target(
|
||||
name: "LyrebirdUI",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Sources/LyrebirdUI"
|
||||
)
|
||||
)
|
||||
|
||||
// Apple-only pieces, added only when the manifest host is macOS.
|
||||
//
|
||||
// `#if` cannot appear as an element inside an array literal in a package
|
||||
// manifest, so these are appended to the already-built `package` instead of
|
||||
// being conditionalized in place. On a native Linux/Windows host (in-container
|
||||
// `swift build`/`swift test`, CI) they are simply absent, so nothing tries to
|
||||
// compile SwiftUI/AppKit or the AudioToolbox-importing test files.
|
||||
//
|
||||
// • LyrebirdUITests — exercises LyrebirdUI (the module itself is now
|
||||
// cross-platform and appended above the initializer).
|
||||
// • LyrebirdBenchmark — micro-benchmarks Accelerate/vDSP primitives directly.
|
||||
// • LyrebirdTests — the main suite; still imports Apple frameworks
|
||||
// directly in some files (e.g. AUv3 driver tests).
|
||||
// Porting its platform-neutral majority to run on
|
||||
// Linux, plus Linux-runnable golden DSP tests, is a
|
||||
// separate work item.
|
||||
//
|
||||
// Cross-compiling from a Mac keeps the host as macOS, so Apple-SDK builds are
|
||||
// unaffected — they still see every target.
|
||||
#if os(macOS)
|
||||
package.targets.append(contentsOf: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdBenchmark",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Sources/LyrebirdBenchmark",
|
||||
swiftSettings: [.unsafeFlags(["-O"])]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdTests",
|
||||
dependencies: ["LyrebirdSynth"],
|
||||
path: "Tests/LyrebirdTests",
|
||||
linkerSettings: [
|
||||
.linkedFramework("AudioToolbox", .when(platforms: [.macOS, .iOS])),
|
||||
.linkedFramework("Accelerate", .when(platforms: [.macOS, .iOS])),
|
||||
]
|
||||
),
|
||||
.testTarget(
|
||||
name: "LyrebirdUITests",
|
||||
dependencies: [
|
||||
"LyrebirdUI",
|
||||
"LyrebirdSynth",
|
||||
],
|
||||
path: "Tests/LyrebirdUITests"
|
||||
),
|
||||
])
|
||||
#endif
|
||||
|
||||
// Linux live audio. `ALSAAudioDriver` needs libasound's headers, which are not
|
||||
// installed by default on a build box (`apt-get install libasound2-dev`), so
|
||||
// the target is added only when the manifest is being evaluated ON Linux —
|
||||
// where those headers can actually exist. A macOS host never sees it, whether
|
||||
// building for Apple platforms or cross-compiling to Linux; a cross-compiled
|
||||
// Linux binary therefore has no live-audio driver, only offline NRT rendering.
|
||||
// Build natively on Linux to get audio out.
|
||||
//
|
||||
// Escape hatch: set `LYREBIRD_DISABLE_ALSA=1` to build the rest of Lyrebird on
|
||||
// a Linux box that has no ALSA development package. Everything except the
|
||||
// driver still works — `ALSAAudioDriver` is `#if canImport(CALSA)`-guarded and
|
||||
// simply will not exist, and `makeDefaultAudioDriver()` returns an
|
||||
// `OfflineDriver` instead. Note that SwiftPM caches evaluated manifests, so
|
||||
// flipping this variable on an existing checkout may need the cache cleared
|
||||
// (`rm -rf .build`, or a fresh `--scratch-path`) before it takes effect.
|
||||
#if os(Linux)
|
||||
if ProcessInfo.processInfo.environment["LYREBIRD_DISABLE_ALSA"] == nil {
|
||||
package.targets.append(
|
||||
.systemLibrary(
|
||||
name: "CALSA",
|
||||
path: "Sources/CALSA",
|
||||
pkgConfig: "alsa",
|
||||
providers: [
|
||||
.apt(["libasound2-dev"]),
|
||||
]
|
||||
)
|
||||
)
|
||||
if let synthIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdSynth" }) {
|
||||
package.targets[synthIndex].dependencies.append(.target(name: "CALSA"))
|
||||
}
|
||||
// The portable test target needs it too: its ALSA tests are guarded on
|
||||
// `canImport(CALSA)`, which is only true where the module is a dependency.
|
||||
// Without this the guard is always false and the driver's tests silently
|
||||
// never run.
|
||||
if let testIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdPortableTests" }) {
|
||||
package.targets[testIndex].dependencies.append(.target(name: "CALSA"))
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Linux backend for the cross-platform `LyrebirdUI`: SwiftOpenUI (GTK4). This is
|
||||
// now a DEFAULT Linux dependency — building `LyrebirdUI` on Linux pulls
|
||||
// SwiftOpenUI and needs `libgtk-4-dev`. (The default *core* Linux CI lane builds
|
||||
// only LyrebirdSynth / LyrebirdGraphDSL / LyrebirdCLI, so it does not build the
|
||||
// UI or need GTK; a plain `swift build` on Linux does.)
|
||||
//
|
||||
// Pinned to a personal fork commit carrying the GTK4 drag fix ("GTK4: continuous
|
||||
// drag for Canvas value controls": @Observable narrow path + live subtree redraw
|
||||
// + global interaction deferral with linked-control redraw). Move the pin to
|
||||
// `codelynx/SwiftOpenUI` + a version once the fix lands upstream and a release is
|
||||
// tagged. See spikes/SwiftOpenUIKnob/FORK_PATCH_PLAN.md.
|
||||
//
|
||||
// `LyrebirdUI`'s controls bind core `@UIParam` / `UIParamNode` (in
|
||||
// `LyrebirdSynth`), the same model the SwiftUI controls use, so one synthesizer's
|
||||
// parameters drive both platforms.
|
||||
#if os(Linux)
|
||||
// Set LYREBIRD_SWIFTOPENUI_LOCAL=/path/to/SwiftOpenUI to build against a local
|
||||
// fork checkout instead of the pinned release — used to iterate the GTK4 fork
|
||||
// without a push/pin round-trip (this Mac can't build the GTK4 backend; a Linux
|
||||
// container or the VM does). Unset (the default), it resolves the pinned tag.
|
||||
package.dependencies.append(
|
||||
ProcessInfo.processInfo.environment["LYREBIRD_SWIFTOPENUI_LOCAL"].map {
|
||||
.package(name: "SwiftOpenUI", path: $0)
|
||||
} ??
|
||||
// Pinned to the fork's tagged release 0.5.0 (== commit a392026): 0.1.0
|
||||
// (Patches A–F narrow-path + GTK4Backend.openStandaloneWindow → LyrebirdWindow
|
||||
// / presentInWindow + GTK4PointerTracking → Linux MouseTracker), plus the
|
||||
// GtkSourceView-backed `CodeEditor` view (Swift highlighting + gutter) used by
|
||||
// the Linux live-compile scratch editor — which adds a system dependency on
|
||||
// libgtksourceview-5-dev. A tag rather than a bare commit gives a stable,
|
||||
// human-readable release reference; bump it when the fork cuts a new release.
|
||||
// (Upstreaming to codelynx/SwiftOpenUI remains the open follow-on — see
|
||||
// docs/ui/linux-parity-plan.md.)
|
||||
.package(
|
||||
url: "https://github.com/joshpar/SwiftOpenUI",
|
||||
exact: "0.7.0"
|
||||
)
|
||||
)
|
||||
// Give the cross-platform LyrebirdUI target its Linux (GTK4) backend deps.
|
||||
if let uiIndex: Int = package.targets.firstIndex(where: { $0.name == "LyrebirdUI" }) {
|
||||
package.targets[uiIndex].dependencies.append(contentsOf: [
|
||||
.product(name: "SwiftOpenUI", package: "SwiftOpenUI"),
|
||||
.product(name: "BackendGTK4", package: "SwiftOpenUI"),
|
||||
])
|
||||
}
|
||||
// Runnable GTK4 GUI demo: `swift run LyrebirdUILinuxDemo`.
|
||||
package.targets.append(
|
||||
.executableTarget(
|
||||
name: "LyrebirdUILinuxDemo",
|
||||
dependencies: ["LyrebirdSynth", "LyrebirdUI"],
|
||||
path: "Sources/LyrebirdUILinuxDemo"
|
||||
)
|
||||
)
|
||||
#endif
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Lyrebird
|
||||
|
||||
A native macOS/iOS audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles Core Audio I/O and signal graph evaluation with no heap allocation on the real-time thread.
|
||||
A native macOS, iOS, and Linux audio synthesis framework written in Swift. Implement `Generator` and `Synthesizer` protocols; the Lyrebird engine handles platform audio I/O (Core Audio on Apple, ALSA on Linux) and signal graph evaluation with no heap allocation on the real-time thread.
|
||||
|
||||
Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a single-process architecture.
|
||||
|
||||
@@ -8,7 +8,7 @@ Informed by 20+ years of SuperCollider practice, adapted to Swift idioms and a s
|
||||
|
||||
## A quick taste
|
||||
|
||||
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives Core Audio and schedules voices sample-accurately.
|
||||
Three layers, each usable on its own: **Generators** are the unit signal graph, **Synthesizers** package a graph plus live parameters into a playable voice, and the **Engine** drives the platform audio backend (Core Audio on Apple, ALSA on Linux) and schedules voices sample-accurately.
|
||||
|
||||
### Generators — compose a signal graph with operators
|
||||
|
||||
@@ -100,7 +100,7 @@ tone.amp = 0.1
|
||||
engine.remove(tone) // fades out at the next block boundary
|
||||
```
|
||||
|
||||
Prefer a GUI? The `LyrebirdScratchDemo` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||
Prefer a GUI? The `LyrebirdScratch` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||
|
||||
```swift
|
||||
// Snippet body — `context: SnippetContext` is in scope.
|
||||
@@ -128,10 +128,15 @@ The REPL is text-only and works from any project that depends on Lyrebird; the s
|
||||
|
||||
## Requirements
|
||||
|
||||
| Platform | OS | Xcode | Swift |
|
||||
| Platform | OS | IDE | Swift |
|
||||
|---|---|---|---|
|
||||
| macOS | 15+ | 16+ | 6.0 |
|
||||
| iOS | 18+ | 16+ | 6.0 |
|
||||
| macOS | 15+ | Xcode 16+ | 6.0 |
|
||||
| iOS | 18+ | Xcode 16+ | 6.0 |
|
||||
| Linux | Ubuntu 22.04+ ¹ | VS Code ² | 6.0 |
|
||||
|
||||
¹ Any swift.org-supported distribution with a Swift 6.0+ toolchain. Install `libasound2-dev` for live audio via the ALSA driver; offline/NRT rendering needs no audio device or ALSA.
|
||||
|
||||
² VS Code with the [Swift extension](https://marketplace.visualstudio.com/items?itemName=swiftlang.swift-vscode) (build/debug via SourceKit-LSP); any editor works with the `swift` CLI. Linux setup walk-through: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||
|
||||
---
|
||||
|
||||
@@ -149,6 +154,25 @@ That's it — the `Lyrebird` product links **statically**, so there's no dynamic
|
||||
|
||||
Full walk-through (SPM manifest form, local-path dev dependency, per-template details): [`INSTALLATION_AND_USAGE.md`](INSTALLATION_AND_USAGE.md). DocC version: **Getting Started ▸ Adding Lyrebird to your own Xcode project**.
|
||||
|
||||
**On Linux (or any SwiftPM project without the Xcode UI)** — there's no "Add Package Dependencies" dialog, so declare it in `Package.swift`:
|
||||
|
||||
```swift
|
||||
dependencies: [
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.0.0"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "MyApp",
|
||||
dependencies: [
|
||||
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||
// .product(name: "LyrebirdUI", package: "Lyrebird"), // Apple-only — SwiftUI controls
|
||||
]
|
||||
),
|
||||
]
|
||||
```
|
||||
|
||||
Then `import LyrebirdSynth`. On Linux the non-UI core — engine, generators, CLI, offline render, live ALSA audio, MIDI, and OSC — builds and runs with no Xcode and no SwiftUI (`LyrebirdUI` is Apple-only; a GTK4 UI ships as a separate demo). Full setup: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||
|
||||
---
|
||||
|
||||
## Opening in Xcode
|
||||
@@ -176,7 +200,7 @@ Workspace scheme selector exposes ten entries:
|
||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
||||
| `LyrebirdScratchDemo` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
| `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||
|
||||
@@ -190,6 +214,25 @@ Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||
| Build fails with Swift driver errors | Xcode 26 bug affecting the **demo workspace** (which dynamic-links for live-coding) — it already sets `SWIFT_USE_INTEGRATED_DRIVER = NO` + `parallelizeBuildables = NO`. Your own project links Lyrebird statically and is unaffected. |
|
||||
| `dyld: Library not loaded` | Only the bundled demos/AUv3 use the dynamic `LyrebirdDynamic` product; their entitlements already set `disable-library-validation`. External consumers link the static `Lyrebird` product and never hit this. |
|
||||
|
||||
### On Linux — VS Code or any editor (no Xcode)
|
||||
|
||||
Xcode, the `.xcworkspace`, and the schemes above are Apple-only. On Linux there's no workspace to open — point an editor at the package directory and drive it from the terminal:
|
||||
|
||||
```bash
|
||||
code --install-extension swiftlang.swift-vscode # once: the official Swift extension (SourceKit-LSP: autocomplete, jump-to-def, debug)
|
||||
code . # open the package in VS Code
|
||||
```
|
||||
|
||||
There are no schemes — run targets directly:
|
||||
|
||||
```bash
|
||||
swift build && swift test # build + run the Linux test suites
|
||||
swift run LyrebirdCLI repl # the CLI (also `new`, scaffolding, …)
|
||||
LYREBIRD_ENABLE_LINUX_UI=1 swift run LyrebirdUILinuxDemo # the GTK4 UI demo
|
||||
```
|
||||
|
||||
The SwiftUI / AUv3 / iOS demos in the scheme table do not build on Linux. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||
|
||||
---
|
||||
|
||||
## Building and testing from the terminal
|
||||
@@ -218,7 +261,7 @@ All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
Each demo has a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
||||
|
||||
@@ -284,7 +327,7 @@ LyrebirdII/
|
||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
||||
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
||||
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
|
||||
│ └── LyrebirdScratch/ # live-coding scratchpad (macOS, no sandbox)
|
||||
├── Tests/
|
||||
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
||||
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
||||
|
||||
@@ -7,6 +7,543 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 2.3.0 — Edit-ended callback on continuous controls
|
||||
|
||||
A small, additive, source-compatible release. The continuous `LyrebirdUI`
|
||||
controls drive their parameter node(s) continuously while dragging, which gives
|
||||
a host no single "the user finished this edit" signal. This adds one.
|
||||
|
||||
**New — `.onEditingEnded` on the continuous controls.** `ParameterKnob`,
|
||||
`ParameterSlider`, `ParameterXY`, and `MultiSlider` gain an `.onEditingEnded`
|
||||
modifier (both the SwiftUI and the Linux/GTK4 variants) that fires **once per
|
||||
drag gesture**, reporting the value(s) at the start and end of the drag. A host
|
||||
can use it to record a single edit per gesture — an undo checkpoint, say —
|
||||
instead of one per intermediate update. The payload matches each control:
|
||||
`(previous, new)` doubles for the knob and slider, a pair of `(x, y)` tuples for
|
||||
the XY pad, and the before/after cell-value arrays for the multi-slider.
|
||||
|
||||
Additive and drop-in over 2.2.x: every control's public initializer is
|
||||
unchanged (the callback is attached by the modifier), so existing call sites and
|
||||
DocC links are unaffected. See `docs/ui/gui-system.md` for examples.
|
||||
|
||||
---
|
||||
|
||||
## 2.2.0 — Live-parameter ramp origin primed at synth add
|
||||
|
||||
A small-but-behavioral release. One fix to how `@UIParam` / `@LiveParam` values
|
||||
are delivered on a synth's first rendered block, plus the internal hook that
|
||||
backs it. The public API is source-compatible — the one new protocol member is
|
||||
internal-facing and ships with a default implementation — so this is drop-in
|
||||
over 2.1.x, but the delivery change is observable and is called out below.
|
||||
|
||||
**Fix — a parameter set before the first render is now delivered flat.** When a
|
||||
value is assigned to an `@UIParam` / `@LiveParam` *after the synth is
|
||||
constructed but before it first renders* — most commonly when restoring saved
|
||||
state onto a freshly built synth — the parameter is now delivered as a flat
|
||||
block at that value from sample 0. Previously the first rendered block ramped
|
||||
from the property-declaration default up to the assigned value over one
|
||||
(sub-)block, because the property-wrapper setter advances the atomic target but
|
||||
not the interpolation origin, which stayed at the construction-time default.
|
||||
|
||||
For most parameters that one-block (~a few ms) glide was benign. For a value
|
||||
feeding a decision stage it was not: a `Schmidt` trigger fed a threshold that
|
||||
swept up from the default would latch on the transient and, if the steady signal
|
||||
sat inside the hysteresis band, never reset — e.g. a `NoiseGate` restored from a
|
||||
saved rig would open on load and ignore its threshold. Priming the origin at add
|
||||
removes the sweep.
|
||||
|
||||
Mechanically: `SynthesizerBase`, as part of the `Mirror`-based live-parameter
|
||||
auto-registration it already runs at add time (`rebuildGraph()`, main thread,
|
||||
before the node is visible to the RT thread), now also primes each parameter's
|
||||
ramp origin to its current value via a new `LiveParameterValue._primeRampOrigin()`.
|
||||
`ParameterNode` and `UIParamNode` implement it; external conformers inherit a
|
||||
no-op default, so nothing is source-broken. A re-add (`remove` → change value →
|
||||
`add`) likewise re-primes to the then-current value.
|
||||
|
||||
**Behavior change to be aware of.** Two deliveries changed, both toward "the
|
||||
value you set before starting is the value you get":
|
||||
|
||||
- A value assigned between construction and first render is **flat** on block
|
||||
one, not a ramp from the declaration default. Code that (knowingly or not)
|
||||
relied on that opening glide will no longer see it. If you want an opening
|
||||
ramp, drive the parameter from a source/envelope or change it after start.
|
||||
- A synth removed, re-assigned while out of the tree, then re-added starts
|
||||
**flat at the new value** rather than gliding from the value it last rendered.
|
||||
|
||||
Live changes made **while the synth is running** are unchanged — they still ramp
|
||||
per (sub-)block from the last rendered value, as before. The source-slot /
|
||||
crossfade path is unaffected (the source overwrites the origin each block).
|
||||
Pinned by `LiveParamRampOriginTests` (flat delivery for `@UIParam` and
|
||||
`@LiveParam`, live-change-still-ramps, remove/change/re-add, and source-slot
|
||||
non-interference).
|
||||
|
||||
---
|
||||
|
||||
## 2.1.1 — Delay-click fix + internal consolidation
|
||||
|
||||
A patch release: one audible bug fix in the delay/comb/allpass family, plus a
|
||||
large internal code-quality pass. No public API is removed or changed — the few
|
||||
new types are internal-facing scaffolding — so this is drop-in over 2.1.0.
|
||||
|
||||
**Fix — allpass fractional-delay click under modulation.** The allpass
|
||||
interpolation mode (`.allpass`) of `DelayLine`, `CombFilter`, `AllpassFilter`,
|
||||
and `DelayLineFeedback` mishandled its recursive filter state when a modulated
|
||||
delay crossed an exact integer-sample boundary: `AllpassFilter` and
|
||||
`DelayLineFeedback` produced an audible click (a sample-to-sample step several
|
||||
times the surrounding signal), and the four generators disagreed on the
|
||||
behavior. All four now record the integer-delayed sample as the interpolator's
|
||||
previous output, which is click-free and consistent. Only `.allpass`
|
||||
interpolation under a *modulated* delay was affected; `.none` / `.linear` /
|
||||
`.cubic` and static delays were already correct. Guarded by a per-generator
|
||||
regression suite.
|
||||
|
||||
**Internal consolidation (no behavioral change).** Roughly 160 duplicated
|
||||
call-site patterns and several near-identical generator shells were folded into
|
||||
shared helpers and base classes — block-boundary input reads, the per-sample
|
||||
phase wrap, the scalar mul/add fold, the held-constant control fill, the
|
||||
single-input math operators (`UnaryMathBase`), the chaotic oscillators'
|
||||
render body, the spectral FFT-size guards, the spectral feature analysers
|
||||
(`SpectralFeatureControlBase`), and the ~96 block-rate control generators that
|
||||
bypass sub-blocking (now a `BlockRateControlGenerator` marker protocol, which
|
||||
also drops an unused ~4 KB per-instance buffer allocation). Output is
|
||||
bit-identical across the generator library; the full test suite is unchanged.
|
||||
|
||||
---
|
||||
|
||||
## 2.1.0 — Swift 6.4 modernization
|
||||
|
||||
An internal-hardening release adopting modern Swift on the 6.4 toolchain. No
|
||||
behavioral change, and the public surface stays source-compatible.
|
||||
|
||||
**Typed throws.** The closed-error-set APIs now declare their concrete error
|
||||
type instead of untyped `throws`, so a caller gets an exhaustive `catch` with no
|
||||
downcast: OSC (`OSCDecodeError` / `OSCServerError`), MIDI (`MIDIError`, on both
|
||||
the CoreMIDI and ALSA backends), the engine's bus / config / parameter setters,
|
||||
the public node-add surface — `add` / `schedule` — (`EngineAddError`), and the
|
||||
self-contained file codecs (`WavFileError` / `RF64WriterError` /
|
||||
`SpectralFileError`). Narrowing an API from `throws` to `throws(E)` is
|
||||
source-compatible — existing `try` call sites are unaffected. The WAV and
|
||||
Spectral codecs gain an `.ioFailure` case that funnels an underlying
|
||||
`FileHandle` failure into the typed error.
|
||||
|
||||
**Concurrency & memory hardening (internal).** NSLock-guarded state in the
|
||||
scheduling and MIDI classes moved into `Mutex<State>` for compiler-enforced lock
|
||||
discipline, and the Spectral/FFT scratch owners moved from hand-managed raw
|
||||
pointers to a `~Copyable` `RTScratchBuffer` (compiler-guaranteed single free, no
|
||||
ARC on the handle). No API or behavioral change.
|
||||
|
||||
---
|
||||
|
||||
## 2.0.0 — Linux support
|
||||
|
||||
The major release: Lyrebird now runs on **Linux**, in addition to macOS and iOS.
|
||||
Everything on Apple platforms is unchanged — the entire Linux surface is additive
|
||||
— but the port is large enough to warrant a major version.
|
||||
|
||||
**Cross-platform core.** The engine, the full generator library, the CLI, the
|
||||
REPL, offline render (NRT → WAV), and the interpreted graph DSL build and run on
|
||||
Linux (Ubuntu 24.04, swift.org toolchain). A new `LyrebirdDSP` module provides
|
||||
portable `vDSP`/`vv` implementations so the DSP that relied on Accelerate runs
|
||||
off Apple; the portable FFT, biquad, and vector paths are golden-value verified.
|
||||
CI covers x86_64; ARM64 (e.g. a Parallels VM) is a supported dev target.
|
||||
|
||||
**Live audio, MIDI, OSC on Linux.**
|
||||
|
||||
- **`ALSAAudioDriver`** — live full-duplex audio over ALSA. `makeDefaultAudioDriver()`
|
||||
resolves to it on Linux; build with `LYREBIRD_DISABLE_ALSA=1` on boxes with no
|
||||
sound stack.
|
||||
- **ALSA-sequencer MIDI** and a **POSIX-UDP OSC** transport, replacing the
|
||||
CoreMIDI / Network.framework backends off Apple.
|
||||
- A **portable WAV codec** (`WavFileWriter` / `WavFileReader`) for soundfile I/O
|
||||
and DiskIn where AudioToolbox is unavailable (CAF/AIFF/AAC stay Apple-only).
|
||||
|
||||
**GTK4 GUI.** `LyrebirdUI` is now one cross-platform module — SwiftUI on Apple,
|
||||
GTK4 (on the SwiftOpenUI backend) on Linux. Ported controls: knob, slider, label,
|
||||
button, XY pad, plus the oscilloscope, envelope, and CPU-status views, with
|
||||
standalone windows and live mouse input (`Mouse.X` / `Mouse.Y` / `Mouse.Click`).
|
||||
Every control bound to a `@UIParam` node stays in sync — the same parameter model
|
||||
the macOS controls use.
|
||||
|
||||
**Live-coding scratchpad on Linux.** The `LiveCompile` live-coding subsystem runs
|
||||
on Linux: a GtkSourceView editor with Swift highlighting and a gutter, `Ctrl+Space`
|
||||
sourcekit-lsp completion, run-fresh / run-additive / line-evaluation, a Stop-audio
|
||||
panic button, a live oscilloscope, and a native File menu (New / Open… / Save /
|
||||
Save As…) with `Ctrl+N/O/S` accelerators and `GtkFileDialog` save/load.
|
||||
|
||||
**Behavioral change (all platforms).** `SynthesisEngine.stop()` now tears down the
|
||||
node tree and unbinds every non-persistent synth it was hosting, so a stop → re-add
|
||||
of the same instance needs no intervening `processBlock`.
|
||||
|
||||
See `LINUX_README.md` for Linux setup, build, and usage.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.1 — Neural-amp model importer
|
||||
|
||||
A patch release. One backward-compatible addition:
|
||||
|
||||
- **`ProteusModelImporter`** — loads a GuitarML **Proteus / NeuralPi** model JSON (single-layer
|
||||
LSTM capture) into a `NeuralAmpModel` for `LSTMAmp`. The state-dict tensors map straight onto
|
||||
`NeuralAmpModel`'s layout (PyTorch gate order; `skip` → residual); unsupported topologies and
|
||||
inconsistent tensor shapes throw. Model files are user-supplied — none are bundled (GuitarML
|
||||
models are GPL-3.0). A binary NAM `.nam` importer remains future work.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.0 — Amp-modeling core: tone stack, triode stage, neural amp
|
||||
|
||||
A minor release. Three new, backward-compatible generators — the DSP core for guitar-amp
|
||||
modeling (consumed by the ShoeGaze 2.0 amp pedals):
|
||||
|
||||
- **`ToneStack`** — passive Fender/Marshall/Vox tone stack (bass/mid/treble). Models the
|
||||
interactive RC network as a whole (Yeh & Smith closed form → bilinear → 3rd-order IIR), so the
|
||||
controls load each other exactly as on the real amp. Model-selectable via `ToneStackModel`.
|
||||
- **`TriodeStage`** — tube-style preamp gain stage: a biased asymmetric `tanh` soft-clip (grid
|
||||
bias → even-harmonic warmth) evaluated at 2×/4× oversampling, with an output coupling
|
||||
(DC-block) high-pass. A musically-voiced static waveshaper; a full wave-digital triode remains
|
||||
future work.
|
||||
- **`LSTMAmp`** + `NeuralAmpModel` — real-time neural amp-capture inference (single-layer LSTM,
|
||||
GuitarML Proteus / NeuralPi topology), pure Swift, RT-safe (pre-allocated weights, no
|
||||
render-thread allocation). `NeuralAmpModel` is a `Codable` weight container with a validating
|
||||
decoder. An importer for external NAM `.nam` / Proteus JSON files is planned for a later release.
|
||||
|
||||
All three are additive; existing code is unaffected.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.4 — `LookAheadLimiter` release time decoupled from look-ahead
|
||||
|
||||
A patch release. One backward-compatible library addition.
|
||||
|
||||
`LookAheadLimiter` gains a `releaseTime` parameter, independent of
|
||||
`lookAheadTime`:
|
||||
|
||||
```swift
|
||||
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
|
||||
```
|
||||
|
||||
Previously the gain-release one-pole coefficient was derived from
|
||||
`lookAheadTime` (default 5 ms), so the release was fast enough to modulate the
|
||||
gain within a single cycle of a low-frequency signal — audible as distortion on
|
||||
sustained bass when the limiter was driven hard. `releaseTime` (default
|
||||
`0.050`) is now a separate control, read per block from a `ValidGeneratorInput`
|
||||
so it can be driven by a live parameter / knob. The look-ahead window size and
|
||||
the no-overshoot ceiling guarantee are unchanged.
|
||||
|
||||
The new parameter has a default, so existing call sites are source-compatible.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.3 — Notarization-ready `macos-ui-xcode` template
|
||||
|
||||
A patch release. Project-scaffolding fixes; no library API changes.
|
||||
|
||||
The `macos-ui-xcode` template (`lyrebird new MyApp --template macos-ui-xcode`)
|
||||
now scaffolds a distributable, notarization-ready macOS performance app out of
|
||||
the box:
|
||||
|
||||
- **Entitlements shipped and wired** — `<name>.entitlements` grants
|
||||
`com.apple.security.device.audio-input` (wired via `CODE_SIGN_ENTITLEMENTS`
|
||||
in both build configs), plus `NSMicrophoneUsageDescription` in `Info.plist`.
|
||||
Under the Hardened Runtime (already enabled) the OS hard-kills the process the
|
||||
moment the AUHAL input bus opens without these. They are harmless for
|
||||
output-only synths — no permission prompt fires until input is actually used.
|
||||
The app is deliberately **unsandboxed**: a live-performance app needs
|
||||
unrestricted audio-device / file / MIDI / OSC access the App Sandbox gates.
|
||||
|
||||
- **Compiles under Swift 6** — fixed a latent actor-isolation error that kept
|
||||
the generated project from building: `NoteController` (calls the engine's
|
||||
`@MainActor add(_:)`) and `AppDelegate` (constructs the main-actor controller
|
||||
and synth) are now `@MainActor`. Xcode app templates are excluded from the
|
||||
`swift build` CI matrix, so this had never been compile-checked; it is now
|
||||
verified end-to-end with `xcodebuild`.
|
||||
|
||||
A normal Lyrebird app needs no module-bundling: Lyrebird is statically linked
|
||||
from SPM source. (The swiftmodule / `LyrebirdC` bundling in `LyrebirdScratch`,
|
||||
added in 1.6.2, is unique to its runtime `swiftc` scratchpad.)
|
||||
|
||||
---
|
||||
|
||||
## 1.6.2 — Live Scratch: distributable / notarized app
|
||||
|
||||
A patch release. Live Scratch packaging only; no library API changes.
|
||||
|
||||
A notarized, moved-off-the-build-machine `LyrebirdScratch.app` could not compile
|
||||
snippets — the Swift scratchpad shells out to `swiftc`, and the modules it needs
|
||||
(`LyrebirdSynth`, `LyrebirdLiveCompile`, and the `LyrebirdC` C-shim they depend on)
|
||||
lived only in the dev build tree. Two failures surfaced in order — `no such module
|
||||
'LyrebirdSynth'`, then `missing required module 'LyrebirdC'`. Both are now fixed:
|
||||
|
||||
- **Swiftmodules bundled** — a build phase copies the Lyrebird `.swiftmodule`s into
|
||||
`Resources/LyrebirdArtifacts/Modules` inside the app, and the live compiler adds
|
||||
that directory to its import search path.
|
||||
- **LyrebirdC module relocatable** — the SPM *source* `module.modulemap` (relative
|
||||
header path, so map + `include/` are self-contained) is bundled into
|
||||
`LyrebirdArtifacts/LyrebirdC.build/`, and staging copies relative-header module
|
||||
maps verbatim so the Clang module resolves from the bundle rather than the
|
||||
absolute dev path Xcode's generated map baked in.
|
||||
|
||||
Verified end-to-end: a snippet compile resolving modules **only** from the app
|
||||
bundle typechecks clean, and the notarized app runs the Swift scratchpad on a
|
||||
machine without the dev tree.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.1 — Live Scratch: Swift-toolchain detection
|
||||
|
||||
A patch release. Live Scratch quality-of-life; no library API changes.
|
||||
|
||||
The Swift scratchpad compiles snippets by shelling out to `swiftc` (Xcode or the
|
||||
Command Line Tools). Previously a missing toolchain only surfaced as a compile
|
||||
error in the console on the first Run. Now the app **detects it at launch** and
|
||||
shows an alert with actionable install guidance:
|
||||
|
||||
- **Install Command Line Tools** — launches Apple's own installer (`xcode-select
|
||||
--install`); the app never installs anything silently.
|
||||
- **Get Xcode** — opens the App Store product page.
|
||||
|
||||
The check is alert-only and never blocks the app: the **Graph DSL mode needs no
|
||||
toolchain**, so it's the zero-install fallback. (`ToolchainProbe` classifies the
|
||||
toolchain into available / missing-developer-tools / missing-swiftc / missing-SDK,
|
||||
with injectable resolvers so the missing states are unit-tested without uninstalling
|
||||
anything.)
|
||||
|
||||
---
|
||||
|
||||
## 1.6.0 — Soundfile format expansion
|
||||
|
||||
A minor release. Backward-compatible — the existing default write formats are
|
||||
unchanged; everything here is additive. One shared `AudioFileFormat` enum now
|
||||
drives every writer (`LyrebirdBuffer.write`, offline `NRTDriver` renders, and the
|
||||
real-time `DiskOut.Audio` recorder).
|
||||
|
||||
### New — audio output formats
|
||||
|
||||
```swift
|
||||
// Buffer / NRT / DiskOut (PCM):
|
||||
try buf.write(to: url, format: .wavInt24, sampleRate: 48000) // 16 / 24-bit WAV
|
||||
try buf.write(to: url, format: .aiffFloat32, sampleRate: 48000) // AIFF-C float
|
||||
try buf.write(to: url, format: .cafFloat32, sampleRate: 48000) // CAF (uncapped)
|
||||
|
||||
// Files past 4 GB — RF64/BW64, keeps the .wav extension:
|
||||
try buf.write(to: url, format: .rf64Float32, sampleRate: 96000)
|
||||
try buf.write(to: url, format: .rf64Int24, sampleRate: 96000)
|
||||
|
||||
// Compressed .m4a — offline writers only (LyrebirdBuffer.write / NRTDriver):
|
||||
try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps
|
||||
try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps
|
||||
try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless
|
||||
```
|
||||
|
||||
- **WAV bit depths** — 16-bit and 24-bit signed-integer PCM alongside 32-bit float.
|
||||
- **AIFF-C** and **CAF** float output across all writers.
|
||||
- **RF64 / BW64** (EBU Tech 3306) — the 64-bit-sized WAV variant for files past the
|
||||
4 GB limit, written by Lyrebird's own `RF64Writer` (CoreAudio has no RF64 *writer*;
|
||||
it reads them back fine). Opt-in `.rf64Float32` / `.rf64Int24`.
|
||||
- **Compressed AAC + Apple Lossless** (`.m4a`) — encoded natively through
|
||||
`ExtAudioFile`/`AudioConverter`, no third-party dependency. **Offline writers only**
|
||||
(`LyrebirdBuffer.write`, `NRTDriver`); `DiskOut.Audio` streams PCM/RF64 only. (MP3 is
|
||||
not offered — CoreAudio has no MP3 encoder.)
|
||||
- **Selectable NRT output** — `NRTDriver` / `NRTJob` take a `format:` (default CAF/float,
|
||||
unchanged), so offline renders and the multi-engine batch pool can bounce to any format.
|
||||
|
||||
### New — large-file safety
|
||||
|
||||
Plain WAV and AIFF-C carry 32-bit size fields (a 4 GB cap). A write projected past
|
||||
that now **throws `fileTooLargeForContainer`** (buffer / NRT) or stops cleanly and sets
|
||||
a pollable `fileTooLarge` flag (streaming `DiskOut`) instead of silently producing a
|
||||
truncated file. CAF and RF64 are 64-bit-sized and uncapped. `NRTDriver` also validates
|
||||
its `duration` (finite, non-negative) — `NRTDriverError.invalidDuration`.
|
||||
|
||||
### New — Live Scratch: Render-to-File format picker
|
||||
|
||||
The Scratch **Render to File** (⌥⌘R) save dialog now carries a **Format** popup (WAV
|
||||
32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV, and compressed AAC / Apple
|
||||
Lossless) plus the duration field, folded into one dialog. It remembers the last
|
||||
format. Sample rate and channel count still mirror the live engine.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`DiskOutFormat` is deprecated** — it is now a type alias for `AudioFileFormat`.
|
||||
Existing `DiskOutFormat.wavFloat32` / `.aiff` / etc. spellings keep compiling (with a
|
||||
deprecation warning); migrate to `AudioFileFormat` directly.
|
||||
- `LyrebirdEventList.record(directory:format:)` now takes an `AudioFileFormat`. Stem
|
||||
recording is PCM/RF64 only — a compressed format is rejected with a logged message
|
||||
(stems stream through `DiskOut`, which does not do compressed).
|
||||
|
||||
---
|
||||
|
||||
## 1.5.0 — `LyrebirdRandom` + the Live Scratch editor grows up
|
||||
|
||||
A minor release. Backward-compatible — new public API plus a wave of Live Scratch
|
||||
tooling. No changes to existing behavior.
|
||||
|
||||
### New — scalar draws from any distribution (`LyrebirdRandom`)
|
||||
|
||||
Lyrebird had distribution-tied **signals** (noise generators), **sequences**
|
||||
(`Pattern`, `TemporalStream`), and the `DistributionKind` sampling math — but no
|
||||
ergonomic way to get *one value* from a named distribution. `LyrebirdRandom`
|
||||
fills that gap:
|
||||
|
||||
```swift
|
||||
var r = LyrebirdRandom(seed: 42)
|
||||
let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||
let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||
let jitter: Double = r.gauss(mean: 0, dev: 0.02)
|
||||
let skew: Double = r.beta(low: 0, high: 1, alpha: 2, beta: 5)
|
||||
let spike: Double = r.laplace(scale: 1.0)
|
||||
```
|
||||
|
||||
- **`LyrebirdRandom`** — a seedable value type owning a xorshift64 state, so a
|
||||
seed gives a fully reproducible stream of draws (what scored/rendered music
|
||||
wants). Named methods for every family in `DistributionKind` (uniform, low/
|
||||
high/mean-biased, exponential-range, exponential, gamma, laplace, asymmetric
|
||||
laplace, half-cosine, logistic, poisson, arcsin, beta, cauchy, gauss), plus a
|
||||
generic `value(_:parX:parY:parA:parB:)` reaching any kind.
|
||||
- **`LyrebirdRandom.shared`** (`SharedRandom`) — a process-wide, thread-safe
|
||||
source for throwaway draws (system-seeded, non-reproducible). The global
|
||||
**`Random`** is a shorthand for it, for the common non-seeded case:
|
||||
`Random.uniform(low: 0, high: 1)`. (Takes a lock — not RT-safe; use an owned
|
||||
`LyrebirdRandom` inside a Generator.)
|
||||
- **`DistributionKind.sample(parX:parY:parA:parB:using:)`** — the public
|
||||
single-draw dispatcher, now the single source of truth for the case→sampler
|
||||
mapping: `TemporalTendency` and `DemandTemporalTendency` were refactored onto it
|
||||
(behavior pinned by the golden-value tests), so a scalar draw and a stream of
|
||||
the same distribution agree given the same seed.
|
||||
|
||||
For a plain uniform scalar the Swift stdlib (`Double.random(in:)`) is still the
|
||||
lightest choice; reach for `LyrebirdRandom` when you want a *shaped* distribution
|
||||
or a reproducible seeded stream.
|
||||
|
||||
### Live Scratch — renamed and a lot more capable
|
||||
|
||||
The macOS live-coding scratchpad graduated from a demo to a shipping app:
|
||||
**`LyrebirdScratchDemo` → `LyrebirdScratch`** (bundle id
|
||||
`net.realizedsound.LyrebirdScratch`; project, scheme, entitlements renamed). New
|
||||
in the editor:
|
||||
|
||||
- **Render to File (⌥⌘R)** — bounce the selection (or whole buffer) to a **CAF**
|
||||
file offline instead of playing it live. Prompts for a path and duration, builds
|
||||
the graph on a throwaway `NRTDriver` engine mirroring the live engine's settings
|
||||
(so the bounce matches what you heard), renders faster-than-real-time off the
|
||||
main thread, and reveals the file in Finder. Only **sample-clock** timing renders
|
||||
(`engine.schedule`, in-graph triggers) — wall-clock routine/task waits don't.
|
||||
- **Format Code (⌥⌘F)** — pretty-print the buffer with the toolchain's
|
||||
`swift-format`. No-op on a blank buffer; parse errors go to the console.
|
||||
- **Line-number gutter** — a floating `ScratchLineNumberGutter` overlay,
|
||||
positioned from each row's line-fragment rect so numbers align on blank and
|
||||
wrapped lines. (An `NSRulerView` attempt was abandoned — `rulersVisible`
|
||||
mis-tiles the document view inside a SwiftUI `NSViewRepresentable`, blanking the
|
||||
editor.)
|
||||
- **`Foundation` in scope** — snippets can use `pow`, `sin`, `sqrt`, `Date`, … with
|
||||
no `import` (a snippet can't declare one — its body is wrapped in the entry
|
||||
function).
|
||||
- **Manual code completion (Esc / F5)** — no more auto-trigger on `.` that
|
||||
ambushed typing; completion replaces the partial word, not the receiver.
|
||||
- **Fixed — editor scroll-jump**: the engine status readout refreshed via
|
||||
`.id(engineTick)`, tearing down subviews every heartbeat and nudging the scroll
|
||||
offset. Stats now update in place from an `@State` snapshot.
|
||||
|
||||
### New — compile artifacts stage into Application Support (no Documents prompt)
|
||||
|
||||
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts, which in
|
||||
a dev checkout live under `~/Documents` — tripping the macOS "wants to access your
|
||||
Documents folder" gate. `LiveSession.stageArtifacts()` copies the minimal set into
|
||||
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` (ungated), rewriting
|
||||
the C module map's absolute umbrella-header path to a staged copy so the compile
|
||||
is self-contained. Idempotent (a receipt skips an unchanged source), best-effort
|
||||
(falls back to the build dir). A **shipped** app carrying its artifacts in
|
||||
`Contents/Resources/LyrebirdArtifacts` never reads a gated folder — groundwork for
|
||||
a standalone `LyrebirdScratch.app` download.
|
||||
|
||||
### Docs
|
||||
|
||||
New guidance on snippet **timing / scheduling** — `engine.schedule`,
|
||||
`LyrebirdRoutine` / `LyrebirdTask` (background-thread waits), `LyrebirdClock`,
|
||||
in-graph triggers — the retention rule (the snippet is transient), and which
|
||||
mechanisms survive an offline NRT render vs. which are wall-clock-only.
|
||||
|
||||
---
|
||||
|
||||
## 1.4.2 — Live-coding: Run Selection + graceful slot release
|
||||
|
||||
A minor release. Backward-compatible — additive conveniences to the (macOS-only)
|
||||
live-coding editor that make per-fragment evaluation and voice lifecycle feel
|
||||
like a proper live-coding environment. No changes to existing public API.
|
||||
|
||||
### New — Run Selection (⌘E)
|
||||
|
||||
Evaluate just the **highlighted text** and *add* it to whatever is already
|
||||
playing — always additively, never a replace. It leaves the rest of the buffer
|
||||
and the whole-buffer re-evaluation baseline (the clean/dirty badge still reflects
|
||||
your last full run) untouched. This is the live-coding "evaluate this line/region,
|
||||
keep going" gesture: audition a single voice, layer it in, iterate. Works in both
|
||||
Swift and Graph DSL modes; no-op with no selection. ⌘↩ / ⌘⇧↩ (whole buffer) are
|
||||
unchanged.
|
||||
|
||||
### New — Start a voice, release it later (`context.release(slot:)`)
|
||||
|
||||
Named slots are the persistent **handle** across evaluations — the slot *name* is
|
||||
your reference (Swift `let`/`var` bindings can't carry from one snippet to the
|
||||
next, since each ⌘↩/⌘E is a separately-compiled unit). Pair that with Run
|
||||
Selection to start a voice in one evaluation and let it go in another:
|
||||
|
||||
```swift
|
||||
// ⌘E this line — start a persistent, gated voice named "pad":
|
||||
context.play(slot: "pad") { EnvGen(gate: 1, /* free-on-done */) * OscSaw.Audio(freq: 110) }
|
||||
|
||||
// …later, ⌘E this line — graceful release: the envelope tails out, then frees:
|
||||
context.release(slot: "pad")
|
||||
```
|
||||
|
||||
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||
frees the name; the voice self-frees via its done-action (and, as a safety net,
|
||||
stays reclaimable by **Clear Synths** if it never does).
|
||||
- `context.free(slot:)` is the **immediate** hard stop — the counterpart, no tail.
|
||||
|
||||
### New — Engine panel (scope + status)
|
||||
|
||||
A panel at the bottom of the scratch window gives an always-on view of the
|
||||
running engine: a live dual-channel **oscilloscope** of the output (fed by a
|
||||
`ScopeCapture` the session attaches to the output buses), plus **CPU
|
||||
average/peak** meter bars and **synth / group / snippet** counts.
|
||||
|
||||
### New — Reset Session + Restart to Reclaim Memory
|
||||
|
||||
Two Run-menu commands for the by-design snippet-dylib cost:
|
||||
|
||||
- **Reset Session** — an in-process, *non-destructive* reset: stops all snippet
|
||||
audio, shuts down the code-completion server (freeing its subprocess and temp
|
||||
files), and clears diagnostics. Your buffer is untouched.
|
||||
- **Restart to Reclaim Memory…** — relaunches the app (with a confirmation), the
|
||||
only way to actually free the mapped snippet dylibs, which cannot be unloaded
|
||||
in-process.
|
||||
|
||||
### New — Console panel
|
||||
|
||||
An always-open panel down the right side logs everything: snippet
|
||||
`context.reportMessage(_:)` output (the live-coding `print`), compile / Graph DSL
|
||||
**errors** with their `line:col`, and a one-line notice per run — oldest first,
|
||||
auto-scrolled, with a **Clear** button. Errors moved here from the old transient
|
||||
bottom strip so they stay visible while you fix them.
|
||||
|
||||
### Faster typing
|
||||
|
||||
Cut the per-keystroke cost in the editor: syntax highlighting is debounced
|
||||
(coalesced after a brief pause instead of a full-buffer re-tokenize on every
|
||||
key), `updateNSView` fast-paths a pure text change, and redundant `@Published`
|
||||
republishes (selection, re-eval state) are elided.
|
||||
|
||||
### Changed — code completion is now manual (Esc / F5)
|
||||
|
||||
Completion no longer auto-opens on `.`. The auto-trigger ambushed typing — after
|
||||
`Pan2.` the popup opened and couldn't be dismissed by deleting, trapping the
|
||||
caret until a candidate was picked. Invoke completion deliberately with **Esc**
|
||||
(or **F5**); a member request after a dot still resolves. Wider default scratch
|
||||
window too (75% of the visible screen width).
|
||||
|
||||
---
|
||||
|
||||
## 1.4.1 — "Learning Swift for Lyrebird" intro guide
|
||||
|
||||
A documentation-only release, continuing the doc improvements begun in 1.3. No
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// calsa-shim.h
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
//
|
||||
// Single include point for the ALSA C library (libasound), used by
|
||||
// ALSAAudioDriver on Linux. Kept as a shim header rather than pointing the
|
||||
// module map straight at <alsa/asoundlib.h> so the include path resolves the
|
||||
// same way regardless of where the distribution installs the ALSA headers.
|
||||
|
||||
#ifndef LYREBIRD_CALSA_SHIM_H
|
||||
#define LYREBIRD_CALSA_SHIM_H
|
||||
|
||||
#include <alsa/asoundlib.h>
|
||||
|
||||
#endif /* LYREBIRD_CALSA_SHIM_H */
|
||||
@@ -0,0 +1,5 @@
|
||||
module CALSA [system] {
|
||||
header "include/calsa-shim.h"
|
||||
link "asound"
|
||||
export *
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -40,3 +41,4 @@ public struct LyrebirdAUFactoryPreset: Sendable {
|
||||
self.sourceSlots = sourceSlots
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -26,3 +27,4 @@ public struct LyrebirdAUParameterEntry {
|
||||
/// and to write new values via `_writeAtomicValue`.
|
||||
public let node: any LiveParameterValue
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -74,3 +75,4 @@ public let lyrebirdAUParameterDefaultFlags: AudioUnitParameterOptions = [
|
||||
.flag_IsWritable,
|
||||
.flag_CanRamp,
|
||||
]
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
@@ -100,3 +101,4 @@ public enum LyrebirdAUParameterMapping {
|
||||
return (tree, nodes)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if canImport(AudioToolbox)
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
@@ -118,3 +119,4 @@ public enum LyrebirdAUPresetSourceRegistry {
|
||||
return _factories.keys.sorted()
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||