Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI, REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive. See RELEASES.md and LINUX_README.md. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Errors raised while staging compile artifacts into Application Support.
|
||||
enum ArtifactStagingError: Error {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -665,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
|
||||
}
|
||||
|
||||
@@ -690,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
|
||||
}
|
||||
@@ -754,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
|
||||
@@ -781,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 {
|
||||
@@ -805,7 +861,9 @@ 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
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
extension LiveSession {
|
||||
|
||||
@@ -178,6 +178,16 @@ extension LiveSession {
|
||||
// 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)
|
||||
@@ -218,10 +228,29 @@ extension LiveSession {
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return [] }
|
||||
return entries.filter {
|
||||
$0.pathExtension == "dylib" && $0.lastPathComponent.hasPrefix("libLyrebird")
|
||||
$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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -7,14 +7,14 @@
|
||||
// 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 only — iOS cannot exec
|
||||
// subprocesses. Writes the source to a temp file and runs `swift-format format
|
||||
// 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)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Stateless `swift-format` wrapper.
|
||||
public enum SwiftFormatter {
|
||||
@@ -72,14 +72,20 @@ public enum SwiftFormatter {
|
||||
label: "net.realizedsound.lyrebird.swift-format-drain",
|
||||
attributes: .concurrent
|
||||
)
|
||||
var outData: Data = Data()
|
||||
var errData: Data = Data()
|
||||
// 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 { outData = outHandle.readDataToEndOfFile(); group.leave() }
|
||||
drainQueue.async { outBox.data = outHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.enter()
|
||||
drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() }
|
||||
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) ?? ""
|
||||
@@ -137,4 +143,13 @@ public enum SwiftFormatter {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
|
||||
/// Errors raised while formatting snippet source with `swift-format`.
|
||||
public enum SwiftFormatterError: Error {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#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
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
#if os(macOS) || os(Linux)
|
||||
import Foundation
|
||||
|
||||
/// Detects whether a usable Swift toolchain is present, so the app can warn the user
|
||||
|
||||
@@ -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,12 @@ 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
|
||||
@@ -442,9 +445,39 @@ 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.
|
||||
|
||||
@@ -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)
|
||||
Reference in New Issue
Block a user