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:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user