662 lines
28 KiB
Swift
662 lines
28 KiB
Swift
// 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
|
||
@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
|
||
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)
|
||
}
|
||
)
|
||
.frame(minHeight: editorMinHeight)
|
||
Divider()
|
||
statusBar
|
||
if !model.diagnostics.isEmpty {
|
||
Divider()
|
||
diagnosticsList
|
||
}
|
||
}
|
||
.frame(minWidth: scratchMinWidth, 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
|
||
engineTick &+= 1
|
||
// Settle a `.queued` readiness badge once its swap has fired.
|
||
model.refreshQueuedState()
|
||
}
|
||
}
|
||
|
||
private var engineBar: some View {
|
||
let engine: SynthesisEngine = model.session.engine
|
||
return HStack(spacing: toolbarSpacing) {
|
||
Button {
|
||
model.toggleEngine()
|
||
engineTick &+= 1
|
||
} label: {
|
||
HStack(spacing: reevalBadgeSpacing) {
|
||
Circle()
|
||
.fill(engine.isRunning ? Color.green : Color.red)
|
||
.frame(width: engineDotSize, height: engineDotSize)
|
||
Text(engine.isRunning ? "engine running" : "▶ start engine")
|
||
.font(.system(.caption, design: .monospaced))
|
||
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
|
||
}
|
||
}
|
||
.buttonStyle(.plain)
|
||
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||
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)
|
||
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)
|
||
.id(engineTick)
|
||
}
|
||
|
||
/// 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))
|
||
}
|
||
|
||
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(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)."
|
||
}
|
||
}
|
||
|
||
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
|
||
private let reevalBadgeSpacing: CGFloat = 4
|
||
}
|
||
|
||
/// 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)"
|
||
}
|
||
// No user-body line. A swiftc preamble hit carries a real (1-based)
|
||
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
|
||
// harness/preamble at all), so label the two cases distinctly.
|
||
return diagnostic.rawLine >= 1
|
||
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||
: "(file)"
|
||
}
|
||
|
||
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
|
||
}
|
||
|
||
/// `NSTextView` subclass that fixes member-completion behavior.
|
||
///
|
||
/// The default `rangeForUserCompletion` scans back over the whole dotted
|
||
/// expression, so completing a member right after a `.` (e.g. `context.` →
|
||
/// `engine`) would *replace* the receiver (`context`) with the chosen member
|
||
/// instead of inserting after the dot. When the character before the insertion
|
||
/// point is a `.`, this override returns an empty range at the caret, so the
|
||
/// completion is a pure insertion and `context.engine` is produced.
|
||
/// UTF-16 code unit for `.` (the member-access operator that triggers and
|
||
/// shapes completion).
|
||
private let dotCharacterCode: unichar = 46
|
||
|
||
/// Whether `selection` is a bare insertion point sitting immediately after a
|
||
/// `.` in `text` — the member-completion trigger condition.
|
||
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
|
||
guard selection.length == 0, selection.location > 0, selection.location <= text.length
|
||
else { return false }
|
||
return text.character(at: selection.location - 1) == dotCharacterCode
|
||
}
|
||
|
||
final class ScratchTextView: NSTextView {
|
||
override var rangeForUserCompletion: NSRange {
|
||
let sel: NSRange = selectedRange()
|
||
if caretFollowsDot(in: string as NSString, selection: sel) {
|
||
return NSRange(location: sel.location, length: 0)
|
||
}
|
||
return super.rangeForUserCompletion
|
||
}
|
||
}
|
||
|
||
/// `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]
|
||
|
||
@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
|
||
|
||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||
|
||
func textDidChange(_ notification: Notification) {
|
||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||
parent.text = tv.string
|
||
parent.applyHighlight(to: tv)
|
||
// Auto-trigger member completion right after a `.` is typed.
|
||
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
|
||
triggerCompletion(tv)
|
||
}
|
||
}
|
||
|
||
/// 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<Int>?) -> [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)
|
||
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)
|
||
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 {
|
||
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)
|
||
}
|
||
|
||
// 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
|
||
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
|