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