Repository Public
1// ORIX DJ2// File: App/Sources/Features/Docs/ScriptSupport.swift3// Description: Shared helpers for showing ORIX Script outside the editor: syntax colouring from the real lexer, and4// compile + simulate of a snippet off the main thread with a cache of the outcomes.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011enum ScriptHighlighter {12 static func color(_ c: TokenClass) -> Color {13 switch c {14 case .keyword: ORIX.Palette.accent15 case .root: ORIX.Palette.accentSecondary16 case .number: ORIX.Palette.warning17 case .string: ORIX.Palette.success18 case .comment: ORIX.Palette.textTertiary19 case .symbol: ORIX.Palette.textSecondary20 case .identifier: ORIX.Palette.textPrimary21 }22 }2324 /// Coloured text for a script, using `Lexer.highlight`. Works on text that does not compile.25 static func attributed(_ source: String, size: CGFloat) -> AttributedString {26 let font = Font.system(size: size, design: .monospaced)27 let utf16 = Array(source.utf16)28 var out = AttributedString()29 var cursor = 030 func piece(_ range: Range<Int>, _ color: Color, italic: Bool = false) {31 guard range.lowerBound < range.upperBound else { return }32 var a = AttributedString(String(decoding: utf16[range], as: UTF16.self))33 a.font = italic ? font.italic() : font34 a.foregroundColor = color35 out.append(a)36 }37 for span in Lexer.highlight(source) {38 let lower = max(cursor, min(span.range.lowerBound, utf16.count)), upper = min(span.range.upperBound, utf16.count)39 guard upper > lower else { continue }40 piece(cursor ..< lower, ORIX.Palette.textPrimary)41 piece(lower ..< upper, color(span.tokenClass), italic: span.tokenClass == .comment)42 cursor = upper43 }44 piece(cursor ..< utf16.count, ORIX.Palette.textPrimary)45 return out46 }47}4849/// What compiling and simulating a snippet produced.50struct ScriptOutcome: Sendable {51 /// The snippet had no `automation` block and was wrapped in one.52 var wrapped: Bool53 var errors: [Diagnostic]54 var warnings: [Diagnostic]55 var simulation: SimulationResult?5657 static func hasAutomation(_ source: String) -> Bool {58 source.range(of: #"(?m)^\s*automation\b"#, options: .regularExpression) != nil59 }6061 /// The snippet as a complete script: statements without an `automation` are placed inside one.62 static func complete(_ source: String) -> String {63 if hasAutomation(source) { return source.hasSuffix("\n") ? source : source + "\n" }64 let body = source.trimmingCharacters(in: .newlines).components(separatedBy: "\n").map { $0.isEmpty ? "" : " " + $0 }.joined(separator: "\n")65 return "automation \"Example\" {\n\(body)\n}\n"66 }6768 /// Compiles the snippet and, when it compiles and `simulate` is set, runs it in the simulator. Safe on any thread.69 static func evaluate(_ source: String, simulate: Bool = true) -> ScriptOutcome {70 let wrapped = !hasAutomation(source)71 let compiled = ScriptCompiler.compile(complete(source))72 func relocate(_ d: Diagnostic) -> Diagnostic {73 guard wrapped else { return d }74 var d = d75 d.location = SourceLocation(line: max(1, d.location.line - 1), column: max(1, d.location.column - 4))76 return d77 }78 var outcome = ScriptOutcome(wrapped: wrapped, errors: compiled.errors.map(relocate), warnings: compiled.warnings.map(relocate), simulation: nil)79 if simulate, let program = compiled.program { outcome.simulation = Simulator.run(program) }80 return outcome81 }82}8384/// Outcomes of the snippets the user ran, kept while the app runs so that scrolling does not lose them.85@MainActor @Observable86final class ScriptRunCache {87 static let shared = ScriptRunCache()88 private(set) var outcomes: [String: ScriptOutcome] = [:]89 private(set) var running: Set<String> = []9091 func outcome(for source: String) -> ScriptOutcome? { outcomes[source] }92 func isRunning(_ source: String) -> Bool { running.contains(source) }9394 func run(_ source: String, simulate: Bool = true) {95 guard !running.contains(source) else { return }96 running.insert(source)97 Task {98 let outcome = await Task.detached(priority: .userInitiated) { ScriptOutcome.evaluate(source, simulate: simulate) }.value99 outcomes[source] = outcome100 running.remove(source)101 }102 }103104 func clear(_ source: String) { outcomes[source] = nil }105 func store(_ outcome: ScriptOutcome, for key: String) { outcomes[key] = outcome }106}107108extension AutomationState {109 var label: LocalizedStringKey {110 switch self {111 case .running: "Running"112 case .paused: "Paused"113 case .finished: "Finished"114 case .stopped: "Stopped"115 case .failed: "Failed"116 }117 }118}119120func formatBeats(_ beats: Double) -> String {121 beats == beats.rounded() ? String(format: "%.0f", beats) : String(format: "%.2f", beats)122}123124func traceLine(_ e: TraceEvent) -> String {125 String(format: "%7.2f ", e.beat) + e.kind.rawValue.padding(toLength: 8, withPad: " ", startingAt: 0) + " " + e.text126}127128/// The inline result of a simulated run: state, beats, actions, warnings and the first lines of the trace.129struct SimulationSummaryView: View {130 var simulation: SimulationResult131 var traceLines = 8132 var scale: CGFloat = 1133134 var body: some View {135 VStack(alignment: .leading, spacing: 6) {136 HStack(spacing: ORIX.Space.sm) {137 let failed = simulation.error != nil138 Label {139 Text(simulation.timedOut ? "Still running" : simulation.state.label)140 } icon: {141 Image(systemName: failed ? "xmark.octagon.fill" : (simulation.timedOut ? "clock.badge.exclamationmark" : "checkmark.circle.fill"))142 }143 .foregroundStyle(failed ? ORIX.Palette.danger : (simulation.timedOut ? ORIX.Palette.warning : ORIX.Palette.success))144 .font(.system(size: 12 * scale, weight: .semibold))145 Text("\(formatBeats(simulation.beats)) beats")146 Text("\(simulation.actions.count) actions")147 Text("\(simulation.stats.writes + simulation.stats.rampWrites) writes")148 if !simulation.warnings.isEmpty { Label("\(simulation.warnings.count) warnings", systemImage: "exclamationmark.triangle").foregroundStyle(ORIX.Palette.warning) }149 }150 .font(.system(size: 11 * scale).monospacedDigit())151 .foregroundStyle(ORIX.Palette.textSecondary)152 if let e = simulation.error {153 Text(verbatim: e.description).font(.system(size: 12 * scale)).foregroundStyle(ORIX.Palette.danger).textSelection(.enabled)154 }155 if simulation.timedOut {156 Text("The simulator stops after \(formatBeats(simulation.beats)) beats; the automation was still alive, which is normal for one that waits for events.")157 .font(.system(size: 11 * scale)).foregroundStyle(ORIX.Palette.textSecondary)158 }159 if !simulation.trace.isEmpty, traceLines > 0 {160 let shown = simulation.trace.prefix(traceLines)161 VStack(alignment: .leading, spacing: 1) {162 ForEach(Array(shown.enumerated()), id: \.offset) { _, e in163 Text(verbatim: traceLine(e))164 .foregroundStyle(e.kind == .error ? ORIX.Palette.danger : (e.kind == .warning ? ORIX.Palette.warning : ORIX.Palette.textSecondary))165 }166 if simulation.trace.count > shown.count {167 Text("… \(simulation.trace.count - shown.count) more trace lines").foregroundStyle(ORIX.Palette.textTertiary)168 }169 }170 .font(.system(size: 11 * scale, design: .monospaced))171 .textSelection(.enabled)172 }173 }174 .frame(maxWidth: .infinity, alignment: .leading)175 }176}177178/// Compiler messages with their lines.179struct DiagnosticsListView: View {180 var diagnostics: [Diagnostic]181 var scale: CGFloat = 1182183 var body: some View {184 VStack(alignment: .leading, spacing: 3) {185 ForEach(Array(diagnostics.enumerated()), id: \.offset) { _, d in186 HStack(alignment: .firstTextBaseline, spacing: 6) {187 Image(systemName: d.severity == .error ? "xmark.octagon.fill" : "exclamationmark.triangle.fill")188 .foregroundStyle(d.severity == .error ? ORIX.Palette.danger : ORIX.Palette.warning)189 .accessibilityLabel(d.severity == .error ? Text("Error") : Text("Warning"))190 Text("Line \(d.location.line)").font(.system(size: 11 * scale, weight: .semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.textSecondary)191 Text(verbatim: "\(d.message) [\(d.code)]").font(.system(size: 12 * scale)).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled)192 }193 }194 }195 .frame(maxWidth: .infinity, alignment: .leading)196 }197}198199func copyToPasteboard(_ text: String) {200 NSPasteboard.general.clearContents()201 NSPasteboard.general.setString(text, forType: .string)202}203