Files
Lyrebird/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchView.swift
T
2026-06-01 18:27:40 -07:00

410 lines
16 KiB
Swift

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