// 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