v2.4.1 release: scratchpad polish + demo cleanup
Maintenance release, no framework API changes. Scratchpad: Kill All Sound (⌘K) rename, mode-switch desync fix, code-completion prefix filtering restored (⌃Space Show Completions). Demos: GUIDemo voices + CLI EventPattern BlipVoice moved into Synthesizers/, EventPattern demo split into makeLead/makeBass, GUIDemo doc drift fixed (conductor default). LyrebirdScratch gains a SwiftPM package so the workspace shows it like GUIDemo (.xcodeproj kept for distribution). Linux live-coding scratchpad documented.
This commit is contained in:
+1
-1
@@ -9,7 +9,7 @@ build/
|
||||
*.d
|
||||
*.swp
|
||||
.DS_Store
|
||||
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
|
||||
.swiftpm/
|
||||
xcuserdata/
|
||||
*.xcuserstate
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
C1A000000000000000000013 /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C1A000000000000000000012 /* Lyrebird */; };
|
||||
C1A000000000000000000016 /* SineTone.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000014 /* SineTone.swift */; };
|
||||
C1A000000000000000000017 /* DelaySample.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A000000000000000000015 /* DelaySample.swift */; };
|
||||
C1A00000000000000000001B /* BlipVoice.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1A00000000000000000001A /* BlipVoice.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -40,6 +41,7 @@
|
||||
C1A000000000000000000006 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
C1A000000000000000000014 /* SineTone.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SineTone.swift; sourceTree = "<group>"; };
|
||||
C1A000000000000000000015 /* DelaySample.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DelaySample.swift; sourceTree = "<group>"; };
|
||||
C1A00000000000000000001A /* BlipVoice.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BlipVoice.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -95,6 +97,7 @@
|
||||
035B00092FAB0000007F0001 /* General */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C1A00000000000000000001A /* BlipVoice.swift */,
|
||||
C1A000000000000000000015 /* DelaySample.swift */,
|
||||
C1A000000000000000000014 /* SineTone.swift */,
|
||||
);
|
||||
@@ -216,6 +219,7 @@
|
||||
C1A000000000000000000016 /* SineTone.swift in Sources */,
|
||||
035A2F472FAA6950007F6289 /* PercTimeStretch.swift in Sources */,
|
||||
C1A000000000000000000017 /* DelaySample.swift in Sources */,
|
||||
C1A00000000000000000001B /* BlipVoice.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@ import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Demonstrates ``EventPattern`` — Lyrebird's event-driven player: bound value patterns drive a
|
||||
/// fresh self-freeing voice per event, played as a dur/legato-timed stream.
|
||||
/// fresh self-freeing ``BlipVoice`` per event, played as a dur/legato-timed stream.
|
||||
///
|
||||
/// Also shows two patterns running together via ``ParallelEventPattern``: a lead phrase and a
|
||||
/// bass line that enters a few beats in on the same beat grid, with a single
|
||||
@@ -17,87 +17,55 @@ import LyrebirdSynth
|
||||
final class EventPatternDemo: DemoProtocol {
|
||||
|
||||
private let engine: SynthesisEngine
|
||||
private let tempoBPM: Double = 132.0
|
||||
|
||||
/// Beats the bass waits before its first note. Shared tempo means both parts share a beat
|
||||
/// grid, so this is a plain offset on that grid.
|
||||
private let leadInBeats: Double = 2.0
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
}
|
||||
|
||||
/// A gated voice (``EventGated``): a sine through an `EnvelopeGen` whose gate holds it at full
|
||||
/// level while the note sounds, then plays a release and frees the voice via
|
||||
/// `doneAction: .freeNode` when `EventPattern` closes the gate at the note's sustain. No
|
||||
/// external removal, so the release is never hard-cut — nothing to tune, no click.
|
||||
private final class BlipVoice: SynthesizerBase, EventGated {
|
||||
/// Envelope release length in seconds — how long a note rings after its gate closes.
|
||||
/// Exposed so the demo can let the final note's tail finish before stopping the engine.
|
||||
nonisolated static let releaseSeconds: Double = 0.3
|
||||
/// Envelope attack length in seconds.
|
||||
nonisolated static let attackSeconds: Double = 0.01
|
||||
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.2
|
||||
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
override func build() {
|
||||
// `releaseNode: 1` holds at `levels[1]` (full) while the gate is open; when the gate
|
||||
// drops to 0 the generator plays segment 1 (the release to 0) and then self-frees.
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [BlipVoice.attackSeconds, BlipVoice.releaseSeconds],
|
||||
curves: [.welch, .welch],
|
||||
releaseNode: 1
|
||||
)
|
||||
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: envelope,
|
||||
gate: $gate,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
|
||||
output(bus: 0, source: source * shaped)
|
||||
}
|
||||
}
|
||||
|
||||
func runDemo() {
|
||||
print("\n── EventPattern demo ──")
|
||||
|
||||
let tempoBPM: Double = 132.0
|
||||
|
||||
// Pattern 1 — the lead: a short A-minor-pentatonic phrase, written as named pitches rather
|
||||
// than raw Hz (equivalent MIDI form: `Pitch.midi(69).frequency`, etc.), played three times.
|
||||
/// The lead: a short A-minor-pentatonic phrase, written as named pitches rather than raw Hz
|
||||
/// (equivalent MIDI form: `Pitch.midi(69).frequency`, etc.), played three times.
|
||||
private func makeLead() -> EventPattern<BlipVoice> {
|
||||
let phrase: [Pitch] = [
|
||||
.named(.a, 4), .named(.c, 5), .named(.d, 5), .named(.e, 5),
|
||||
.named(.g, 5), .named(.e, 5), .named(.d, 5), .named(.c, 5),
|
||||
]
|
||||
let leadFreqs: [Double] = phrase.compactMap(\.frequency)
|
||||
let lead: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
|
||||
.bind(\.freq, .sequence(leadFreqs, repeats: 1))
|
||||
let freqs: [Double] = phrase.compactMap(\.frequency)
|
||||
return EventPattern(make: { BlipVoice() })
|
||||
.bind(\.freq, .sequence(freqs, repeats: 1))
|
||||
.bind(\.amp, .uniformRandom(low: 0.15, high: 0.3))
|
||||
.dur(.sequence([0.25, 0.25, 0.25, 0.5]))
|
||||
.legato(0.8)
|
||||
.tempo(tempoBPM)
|
||||
.repeats(3)
|
||||
}
|
||||
|
||||
// Pattern 2 — a bass line that enters `leadInBeats` after the lead and outlasts it.
|
||||
// There is no cross-pattern clock: `ParallelEventPattern` launches both children from the
|
||||
// one `play` call, so they share a start instant, and at the SAME tempo they share a beat
|
||||
// grid. `addAfter(beats:)` staggers the bass's entry on that grid — the bass simply waits
|
||||
// `leadInBeats` beats before its first note.
|
||||
let leadInBeats: Double = 2.0
|
||||
let bassPhrase: [Pitch] = [.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2)]
|
||||
let bassFreqs: [Double] = bassPhrase.compactMap(\.frequency)
|
||||
let bass: EventPattern<BlipVoice> = EventPattern(make: { BlipVoice() })
|
||||
.bind(\.freq, .sequence(bassFreqs, repeats: 1))
|
||||
/// The bass: one slow phrase at the same tempo, entered `leadInBeats` after the lead and
|
||||
/// outlasting it. No cross-pattern clock — ``ParallelEventPattern`` launches both children
|
||||
/// from the one `play` call, so they share a start instant and (at equal tempo) a beat grid.
|
||||
private func makeBass() -> EventPattern<BlipVoice> {
|
||||
let phrase: [Pitch] = [.named(.a, 2), .named(.a, 2), .named(.g, 2), .named(.e, 2)]
|
||||
let freqs: [Double] = phrase.compactMap(\.frequency)
|
||||
return EventPattern(make: { BlipVoice() })
|
||||
.bind(\.freq, .sequence(freqs, repeats: 1))
|
||||
.bind(\.amp, .uniformRandom(low: 0.2, high: 0.3))
|
||||
.dur(.sequence([1.0]))
|
||||
.legato(0.9)
|
||||
.tempo(tempoBPM)
|
||||
.repeats(1)
|
||||
}
|
||||
|
||||
// Start both together, staggering the bass two beats in, and control them as one handle.
|
||||
func runDemo() {
|
||||
print("\n── EventPattern demo ──")
|
||||
|
||||
// Start both together, staggering the bass `leadInBeats` in, and control them as one handle.
|
||||
let ensemble: ParallelEventPattern = ParallelEventPattern()
|
||||
ensemble.add(lead)
|
||||
ensemble.addAfter(beats: leadInBeats, eventPattern: bass)
|
||||
ensemble.add(makeLead())
|
||||
ensemble.addAfter(beats: leadInBeats, eventPattern: makeBass())
|
||||
let handle: EventPatternHandle = ensemble.play(on: engine)
|
||||
|
||||
// `waitUntilComplete` blocks until EVERY child task has finished — so it waits for the
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
// BlipVoice.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// A gated voice (``EventGated``): a sine through an `EnvelopeGen` whose gate holds it at full
|
||||
/// level while the note sounds, then plays a release and frees the voice via
|
||||
/// `doneAction: .freeNode` when ``EventPattern`` closes the gate at the note's sustain. No
|
||||
/// external removal, so the release is never hard-cut — nothing to tune, no click.
|
||||
///
|
||||
/// Used by ``EventPatternDemo`` for both the lead and the bass part.
|
||||
final class BlipVoice: SynthesizerBase, EventGated {
|
||||
/// Envelope release length in seconds — how long a note rings after its gate closes.
|
||||
/// Exposed so a caller can let the final note's tail finish before stopping the engine.
|
||||
nonisolated static let releaseSeconds: Double = 0.3
|
||||
/// Envelope attack length in seconds.
|
||||
nonisolated static let attackSeconds: Double = 0.01
|
||||
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.2
|
||||
@LiveParam var gate: Double = 1.0 // open by default so the attack fires on add
|
||||
|
||||
var eventGate: ParameterNode { $gate }
|
||||
|
||||
override func build() {
|
||||
// `releaseNode: 1` holds at `levels[1]` (full) while the gate is open; when the gate
|
||||
// drops to 0 the generator plays segment 1 (the release to 0) and then self-frees.
|
||||
let envelope: Envelope = Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [BlipVoice.attackSeconds, BlipVoice.releaseSeconds],
|
||||
curves: [.welch, .welch],
|
||||
releaseNode: 1
|
||||
)
|
||||
let shaped: EnvelopeGen.Audio = EnvelopeGen.Audio(
|
||||
envelope: envelope,
|
||||
gate: $gate,
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let source: OscSin.Audio = OscSin.Audio(freq: $freq, mul: $amp)
|
||||
output(bus: 0, source: source * shaped)
|
||||
}
|
||||
}
|
||||
@@ -27,8 +27,9 @@ so the controls, the oscilloscope, and the CPU meters are identical.
|
||||
## Run it
|
||||
|
||||
```bash
|
||||
swift run LyrebirdGUIDemo # vector oscillator (default)
|
||||
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
||||
swift run LyrebirdGUIDemo # event conductor (default)
|
||||
LYREBIRD_DEMO=vector swift run LyrebirdGUIDemo # vector oscillator
|
||||
LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
||||
```
|
||||
|
||||
- **macOS** — no extra setup; a native window opens with live audio via Core Audio.
|
||||
@@ -47,12 +48,16 @@ LYREBIRD_DEMO=sine swift run LyrebirdGUIDemo # stereo sine tone
|
||||
|
||||
## What each demo shows
|
||||
|
||||
- **conductor** (default) — `ConductorDemoVoice` driven by an `EventConductor`:
|
||||
start/stop the engine, then toggle a top and a bottom part, each entering on the
|
||||
next beat and repeating while it runs, over a live oscilloscope. Showcases the
|
||||
2.4.0 event system. Nothing plays until you start the engine and a part.
|
||||
- **vector** — `VectorOscillatorUI`: an XY pad crossfades four corner wavetables
|
||||
(sine / saw-ish / triangle / Hanning); frequency and amplitude knobs; a live
|
||||
oscilloscope and CPU-load strip.
|
||||
- **sine** — `SineToneUI`: a frequency slider, amplitude and pan knobs, a level
|
||||
readout, the scope and CPU strip, and a static envelope plot.
|
||||
|
||||
Add a synth by dropping a `SynthesizerBase` subclass and a node-based view into
|
||||
`LyrebirdGUIDemoKit`, then extend `DemoSelection` and the `demoContent()` switch
|
||||
in `main.swift`.
|
||||
Add a synth by dropping a `SynthesizerBase` subclass into
|
||||
`LyrebirdGUIDemoKit/Synthesizers/` and a node-based view into `LyrebirdGUIDemoKit`,
|
||||
then extend `DemoSelection` and the `demoContent()` switch in `main.swift`.
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// • Linux — a GTK4 `App`/`WindowGroup` scene run by `GTK4Backend`.
|
||||
//
|
||||
// Run either with `swift run LyrebirdGUIDemo`. Pick the synth with
|
||||
// `LYREBIRD_DEMO=vector` (default), `sine`, or `conductor`.
|
||||
// `LYREBIRD_DEMO=conductor` (default), `vector`, or `sine`.
|
||||
//
|
||||
// `@ViewBuilder` and the window hosts come from SwiftUI on macOS and from
|
||||
// SwiftOpenUI (re-exported through `LyrebirdUI`) on Linux — hence the single
|
||||
|
||||
@@ -11,7 +11,7 @@ import Foundation
|
||||
/// selection so one binary covers every patch.
|
||||
public enum DemoSelection: String, Sendable {
|
||||
|
||||
/// Vector oscillator with an XY blend pad (the default).
|
||||
/// Vector oscillator with an XY blend pad.
|
||||
case vector
|
||||
|
||||
/// Stereo sine tone with frequency / amplitude / pan controls.
|
||||
@@ -19,9 +19,10 @@ public enum DemoSelection: String, Sendable {
|
||||
|
||||
/// Live event ensemble: engine start/stop plus top and bottom parts driven by an
|
||||
/// ``EventConductor``. The view owns the engine, so nothing starts at launch.
|
||||
/// This is the default — it showcases the headline event system.
|
||||
case conductor
|
||||
|
||||
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.vector`).
|
||||
/// Resolve the selection from `LYREBIRD_DEMO` (defaults to `.conductor`).
|
||||
public static func fromEnvironment() -> DemoSelection {
|
||||
let raw: String = ProcessInfo.processInfo.environment["LYREBIRD_DEMO"]?.lowercased() ?? "conductor"
|
||||
return DemoSelection(rawValue: raw) ?? .conductor
|
||||
|
||||
@@ -196,7 +196,7 @@
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
CURRENT_PROJECT_VERSION = 3;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
@@ -208,12 +208,13 @@
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "Lyrebird Scratch";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
MARKETING_VERSION = 2.4.1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
@@ -238,7 +239,7 @@
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
CURRENT_PROJECT_VERSION = 3;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
@@ -249,12 +250,13 @@
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = "Lyrebird Scratch";
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
MARKETING_VERSION = 2.4.1;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.6.3</string>
|
||||
<string>2.4.1</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>3</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"originHash" : "00d9a3997266cf2e38ebfa0f16e7978ca242180f4745b918a490a4758ba8e753",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/andybest/linenoise-swift",
|
||||
"state" : {
|
||||
"revision" : "afc897c02b030af7333105c4fedcd843a8339238",
|
||||
"version" : "0.0.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
"identity" : "nimble",
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://github.com/Quick/Nimble.git",
|
||||
"state" : {
|
||||
"revision" : "e9d769113660769a4d9dd3afb855562c0b7ae7b0",
|
||||
"version" : "7.3.4"
|
||||
}
|
||||
}
|
||||
],
|
||||
"version" : 3
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Package.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
// The live-coding scratchpad as a SwiftPM package, so the umbrella
|
||||
// `Lyrebird.xcworkspace` shows it the same way as `LyrebirdGUIDemo` — a package,
|
||||
// not a nested `.xcodeproj`. A sibling `LyrebirdScratch.xcodeproj` is kept on
|
||||
// disk for distribution builds (custom app icon, entitlements, the module-
|
||||
// staging run-script that makes an *exported* `.app` self-contained); the
|
||||
// package form is the dev-run / in-workspace view.
|
||||
//
|
||||
// macOS only. The Linux scratchpad host is `LyrebirdScratchLinuxDemo` in the
|
||||
// `LiveCompile/` sub-package (GTK4 / SwiftOpenUI); this executable is the AppKit
|
||||
// (NSTextView + menu) counterpart.
|
||||
//
|
||||
// Dynamic products on purpose: the live-compile stack dlopens freshly compiled
|
||||
// snippet dylibs that `import LyrebirdSynth` / `LyrebirdLiveCompile`. Linking the
|
||||
// single shared `libLyrebirdDynamic` + `libLyrebirdLiveCompileUIDynamic` (rather
|
||||
// than static-folding a second copy of LyrebirdSynth's ObjC classes into this
|
||||
// executable) is what avoids duplicate class registration at dlopen time — the
|
||||
// same reason the `LiveCompile` sub-package exists.
|
||||
//
|
||||
// Run: `swift build` first (so the …Dynamic dylibs exist in the build dir for
|
||||
// the snippet link), then `swift run LyrebirdScratch`. As a bare SwiftPM
|
||||
// executable there is no Hardened Runtime or App Sandbox, so the swiftc
|
||||
// shell-out and the unsigned-snippet dlopen both work without entitlements (the
|
||||
// `.xcodeproj` needs `disable-library-validation` only because an Xcode app
|
||||
// target enables Hardened Runtime by default).
|
||||
let package = Package(
|
||||
name: "LyrebirdScratch",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
.package(name: "Lyrebird", path: "../.."),
|
||||
.package(name: "LyrebirdLiveCompile", path: "../../LiveCompile"),
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "LyrebirdScratch",
|
||||
dependencies: [
|
||||
.product(name: "LyrebirdDynamic", package: "Lyrebird"),
|
||||
.product(name: "LyrebirdLiveCompileUIDynamic", package: "LyrebirdLiveCompile"),
|
||||
],
|
||||
path: "LyrebirdScratch",
|
||||
exclude: [
|
||||
"Info.plist",
|
||||
"LyrebirdScratch.entitlements",
|
||||
"Assets.xcassets",
|
||||
]
|
||||
),
|
||||
]
|
||||
)
|
||||
+1
-1
@@ -214,7 +214,7 @@ Scratchpad features:
|
||||
- **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
|
||||
- **Kill 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
|
||||
|
||||
+22
-6
@@ -1,18 +1,18 @@
|
||||
# Lyrebird — Start Here
|
||||
|
||||
Eight demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
Nine demo projects live in this workspace. This guide covers how to open them, what each one does, where to add your own synthesizers, and the gotchas that will bite you if you don't know about them.
|
||||
|
||||
---
|
||||
|
||||
## Opening the Workspace
|
||||
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all eight demo projects together so they share the local Lyrebird package.
|
||||
Open **`Lyrebird.xcworkspace`** — not any individual `.xcodeproj` file. The workspace links all nine demo projects together so they share the local Lyrebird package.
|
||||
|
||||
Once open, pick a scheme from the scheme picker at the top of the Xcode window and hit Run.
|
||||
|
||||
---
|
||||
|
||||
## The Eight Demos
|
||||
## The Nine Demos
|
||||
|
||||
### LyrebirdQuickstartDemo — Fastest Sound
|
||||
|
||||
@@ -61,6 +61,17 @@ final class MySynth: SynthesizerBase {
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdGUIDemo — Cross-Platform GUI (macOS + Linux)
|
||||
|
||||
One SwiftPM package whose SwiftUI-style UI builds on **both** macOS (AppKit) and Linux (GTK4 via SwiftOpenUI) from shared source — the same selection drives either front end. Three patches ship, chosen by `LYREBIRD_DEMO`.
|
||||
|
||||
- **Where the synths live:** `Demos/LyrebirdGUIDemo/Sources/LyrebirdGUIDemoKit/Synthesizers/` — `ConductorDemoVoice`, `VectorOscillatorUI`, `SineToneUI`. The views, `DemoSelection`, and the demo controllers sit alongside in `LyrebirdGUIDemoKit/`.
|
||||
- **Patches:** `conductor` (default) — a live `EventConductor` ensemble with engine start/stop and top/bottom part toggles; `vector` — an XY blend pad over four wavetables; `sine` — a frequency/amp/pan tone. Nothing plays until you start it.
|
||||
- **Run it:** `cd Demos/LyrebirdGUIDemo && swift run LyrebirdGUIDemo` (add `LYREBIRD_DEMO=vector` or `=sine` to pick another patch). On Linux needs `libgtk-4-dev` plus `libasound2-dev` + a sound device for audio.
|
||||
- **It's a package, not an `.xcodeproj`:** open the folder (or `Package.swift`) in Xcode, pick the `LyrebirdGUIDemo` scheme, and Run.
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdiOSDemo — iOS App
|
||||
|
||||
A SwiftUI app using `iOSAudioDriver` (RemoteIO). Same `@UIParam` knob system as the macOS demo.
|
||||
@@ -143,7 +154,11 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
|
||||
|
||||
### 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.
|
||||
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target. (Linux has its own GTK4 host — `swift run LyrebirdScratchLinuxDemo` in `LiveCompile/`; see `LINUX_README.md`.)
|
||||
|
||||
Build it either way, like `LyrebirdGUIDemo`:
|
||||
- **Package** — `Demos/LyrebirdScratch/Package.swift` builds the AppKit host as a plain executable. From that folder: `swift build` then `swift run LyrebirdScratch` (the `swift build` first makes the `…Dynamic` dylibs the snippet link needs). This is how it appears in `Lyrebird.xcworkspace`.
|
||||
- **Xcode project** — the sibling `LyrebirdScratch.xcodeproj` is kept for distribution builds (custom app icon, entitlements, and a run-script that bundles the Lyrebird module artifacts into an exported `.app`).
|
||||
|
||||
**v1 surface:**
|
||||
- Type arbitrary Swift code in the editor pane. The snippet body has `context: SnippetContext` in scope.
|
||||
@@ -154,10 +169,11 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
|
||||
- `context.reportMessage(_:)` — writes a string back to the host status bar.
|
||||
- **⌘↩** — compile and replace. Removes the previous run's anonymous synths (named slots persist), compiles the snippet via `swiftc -emit-library`, `dlopen`s the resulting dylib, calls `lyrebird_snippet_entry`.
|
||||
- **⌘⇧↩** — compile additive. Prior synths stay in the engine.
|
||||
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
|
||||
- **Kill All Sound** (⌘K, menu) — panic stop / full reset: removes all tracked synths *and* every named slot immediately.
|
||||
- **⌃Space** (Show Completions) / Esc / F5 — manual code completion at the caret (Swift mode).
|
||||
|
||||
**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 (`LyrebirdScratch.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. In the `.xcodeproj` build the entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib. The package (`swift run`) build is a bare executable with neither the App Sandbox nor Hardened Runtime, so it needs no entitlement — the shell-out and `dlopen` just work.
|
||||
|
||||
**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.
|
||||
|
||||
|
||||
@@ -182,7 +182,78 @@ public actor SnippetCompletionService {
|
||||
// User line 0 sits at wrapped line `userBodyLineOffset - 1` (0-based);
|
||||
// the column is unchanged (the preamble adds only whole lines).
|
||||
let wrappedLine: Int = line + (_userBodyLineOffset - 1)
|
||||
return try await _client.completion(uri: _fileURI, line: wrappedLine, character: character)
|
||||
let items: [LSPCompletionItem] = try await _client.completion(
|
||||
uri: _fileURI, line: wrappedLine, character: character)
|
||||
// sourcekit-lsp returns a bare-identifier completion as the *whole*
|
||||
// visible-symbol universe (hundreds of SDK/stdlib globals), unsorted and
|
||||
// unfiltered — LSP expects the client to narrow it by the typed prefix.
|
||||
// Member completion (after `.`) is already server-scoped, so its prefix
|
||||
// is empty and this leaves it untouched. Without this, typing `OscS` and
|
||||
// asking for completion floods the window with Darwin/IOKit globals and
|
||||
// buries (or truncates away) the real `Osc*` types.
|
||||
let prefix: String = SnippetCompletionService.partialWord(
|
||||
in: userBody, line: line, character: character)
|
||||
return SnippetCompletionService.filterAndRank(items, prefix: prefix)
|
||||
}
|
||||
|
||||
/// The identifier fragment immediately before the caret — letters, digits and
|
||||
/// underscores — on the user-body `line` up to `character` (zero-based,
|
||||
/// UTF-16). Empty when the character before the caret is not an identifier
|
||||
/// character (e.g. a `.` member completion, or start of line).
|
||||
static func partialWord(in userBody: String, line: Int, character: Int) -> String {
|
||||
let lines: [Substring] = userBody.split(separator: "\n", omittingEmptySubsequences: false)
|
||||
guard line >= 0, line < lines.count else { return "" }
|
||||
let units: [UInt16] = Array(lines[line].utf16)
|
||||
let end: Int = min(character, units.count)
|
||||
var start: Int = end
|
||||
while start > 0, isIdentifierUTF16(units[start - 1]) {
|
||||
start -= 1
|
||||
}
|
||||
guard start < end else { return "" }
|
||||
return String(decoding: units[start..<end], as: UTF16.self)
|
||||
}
|
||||
|
||||
/// ASCII letter / digit / underscore — the same identifier class the editor's
|
||||
/// `rangeForUserCompletion` uses to pick the word the completion replaces.
|
||||
private static func isIdentifierUTF16(_ u: UInt16) -> Bool {
|
||||
let underscore: UInt16 = 95
|
||||
let zero: UInt16 = 48, nine: UInt16 = 57
|
||||
let upperA: UInt16 = 65, upperZ: UInt16 = 90
|
||||
let lowerA: UInt16 = 97, lowerZ: UInt16 = 122
|
||||
return u == underscore
|
||||
|| (u >= zero && u <= nine)
|
||||
|| (u >= upperA && u <= upperZ)
|
||||
|| (u >= lowerA && u <= lowerZ)
|
||||
}
|
||||
|
||||
/// Narrow `items` to those matching `prefix` (case-insensitive, by `label`)
|
||||
/// and order best-first. An empty `prefix` keeps every item (member
|
||||
/// completion is already scoped by the server) and only sorts it. With a
|
||||
/// prefix, exact case-insensitive prefix matches come first, then anything
|
||||
/// that merely contains the fragment (so a mistyped case or an internal match
|
||||
/// still surfaces), each group ordered by the server's `sortText` then label.
|
||||
static func filterAndRank(_ items: [LSPCompletionItem], prefix: String) -> [LSPCompletionItem] {
|
||||
func ordered(_ group: [LSPCompletionItem]) -> [LSPCompletionItem] {
|
||||
group.sorted { a, b in
|
||||
let ka: String = a.sortText ?? a.label
|
||||
let kb: String = b.sortText ?? b.label
|
||||
if ka != kb { return ka < kb }
|
||||
return a.label < b.label
|
||||
}
|
||||
}
|
||||
guard !prefix.isEmpty else { return ordered(items) }
|
||||
let needle: String = prefix.lowercased()
|
||||
var prefixed: [LSPCompletionItem] = []
|
||||
var contained: [LSPCompletionItem] = []
|
||||
for item: LSPCompletionItem in items {
|
||||
let hay: String = item.label.lowercased()
|
||||
if hay.hasPrefix(needle) {
|
||||
prefixed.append(item)
|
||||
} else if hay.contains(needle) {
|
||||
contained.append(item)
|
||||
}
|
||||
}
|
||||
return ordered(prefixed) + ordered(contained)
|
||||
}
|
||||
|
||||
/// Shut down the server and remove the workspace. Safe to call more than once.
|
||||
|
||||
@@ -302,7 +302,7 @@ public struct LyrebirdScratchLinuxView: View {
|
||||
Button {
|
||||
model.killAudio()
|
||||
} label: {
|
||||
Text("Stop audio")
|
||||
Text("Kill audio")
|
||||
}
|
||||
Button {
|
||||
model.clear()
|
||||
|
||||
@@ -54,13 +54,14 @@ window.open {
|
||||
| ⌘↩ | 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. |
|
||||
| Esc / F5 / ⌃Space | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. ⌃Space is the **Show Completions** menu item; Esc and F5 map to the same handler. 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. |
|
||||
| ⌘K | **Kill All Sound** — panic stop. Calls ``LyrebirdScratchModel/clearTracked()``: removes the anonymous tracked synths *and* every named slot, and silences the engine. |
|
||||
|
||||
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.
|
||||
The toolbar exposes the run actions as buttons; **Kill All Sound** (⌘K) lives in
|
||||
the menu and 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
|
||||
@@ -459,7 +460,7 @@ macOS view; the difference is the editor and its chrome:
|
||||
- **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()``.
|
||||
- **Kill 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
|
||||
|
||||
@@ -141,6 +141,17 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
// Manual code-completion (Swift mode). No target: routed down the
|
||||
// responder chain to the focused `ScratchTextView`, which funnels it to
|
||||
// the same async LSP fetch as Esc / F5. ⌃Space mirrors the Linux editor;
|
||||
// if the system has claimed ⌃Space (input-source switching), Esc / F5
|
||||
// still work.
|
||||
let complete: NSMenuItem = NSMenuItem(title: "Show Completions",
|
||||
action: #selector(ScratchTextView.scratchShowCompletions(_:)),
|
||||
keyEquivalent: " ")
|
||||
complete.keyEquivalentModifierMask = [.control]
|
||||
menu.addItem(complete)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
||||
action: #selector(formatCode(_:)),
|
||||
keyEquivalent: "f"))
|
||||
@@ -173,7 +184,7 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
render.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(render)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
menu.addItem(target(NSMenuItem(title: "Kill All Sound",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
|
||||
@@ -40,6 +40,8 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
public nonisolated static let defaultPlaceholder: String = """
|
||||
// ⌘↩ — compile + run (removes synths from the previous run first).
|
||||
// ⌘⇧↩ — additive run (keep previously played synths around).
|
||||
// ⌘K — kill all sound (stop everything now; the engine stays running).
|
||||
// ⌃Space (or Esc / F5) — code completion (Swift mode).
|
||||
//
|
||||
// The snippet body has `context: SnippetContext` in scope.
|
||||
// `context.play { <graph> }` → play a bare generator graph, no subclass needed.
|
||||
@@ -212,9 +214,20 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
|
||||
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
||||
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
||||
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
|
||||
/// with the mode. See ``ScratchEvalMode``.
|
||||
@Published public private(set) var evalMode: ScratchEvalMode = .swift
|
||||
/// instantly. See ``ScratchEvalMode``.
|
||||
///
|
||||
/// Publicly settable so a SwiftUI `Picker` can two-way-bind it directly —
|
||||
/// a single synchronous `@Published` write with no deferred `Task`, which
|
||||
/// is what keeps the segmented control and this value from desyncing. The
|
||||
/// mode's *side-effects* (placeholder swap, baseline/diagnostic reset) are
|
||||
/// not run by the setter: a UI host applies them from
|
||||
/// `.onChange(of:)` via ``applyModeSwitchSideEffects(from:to:)`` (so the
|
||||
/// multi-property mutation runs outside the view-update pass), and
|
||||
/// programmatic callers use ``switchMode(to:)``, which does both. (A
|
||||
/// programmatic `switchMode` under a mounted view therefore applies the
|
||||
/// side-effects once directly and once more via `onChange` — an idempotent
|
||||
/// repeat; see ``applyModeSwitchSideEffects(from:to:)``.)
|
||||
@Published public var evalMode: ScratchEvalMode = .swift
|
||||
|
||||
public let session: LiveSession
|
||||
|
||||
@@ -495,12 +508,33 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// markers against a buffer the current mode never evaluated.
|
||||
public func switchMode(to mode: ScratchEvalMode) {
|
||||
guard mode != evalMode else { return }
|
||||
if text == LyrebirdScratchModel.defaultPlaceholder(for: evalMode) {
|
||||
let previous: ScratchEvalMode = evalMode
|
||||
evalMode = mode
|
||||
applyModeSwitchSideEffects(from: previous, to: mode)
|
||||
}
|
||||
|
||||
/// Apply the consequences of a mode change — swap the seed placeholder (only
|
||||
/// when the buffer still holds the previous mode's untouched placeholder),
|
||||
/// drop the last-run baseline, and clear diagnostics from a prior run in the
|
||||
/// old mode.
|
||||
///
|
||||
/// Split out of ``switchMode(to:)`` so a SwiftUI host can bind ``evalMode``
|
||||
/// directly and run these from `.onChange(of:)` — outside the view-update
|
||||
/// pass, which is where mutating several `@Published` properties at once is
|
||||
/// allowed. The UI's normal path is a plain `evalMode` write reacted to in
|
||||
/// `onChange`; `switchMode(to:)` is the programmatic path and applies the
|
||||
/// side-effects itself. When a programmatic `switchMode(to:)` happens while a
|
||||
/// view is mounted, `onChange` then fires this a *second* time — a harmless
|
||||
/// repeat: the placeholder swap is a no-op (the buffer no longer equals the
|
||||
/// previous placeholder after the first pass) and the baseline/diagnostic
|
||||
/// resets are idempotent. No-op when `previous == to`.
|
||||
public func applyModeSwitchSideEffects(from previous: ScratchEvalMode, to mode: ScratchEvalMode) {
|
||||
guard previous != mode else { return }
|
||||
if text == LyrebirdScratchModel.defaultPlaceholder(for: previous) {
|
||||
text = LyrebirdScratchModel.defaultPlaceholder(for: mode)
|
||||
}
|
||||
lastEvaluatedText = nil
|
||||
diagnostics = []
|
||||
evalMode = mode
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
@@ -671,7 +705,7 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
// (unsafe), so the mapped-snippet count is unchanged — refresh the mirror
|
||||
// so the UI stays truthful about it.
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
statusMessage = "Cleared all synths (tracked + slots)."
|
||||
statusMessage = "Killed all sound (tracked synths + named slots cleared)."
|
||||
lastEvaluatedText = nil
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
@@ -130,6 +130,12 @@ public struct LyrebirdScratchView: View {
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
// The mode Picker binds `evalMode` directly (synchronous, desync-free);
|
||||
// its side-effects run here, outside the view-update pass, so mutating
|
||||
// several @Published properties at once is allowed.
|
||||
.onChange(of: model.evalMode) { previous, mode in
|
||||
model.applyModeSwitchSideEffects(from: previous, to: mode)
|
||||
}
|
||||
}
|
||||
|
||||
/// The editor column: engine controls, editor, status, engine panel.
|
||||
@@ -393,14 +399,14 @@ public struct LyrebirdScratchView: View {
|
||||
/// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the
|
||||
/// seed placeholder follows the mode.
|
||||
private var modePicker: some View {
|
||||
Picker("Mode", selection: Binding(
|
||||
get: { model.evalMode },
|
||||
// Defer to the next main-actor tick: the Picker's `set` runs inside
|
||||
// SwiftUI's view-update pass, and `switchMode` mutates @Published
|
||||
// state ("Publishing changes from within view updates is not
|
||||
// allowed"). Scheduling it off the current pass avoids that.
|
||||
set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } }
|
||||
)) {
|
||||
// Bind `evalMode` directly: the segmented control writes one @Published
|
||||
// value synchronously, so the displayed segment and `model.evalMode`
|
||||
// can't desync (the old deferred-`Task` set let a re-render — e.g. the
|
||||
// @Published burst from ⌘K's kill — revert the segment before the Task
|
||||
// applied the switch, after which `switchMode`'s equality guard ate the
|
||||
// next click and the toggle appeared stuck). The mode's side-effects run
|
||||
// from `.onChange(of: model.evalMode)` on the body, off the update pass.
|
||||
Picker("Mode", selection: $model.evalMode) {
|
||||
ForEach(ScratchEvalMode.allCases, id: \.self) { mode in
|
||||
Text(mode.title).tag(mode)
|
||||
}
|
||||
@@ -604,6 +610,15 @@ final class ScratchTextView: NSTextView {
|
||||
onManualComplete?()
|
||||
}
|
||||
|
||||
/// Menu-driven completion trigger (Edit ▸ Show Completions, ⌃Space). Routed
|
||||
/// down the responder chain to the focused editor so the menu item needs no
|
||||
/// explicit target; funnels to the same async-fetch path as Esc / F5 rather
|
||||
/// than AppKit's bare `complete(_:)`, so the candidates are fetched before
|
||||
/// the window opens.
|
||||
@objc func scratchShowCompletions(_ 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.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// SnippetCompletionFilterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS) || os(Linux)
|
||||
import Testing
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Unit coverage for the prefix narrowing that `SnippetCompletionService`
|
||||
/// applies to a raw sourcekit-lsp completion list. sourcekit-lsp returns a
|
||||
/// bare-identifier completion as the whole visible-symbol universe, unsorted and
|
||||
/// unfiltered; without this narrowing the editor floods with SDK globals and
|
||||
/// buries the real matches. No LSP server is launched — these exercise the pure
|
||||
/// `partialWord` / `filterAndRank` helpers.
|
||||
@Suite("Snippet completion prefix filtering")
|
||||
struct SnippetCompletionFilterTests {
|
||||
|
||||
private func item(_ label: String, sortText: String? = nil) -> LSPCompletionItem {
|
||||
LSPCompletionItem(
|
||||
label: label,
|
||||
detail: nil,
|
||||
insertText: label,
|
||||
kind: nil,
|
||||
sortText: sortText
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: partialWord
|
||||
|
||||
@Test func partialWordReadsIdentifierBeforeCaretOnLaterLine() {
|
||||
let body: String = "// a comment line\ncontext.reportMessage(\"hi\")\nOscS"
|
||||
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 2, character: 4)
|
||||
#expect(prefix == "OscS")
|
||||
}
|
||||
|
||||
@Test func partialWordIsEmptyRightAfterADot() {
|
||||
// Member completion: the char before the caret is `.`, not an identifier.
|
||||
let body: String = "let x = OscSin."
|
||||
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 0, character: 15)
|
||||
#expect(prefix == "")
|
||||
}
|
||||
|
||||
@Test func partialWordIsEmptyAtLineStart() {
|
||||
let body: String = "foo\nbar"
|
||||
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 1, character: 0)
|
||||
#expect(prefix == "")
|
||||
}
|
||||
|
||||
@Test func partialWordClampsCharacterPastLineEnd() {
|
||||
let body: String = "OscSin"
|
||||
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 0, character: 999)
|
||||
#expect(prefix == "OscSin")
|
||||
}
|
||||
|
||||
@Test func partialWordStopsAtNonIdentifierBoundary() {
|
||||
let body: String = "Pan2(input: OscS"
|
||||
let prefix: String = SnippetCompletionService.partialWord(in: body, line: 0, character: 16)
|
||||
#expect(prefix == "OscS")
|
||||
}
|
||||
|
||||
// MARK: filterAndRank
|
||||
|
||||
@Test func filterDropsNonMatchingGlobalsAndKeepsPrefixMatches() {
|
||||
let items: [LSPCompletionItem] = [
|
||||
item("IOHIDTransactionSetDirection(_:_:)"),
|
||||
item("OscSaw"),
|
||||
item("kOSNotificationMessageID"),
|
||||
item("OscSin"),
|
||||
item("CFNetDiagnosticSetName(_:_:)"),
|
||||
]
|
||||
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "OscS")
|
||||
let labels: [String] = out.map { $0.label }
|
||||
#expect(labels == ["OscSaw", "OscSin"])
|
||||
}
|
||||
|
||||
@Test func filterIsCaseInsensitiveAndRanksPrefixBeforeContains() {
|
||||
let items: [LSPCompletionItem] = [
|
||||
item("myOscSub"), // contains, not prefix
|
||||
item("oscSin"), // prefix (case-insensitive)
|
||||
item("Unrelated"),
|
||||
]
|
||||
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "OSCS")
|
||||
let labels: [String] = out.map { $0.label }
|
||||
#expect(labels == ["oscSin", "myOscSub"])
|
||||
}
|
||||
|
||||
@Test func emptyPrefixKeepsEveryItemSortedBySortText() {
|
||||
// Member completion path: nothing is dropped, only ordered.
|
||||
let items: [LSPCompletionItem] = [
|
||||
item("Control", sortText: "2"),
|
||||
item("Audio", sortText: "1"),
|
||||
]
|
||||
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "")
|
||||
#expect(out.map { $0.label } == ["Audio", "Control"])
|
||||
}
|
||||
|
||||
@Test func noMatchYieldsEmptyRatherThanGlobalFlood() {
|
||||
let items: [LSPCompletionItem] = [
|
||||
item("IOHIDTransactionSetDirection(_:_:)"),
|
||||
item("kOSNotificationMessageID"),
|
||||
]
|
||||
let out: [LSPCompletionItem] = SnippetCompletionService.filterAndRank(items, prefix: "OscS")
|
||||
#expect(out.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -97,7 +97,7 @@ struct LyrebirdScratchModelTests {
|
||||
await model.run(additive: false)
|
||||
model.clearTracked()
|
||||
#expect(model.trackedSynthCount == 0)
|
||||
#expect(model.statusMessage == "Cleared all synths (tracked + slots).")
|
||||
#expect(model.statusMessage == "Killed all sound (tracked synths + named slots cleared).")
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
@@ -22,6 +22,9 @@
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratch">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
||||
</FileRef>
|
||||
|
||||
@@ -251,7 +251,7 @@ Workspace scheme selector exposes eleven entries:
|
||||
| `LyrebirdUI` | Builds the `LyrebirdUI` module only (SwiftUI parameter controls + visualisations) | macOS |
|
||||
| `LyrebirdDemo` | CLI — plays through default output via `makeDefaultAudioDriver()` | macOS · Linux |
|
||||
| `LyrebirdMacOSDemo` | SwiftUI app — live oscilloscope, `@UIParam` knobs | macOS |
|
||||
| `LyrebirdGUIDemo` | Cross-platform GUI — one shared source; SwiftUI here, GTK4 on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
|
||||
| `LyrebirdGUIDemo` | Cross-platform GUI — one shared source; SwiftUI here, GTK4 on Linux (`LYREBIRD_DEMO=conductor`/`vector`/`sine`) | macOS · Linux |
|
||||
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||
| `LyrebirdNRTDemo` | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||
@@ -294,7 +294,7 @@ The CLI demo projects build and run on Linux too — each is its own package, so
|
||||
(cd Demos/LyrebirdQuickstartDemo && swift run) # a 440 Hz sine (needs libasound + a sound device)
|
||||
(cd Demos/LyrebirdDemo && swift run) # reverb smoke-test through default output
|
||||
(cd Demos/LyrebirdScoreDemo && swift run) # notated Score → MusicXML + a rendered WAV (no device)
|
||||
(cd Demos/LyrebirdGUIDemo && swift run) # cross-platform GUI via GTK4 (needs libgtk-4-dev); LYREBIRD_DEMO=vector|sine
|
||||
(cd Demos/LyrebirdGUIDemo && swift run) # cross-platform GUI via GTK4 (needs libgtk-4-dev); LYREBIRD_DEMO=conductor|vector|sine
|
||||
```
|
||||
|
||||
The four CLI demos plus `LyrebirdGUIDemo` (a GTK4 window here, SwiftUI on macOS) run on Linux; the AUv3 / iOS / `LyrebirdMacOSDemo` GUI demos are Apple-only. Full walk-through — toolchain, VS Code, building, running a sample: [`docs/linux-getting-started.md`](docs/linux-getting-started.md).
|
||||
@@ -322,7 +322,7 @@ All nine live in [`Demos/`](Demos/). Each is its own SwiftPM package depending o
|
||||
|---|---|---|
|
||||
| [`LyrebirdQuickstartDemo`](Demos/LyrebirdQuickstartDemo/) | CLI — fastest sound: a one-oscillator `SineTone` plays 440 Hz for 10 s, then exits (mirrors the `quickstart` template) | macOS · Linux |
|
||||
| [`LyrebirdDemo`](Demos/LyrebirdDemo/) | CLI — plays through default output via `makeDefaultAudioDriver()` (Core Audio on macOS, ALSA on Linux) | macOS · Linux |
|
||||
| [`LyrebirdGUIDemo`](Demos/LyrebirdGUIDemo/) | GUI — live `@UIParam` controls, XY pad, oscilloscope, CPU meters, from one shared source; AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux (`LYREBIRD_DEMO=vector`/`sine`) | macOS · Linux |
|
||||
| [`LyrebirdGUIDemo`](Demos/LyrebirdGUIDemo/) | GUI — live `EventConductor` ensemble (default), XY pad, sine tone, oscilloscope, CPU meters, from one shared source; AppKit/SwiftUI on macOS, GTK4/SwiftOpenUI on Linux (`LYREBIRD_DEMO=conductor`/`vector`/`sine`) | macOS · Linux |
|
||||
| [`LyrebirdMacOSDemo`](Demos/LyrebirdMacOSDemo/) | SwiftUI app — live oscilloscope, `@UIParam` knobs, vector / sine / spectral-bin-delay patches | macOS |
|
||||
| [`LyrebirdiOSDemo`](Demos/LyrebirdiOSDemo/) | SwiftUI app — same UI system via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render via `NRTDriver` (CAF on macOS, WAV on Linux) | macOS · Linux |
|
||||
@@ -330,7 +330,7 @@ All nine live in [`Demos/`](Demos/). Each is its own SwiftPM package depending o
|
||||
| [`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 |
|
||||
| [`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.
|
||||
Most demos have a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. (`LyrebirdAUv3Demo` keeps its voice in `LyrebirdFMExtension/`; `LyrebirdScratch` has none — it compiles snippets at runtime.) See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+32
@@ -7,6 +7,38 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 2.4.1 — Scratchpad polish and demo cleanup
|
||||
|
||||
A maintenance release: no framework API changes. It sharpens the LiveCompile
|
||||
scratchpad's UX and tidies the demos and their documentation.
|
||||
|
||||
**Scratchpad — "Kill All Sound".** The panic command that stops every tracked
|
||||
synth and clears the slots is now named **Kill All Sound** (⌘K) in the macOS
|
||||
menu, and **Kill audio** on the Linux button, so the control is discoverable
|
||||
rather than buried under a vague label.
|
||||
|
||||
**Scratchpad — mode switch fixed.** Switching the editor between Swift and
|
||||
graph-DSL mode no longer desyncs when ⌘K (or any command) fires mid-switch. The
|
||||
segmented control now binds the model's mode directly and applies the
|
||||
placeholder/diagnostic reset as an `onChange` side effect, so the picker and the
|
||||
model can never disagree.
|
||||
|
||||
**Scratchpad — code completion restored.** Manual completion (⌃Space) works
|
||||
again and no longer floods the editor: the client now derives the typed prefix
|
||||
and filters/ranks the language-server candidates against it, instead of dumping
|
||||
the entire visible-symbol universe over the caret. Member completion after `.`
|
||||
is unchanged (already server-scoped).
|
||||
|
||||
**Demos — cleanup.** The GUI demo's three voices moved into a `Synthesizers/`
|
||||
folder to match the per-demo convention, and the CLI `EventPattern` demo was
|
||||
split so its lead and bass builders are separate helpers and its `BlipVoice`
|
||||
lives in its own file. Demo READMEs and `LYREBIRD_START_HERE` were corrected to
|
||||
match the code — the cross-platform GUI demo now defaults to the event
|
||||
conductor, and the live-coding scratchpad's Linux (GTK4) support is documented
|
||||
alongside macOS.
|
||||
|
||||
---
|
||||
|
||||
## 2.4.0 — Event patterns and the live event conductor
|
||||
|
||||
An additive, source-compatible release that adds a declarative, event-driven
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The current Lyrebird framework and CLI version.
|
||||
public let lyrebirdVersion: String = "2.4.0"
|
||||
public let lyrebirdVersion: String = "2.4.1"
|
||||
|
||||
/// The banner printed when the interactive shell or REPL session starts.
|
||||
public let welcomeBanner: String = """
|
||||
|
||||
@@ -209,4 +209,7 @@ minimal scratch window → (optional) full GtkSourceView editor.
|
||||
— the Process/EventList family (`LyrebirdEventListPerformanceView` inline,
|
||||
hosting `LyrebirdEventListView` + per-process `LyrebirdProcessView` strips,
|
||||
plus `presentInWindow` for EventListPerformance / EventList / RunningProcesses).
|
||||
5. (Stretch) live-coding scratchpad usable on Linux — not started.
|
||||
5. ✅ Live-coding scratchpad usable on Linux — done. GTK4 host
|
||||
`LyrebirdScratchLinuxDemo` (`LinuxScratchView` / `LinuxScratchModel` on the
|
||||
SwiftOpenUI backend, GtkSourceView editor + completion + save/load + live
|
||||
scope). Run + setup in `LINUX_README.md`; full surface in LiveCoding.docc.
|
||||
|
||||
Reference in New Issue
Block a user