1.0.0 release

This commit is contained in:
2026-06-01 18:27:40 -07:00
parent b1ab0f102c
commit 1f20fcab20
1151 changed files with 230703 additions and 14 deletions
@@ -0,0 +1,57 @@
// CompiledSnippet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// `CompiledSnippet` owns the `dlopen` handle and the resolved entry function
// pointer for one snippet's dylib. Held by the live session for the lifetime of
// the process — dylib unload is unsafe while live `Synth` instances may still
// reference types defined in the dylib. (See plan in
// `memory/project_live_compile_phases.md` non-goals.)
import Foundation
#if os(macOS)
/// Handle to one successfully compiled and loaded snippet.
///
/// Intentionally a `final class` (not a `struct`): owning the `dlopen` handle
/// via reference identity means moves / copies cannot duplicate or accidentally
/// drop ownership. There is no `deinit` that calls `dlclose` — see the file
/// header.
///
/// `@unchecked Sendable`: every stored field is `let`; the `dlopen` handle and
/// the resolved entry pointer are both thread-safe to hold and read after the
/// compile completes (the loader serialises symbol resolution). Allows
/// `LiveSession.compileAndRunAsync` to return one across a `Task.detached`
/// boundary.
public final class CompiledSnippet: @unchecked Sendable {
/// Module name passed to `swiftc -module-name`; useful for diagnostics.
public let moduleName: String
/// Path to the dylib that was `dlopen`'d.
public let dylibPath: String
/// Resolved entry function pointer. Calling this is Phase 143's job.
public let entry: SnippetEntry
/// Raw `dlopen` handle. Kept so the OS keeps the dylib mapped.
public let handle: UnsafeMutableRawPointer
init(
moduleName: String,
dylibPath: String,
entry: SnippetEntry,
handle: UnsafeMutableRawPointer
) {
self.moduleName = moduleName
self.dylibPath = dylibPath
self.entry = entry
self.handle = handle
}
}
#endif
@@ -0,0 +1,52 @@
// Diagnostic.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// One parsed `swiftc` diagnostic, with `line` already mapped from the wrapped-
// snippet coordinate space back to the user's snippet coordinate space (via the
// `userBodyLineOffset` from `SnippetHarness.wrap(userBody:)`).
//
// The editor in Phase 145 (`LyrebirdScratchView`) renders diagnostics in its
// margin gutter using `(line, column)` directly.
#if os(macOS)
public struct Diagnostic: Equatable, Sendable {
/// 1-based line number in the **user's** snippet body. May be `nil` when the
/// diagnostic landed inside the harness preamble (i.e. the wrapped line
/// number is less than `userBodyLineOffset`) — that almost always points at
/// the user importing a missing module or otherwise breaking the preamble.
public let line: Int?
/// 1-based column number. swiftc emits the same column for preamble and
/// user-body lines, so no translation is needed.
public let column: Int
public let severity: DiagnosticSeverity
public let message: String
/// 1-based line number swiftc actually reported, before user-coordinate
/// translation. Useful for debugging the parser; not surfaced to end users.
public let rawLine: Int
public init(
line: Int?,
column: Int,
severity: DiagnosticSeverity,
message: String,
rawLine: Int
) {
self.line = line
self.column = column
self.severity = severity
self.message = message
self.rawLine = rawLine
}
}
#endif
@@ -0,0 +1,101 @@
// DiagnosticParser.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// `DiagnosticParser.parse(stderr:userBodyLineOffset:)` walks the swiftc stderr
// stream line by line, extracts diagnostics matching the standard
// `<path>:<line>:<column>: <severity>: <message>` shape, and re-maps line
// numbers from wrapped-snippet coordinates back to user-snippet coordinates.
//
// swiftc stderr format (one diagnostic):
//
// /tmp/.../Snippet.swift:7:14: error: cannot convert value of type 'String' to 'Int'
// 7 | let x: Int = "nope"
// | `- error: cannot convert value of type 'String' to 'Int'
//
// We pick up the first line (the location/severity/message header) and ignore
// the source-context lines that follow.
import Foundation
#if os(macOS)
public enum DiagnosticParser {
/// Compiled once at first access. Pattern matches the standard swiftc
/// header line: `<path>:<line>:<column>: <severity>: <message>`.
/// `try!` is safe — the pattern is a compile-time literal that cannot fail
/// `NSRegularExpression`'s validator.
private static let _headerRegex: NSRegularExpression = {
// swiftlint:disable:next force_try
try! NSRegularExpression(
pattern: #"^(.+?):(\d+):(\d+):\s+(error|warning|note):\s+(.*)$"#
)
}()
/// Parse swiftc stderr into a list of structured diagnostics, with line
/// numbers translated to user-snippet coordinates.
///
/// - Parameters:
/// - stderr: Raw swiftc stderr text. May be empty.
/// - userBodyLineOffset: 1-based line on which the user's body starts in
/// the wrapped source — typically `SnippetHarness.wrap(userBody:).userBodyLineOffset`.
/// Diagnostics on `rawLine >= userBodyLineOffset` are mapped to
/// `rawLine - (userBodyLineOffset - 1)`; diagnostics on earlier lines
/// keep `line = nil` to signal "in the harness preamble".
/// - Returns: One `Diagnostic` per matched header line, in stderr order.
public static func parse(stderr: String, userBodyLineOffset: Int) -> [Diagnostic] {
var result: [Diagnostic] = []
for rawLine: String.SubSequence in stderr.split(separator: "\n", omittingEmptySubsequences: false) {
guard let diag: Diagnostic = parseLine(String(rawLine), userBodyLineOffset: userBodyLineOffset) else {
continue
}
result.append(diag)
}
return result
}
/// Parse one stderr line. Returns `nil` for non-header lines (source-context
/// rows, caret markers, blank lines).
static func parseLine(_ rawLine: String, userBodyLineOffset: Int) -> Diagnostic? {
// Pattern (anchored):
// <path>:<line>:<column>: <severity>: <message>
// Where <path> contains no colon-space combos, and <severity> ∈ {error, warning, note}.
//
// The path may legally contain `:` on macOS (filesystem allows it), so use a
// greedy-then-validate approach: scan from the right for the third-from-last
// `:` and split on that. Cheaper: regex with a non-greedy path segment.
let range: NSRange = NSRange(rawLine.startIndex..<rawLine.endIndex, in: rawLine)
guard let match: NSTextCheckingResult = _headerRegex.firstMatch(in: rawLine, range: range),
match.numberOfRanges == 6,
let lineRange: Range<String.Index> = Range(match.range(at: 2), in: rawLine),
let colRange: Range<String.Index> = Range(match.range(at: 3), in: rawLine),
let severityRange: Range<String.Index> = Range(match.range(at: 4), in: rawLine),
let messageRange: Range<String.Index> = Range(match.range(at: 5), in: rawLine),
let rawLineNumber: Int = Int(rawLine[lineRange]),
let column: Int = Int(rawLine[colRange]),
let severity: DiagnosticSeverity = DiagnosticSeverity(rawValue: String(rawLine[severityRange]))
else { return nil }
let userLine: Int?
if rawLineNumber >= userBodyLineOffset {
userLine = rawLineNumber - (userBodyLineOffset - 1)
} else {
userLine = nil
}
return Diagnostic(
line: userLine,
column: column,
severity: severity,
message: String(rawLine[messageRange]),
rawLine: rawLineNumber
)
}
}
#endif
@@ -0,0 +1,19 @@
// DiagnosticSeverity.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// Severity classifier for a parsed swiftc diagnostic line.
#if os(macOS)
public enum DiagnosticSeverity: String, Equatable, Sendable {
case error
case warning
case note
}
#endif
@@ -0,0 +1,51 @@
// LiveCompileError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// Errors raised by `LiveCompiler.compile(source:)`. RT path never sees these:
// compilation is a main-thread (or background-queue) operation that runs long
// before any audio block.
import Foundation
#if os(macOS)
public enum LiveCompileError: Error, CustomStringConvertible, Equatable, Sendable {
/// `xcrun -f swiftc` and the fallback paths all failed.
case swiftcNotFound
/// `swiftc` exited non-zero. `stderr` carries the raw compiler output; Phase
/// 144 parses it into structured diagnostics.
case compileFailed(exitCode: Int32, stderr: String)
/// `dlopen(dylibPath, RTLD_NOW)` returned `nil`. `message` is the `dlerror()`
/// string at the time of the failure.
case dlopenFailed(path: String, message: String)
/// The dylib opened but did not export the expected entry symbol.
case entrySymbolMissing(symbol: String, message: String)
/// A temp-dir / write step failed before `swiftc` was invoked.
case ioFailed(underlying: String)
public var description: String {
switch self {
case .swiftcNotFound:
return "swiftc binary not found in xcrun or standard toolchain paths"
case .compileFailed(let code, let stderr):
return "swiftc exited \(code):\n\(stderr)"
case .dlopenFailed(let path, let message):
return "dlopen failed for \(path): \(message)"
case .entrySymbolMissing(let symbol, let message):
return "missing snippet entry symbol \(symbol): \(message)"
case .ioFailed(let underlying):
return "IO step failed: \(underlying)"
}
}
}
#endif
@@ -0,0 +1,210 @@
// LiveCompiler.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// `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 land in phases 143–146). macOS only —
// iOS cannot exec swiftc.
import Foundation
#if os(macOS)
import Darwin
#endif
#if os(macOS)
/// Symbol the snippet preamble must export. Snippets declare:
///
/// ```swift
/// @_cdecl("lyrebird_snippet_entry")
/// public func entry(_ ctx: UnsafeMutableRawPointer?) { /* ... */ }
/// ```
public let lyrebirdSnippetEntrySymbol: String = "lyrebird_snippet_entry"
/// One-shot snippet compiler. Stateless — every `compile(source:)` allocates a
/// fresh temp dir, dylib name, and `dlopen` handle.
public enum LiveCompiler {
/// Compile `source` to a dylib and resolve the snippet entry symbol.
///
/// - Parameters:
/// - source: Full Swift source, including the `@_cdecl("lyrebird_snippet_entry")`
/// entry. Phase 143's `SnippetHarness` will wrap user input in a preamble that
/// provides this; Phase 142 callers (incl. tests) write the full file.
/// - extraSwiftcArgs: Extra args appended to the `swiftc` invocation. Tests use
/// this for `-suppress-warnings` etc. Production callers leave empty.
/// - Returns: `CompiledSnippet` holding the dlopen handle and entry pointer.
/// - Throws: `LiveCompileError` cases for missing toolchain, compile failure,
/// `dlopen` failure, or missing entry symbol.
public static func compile(
source: String,
extraSwiftcArgs: [String] = []
) throws -> CompiledSnippet {
let swiftc: String = try findSwiftc()
let snippetID: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
let moduleName: String = "LBSnippet_\(snippetID)"
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
do {
try FileManager.default.createDirectory(
at: workDir,
withIntermediateDirectories: true
)
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
} catch {
throw LiveCompileError.ioFailed(underlying: "\(error)")
}
var arguments: [String] = [
"-emit-library",
"-module-name", moduleName,
"-o", dylibPath,
]
if let sdkPath: String = sdkPathViaXcrun() {
arguments.append(contentsOf: ["-sdk", sdkPath])
}
arguments += extraSwiftcArgs
arguments.append(sourcePath)
let result: LiveCompiler.SwiftcResult = try runSwiftc(executable: swiftc, arguments: arguments)
guard result.exitCode == 0 else {
throw LiveCompileError.compileFailed(
exitCode: result.exitCode,
stderr: result.stderr
)
}
guard let handle: UnsafeMutableRawPointer = dlopen(dylibPath, RTLD_NOW) else {
let message: String = dlerror().map { String(cString: $0) } ?? "unknown dlopen error"
throw LiveCompileError.dlopenFailed(path: dylibPath, message: message)
}
guard let symbol: UnsafeMutableRawPointer = dlsym(handle, lyrebirdSnippetEntrySymbol) else {
let message: String = dlerror().map { String(cString: $0) } ?? "unknown dlsym error"
// Leave the dylib mapped — closing it after a successful open would
// unmap its types if anything is already referencing them. The
// failure is post-load, so the safe action is to leak.
throw LiveCompileError.entrySymbolMissing(
symbol: lyrebirdSnippetEntrySymbol,
message: message
)
}
let entry: SnippetEntry = unsafeBitCast(symbol, to: SnippetEntry.self)
return CompiledSnippet(
moduleName: moduleName,
dylibPath: dylibPath,
entry: entry,
handle: handle
)
}
// MARK: - swiftc resolution
/// First-success search:
/// 1. `xcrun -f swiftc` (honours `DEVELOPER_DIR` and the user's active Xcode).
/// 2. Hard-coded toolchain paths.
static func findSwiftc() throws -> String {
if let xcrun: String = swiftcViaXcrun() {
return xcrun
}
let candidates: [String] = [
"/usr/bin/swiftc",
"/usr/local/bin/swiftc",
"/opt/homebrew/bin/swiftc",
]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw LiveCompileError.swiftcNotFound
}
/// `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? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["--show-sdk-path"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
private static func swiftcViaXcrun() -> String? {
let xcrunPath: String = "/usr/bin/xcrun"
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: xcrunPath)
process.arguments = ["-f", "swiftc"]
let stdout: Pipe = Pipe()
process.standardOutput = stdout
// xcrun's stderr is short, but attaching a Pipe without draining it could
// deadlock if it ever filled the OS pipe buffer (~64 KB) while we block on
// stdout. Route to /dev/null at the OS level.
process.standardError = FileHandle.nullDevice
do {
try process.run()
process.waitUntilExit()
} catch {
return nil
}
guard process.terminationStatus == 0 else { return nil }
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
return trimmed.isEmpty ? nil : trimmed
}
// MARK: - swiftc invocation
struct SwiftcResult {
let exitCode: Int32
let stderr: String
}
private static func runSwiftc(executable: String, arguments: [String]) throws -> SwiftcResult {
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: executable)
process.arguments = arguments
let stderrPipe: Pipe = Pipe()
process.standardError = stderrPipe
// stdout discarded — swiftc emits no useful output in -emit-library mode.
// Use FileHandle.nullDevice (not Pipe()) so the OS drops the bytes itself;
// an undrained Pipe deadlocks against the blocking stderr read below if
// swiftc ever writes more than the pipe buffer (~64 KB) to stdout.
process.standardOutput = FileHandle.nullDevice
do {
try process.run()
} catch {
throw LiveCompileError.ioFailed(underlying: "swiftc launch failed: \(error)")
}
let stderrData: Data = stderrPipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
let stderrString: String = String(data: stderrData, encoding: .utf8) ?? ""
return SwiftcResult(exitCode: process.terminationStatus, stderr: stderrString)
}
}
#endif
@@ -0,0 +1,326 @@
// LiveSession.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `LiveSession` owns the `SynthesisEngine` and tracks every `Synthesizer` that
// each snippet `play(_:)`s, so the next non-additive re-evaluation can
// `engine.remove(_:)` them before running fresh user code. Also caches every
// `CompiledSnippet` so the dylibs stay mapped — see the leak-by-design note in
// `CompiledSnippet.swift`.
#if os(macOS)
import Foundation
import LyrebirdSynth
/// Host-side owner of one live-coding session.
///
/// Holds the `SynthesisEngine` that snippets target, the swiftc flags used to
/// compile snippets, and the tracking lists needed for re-evaluation cleanup.
/// Snippets receive a `SnippetContext` bound to this session through
/// `compileAndRun(_:additive:)`.
public final class LiveSession {
public let engine: SynthesisEngine
/// `-I` paths threaded to `swiftc` for module discovery.
public let importPaths: [URL]
/// `-L` paths threaded to `swiftc` for library search.
public let librarySearchPaths: [URL]
/// Bare library names threaded to `swiftc` as `-l<name>`.
public let libraries: [String]
/// `-Xlinker -rpath -Xlinker <path>` entries baked into the snippet dylib
/// so `dlopen` resolves dependent dylibs (`libLyrebird.dylib` etc.) at
/// runtime without `DYLD_LIBRARY_PATH` ceremony.
public let rpaths: [URL]
/// Side-channel for snippet `context.reportSampleRate(_:)` calls. Tests read
/// via `@testable import`; not part of the public API.
internal var reportedSampleRate: Double?
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
/// via `@testable import`; not part of the public API.
internal var lastSnippetMessage: String?
// Tracked state — all access guarded by `trackingLock`.
private let trackingLock: NSLock = NSLock()
private var trackedSynths: [any Synthesizer] = []
private var loadedSnippets: [CompiledSnippet] = []
public init(
engine: SynthesisEngine,
importPaths: [URL] = LiveSession.defaultImportPaths(),
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
libraries: [String] = ["Lyrebird", "LyrebirdLiveCompile"],
rpaths: [URL] = LiveSession.defaultRpaths()
) {
self.engine = engine
self.importPaths = importPaths
self.librarySearchPaths = librarySearchPaths
self.libraries = libraries
self.rpaths = rpaths
}
/// Wrap `userBody` in the standard harness, compile, and call the snippet's
/// `lyrebird_snippet_entry` with a `SnippetContext` bound to this session.
///
/// - Parameters:
/// - userBody: Swift code that runs inside the snippet entry. Has access
/// to a local `context: SnippetContext`.
/// - additive: When `false` (default), removes every previously tracked
/// synth before running. When `true`, leaves prior synths in place
/// (⌘⇧↩ semantics in the future `LyrebirdScratchView` editor).
/// - Returns: The compiled snippet handle. Retained internally so the dylib
/// stays mapped; callers can ignore it.
@discardableResult
public func compileAndRun(_ userBody: String, additive: Bool = false) throws -> CompiledSnippet {
if !additive {
clearTracked()
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let snippet: CompiledSnippet = try compileWrapped(wrapped)
runEntry(of: snippet)
return snippet
}
/// Asynchronous variant of ``compileAndRun(_:additive:)``. The swiftc
/// compile runs on a background `Task.detached`; the snippet entry then
/// executes on the caller's actor (typically the main actor, so snippets
/// can touch UI-side state). Lets `LyrebirdScratchView`'s editor stay
/// responsive during the compile.
///
/// - Precondition: only one in-flight invocation at a time per `LiveSession`.
/// Concurrent calls can interleave `clearTracked()` with the prior call's
/// not-yet-completed `runEntry`, silently dropping tracked synths. The
/// built-in caller `LyrebirdScratchModel` serialises through its
/// `isCompiling` flag; out-of-tree callers must enforce the same.
///
/// - Parameters:
/// - userBody: Same as the synchronous variant.
/// - additive: Same as the synchronous variant.
/// - Returns: The compiled snippet handle. Retained internally.
@discardableResult
public func compileAndRunAsync(_ userBody: String, additive: Bool = false) async throws -> CompiledSnippet {
if !additive {
clearTracked()
}
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: userBody)
let args: [String] = makeSwiftcArgs()
let snippet: CompiledSnippet = try await Task.detached(priority: .userInitiated) {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: args)
}.value
runEntry(of: snippet)
return snippet
}
// Synchronous compile body used by both `compileAndRun` and the detached
// background `Task` inside `compileAndRunAsync`. Wraps the
// `LiveCompileError` → `LiveSessionError` translation in one place.
private static func compileBlocking(wrapped: WrappedSnippet, extraArgs: [String]) throws -> CompiledSnippet {
do {
return try LiveCompiler.compile(
source: wrapped.source,
extraSwiftcArgs: extraArgs
)
} catch let error as LiveCompileError {
if case .compileFailed(_, let stderr) = error {
let diagnostics: [Diagnostic] = DiagnosticParser.parse(
stderr: stderr,
userBodyLineOffset: wrapped.userBodyLineOffset
)
throw LiveSessionError.snippetCompileFailed(
diagnostics: diagnostics,
underlying: error
)
}
throw LiveSessionError.compilerError(error)
}
}
private func compileWrapped(_ wrapped: WrappedSnippet) throws -> CompiledSnippet {
try LiveSession.compileBlocking(wrapped: wrapped, extraArgs: makeSwiftcArgs())
}
private func runEntry(of snippet: CompiledSnippet) {
let context: SnippetContext = SnippetContext(session: self)
withExtendedLifetime(context) {
let opaque: UnsafeMutableRawPointer = Unmanaged.passUnretained(context).toOpaque()
snippet.entry(opaque)
}
trackingLock.lock(); defer { trackingLock.unlock() }
loadedSnippets.append(snippet)
}
/// Currently tracked synth count. Thread-safe.
public var trackedSynthCount: Int {
trackingLock.lock(); defer { trackingLock.unlock() }
return trackedSynths.count
}
/// Remove every tracked synth from the engine and clear the tracking list.
/// Called automatically by `compileAndRun(_:additive: false)`.
public func clearTracked() {
let snapshot: [any Synthesizer]
do {
trackingLock.lock(); defer { trackingLock.unlock() }
snapshot = trackedSynths
trackedSynths.removeAll()
}
for synth: any Synthesizer in snapshot {
_ = engine.remove(synth)
}
}
/// Internal hook for `SnippetContext.play(_:)`. Thread-safe.
func track(_ synth: any Synthesizer) {
trackingLock.lock(); defer { trackingLock.unlock() }
trackedSynths.append(synth)
}
// MARK: - swiftc flag construction
private func makeSwiftcArgs() -> [String] {
var args: [String] = []
for path: URL in importPaths {
args += ["-I", path.path]
}
// Clang module maps (e.g. `LyrebirdC.modulemap`) generated by Xcode for
// SPM C targets — surface each as `-Xcc -fmodule-map-file=<path>` so
// swiftc's embedded clang can resolve the underlying C module declared
// in a Swift module's dependency record.
for url: URL in LiveSession.discoverClangModuleMaps(in: importPaths) {
args += ["-Xcc", "-fmodule-map-file=\(url.path)"]
}
// When a Lyrebird dylib exists in any -L path, link against it
// (-l<name>) and bake an rpath. When no dylib is found (Xcode SPM
// case — modules statically linked into the host app), use
// `-undefined dynamic_lookup` so the snippet's dylib defers symbol
// resolution to runtime, where dyld finds Lyrebird's symbols in the
// already-loaded host process.
let hasDylib: Bool = librarySearchPaths.contains { url in
LiveSession.hasLyrebirdDylib(in: url)
}
if hasDylib {
for path: URL in librarySearchPaths {
args += ["-L", path.path]
}
for lib: String in libraries {
args += ["-l\(lib)"]
}
for path: URL in rpaths {
args += ["-Xlinker", "-rpath", "-Xlinker", path.path]
}
} else {
args += ["-Xlinker", "-undefined", "-Xlinker", "dynamic_lookup"]
}
return args
}
/// Walk up from each import path looking for Xcode's
/// `Build/Intermediates.noindex/GeneratedModuleMaps/` directory and return
/// every `*.modulemap` it contains. Empty on `swift build` SPM layouts
/// (where C modules use the package's own `include/module.modulemap`).
static func discoverClangModuleMaps(in importPaths: [URL]) -> [URL] {
let maxWalk: Int = 6
var found: [URL] = []
var visited: Set<String> = Set<String>()
for start: URL in importPaths {
var cur: URL = start
for _ in 0..<maxWalk {
let probe: URL = cur
.appendingPathComponent("Build")
.appendingPathComponent("Intermediates.noindex")
.appendingPathComponent("GeneratedModuleMaps")
if FileManager.default.fileExists(atPath: probe.path),
!visited.contains(probe.path) {
visited.insert(probe.path)
if let entries: [URL] = try? FileManager.default.contentsOfDirectory(at: probe, includingPropertiesForKeys: nil) {
for entry: URL in entries where entry.pathExtension == "modulemap" {
found.append(entry)
}
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return found
}
// MARK: - Build-dir discovery
/// Best-effort discovery of the SPM `.build/<triple>/<config>` directory
/// that contains `libLyrebird.dylib` and the swiftmodule directories. Used
/// as the default for `importPaths`/`librarySearchPaths`/`rpaths`. Hosts can
/// override by passing explicit URLs.
///
/// Searches, in order:
/// 1. Walks up from `Bundle(for: LiveSession.self).bundleURL` — this resolves
/// to the directory holding `libLyrebirdLiveCompile.dylib` at runtime,
/// which is the SPM debug/release dir.
/// 2. Walks up from `Bundle.main.executableURL` — fallback for the case
/// where the host bundles the dylibs into an `.app`.
public static func currentBuildDir() -> URL? {
let maxWalk: Int = 6
let candidates: [URL] = [
Bundle(for: LiveSession.self).bundleURL,
Bundle.main.executableURL ?? Bundle.main.bundleURL,
]
// Accept either an SPM-produced .dylib (swift build) or just the
// LyrebirdSynth.swiftmodule (Xcode SPM static-linked into the host app).
// The swiftmodule alone is enough for `-I` module resolution; linking
// falls back to `-undefined dynamic_lookup` when no dylib is found.
// Note: the product/dylib is named `Lyrebird` (libLyrebird.dylib); the
// module/target is named `LyrebirdSynth` (LyrebirdSynth.swiftmodule).
let markers: [String] = ["libLyrebird.dylib", "LyrebirdSynth.swiftmodule"]
for start: URL in candidates {
var cur: URL = start
for _ in 0..<maxWalk {
for marker: String in markers {
let probe: URL = cur.appendingPathComponent(marker)
if FileManager.default.fileExists(atPath: probe.path) {
return cur
}
}
let parent: URL = cur.deletingLastPathComponent()
if parent == cur { break }
cur = parent
}
}
return nil
}
/// `true` when a `libLyrebird.dylib` actually exists in `buildDir`. Used to
/// decide whether to link against the dylib at compile time or fall back to
/// `-undefined dynamic_lookup` so the snippet binds to symbols already
/// resolved in the running process.
public static func hasLyrebirdDylib(in buildDir: URL) -> Bool {
FileManager.default.fileExists(
atPath: buildDir.appendingPathComponent("libLyrebird.dylib").path
)
}
public static func defaultImportPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir, buildDir.appendingPathComponent("Modules")]
}
public static func defaultLibrarySearchPaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir]
}
public static func defaultRpaths() -> [URL] {
guard let buildDir: URL = currentBuildDir() else { return [] }
return [buildDir]
}
}
#endif
@@ -0,0 +1,43 @@
// LiveSessionError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 144
//
// `LiveSession.compileAndRun(_:additive:)` throws this richer error so callers
// see diagnostics pre-mapped to user-snippet coordinates. Other `LiveCompileError`
// cases (toolchain missing, dlopen failure, etc.) pass through under
// `.compilerError`.
#if os(macOS)
public enum LiveSessionError: Error, CustomStringConvertible, Sendable {
/// Snippet failed to compile. `diagnostics` are already line-mapped via the
/// active `SnippetHarness` offset; `underlying` is the raw `swiftc` failure
/// the diagnostics were parsed from.
case snippetCompileFailed(diagnostics: [Diagnostic], underlying: LiveCompileError)
/// Any other `LiveCompileError` case — toolchain missing, dlopen failure,
/// missing entry symbol, IO failure.
case compilerError(LiveCompileError)
public var description: String {
switch self {
case .snippetCompileFailed(let diagnostics, let underlying):
if diagnostics.isEmpty {
return "snippet compile failed:\n\(underlying)"
}
let summary: String = diagnostics.map { diag -> String in
let location: String = diag.line.map { "\($0):\(diag.column)" } ?? "preamble:\(diag.rawLine):\(diag.column)"
return "\(location) \(diag.severity.rawValue): \(diag.message)"
}.joined(separator: "\n")
return "snippet compile failed:\n\(summary)"
case .compilerError(let underlying):
return "live compile error: \(underlying)"
}
}
}
#endif
@@ -0,0 +1,65 @@
// SnippetContext.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `SnippetContext` is the public API surface the user's snippet talks to. The
// host (via `LiveSession.compileAndRun`) constructs one of these, passes the
// opaque pointer to the snippet's `lyrebird_snippet_entry`, and the preamble
// hands the snippet a typed `context: SnippetContext` reference.
//
// Surface is intentionally minimal for v1 (open question 4 in the plan). Snippets
// read `context.engine` for `SynthesisEngine`, call `context.play(_:)` to add a
// synth that the host will track for re-evaluation cleanup, and report back via
// the test-friendly `reportSampleRate(_:)` / `reportMessage(_:)` helpers.
#if os(macOS)
import LyrebirdSynth
public final class SnippetContext {
/// Owning session. `unowned` because the host guarantees the session
/// outlives the snippet `entry` call (entry is invoked synchronously inside
/// `LiveSession.compileAndRun` under a `withExtendedLifetime` on `self`).
public unowned let session: LiveSession
/// Convenience accessor — same as `session.engine`.
public var engine: SynthesisEngine { session.engine }
init(session: LiveSession) {
self.session = session
}
/// Add `synth` to the engine and track it so the next non-additive
/// re-evaluation (`LiveSession.compileAndRun(_:additive: false)`) removes it.
/// - Returns: `true` if the engine accepted the enqueue; `false` if
/// `engine.add` threw (e.g. cross-engine binding, double-add, queue full).
@discardableResult
public func play(_ synth: any Synthesizer) -> Bool {
do {
try session.engine.add(synth)
session.track(synth)
return true
} catch {
session.lastSnippetMessage = "engine.add failed: \(error)"
return false
}
}
/// Snippet-side hook for test verification: report the engine's sample rate
/// back through the session so tests can confirm the `context.engine`
/// linkage compiled and called correctly.
public func reportSampleRate(_ rate: Double) {
session.reportedSampleRate = rate
}
/// Snippet-side hook for test verification: record an arbitrary message
/// back on the session. Lets tests confirm the snippet body executed.
public func reportMessage(_ message: String) {
session.lastSnippetMessage = message
}
}
#endif
@@ -0,0 +1,19 @@
// SnippetEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 142 core
//
// C ABI signature of the snippet's exported entry point.
#if os(macOS)
/// Snippets export this symbol via `@_cdecl("lyrebird_snippet_entry")`. Phase
/// 143 will pass a pointer to a `LiveSession` (or harness context) here;
/// Phase 142 only requires that snippets can declare a function matching this
/// signature.
public typealias SnippetEntry = @convention(c) (UnsafeMutableRawPointer?) -> Void
#endif
@@ -0,0 +1,43 @@
// SnippetHarness.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// `SnippetHarness.wrap(userBody:)` produces the full Swift source that
// `LiveCompiler.compile(source:)` feeds to swiftc. The preamble imports the
// modules the snippet needs, declares the C ABI entry, and binds `context: SnippetContext`
// from the opaque pointer the host hands in. The user's body is dropped in as
// the function body.
#if os(macOS)
public enum SnippetHarness {
/// Wraps `userBody` in the standard preamble.
public static func wrap(userBody: String) -> WrappedSnippet {
let preamble: String = """
import LyrebirdSynth
import LyrebirdLiveCompile
@_cdecl("lyrebird_snippet_entry")
public func lyrebird_snippet_entry(_ ctx: UnsafeMutableRawPointer?) {
guard let ctx else { return }
let context = Unmanaged<SnippetContext>.fromOpaque(ctx).takeUnretainedValue()
_ = context
"""
// Count newlines in the preamble: the user's body starts on the next line.
// `components(separatedBy: "\n")` over a string ending in "\n" yields N+1
// elements (the last is empty); offset = count of those elements = lines
// before the user body + 1 (the line on which the body starts).
let lineOffset: Int = preamble.components(separatedBy: "\n").count
let suffix: String = "\n}\n"
let source: String = preamble + userBody + suffix
return WrappedSnippet(source: source, userBodyLineOffset: lineOffset)
}
}
#endif
@@ -0,0 +1,22 @@
// WrappedSnippet.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdLiveCompile — Phase 143
//
// Output of `SnippetHarness.wrap(userBody:)`. Carries the full Swift source
// that `swiftc` will compile, plus the 1-based line number on which the user's
// body begins. Phase 144's diagnostic parser subtracts `userBodyLineOffset - 1`
// from each swiftc-reported line so error rows point back at the row the user
// typed.
#if os(macOS)
public struct WrappedSnippet: Equatable {
public let source: String
public let userBodyLineOffset: Int
}
#endif
@@ -0,0 +1,86 @@
# Live coding with `LyrebirdScratchView`
A SwiftUI scratchpad for hot-swapping snippets through `LyrebirdLiveCompile`.
## Overview
`LyrebirdScratchView` pairs an `NSTextView`-backed Swift editor with a `LiveSession`
that owns the audio engine. Pressing **⌘↩** wraps the snippet body in the standard
harness, shells out to `swiftc`, `dlopen`s the resulting dylib, and calls the
snippet's `lyrebird_snippet_entry` with a `SnippetContext` bound to the session.
Synthesizers played via `context.play(_:)` are tracked, so the next non-additive
run replaces them. **⌘⇧↩** layers a new snippet on top of the prior ones.
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.
## Hosting
```swift
import LyrebirdSynth
import LyrebirdUI // LyrebirdWindow
import LyrebirdLiveCompile // LiveSession
import LyrebirdLiveCompileUI // LyrebirdScratchView
let engine = SynthesisEngine(/* … */)
try engine.start()
let session = LiveSession(engine: engine)
let window = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
window.open {
LyrebirdScratchView(session: session)
}
```
## Keyboard shortcuts
| Shortcut | Action |
|----------|--------|
| ⌘↩ | Compile + run. Removes synths from the previous run before executing. |
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
`LiveSession.clearTracked()` directly.
## Snippet API surface
A snippet has one local in scope:
```swift
context: SnippetContext
```
`SnippetContext` is intentionally minimal in v1:
- `context.engine` — the host `SynthesisEngine`.
- `context.play(_:)` — add a `Synthesizer` to the engine and register it for
cleanup on the next non-additive run.
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
`print`-style probes during development).
## Threading
All UI is `@MainActor`-isolated. `LiveSession.compileAndRun` is invoked
synchronously inside the button action, so the editor freezes for the duration
of the `swiftc` invocation (≈ 1 second cold, much faster on warm cache). v1
accepts that trade-off; an off-main compile path is on the polish list.
## Limitations
- macOS only.
- No syntax highlighting, code completion, or line-number gutter (deferred).
- Compiled dylibs are leaked by design — types in a loaded snippet may still be
referenced by tracked synths; unloading is unsafe.
- The host `.app` must not be sandboxed and must allow library validation to be
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
dylib is `dlopen`'d.
## Topics
- ``LyrebirdScratchView``
- ``LyrebirdScratchModel``
@@ -0,0 +1,288 @@
// LyrebirdScratchMenuController.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import UniformTypeIdentifiers
import LyrebirdSynth
import LyrebirdLiveCompile
/// Builds and installs the macOS application menu bar for a live-coding host
/// driven by a `LyrebirdScratchModel`. Owns the action targets so menu items
/// stay wired for the lifetime of the controller.
@MainActor
public final class LyrebirdScratchMenuController: NSObject {
public let model: LyrebirdScratchModel
public init(model: LyrebirdScratchModel) {
self.model = model
}
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
/// Help) and assign it to `NSApplication.shared.mainMenu`.
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
let mainMenu: NSMenu = NSMenu()
mainMenu.addItem(appMenuItem(appName: appName))
mainMenu.addItem(fileMenuItem())
mainMenu.addItem(editMenuItem())
mainMenu.addItem(runMenuItem())
mainMenu.addItem(viewMenuItem())
mainMenu.addItem(windowMenuItem())
NSApplication.shared.mainMenu = mainMenu
}
// MARK: App menu
private func appMenuItem(appName: String) -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: appName)
menu.addItem(NSMenuItem(title: "About \(appName)",
action: #selector(NSApplication.orderFrontStandardAboutPanel(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
let services: NSMenuItem = NSMenuItem(title: "Services", action: nil, keyEquivalent: "")
let servicesMenu: NSMenu = NSMenu(title: "Services")
services.submenu = servicesMenu
NSApplication.shared.servicesMenu = servicesMenu
menu.addItem(services)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Hide \(appName)",
action: #selector(NSApplication.hide(_:)),
keyEquivalent: "h"))
let hideOthers: NSMenuItem = NSMenuItem(title: "Hide Others",
action: #selector(NSApplication.hideOtherApplications(_:)),
keyEquivalent: "h")
hideOthers.keyEquivalentModifierMask = [.command, .option]
menu.addItem(hideOthers)
menu.addItem(NSMenuItem(title: "Show All",
action: #selector(NSApplication.unhideAllApplications(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit \(appName)",
action: #selector(NSApplication.terminate(_:)),
keyEquivalent: "q"))
item.submenu = menu
return item
}
// MARK: File menu
private func fileMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "File")
menu.addItem(target(NSMenuItem(title: "New",
action: #selector(newSnippet(_:)),
keyEquivalent: "n")))
menu.addItem(target(NSMenuItem(title: "Open…",
action: #selector(openSnippet(_:)),
keyEquivalent: "o")))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Save",
action: #selector(saveSnippet(_:)),
keyEquivalent: "s")))
let saveAs: NSMenuItem = NSMenuItem(title: "Save As…",
action: #selector(saveSnippetAs(_:)),
keyEquivalent: "s")
saveAs.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(saveAs))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Close",
action: #selector(NSWindow.performClose(_:)),
keyEquivalent: "w"))
item.submenu = menu
return item
}
// MARK: Edit menu — wires to the first responder so NSTextView gets it
private func editMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Edit")
menu.addItem(NSMenuItem(title: "Undo",
action: Selector(("undo:")),
keyEquivalent: "z"))
let redo: NSMenuItem = NSMenuItem(title: "Redo",
action: Selector(("redo:")),
keyEquivalent: "z")
redo.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(redo)
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Cut",
action: #selector(NSText.cut(_:)),
keyEquivalent: "x"))
menu.addItem(NSMenuItem(title: "Copy",
action: #selector(NSText.copy(_:)),
keyEquivalent: "c"))
menu.addItem(NSMenuItem(title: "Paste",
action: #selector(NSText.paste(_:)),
keyEquivalent: "v"))
menu.addItem(NSMenuItem(title: "Select All",
action: #selector(NSText.selectAll(_:)),
keyEquivalent: "a"))
menu.addItem(NSMenuItem.separator())
let find: NSMenuItem = NSMenuItem(title: "Find…",
action: #selector(NSTextView.performFindPanelAction(_:)),
keyEquivalent: "f")
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
menu.addItem(find)
item.submenu = menu
return item
}
// MARK: Run menu
private func runMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Run")
menu.addItem(target(NSMenuItem(title: "Run",
action: #selector(runSnippet(_:)),
keyEquivalent: "\r")))
let runAdd: NSMenuItem = NSMenuItem(title: "Run Additive",
action: #selector(runSnippetAdditive(_:)),
keyEquivalent: "\r")
runAdd.keyEquivalentModifierMask = [.command, .shift]
menu.addItem(target(runAdd))
menu.addItem(NSMenuItem.separator())
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
action: #selector(clearSynths(_:)),
keyEquivalent: "k")))
item.submenu = menu
return item
}
// MARK: View menu
private func viewMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "View")
let wrap: NSMenuItem = target(NSMenuItem(title: "Wrap Lines",
action: #selector(toggleWrap(_:)),
keyEquivalent: "l"))
wrap.keyEquivalentModifierMask = [.command, .option]
menu.addItem(wrap)
menu.addItem(NSMenuItem.separator())
let inc: NSMenuItem = target(NSMenuItem(title: "Increase Font Size",
action: #selector(increaseFontSize(_:)),
keyEquivalent: "+"))
menu.addItem(inc)
menu.addItem(target(NSMenuItem(title: "Decrease Font Size",
action: #selector(decreaseFontSize(_:)),
keyEquivalent: "-")))
menu.addItem(target(NSMenuItem(title: "Reset Font Size",
action: #selector(resetFontSize(_:)),
keyEquivalent: "0")))
item.submenu = menu
return item
}
// MARK: Window menu
private func windowMenuItem() -> NSMenuItem {
let item: NSMenuItem = NSMenuItem()
let menu: NSMenu = NSMenu(title: "Window")
menu.addItem(NSMenuItem(title: "Minimize",
action: #selector(NSWindow.performMiniaturize(_:)),
keyEquivalent: "m"))
menu.addItem(NSMenuItem(title: "Zoom",
action: #selector(NSWindow.performZoom(_:)),
keyEquivalent: ""))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Bring All to Front",
action: #selector(NSApplication.arrangeInFront(_:)),
keyEquivalent: ""))
item.submenu = menu
NSApplication.shared.windowsMenu = menu
return item
}
// MARK: - Action targets
private func target(_ item: NSMenuItem) -> NSMenuItem {
item.target = self
return item
}
@objc private func newSnippet(_ sender: Any?) {
model.text = LyrebirdScratchModel.defaultPlaceholder
}
@objc private func openSnippet(_ sender: Any?) {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.message = "Open a Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.load(from: url)
} catch {
model.reportLoadError(url: url, error: error)
}
}
}
@objc private func saveSnippet(_ sender: Any?) {
if let url: URL = model.documentURL {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
return
}
saveSnippetAs(sender)
}
@objc private func saveSnippetAs(_ sender: Any?) {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.swiftSource]
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
panel.message = "Save Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
}
}
@objc private func runSnippet(_ sender: Any?) {
Task { @MainActor in _ = await model.run(additive: false) }
}
@objc private func runSnippetAdditive(_ sender: Any?) {
Task { @MainActor in _ = await model.run(additive: true) }
}
@objc private func clearSynths(_ sender: Any?) {
model.clearTracked()
}
@objc private func toggleWrap(_ sender: Any?) {
model.toggleWrapsLines()
if let item: NSMenuItem = sender as? NSMenuItem {
item.state = model.wrapsLines ? .on : .off
}
}
@objc private func increaseFontSize(_ sender: Any?) {
model.bumpFontSize(by: 1)
}
@objc private func decreaseFontSize(_ sender: Any?) {
model.bumpFontSize(by: -1)
}
@objc private func resetFontSize(_ sender: Any?) {
model.resetFontSize()
}
}
#endif
@@ -0,0 +1,227 @@
// LyrebirdScratchModel.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 145
//
// Backing model for `LyrebirdScratchView`. Owns the editable snippet text, the
// most recent compile result, and the host `LiveSession`. Pulled out of the
// view so logic can be exercised without instantiating SwiftUI.
//
// macOS only — wraps `LyrebirdLiveCompile`, which itself is macOS-only.
#if os(macOS)
import Foundation
import CoreGraphics
import LyrebirdSynth
import LyrebirdLiveCompile
/// Observable backing model for `LyrebirdScratchView`.
///
/// Drives one live-coding editor pane. `run(additive:)` awaits
/// `LiveSession.compileAndRunAsync` so the swiftc invocation runs off the main
/// actor and the editor stays responsive. ``isCompiling`` flips around the
/// await so SwiftUI can disable the Run buttons and surface a "Compiling…"
/// status while the dylib build is in flight.
@MainActor
public final class LyrebirdScratchModel: ObservableObject {
/// Default placeholder text loaded into a fresh model. Walks the user
/// through the two keyboard shortcuts and the in-snippet API surface.
/// `nonisolated` so callers in a non-main context (e.g. SwiftUI init's
/// default-argument evaluation, which is not implicitly main-actor) can
/// reference it without a Swift 6 isolation diagnostic.
public nonisolated static let defaultPlaceholder: String = """
// ⌘↩ — compile + run (removes synths from the previous run first).
// ⌘⇧↩ — additive run (keep previously played synths around).
//
// The snippet body has `context: SnippetContext` in scope.
// `context.engine` → the host `SynthesisEngine`.
// `context.play(synth)` → adds a `Synthesizer` and tracks it for cleanup.
// `context.reportMessage(_)`→ writes back to the host (useful for `print`-style probes).
class SineSynth: SynthesizerBase {
override func build() {
let sine = OscSin.Audio(freq: 440, mul: 0.15)
let stereo = Pan2(input: sine, pan: 0)
output(bus: 0, source: stereo)
}
}
let synth = SineSynth()
_ = context.play(synth)
context.reportMessage("playing 440 Hz sine — stereo, centered")
"""
/// Current editor text. View binds to this; user edits flow back here via
/// the `NSTextView` delegate inside `LyrebirdScratchView`.
@Published public var text: String
/// Parsed swiftc diagnostics from the last `run(additive:)` invocation.
/// Empty when the last run compiled cleanly or has not yet been attempted.
@Published public private(set) var diagnostics: [Diagnostic] = []
/// Single-line human-readable status line shown beneath the editor.
/// Updated by `run(additive:)` and `clearTracked()`.
@Published public private(set) var statusMessage: String = ""
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
/// `clearTracked` call so the toolbar can show the count without polling.
@Published public private(set) var trackedSynthCount: Int
/// `true` while a `run(additive:)` invocation is awaiting the background
/// swiftc compile. View code disables Run / Run Additive buttons against
/// this so a second compile cannot stack on top of a still-running one.
@Published public private(set) var isCompiling: Bool = false
/// URL of the file the editor text was last saved to or loaded from. `nil`
/// when the editor holds unsaved scratch content. The view uses this to
/// distinguish a silent overwrite (⌘S) from a Save As… prompt.
@Published public private(set) var documentURL: URL?
/// Editor font size in points. Clamped to `[minFontSize, maxFontSize]`.
@Published public var fontSize: CGFloat = 13
/// When `true`, lines wrap at the editor's right edge instead of scrolling
/// horizontally.
@Published public var wrapsLines: Bool = true
public let session: LiveSession
public nonisolated static let minFontSize: CGFloat = 9
public nonisolated static let maxFontSize: CGFloat = 32
public nonisolated static let defaultFontSize: CGFloat = 13
public func bumpFontSize(by delta: CGFloat) {
fontSize = max(LyrebirdScratchModel.minFontSize,
min(LyrebirdScratchModel.maxFontSize, fontSize + delta))
}
public func resetFontSize() {
fontSize = LyrebirdScratchModel.defaultFontSize
}
public func toggleWrapsLines() {
wrapsLines.toggle()
}
/// - Parameters:
/// - session: Host `LiveSession` the model forwards compile + cleanup
/// calls to. Retained for the model's lifetime.
/// - initialText: Seed text loaded into `text`. Defaults to
/// ``defaultPlaceholder``.
public init(
session: LiveSession,
initialText: String = LyrebirdScratchModel.defaultPlaceholder
) {
self.session = session
self.text = initialText
self.trackedSynthCount = session.trackedSynthCount
}
/// Compile and execute the current `text`. Updates `diagnostics`,
/// `statusMessage`, `trackedSynthCount`, and ``isCompiling``.
///
/// Awaits `LiveSession.compileAndRunAsync`, which runs swiftc on a
/// `Task.detached`. The view's Run / Run Additive buttons bind to
/// ``isCompiling`` and stay disabled until this method returns.
///
/// - Parameter additive: When `false`, the session removes every
/// previously tracked synth before running. When `true`, prior synths
/// stay in the engine (⌘⇧↩ in the view).
/// - Returns: `true` when the snippet compiled and its entry returned
/// without throwing; `false` otherwise.
@discardableResult
public func run(additive: Bool) async -> Bool {
guard !isCompiling else { return false }
let body: String = text
diagnostics = []
statusMessage = "Compiling…"
isCompiling = true
defer {
isCompiling = false
trackedSynthCount = session.trackedSynthCount
}
do {
try await session.compileAndRunAsync(body, additive: additive)
let mode: String = additive ? "additive" : "replaced"
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
return true
} catch let sessionError as LiveSessionError {
switch sessionError {
case .snippetCompileFailed(let diags, let underlying):
if diags.isEmpty {
diagnostics = [Diagnostic(
line: nil,
column: 0,
severity: .error,
message: "\(underlying)",
rawLine: 0
)]
statusMessage = "Compile failed — see diagnostics below."
} else {
diagnostics = diags
let plural: String = diags.count == 1 ? "" : "s"
statusMessage = "Compile failed — \(diags.count) diagnostic\(plural)."
}
case .compilerError(let underlying):
statusMessage = "Compiler error: \(underlying)"
}
return false
} catch {
statusMessage = "Error: \(error)"
return false
}
}
/// Forward to `LiveSession.clearTracked()` and refresh `trackedSynthCount`.
public func clearTracked() {
session.clearTracked()
trackedSynthCount = session.trackedSynthCount
statusMessage = "Cleared tracked synths."
}
// MARK: - Snippet save / load
/// Replace `text` with the UTF-8 contents at `url`, set ``documentURL``
/// for subsequent saves, and refresh the status line.
///
/// - Parameter url: File to read. Caller (view) is responsible for the
/// `NSOpenPanel` UI; this method does the IO.
public func load(from url: URL) throws {
let loaded: String = try String(contentsOf: url, encoding: .utf8)
text = loaded
documentURL = url
diagnostics = []
statusMessage = "Loaded \(url.lastPathComponent)."
}
/// Write `text` to `url` as UTF-8, set ``documentURL``, refresh status.
///
/// - Parameter url: Destination. Overwrites if present. Caller drives the
/// `NSSavePanel` UI.
public func save(to url: URL) throws {
try text.write(to: url, atomically: true, encoding: .utf8)
documentURL = url
statusMessage = "Saved \(url.lastPathComponent)."
}
/// Surface a load failure on the status line without throwing across the
/// view layer. Called by the view after `NSOpenPanel` returned a URL that
/// `load(from:)` rejected.
public func reportLoadError(url: URL, error: Error) {
statusMessage = "Load failed (\(url.lastPathComponent)): \(error.localizedDescription)"
}
/// Surface a save failure on the status line without throwing across the
/// view layer. Called by the view after `NSSavePanel` returned a URL that
/// `save(to:)` rejected.
public func reportSaveError(url: URL, error: Error) {
statusMessage = "Save failed (\(url.lastPathComponent)): \(error.localizedDescription)"
}
}
#endif
@@ -0,0 +1,409 @@
// LyrebirdScratchView.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 145
//
// `LyrebirdScratchView` — SwiftUI scratchpad editor for live-coded snippets.
// Wraps an `NSTextView` for the editor surface, drives a `LyrebirdScratchModel`
// for compile state, and surfaces parsed `Diagnostic`s in a scrollable list
// below the editor. macOS-only; iOS hosting is deferred (no swiftc on device).
#if os(macOS)
import AppKit
import SwiftUI
import UniformTypeIdentifiers
import LyrebirdSynth
import LyrebirdLiveCompile
/// SwiftUI scratchpad for live-compiled Lyrebird snippets.
///
/// Pair with a `LiveSession` that owns the audio engine, drop the view into a
/// `LyrebirdWindow`, and ⌘↩ replaces the prior run while ⌘⇧↩ adds to it.
/// Diagnostics from a failed compile are listed under the editor with the
/// user's snippet-row coordinates already mapped by `DiagnosticParser`.
///
/// - Parameters:
/// - session: Host `LiveSession` owning the `SynthesisEngine`. Forwarded
/// into the backing ``LyrebirdScratchModel``.
/// - initialText: Seed text loaded into the editor. Defaults to
/// ``LyrebirdScratchModel/defaultPlaceholder``.
///
/// ## Hosting
///
/// ```swift
/// import LyrebirdUI // LyrebirdWindow
/// import LyrebirdLiveCompile // LiveSession
/// import LyrebirdLiveCompileUI // LyrebirdScratchView
///
/// let session = LiveSession(engine: engine)
/// let win = LyrebirdWindow(title: "Lyrebird Scratch", width: 640, height: 480)
/// win.open { LyrebirdScratchView(session: session) }
/// ```
///
/// ## Threading
///
/// All UI work is `@MainActor`-isolated. The Run / Run Additive buttons
/// dispatch a `Task` that awaits `LyrebirdScratchModel.run(additive:)`, which
/// itself awaits `LiveSession.compileAndRunAsync`. The swiftc subprocess runs
/// on a background `Task.detached`; the snippet entry then resumes on the
/// main actor so it can touch UI-side state. Both Run buttons disable while
/// ``LyrebirdScratchModel/isCompiling`` is `true`.
@MainActor
public struct LyrebirdScratchView: View {
@StateObject private var model: LyrebirdScratchModel
@State private var engineTick: Int = 0
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
///
/// - Parameters:
/// - session: Host live-coding session owning the audio engine. The view
/// does not retain a reference of its own; the wrapped model does.
/// - initialText: Seed text loaded into the editor. Defaults to the
/// onboarding placeholder explaining the two keyboard shortcuts.
public init(
session: LiveSession,
initialText: String = LyrebirdScratchModel.defaultPlaceholder
) {
_model = StateObject(wrappedValue: LyrebirdScratchModel(
session: session,
initialText: initialText
))
}
/// Construct against a pre-built model. Lets tests or alternate hosts
/// inject a model with custom session, text, or pre-populated state.
public init(model: LyrebirdScratchModel) {
_model = StateObject(wrappedValue: model)
}
public var body: some View {
VStack(spacing: 0) {
engineBar
Divider()
ScratchEditor(
text: Binding(
get: { model.text },
set: { model.text = $0 }
),
fontSize: model.fontSize,
wrapsLines: model.wrapsLines
)
.frame(minHeight: editorMinHeight)
Divider()
statusBar
if !model.diagnostics.isEmpty {
Divider()
diagnosticsList
}
}
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
.onReceive(engineRefresh) { _ in engineTick &+= 1 }
}
private var engineBar: some View {
let engine: SynthesisEngine = model.session.engine
return HStack(spacing: toolbarSpacing) {
Circle()
.fill(engine.isRunning ? Color.green : Color.red)
.frame(width: engineDotSize, height: engineDotSize)
Text(engine.isRunning ? "engine running" : "engine stopped")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer()
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
Spacer().frame(width: 8)
Text("synths: \(model.trackedSynthCount)")
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
}
.padding(.horizontal, toolbarPadding)
.padding(.vertical, 6)
.id(engineTick)
}
private func formatCPU(_ value: Double) -> String {
String(format: "%.0f%%", value * 100)
}
public func runSnippet(additive: Bool) {
Task { @MainActor in
_ = await model.run(additive: additive)
}
}
public func presentOpenPanel() {
let panel: NSOpenPanel = NSOpenPanel()
panel.allowedContentTypes = [.swiftSource]
panel.allowsMultipleSelection = false
panel.canChooseDirectories = false
panel.message = "Open a Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.load(from: url)
} catch {
model.reportLoadError(url: url, error: error)
}
}
}
public func saveOrPromptForLocation() {
if let url: URL = model.documentURL {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
return
}
presentSavePanel()
}
public func presentSavePanel() {
let panel: NSSavePanel = NSSavePanel()
panel.allowedContentTypes = [.swiftSource]
panel.nameFieldStringValue = model.documentURL?.lastPathComponent ?? "snippet.swift"
panel.message = "Save Lyrebird snippet"
if panel.runModal() == .OK, let url: URL = panel.url {
do {
try model.save(to: url)
} catch {
model.reportSaveError(url: url, error: error)
}
}
}
private var statusBar: some View {
HStack {
Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.lineLimit(1)
.truncationMode(.middle)
Spacer()
}
.padding(.horizontal, statusHPad)
.padding(.vertical, statusVPad)
}
private var diagnosticsList: some View {
ScrollView {
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
DiagnosticRow(diagnostic: diag)
}
}
.padding(diagnosticListPadding)
}
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
}
// Layout constants — all in points. Kept private; tuned to match
// LyrebirdEngineStatusView's visual density.
private let scratchMinWidth: CGFloat = 520
private let scratchMinHeight: CGFloat = 420
private let editorMinHeight: CGFloat = 240
private let toolbarSpacing: CGFloat = 8
private let toolbarPadding: CGFloat = 8
private let toolbarDividerHeight: CGFloat = 18
private let statusHPad: CGFloat = 8
private let statusVPad: CGFloat = 4
private let diagnosticRowSpacing: CGFloat = 2
private let diagnosticListPadding: CGFloat = 8
private let diagnosticsMinHeight: CGFloat = 80
private let diagnosticsMaxHeight: CGFloat = 200
private let engineDotSize: CGFloat = 8
}
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
/// message in a compact monospaced row.
private struct DiagnosticRow: View {
let diagnostic: Diagnostic
var body: some View {
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
Text(locationString)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(.secondary)
.frame(minWidth: locationColumnWidth, alignment: .leading)
Text(diagnostic.severity.rawValue)
.font(.system(.caption, design: .monospaced))
.foregroundStyle(color(for: diagnostic.severity))
.frame(minWidth: severityColumnWidth, alignment: .leading)
Text(diagnostic.message)
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
Spacer(minLength: 0)
}
}
private var locationString: String {
if let line: Int = diagnostic.line {
return "\(line):\(diagnostic.column)"
}
return "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
}
private func color(for severity: DiagnosticSeverity) -> Color {
switch severity {
case .error: return .red
case .warning: return .orange
case .note: return .secondary
}
}
private let rowGutter: CGFloat = 8
private let locationColumnWidth: CGFloat = 80
private let severityColumnWidth: CGFloat = 56
}
/// `NSViewRepresentable` wrapping a vanilla `NSTextView` inside an
/// `NSScrollView`. Monospaced 13 pt, plain text, no smart-quote / dash /
/// auto-correct interference — matches the editor expectations of someone
/// typing Swift code.
private struct ScratchEditor: NSViewRepresentable {
@Binding var text: String
let fontSize: CGFloat
let wrapsLines: Bool
final class Coordinator: NSObject, NSTextViewDelegate {
var parent: ScratchEditor
init(_ parent: ScratchEditor) { self.parent = parent }
func textDidChange(_ notification: Notification) {
guard let tv: NSTextView = notification.object as? NSTextView else { return }
parent.text = tv.string
}
}
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll: NSScrollView = NSTextView.scrollableTextView()
if let tv: NSTextView = scroll.documentView as? NSTextView {
configure(tv, in: scroll, with: context.coordinator)
}
return scroll
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
context.coordinator.parent = self
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
if fontChanged {
tv.font = font
}
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
tv.defaultParagraphStyle = paragraphStyle
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
applyWrap(to: tv, in: scroll)
if tv.string != text {
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
} else if fontChanged {
reapplyAttrs(to: tv, font: font, paragraph: paragraphStyle)
}
}
private func makeAttrs(font: NSFont, paragraph: NSParagraphStyle) -> [NSAttributedString.Key: Any] {
[
.font: font,
.foregroundColor: NSColor.labelColor,
.paragraphStyle: paragraph,
]
}
private func makeParagraphStyle(for font: NSFont) -> NSParagraphStyle {
let style: NSMutableParagraphStyle = NSMutableParagraphStyle()
let spaceAdvance: CGFloat = (" " as NSString).size(withAttributes: [.font: font]).width
let tabWidth: CGFloat = spaceAdvance * tabSpaces
style.tabStops = []
style.defaultTabInterval = tabWidth
return style
}
private func replaceText(in tv: NSTextView,
with newText: String,
font: NSFont,
paragraph: NSParagraphStyle) {
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
let attributed: NSAttributedString = NSAttributedString(string: newText, attributes: attrs)
tv.textStorage?.setAttributedString(attributed)
tv.typingAttributes = attrs
}
private func reapplyAttrs(to tv: NSTextView,
font: NSFont,
paragraph: NSParagraphStyle) {
guard let storage: NSTextStorage = tv.textStorage else { return }
let attrs: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph)
let range: NSRange = NSRange(location: 0, length: storage.length)
storage.setAttributes(attrs, range: range)
tv.typingAttributes = attrs
}
private func applyWrap(to tv: NSTextView, in scroll: NSScrollView) {
guard let container: NSTextContainer = tv.textContainer else { return }
if wrapsLines {
scroll.hasHorizontalScroller = false
tv.isHorizontallyResizable = false
tv.autoresizingMask = [.width]
container.widthTracksTextView = true
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
} else {
scroll.hasHorizontalScroller = true
tv.isHorizontallyResizable = true
tv.autoresizingMask = []
container.widthTracksTextView = false
container.containerSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude,
height: CGFloat.greatestFiniteMagnitude)
}
tv.needsDisplay = true
}
private func configure(_ tv: NSTextView, in scroll: NSScrollView, with coordinator: Coordinator) {
tv.delegate = coordinator
let editorFont: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
tv.font = editorFont
tv.isRichText = false
tv.isAutomaticQuoteSubstitutionEnabled = false
tv.isAutomaticDashSubstitutionEnabled = false
tv.isAutomaticTextReplacementEnabled = false
tv.isAutomaticSpellingCorrectionEnabled = false
tv.smartInsertDeleteEnabled = false
tv.allowsUndo = true
tv.usesFindBar = true
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
tv.drawsBackground = true
tv.backgroundColor = .textBackgroundColor
tv.textColor = .labelColor
tv.insertionPointColor = .labelColor
tv.selectedTextAttributes = [
.backgroundColor: NSColor.selectedTextBackgroundColor,
.foregroundColor: NSColor.selectedTextColor,
]
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: editorFont)
tv.defaultParagraphStyle = paragraphStyle
tv.typingAttributes = makeAttrs(font: editorFont, paragraph: paragraphStyle)
applyWrap(to: tv, in: scroll)
replaceText(in: tv, with: text, font: editorFont, paragraph: paragraphStyle)
}
private let editorInset: CGFloat = 6
private let tabSpaces: CGFloat = 4
}
#endif
@@ -0,0 +1,145 @@
// ScratchLineNumberRuler.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// LyrebirdUI/LiveCompile — Phase 147
//
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
// Reads laid-out glyph rects from the text view's layout manager and writes one
// 1-based line label per visible line into the ruler's bounds.
#if os(macOS)
import AppKit
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
/// invalidates itself on every text edit and frame change.
final class ScratchLineNumberRuler: NSRulerView {
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
/// swaps the text view performs after attachment.
private weak var textView: NSTextView?
init(scrollView: NSScrollView, textView: NSTextView) {
self.textView = textView
super.init(scrollView: scrollView, orientation: .verticalRuler)
self.clientView = textView
self.ruleThickness = gutterWidth
let center: NotificationCenter = NotificationCenter.default
center.addObserver(self,
selector: #selector(invalidateForChange(_:)),
name: NSText.didChangeNotification,
object: textView)
center.addObserver(self,
selector: #selector(invalidateForChange(_:)),
name: NSView.frameDidChangeNotification,
object: textView)
let clipView: NSClipView = scrollView.contentView
clipView.postsBoundsChangedNotifications = true
center.addObserver(self,
selector: #selector(invalidateForChange(_:)),
name: NSView.boundsDidChangeNotification,
object: clipView)
}
required init(coder: NSCoder) {
fatalError("ScratchLineNumberRuler does not support NSCoder init")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func invalidateForChange(_ note: Notification) {
needsDisplay = true
}
override func drawHashMarksAndLabels(in rect: NSRect) {
guard let textView: NSTextView,
let layoutManager: NSLayoutManager = textView.layoutManager,
let textContainer: NSTextContainer = textView.textContainer else {
return
}
gutterFillColor.setFill()
rect.fill()
gutterDividerColor.setStroke()
let dividerPath: NSBezierPath = NSBezierPath()
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
dividerPath.lineWidth = 1
dividerPath.stroke()
let nsText: NSString = textView.string as NSString
let totalLength: Int = nsText.length
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
let inset: CGFloat = textView.textContainerInset.height
let attrs: [NSAttributedString.Key: Any] = [
.font: rulerFont,
.foregroundColor: gutterTextColor,
]
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
var cursor: Int = charRange.location
let visibleEnd: Int = NSMaxRange(charRange)
while cursor < visibleEnd && cursor <= totalLength {
// `lineRange(for:)` advances cursor by the full line including its
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
// handled by Foundation.
let probeLength: Int = (cursor == totalLength) ? 0 : 0
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
actualCharacterRange: nil)
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
in: textContainer)
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
let label: NSString = "\(lineIndex)" as NSString
let size: CGSize = label.size(withAttributes: attrs)
let drawPoint: NSPoint = NSPoint(
x: bounds.maxX - size.width - rightInset,
y: yInView + ((usedRect.height - size.height) * 0.5)
)
label.draw(at: drawPoint, withAttributes: attrs)
let advance: Int = NSMaxRange(lineRange)
if advance <= cursor { break } // defensive — empty trailing line
cursor = advance
lineIndex += 1
}
}
// 1-based line number of the character at `loc`. Delegates to
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
// that precedes the first visible line.
private func lineNumber(at loc: Int, in text: NSString) -> Int {
if loc <= 0 { return 1 }
var line: Int = 1
let prefixRange: NSRange = NSRange(location: 0, length: loc)
text.enumerateSubstrings(in: prefixRange,
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
line += 1
}
return line
}
private let gutterWidth: CGFloat = 40
private let rightInset: CGFloat = 6
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
private let rulerFontSize: CGFloat = 11
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
private let gutterDividerColor: NSColor = NSColor.separatorColor
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
private var rulerFont: NSFont {
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
}
}
#endif