// LyrebirdScratchView.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT // LyrebirdUI/LiveCompile // // `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 commands (in the /// menu bar built by ``LyrebirdScratchMenuController``) 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. The menu controller gates the Run commands on /// ``ReevalState/canEvaluate`` (disabled while a compile is in flight or the /// buffer is empty); `run(additive:)` additionally guards re-entrancy on /// ``LyrebirdScratchModel/isCompiling``. @MainActor public struct LyrebirdScratchView: View { @StateObject private var model: LyrebirdScratchModel /// Snapshot of the engine's non-`@Published` live stats, refreshed on the /// heartbeat. Bound in place by the status rows — deliberately NOT via /// `.id(tick)`, which forces a subview teardown/rebuild every tick and churns /// the surrounding layout, nudging the editor's scroll position ("screen /// jumping" while scrolled down). Updating an `@State` value re-renders the /// labels in place with stable identity, so the layout stays put. @State private var stats: EngineStats = EngineStats() private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect() /// Non-`@Published` engine values polled on the heartbeat. private struct EngineStats: Equatable { var isRunning: Bool = false var averageCPU: Double = 0 var peakCPU: Double = 0 var synthesizerCount: Int = 0 var groupCount: Int = 0 } private func snapshotStats() -> EngineStats { let e: SynthesisEngine = model.session.engine return EngineStats( isRunning: e.isRunning, averageCPU: e.averageCPU, peakCPU: e.peakCPU, synthesizerCount: e.synthesizerCount, groupCount: e.groupCount ) } /// 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 { HStack(spacing: 0) { mainColumn Divider() consolePanel .frame(width: consoleWidth) } .frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight) .onAppear { // Warm the module cache in the background so the first ⌘↩ is ~0.1 s // instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build. // Idempotent — safe if `onAppear` fires again. model.session.prewarm() } .onReceive(engineRefresh) { _ in let next: EngineStats = snapshotStats() if next != stats { stats = next } // Settle a `.queued` readiness badge once its swap has fired. model.refreshQueuedState() } } /// The editor column: engine controls, editor, status, engine panel. private var mainColumn: some View { VStack(spacing: 0) { engineBar if let hint: String = model.snippetMemoryHint { Divider() snippetMemoryBanner(hint) } Divider() ScratchEditor( text: Binding( get: { model.text }, set: { model.text = $0 } ), fontSize: model.fontSize, wrapsLines: model.wrapsLines, requestCompletions: { line, character in await model.completionItems(line: line, character: character) }, onSelectionChanged: { selected in model.updateSelection(selected) } ) .frame(minHeight: editorMinHeight) Divider() statusBar Divider() enginePanel } } /// Always-open right-side console: report messages, errors, and run notices, /// oldest first, auto-scrolled to the newest. private var consolePanel: some View { VStack(spacing: 0) { HStack { Text("Console") .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) Spacer() Button("Clear") { model.clearConsole() } .buttonStyle(.plain) .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) .disabled(model.consoleEntries.isEmpty) } .padding(.horizontal, statusHPad) .padding(.vertical, statusVPad) Divider() ScrollViewReader { proxy in ScrollView { LazyVStack(alignment: .leading, spacing: 2) { ForEach(model.consoleEntries) { entry in ConsoleRow(entry: entry) } Color.clear.frame(height: 1).id(consoleBottomID) } .padding(diagnosticListPadding) .frame(maxWidth: .infinity, alignment: .leading) } .onChange(of: model.consoleEntries.count) { _, _ in proxy.scrollTo(consoleBottomID, anchor: .bottom) } } } } private var engineBar: some View { let engine: SynthesisEngine = model.session.engine return HStack(spacing: toolbarSpacing) { Button { model.toggleEngine() stats = snapshotStats() } label: { HStack(spacing: reevalBadgeSpacing) { Circle() .fill(stats.isRunning ? Color.green : Color.red) .frame(width: engineDotSize, height: engineDotSize) Text(stats.isRunning ? "engine running" : "▶ start engine") .font(.system(.caption, design: .monospaced)) .foregroundStyle(stats.isRunning ? Color.secondary : Color.primary) } } .buttonStyle(.plain) .help(stats.isRunning ? "Stop the audio engine" : "Start the audio engine") Spacer() Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(stats.averageCPU))") .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) Spacer().frame(width: 8) Text("synths: \(model.trackedSynthCount)") .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) Spacer().frame(width: 8) Text("snippets: \(model.loadedSnippetCount)") .font(.system(.caption, design: .monospaced)) .foregroundStyle(model.snippetMemoryHint == nil ? Color.secondary : Color.orange) .help("Compiled snippet dylibs mapped this session. They can't be " + "unloaded without restarting (Graph DSL mode maps none).") } .padding(.horizontal, toolbarPadding) .padding(.vertical, 6) } /// Warning strip shown once mapped snippet dylibs cross the restart /// threshold — the user-facing safety valve over the by-design leak. private func snippetMemoryBanner(_ hint: String) -> some View { HStack(spacing: reevalBadgeSpacing) { Image(systemName: "exclamationmark.triangle.fill") .foregroundStyle(.orange) Text(hint) .font(.system(.caption, design: .monospaced)) .foregroundStyle(.primary) .fixedSize(horizontal: false, vertical: true) Spacer(minLength: 0) } .padding(.horizontal, toolbarPadding) .padding(.vertical, 6) .background(Color.orange.opacity(0.12)) } /// Bottom engine panel: a live output oscilloscope plus a compact status /// readout (sample rate, CPU average/peak meters, node counts). The status /// text refreshes in place off the ``stats`` snapshot — no `.id(tick)` /// teardown, so the surrounding layout (and the editor's scroll) stays put. private var enginePanel: some View { VStack(alignment: .leading, spacing: 6) { if let scope: ScopeCapture = model.session.scope { ScratchScopeView(capture: scope) .frame(height: scopeHeight) } engineStatusRow } .padding(.horizontal, toolbarPadding) .padding(.vertical, 6) } /// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts. private var engineStatusRow: some View { let engine: SynthesisEngine = model.session.engine return VStack(alignment: .leading, spacing: 6) { HStack { Text("Engine") .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) Spacer() Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch") .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) } cpuMeter(label: "CPU avg", value: stats.averageCPU) cpuMeter(label: "CPU peak", value: stats.peakCPU) Text("synths \(stats.synthesizerCount) · groups \(stats.groupCount) · snippets \(model.loadedSnippetCount)") .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) } } /// One labelled CPU meter bar. `value` is a fraction of one block period /// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun. private func cpuMeter(label: String, value: Double) -> some View { let clamped: CGFloat = CGFloat(min(max(value, 0), 1)) let fill: Color = value > cpuMeterCriticalThreshold ? .red : (value > cpuMeterWarningThreshold ? .orange : .green) return HStack(spacing: 6) { Text(label) .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) .frame(width: cpuLabelWidth, alignment: .leading) GeometryReader { geo in ZStack(alignment: .leading) { RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15)) RoundedRectangle(cornerRadius: 2).fill(fill) .frame(width: geo.size.width * clamped) } } .frame(height: meterHeight) Text(formatCPU(value)) .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) .frame(width: cpuValueWidth, alignment: .trailing) } } private func formatCPU(_ value: Double) -> String { String(format: "%.0f%%", value * 100) } public func runSnippet(additive: Bool) { Task { @MainActor in _ = await model.run(additive: additive) } } /// Evaluate just the current selection, additively. No-op when nothing is /// selected. public func runSelection() { Task { @MainActor in _ = await model.runSelection() } } 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(spacing: toolbarSpacing) { reevalBadge Text(model.statusMessage.isEmpty ? "Ready." : model.statusMessage) .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) .lineLimit(1) .truncationMode(.middle) Spacer() modePicker } .padding(.horizontal, statusHPad) .padding(.vertical, statusVPad) } /// Segmented toggle between the Swift-compile and instant graph-DSL /// evaluators. Routes through ``LyrebirdScratchModel/switchMode(to:)`` so the /// seed placeholder follows the mode. private var modePicker: some View { Picker("Mode", selection: Binding( get: { model.evalMode }, // Defer to the next main-actor tick: the Picker's `set` runs inside // SwiftUI's view-update pass, and `switchMode` mutates @Published // state ("Publishing changes from within view updates is not // allowed"). Scheduling it off the current pass avoids that. set: { newMode in Task { @MainActor in model.switchMode(to: newMode) } } )) { ForEach(ScratchEvalMode.allCases, id: \.self) { mode in Text(mode.title).tag(mode) } } .pickerStyle(.segmented) .labelsHidden() .fixedSize() .help("Swift compiles a snippet dylib; Graph DSL interprets a generator graph instantly, no compile.") } /// Re-evaluation readiness indicator: a colored dot + short label bound to /// ``LyrebirdScratchModel/reevalState``. Tells the user at a glance whether /// an eval is available (dirty), in flight (compiling), matches what is /// playing (clean), or failed. private var reevalBadge: some View { HStack(spacing: reevalBadgeSpacing) { Circle() .fill(reevalColor) .frame(width: engineDotSize, height: engineDotSize) Text(reevalLabel) .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) } .help(reevalHelp) } private var reevalColor: Color { switch model.reevalState { case .empty: return .secondary case .clean: return .green case .dirty: return .yellow case .compiling: return .blue case .queued: return .purple case .failed: return .red } } private var reevalLabel: String { switch model.reevalState { case .empty: return "empty" case .clean: return "clean" case .dirty: return "dirty" case .compiling: return "compiling" case .queued: return "queued" case .failed: return "failed" } } private var reevalHelp: String { switch model.reevalState { case .empty: return "Nothing to evaluate." case .clean: return "Buffer matches what is playing. ⌘↩ re-runs it." case .dirty: return "Edited since the last run — ⌘↩ to re-evaluate." case .compiling: return "Compiling…" case .queued(let beat): return String(format: "Compiled — swap lands on beat %.0f.", beat) case .failed(let count): let plural: String = count == 1 ? "" : "s" return count == 0 ? "Last run failed to compile." : "Last run failed — \(count) diagnostic\(plural)." } } // 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 private let reevalBadgeSpacing: CGFloat = 4 private let scopeHeight: CGFloat = 88 private let meterHeight: CGFloat = 6 private let consoleWidth: CGFloat = 300 private let consoleBottomID: String = "scratch.console.bottom" private let cpuLabelWidth: CGFloat = 58 private let cpuValueWidth: CGFloat = 40 /// CPU-meter fill turns orange above this fraction of one block period, red /// above ``cpuMeterCriticalThreshold``. private let cpuMeterWarningThreshold: Double = 0.5 private let cpuMeterCriticalThreshold: Double = 0.8 } /// One row in the diagnostics list. Renders `(line:col)`, severity, and /// message in a compact monospaced row. private struct ConsoleRow: View { let entry: ScratchConsoleEntry var body: some View { HStack(alignment: .firstTextBaseline, spacing: 6) { Text(glyph) .font(.system(.caption2, design: .monospaced)) .foregroundStyle(color) .frame(width: 14, alignment: .leading) if let location: String = entry.location { Text(location) .font(.system(.caption2, design: .monospaced)) .foregroundStyle(.secondary) } Text(entry.text) .font(.system(.caption, design: .monospaced)) .foregroundStyle(entry.kind == .error ? Color.primary : color) .textSelection(.enabled) .multilineTextAlignment(.leading) .fixedSize(horizontal: false, vertical: true) Spacer(minLength: 0) } } /// Leading glyph per kind: an X for errors, an arrow for messages, a dot for /// info notices. private var glyph: String { switch entry.kind { case .error: return "✗" case .message: return "›" case .info: return "·" } } private var color: Color { switch entry.kind { case .error: return .red case .message: return .cyan case .info: return .secondary } } } /// `NSTextView` subclass that fixes member-completion behavior. /// /// The default `rangeForUserCompletion` scans back over the whole dotted /// expression, so a candidate would *replace* the receiver rather than the /// partial word being typed. Completing a member after `context.` → `engine` /// would replace `context`; accepting an argument label after `OscSin.Audio(` /// → `freq:` would replace `OscSin.Audio`. The correct replace range is just /// the run of identifier characters immediately before the caret (empty after /// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there. /// Whether `c` (a UTF-16 code unit) is a Swift identifier character — /// ASCII letter, digit, or underscore. Sufficient for completion-range /// scanning; identifiers with non-ASCII scalars are not a concern here. private func isIdentifierCodeUnit(_ c: unichar) -> Bool { let underscore: unichar = 95 let zero: unichar = 48, nine: unichar = 57 let upperA: unichar = 65, upperZ: unichar = 90 let lowerA: unichar = 97, lowerZ: unichar = 122 return c == underscore || (c >= zero && c <= nine) || (c >= upperA && c <= upperZ) || (c >= lowerA && c <= lowerZ) } final class ScratchTextView: NSTextView { /// Invoked when the user asks for completion (the standard completion key — /// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then /// shows the completion window. Completion is manual only. var onManualComplete: (() -> Void)? override var rangeForUserCompletion: NSRange { let sel: NSRange = selectedRange() // Never replace across an actual selection — defer to the default. guard sel.length == 0, sel.location <= (string as NSString).length else { return super.rangeForUserCompletion } let ns: NSString = string as NSString var start: Int = sel.location while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) { start -= 1 } return NSRange(location: start, length: sel.location - start) } /// Intercept the built-in `complete:` command (bound to Esc / F5) so the /// candidates are fetched asynchronously first, then shown. Without this, /// pressing Esc would call the delegate with an empty (never-fetched) list. /// Everything else falls through to the normal editor commands. override func doCommand(by selector: Selector) { if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) { onManualComplete?() return } super.doCommand(by: selector) } /// Esc is delivered as `cancelOperation:` (not `complete:`) by the default /// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm — /// only F5 does. Route it here too so Esc invokes completion as documented. /// The completion window, once open, consumes Esc itself to dismiss, so this /// only fires when the window is closed. override func cancelOperation(_ sender: Any?) { onManualComplete?() } /// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``. /// `ScratchEditor.configure` reserves this as the text view's left inset so /// the gutter overlay doesn't cover the text. static let lineNumberGutterWidth: CGFloat = 40 } /// `NSViewRepresentable` wrapping a ``ScratchTextView`` 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 /// Async source of code-completion candidates for a zero-based user-space /// (line, UTF-16 character). Supplied by the view from the model. let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem] /// Called with the current selected substring whenever the selection /// changes (empty when nothing is selected). Drives "Run Selection". let onSelectionChanged: @MainActor (String) -> Void @MainActor final class Coordinator: NSObject, NSTextViewDelegate { var parent: ScratchEditor /// Candidate insert-texts from the most recent completion fetch; served /// synchronously to the text view's completion window via the delegate. private var _completionStrings: [String] = [] /// Monotonic id of the latest completion request; a resolving fetch only /// applies its results if it is still the newest (so a slow older request /// can't clobber a fresher one that landed first). private var _completionGeneration: Int = 0 /// Pending debounced re-highlight; cancelled and rescheduled on each edit /// so a burst of keystrokes re-tokenizes the buffer once, not per key. private var _highlightWork: DispatchWorkItem? /// Last selection substring pushed to the model, so an unchanged selection /// (the common case while typing — caret moves, selection stays empty) /// doesn't republish `@Published` state and re-render the whole view. private var _lastSelectionPushed: String = "" /// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying /// wrap/paragraph settings on a pure text republish (every keystroke). var lastWraps: Bool? /// Idle delay before re-highlighting after an edit. Short enough to feel /// instant once typing pauses; long enough to coalesce a fast burst. private static let highlightDebounce: TimeInterval = 0.045 init(_ parent: ScratchEditor) { self.parent = parent } func textDidChange(_ notification: Notification) { guard let tv: NSTextView = notification.object as? NSTextView else { return } parent.text = tv.string scheduleHighlight(tv) // Completion is manual (Esc), never auto-triggered on `.`: an // unrequested popup ambushes typing and the built-in completion // window is awkward to dismiss mid-edit. } /// Coalesce full-buffer re-highlighting: cancel any pending pass and run /// one shortly after the edits stop. Newly typed characters render in the /// base color immediately (via `typingAttributes`); syntax colors catch /// up a beat later, avoiding an O(n) tokenize on every keystroke. private func scheduleHighlight(_ tv: NSTextView) { _highlightWork?.cancel() let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in guard let self: Coordinator = self, let tv: NSTextView = tv else { return } self.parent.applyHighlight(to: tv) } _highlightWork = work DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work) } /// Push the current selected substring up to the model so "Run Selection" /// knows what (if anything) is selected — but only when it actually /// changed, to avoid a per-caret-move `@Published` republish. func textViewDidChangeSelection(_ notification: Notification) { guard let tv: NSTextView = notification.object as? NSTextView else { return } let sel: NSRange = tv.selectedRange() let selected: String if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length { selected = (tv.string as NSString).substring(with: sel) } else { selected = "" } guard selected != _lastSelectionPushed else { return } _lastSelectionPushed = selected // Defer the @Published mutation: a programmatic text change (via // `updateNSView` → `replaceText`) can clamp the selection and re-post // this notification from inside a SwiftUI update pass. Scheduling on // the next main-actor tick keeps that off the render pass ("Publishing // changes from within view updates is not allowed"). let notify: @MainActor (String) -> Void = parent.onSelectionChanged Task { @MainActor in notify(selected) } } /// The text view calls this synchronously from `complete(_:)`; return the /// candidates fetched asynchronously just before. Replaces the default /// dictionary-word completions entirely. func textView(_ textView: NSTextView, completions words: [String], forPartialWordRange charRange: NSRange, indexOfSelectedItem index: UnsafeMutablePointer?) -> [String] { _completionStrings } /// Fetch completions for the current caret position, then show the text /// view's completion window. No-op when the selection is non-empty (a /// range is selected, not an insertion point) or the fetch is empty. func triggerCompletion(_ tv: NSTextView) { let sel: NSRange = tv.selectedRange() guard sel.length == 0 else { return } let (line, character): (Int, Int) = editorLineAndUTF16Char( in: tv.string, utf16Offset: sel.location) let request: @MainActor (Int, Int) async -> [LSPCompletionItem] = parent.requestCompletions _completionGeneration += 1 let generation: Int = _completionGeneration Task { @MainActor [weak self, weak tv] in let items: [LSPCompletionItem] = await request(line, character) guard let self: Coordinator = self, let tv: NSTextView = tv, !items.isEmpty else { return } // Ignore a superseded request (a newer trigger fired meanwhile) // and one whose caret has since moved. guard generation == self._completionGeneration, tv.selectedRange() == sel else { return } self._completionStrings = items.map { $0.insertText } tv.complete(nil) } } } func makeCoordinator() -> Coordinator { Coordinator(self) } func makeNSView(context: Context) -> NSScrollView { // Build the scroll view around a `ScratchTextView` subclass so its // `rangeForUserCompletion` override can keep member completion from // eating the receiver expression (see the class doc). let scroll: NSScrollView = NSScrollView() scroll.borderType = .noBorder scroll.hasVerticalScroller = true scroll.autoresizingMask = [.width, .height] let tv: ScratchTextView = ScratchTextView(frame: .zero) // Opt into TextKit 1: accessing `layoutManager` permanently switches the // text view off TextKit 2, where `self.layoutManager` is nil — the gutter // drawing needs it to place numbers against laid-out line rects. _ = tv.layoutManager tv.autoresizingMask = [.width] tv.isVerticallyResizable = true tv.isHorizontallyResizable = false tv.minSize = NSSize(width: 0, height: 0) tv.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) tv.textContainer?.widthTracksTextView = true scroll.documentView = tv configure(tv, in: scroll, with: context.coordinator) // Manual completion (Esc): fetch candidates, then show the window. let coordinator: Coordinator = context.coordinator tv.onManualComplete = { [weak coordinator, weak tv] in guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return } coordinator.triggerCompletion(tv) } // Line-number gutter: a floating overlay pinned to the left of the visible // area (see `ScratchLineNumberGutter` for why not an `NSRulerView`). let gutter: ScratchLineNumberGutter = ScratchLineNumberGutter(scrollView: scroll, textView: tv) scroll.addFloatingSubview(gutter, for: .vertical) 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 let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines context.coordinator.lastWraps = wrapsLines let textChanged: Bool = tv.string != text // Fast path: a pure text republish (the per-keystroke case) needs no work // here — the `NSTextView` already holds the text (it's the editor of // record), highlighting is debounced in the Coordinator, and font/wrap // are unchanged. Skip the paragraph-style measure + attribute churn. guard textChanged || fontChanged || wrapChanged else { return } let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font) if fontChanged { tv.font = font } tv.defaultParagraphStyle = paragraphStyle tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle) applyWrap(to: tv, in: scroll) if textChanged { // External change (load, reset, mode switch) — replace + re-highlight. replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle) } else if fontChanged { applyHighlight(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 applyHighlight(to: tv, font: font, paragraph: paragraph) // A direct `setAttributedString` bypasses `NSTextView`'s edit path, so the // gutter (which redraws on `NSText.didChangeNotification`) isn't told to // refresh. Nudge it explicitly after a programmatic replace (format / // load / reset) so the line count doesn't go stale. if let scroll: NSScrollView = tv.enclosingScrollView { for sub: NSView in scroll.subviews { (sub as? ScratchLineNumberGutter)?.refresh() } } } // MARK: - Syntax highlighting /// Re-tokenize the buffer and paint token colors via /// ``ScratchSyntaxHighlighter``. Attribute-only — the string and the /// selection are untouched. private func applyHighlight(to tv: NSTextView, font: NSFont, paragraph: NSParagraphStyle) { guard let storage: NSTextStorage = tv.textStorage else { return } let base: [NSAttributedString.Key : Any] = makeAttrs(font: font, paragraph: paragraph) ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base) tv.typingAttributes = base } /// Convenience for the delegate path, which has only the text view: rebuilds /// the font/paragraph from the current `fontSize`. func applyHighlight(to tv: NSTextView) { let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular) applyHighlight(to: tv, font: font, paragraph: makeParagraphStyle(for: font)) } 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 // Rich text so per-token foreground colors render. User styling can't // creep in: every edit re-runs `applyHighlight`, which normalizes the // font/paragraph over the whole buffer before recoloring, and the smart // substitutions below stay disabled. tv.isRichText = true // Rich text would otherwise allow dragged/pasted images to inject // NSTextAttachment glyphs into the buffer; keep it plain-text-only so the // content is always compilable Swift source. tv.importsGraphics = false tv.isAutomaticQuoteSubstitutionEnabled = false tv.isAutomaticDashSubstitutionEnabled = false tv.isAutomaticTextReplacementEnabled = false tv.isAutomaticSpellingCorrectionEnabled = false tv.smartInsertDeleteEnabled = false tv.allowsUndo = true tv.usesFindBar = true // Left inset reserves the column the `ScratchLineNumberGutter` overlay // draws line numbers into (see `ScratchLineNumberGutter.draw(_:)`). // `textContainerInset` is symmetric, so the right margin matches — // harmless whitespace. tv.textContainerInset = NSSize(width: ScratchTextView.lineNumberGutterWidth, 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