Repository Public
1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/StudioPanels.swift3// Description: Bottom panels of the Automation Studio that read the live engine: the console (REPL), the problems4// list, the automation log and the run / scheduler monitor.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import ORIXDJCore10import SwiftUI1112// MARK: - Console1314struct AutomationConsolePanel: View {15 @Environment(AppModel.self) private var model16 @State private var input = ""17 /// Position in the history while browsing with the arrow keys; nil when typing a new line.18 @State private var historyIndex: Int?19 @State private var draft = ""20 @State private var suggestion = 021 @FocusState private var inputFocused: Bool2223 private static func style(_ kind: ConsoleLineKind) -> (prefix: String, color: Color) {24 switch kind {25 case .input: ("> ", ORIX.Palette.accent)26 case .result: ("= ", ORIX.Palette.textPrimary)27 case .info: ("# ", ORIX.Palette.textSecondary)28 case .error: ("! ", ORIX.Palette.danger)29 }30 }3132 /// The dotted word at the end of the input, and its completions (console commands for a first word).33 private struct Suggestion { var insert: String; var label: String; var detail: String; var doc: String }3435 private var completions: (prefix: String, items: [Suggestion]) {36 let tail = String(input.reversed().prefix { $0.isLetter || $0.isNumber || $0 == "_" || $0 == "." }.reversed())37 guard !tail.isEmpty, tail.first?.isNumber != true else { return ("", []) }38 var items = Autocomplete.completions(for: tail, limit: 12).map { Suggestion(insert: $0.insert, label: $0.label, detail: $0.detail, doc: $0.doc) }39 if tail == input, !tail.contains(".") {40 let commands = ConsoleParser.commands.filter { $0.name.hasPrefix(tail.lowercased()) && $0.name != tail }41 items = commands.map { Suggestion(insert: $0.name, label: $0.usage, detail: "command", doc: $0.doc) } + items42 }43 return (tail, Array(items.prefix(12)))44 }4546 private func accept(_ item: Suggestion, prefix: String) {47 var insert = item.insert48 if let paren = insert.firstIndex(of: "("), item.detail != "builtin" { insert = String(insert[..<paren]) + "()" }49 input = String(input.dropLast(prefix.count)) + insert50 suggestion = 051 }5253 private func submit() {54 let line = input55 input = ""; historyIndex = nil; draft = ""; suggestion = 056 model.runConsole(line)57 }5859 private func browse(_ delta: Int) {60 let history = model.consoleHistory61 guard !history.isEmpty else { return }62 if historyIndex == nil { draft = input }63 let next = (historyIndex ?? history.count) + delta64 if next >= history.count { historyIndex = nil; input = draft; return }65 historyIndex = max(0, next)66 input = history[historyIndex!]67 }6869 var body: some View {70 let found = completions71 VStack(spacing: 0) {72 ScrollViewReader { proxy in73 ScrollView {74 LazyVStack(alignment: .leading, spacing: 1) {75 if model.consoleLines.isEmpty {76 Text("Live console. Type a statement (deck.A.volume = -6dB), an expression (deck.A.bpm) or a command (help). Everything acts on the live engine.")77 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).padding(.vertical, 4)78 }79 ForEach(model.consoleLines) { line in80 let style = Self.style(line.kind)81 (Text(verbatim: style.prefix).foregroundStyle(style.color).fontWeight(.bold) + Text(verbatim: line.text).foregroundStyle(style.color))82 .font(ORIX.Typeface.mono).textSelection(.enabled)83 .frame(maxWidth: .infinity, alignment: .leading)84 .id(line.id)85 // No accessibilityLabel on selectable text: with .textSelection the platform text element and86 // SwiftUI's node ask each other for the label forever (stack overflow on macOS 27). The visible87 // prefix already says what kind of line it is.88 }89 }90 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 6)91 }92 .background(ORIX.Palette.surface)93 .onChange(of: model.consoleLines.last?.id) { _, last in if let last { proxy.scrollTo(last, anchor: .bottom) } }94 .onAppear { if let last = model.consoleLines.last?.id { proxy.scrollTo(last, anchor: .bottom) } }95 .accessibilityIdentifier("automation-console-output")96 }97 if !found.items.isEmpty {98 Divider().overlay(ORIX.Palette.hairline)99 ScrollView(.horizontal, showsIndicators: false) {100 HStack(spacing: 4) {101 ForEach(Array(found.items.enumerated()), id: \.offset) { i, item in102 Button { accept(item, prefix: found.prefix); inputFocused = true } label: {103 HStack(spacing: 4) {104 Text(verbatim: item.label).font(ORIX.Typeface.mono)105 Text(verbatim: item.detail).font(.system(size: 9)).foregroundStyle(ORIX.Palette.textTertiary)106 }107 .padding(.horizontal, 6).frame(height: 20)108 .foregroundStyle(ORIX.Palette.textPrimary)109 .background(i == min(suggestion, found.items.count - 1) ? ORIX.Palette.surfaceRaised : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.chip))110 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip).strokeBorder(i == min(suggestion, found.items.count - 1) ? ORIX.Palette.accent : ORIX.Palette.hairline))111 }112 .buttonStyle(.plain)113 .help(Text(verbatim: item.doc))114 }115 }116 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 3)117 }118 .background(ORIX.Palette.surface)119 .accessibilityIdentifier("automation-console-completions")120 }121 Divider().overlay(ORIX.Palette.hairline)122 HStack(spacing: 6) {123 Text(verbatim: ">").font(ORIX.Typeface.mono.weight(.bold)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)124 TextField("Statement, expression or command", text: $input)125 .textFieldStyle(.plain).font(ORIX.Typeface.mono)126 .focused($inputFocused)127 .autocorrectionDisabled()128 .onSubmit { submit(); inputFocused = true }129 .onKeyPress(.upArrow) { browse(-1); return .handled }130 .onKeyPress(.downArrow) { browse(1); return .handled }131 .onKeyPress(.tab) {132 let c = completions133 guard !c.items.isEmpty else { return .ignored }134 accept(c.items[min(suggestion, c.items.count - 1)], prefix: c.prefix); return .handled135 }136 .onKeyPress(.rightArrow, phases: .down) { press in137 guard press.modifiers.contains(.control) else { return .ignored }138 suggestion = (suggestion + 1) % max(1, completions.items.count); return .handled139 }140 .onChange(of: input) { _, _ in suggestion = 0 }141 // No explicit accessibilityLabel here: on a focused TextField inside a container element it sends142 // SwiftUI's label resolution into infinite recursion (macOS 27). The prompt text is the label.143 .accessibilityIdentifier("automation-console-input")144 if !found.items.isEmpty { Text("Tab completes").font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary) }145 StudioIconButton(title: "Copy Output", symbol: "doc.on.doc") {146 let text = model.consoleLines.map { Self.style($0.kind).prefix + $0.text }.joined(separator: "\n")147 NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType: .string)148 model.show(notice: "Console output copied")149 }150 .disabled(model.consoleLines.isEmpty)151 .accessibilityIdentifier("automation-console-copy")152 StudioIconButton(title: "Clear", symbol: "trash") { model.consoleLines.removeAll() }153 .disabled(model.consoleLines.isEmpty)154 .accessibilityIdentifier("automation-console-clear")155 }156 .padding(.horizontal, ORIX.Space.sm).frame(height: 32)157 .background(ORIX.Palette.surfaceRaised)158 }159 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-console")160 }161}162163// MARK: - Problems164165struct AutomationProblemsPanel: View {166 @Environment(AppModel.self) private var model167 let studio: AutomationStudioState168169 static func symbol(_ s: DiagnosticSeverity) -> (name: String, color: Color, word: String) {170 switch s {171 case .error: ("xmark.octagon.fill", ORIX.Palette.danger, "Error")172 case .warning: ("exclamationmark.triangle.fill", ORIX.Palette.warning, "Warning")173 case .note: ("info.circle.fill", ORIX.Palette.accentSecondary, "Note")174 }175 }176177 var body: some View {178 let doc = model.activeDocument179 let diagnostics = studio.diagnostics(for: doc)180 Group {181 if let doc, studio.validations[doc.id] == nil {182 EmptyState(symbol: "hourglass", title: "Validating", message: "The script is being checked.")183 } else if diagnostics.isEmpty {184 EmptyState(symbol: "checkmark.seal", title: "No problems", message: "The active script compiles without errors or warnings.")185 } else {186 ScrollView {187 LazyVStack(spacing: 0) {188 ForEach(Array(diagnostics.enumerated()), id: \.offset) { _, d in189 let s = Self.symbol(d.severity)190 Button { studio.jump(to: d.location.line, column: d.location.column, in: doc?.id, model: model) } label: {191 HStack(alignment: .firstTextBaseline, spacing: 8) {192 Image(systemName: s.name).foregroundStyle(s.color).frame(width: 14)193 Text(verbatim: s.word).font(.system(size: 11, weight: .semibold)).foregroundStyle(s.color).frame(width: 54, alignment: .leading)194 Text(verbatim: d.message).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).frame(maxWidth: .infinity, alignment: .leading)195 Text(verbatim: d.code).font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textSecondary)196 Text(verbatim: "\(d.location.line):\(d.location.column)").font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 56, alignment: .trailing)197 }198 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 5)199 .contentShape(Rectangle())200 }201 .buttonStyle(.plain)202 .accessibilityLabel(Text(verbatim: "\(s.word), line \(d.location.line), column \(d.location.column): \(d.message)"))203 .accessibilityHint("Shows the location in the editor")204 Divider().overlay(ORIX.Palette.hairline)205 }206 }207 }208 .background(ORIX.Palette.surface)209 }210 }211 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-problems")212 }213}214215// MARK: - Log216217struct AutomationLogPanel: View {218 @Environment(AppModel.self) private var model219 let studio: AutomationStudioState220 @State private var kind: TraceKind?221 @State private var runID: Int?222 @State private var autoscroll = true223224 private static let kinds: [TraceKind] = [.start, .write, .action, .ramp, .spawn, .handler, .print, .warning, .error, .finish]225226 var body: some View {227 let visible = model.logLines.filter { $0.id > studio.logClearedThroughID && (kind == nil || $0.kind == kind) && (runID == nil || $0.runID == runID) }228 let runIDs = Array(Set(model.logLines.filter { $0.id > studio.logClearedThroughID }.map(\.runID))).sorted()229 VStack(spacing: 0) {230 HStack(spacing: ORIX.Space.xs) {231 Picker("Kind", selection: $kind) {232 Text("All kinds").tag(TraceKind?.none)233 ForEach(Self.kinds, id: \.self) { k in Text(verbatim: k.rawValue).tag(TraceKind?.some(k)) }234 }235 .fixedSize().accessibilityIdentifier("automation-log-kind")236 Picker("Run", selection: $runID) {237 Text("All runs").tag(Int?.none)238 ForEach(runIDs, id: \.self) { id in Text(verbatim: id == 0 ? "host" : "#\(id)").tag(Int?.some(id)) }239 }240 .fixedSize().accessibilityIdentifier("automation-log-run")241 Toggle("Autoscroll", isOn: $autoscroll).toggleStyle(.checkbox).accessibilityIdentifier("automation-log-autoscroll")242 Spacer()243 Text("\(visible.count) lines").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary)244 StudioIconButton(title: "Clear", symbol: "trash") {245 studio.logClearedThroughID = model.logLines.last?.id ?? studio.logClearedThroughID246 model.host.clearLog()247 }248 .accessibilityIdentifier("automation-log-clear")249 }250 .controlSize(.small).font(.system(size: 11))251 .padding(.horizontal, ORIX.Space.sm).frame(height: 30)252 Divider().overlay(ORIX.Palette.hairline)253 if visible.isEmpty {254 EmptyState(symbol: "list.bullet.rectangle", title: "No log lines", message: "Lines appear here while automations run on the live engine.")255 } else {256 ScrollViewReader { proxy in257 ScrollView {258 LazyVStack(spacing: 0) {259 ForEach(visible) { line in260 let t = StudioFormat.trace(line.kind)261 HStack(alignment: .firstTextBaseline, spacing: 8) {262 Text(verbatim: line.runID == 0 ? "host" : "#\(line.runID)").frame(width: 38, alignment: .leading).foregroundStyle(ORIX.Palette.textSecondary)263 Text(verbatim: line.automation).frame(width: 150, alignment: .leading).lineLimit(1).foregroundStyle(ORIX.Palette.textPrimary)264 Text(verbatim: String(format: "%.2f", line.beat)).frame(width: 70, alignment: .trailing).foregroundStyle(ORIX.Palette.textSecondary)265 HStack(spacing: 4) { Image(systemName: t.symbol).frame(width: 14); Text(verbatim: line.kind.rawValue) }266 .foregroundStyle(t.color).frame(width: 84, alignment: .leading)267 Text(verbatim: line.text).foregroundStyle(ORIX.Palette.textPrimary).frame(maxWidth: .infinity, alignment: .leading).textSelection(.enabled)268 }269 .font(ORIX.Typeface.mono)270 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 2)271 .id(line.id)272 }273 }274 }275 .background(ORIX.Palette.surface)276 .onChange(of: visible.last?.id) { _, last in if autoscroll, let last { proxy.scrollTo(last, anchor: .bottom) } }277 .onAppear { if autoscroll, let last = visible.last?.id { proxy.scrollTo(last, anchor: .bottom) } }278 }279 }280 }281 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-log")282 }283}284285// MARK: - Monitor286287struct AutomationMonitorPanel: View {288 @Environment(AppModel.self) private var model289290 private func stat(_ title: LocalizedStringKey, _ value: String, warn: Bool = false) -> some View {291 VStack(alignment: .leading, spacing: 1) {292 Text(title).font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)293 HStack(spacing: 3) {294 if warn { Image(systemName: "exclamationmark.triangle.fill").font(.system(size: 9)).foregroundStyle(ORIX.Palette.warning) }295 Text(verbatim: value).font(ORIX.Typeface.value).foregroundStyle(warn ? ORIX.Palette.warning : ORIX.Palette.textPrimary).lineLimit(1)296 }297 }298 .frame(maxWidth: .infinity, alignment: .leading)299 .accessibilityElement(children: .combine)300 }301302 private func runRow(_ r: AutomationRunInfo, live: Bool) -> some View {303 let s = StudioFormat.state(r.state)304 let beats = StudioFormat.number(r.elapsedBeats, decimals: 1) + " / " + (r.lengthBeats.map { StudioFormat.number($0, decimals: 1) } ?? "open") + " beats"305 return VStack(alignment: .leading, spacing: 2) {306 HStack(spacing: 8) {307 Text(verbatim: "#\(r.id)").font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textSecondary)308 Text(verbatim: r.name).font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)309 Spacer(minLength: 4)310 Label { Text(verbatim: s.text) } icon: { Image(systemName: s.symbol) }.font(.system(size: 11, weight: .medium)).foregroundStyle(s.color).lineLimit(1).fixedSize()311 if live {312 if r.state == .paused {313 StudioIconButton(title: "Resume", symbol: "play.fill") { model.host.resume(named: r.name); model.refreshNow() }.accessibilityIdentifier("automation-monitor-resume")314 } else {315 StudioIconButton(title: "Pause", symbol: "pause.fill") { model.host.pause(named: r.name); model.refreshNow() }.accessibilityIdentifier("automation-monitor-pause")316 }317 StudioIconButton(title: "Stop", symbol: "stop.fill", tint: ORIX.Palette.danger) { model.host.stop(run: r.id); model.refreshNow() }.accessibilityIdentifier("automation-monitor-stop")318 }319 }320 Text(verbatim: live ? "\(r.origin) · \(beats) · \(r.tasks) pending tasks · \(r.ramps) ramps · \(r.handlers.count) handlers" + (r.handlers.isEmpty ? "" : " (" + r.handlers.joined(separator: ", ") + ")")321 : "\(r.origin) · \(beats) · \(r.stats.writes) writes · \(r.stats.actions) actions")322 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(2)323 if case let .failed(e) = r.state {324 Text(verbatim: e.description).font(.system(size: 11)).foregroundStyle(ORIX.Palette.danger).lineLimit(2)325 }326 }327 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 5)328 .frame(maxWidth: .infinity, alignment: .leading)329 .accessibilityElement(children: .contain)330 }331332 var body: some View {333 let s = model.schedulerStats334 let rate = model.engine.core.sampleRate335 HStack(alignment: .top, spacing: 0) {336 ScrollView {337 VStack(alignment: .leading, spacing: 0) {338 PaneHeader(title: "Active runs") { Text("\(model.runs.count)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary) }339 if model.runs.isEmpty {340 Text("No automation is running.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).padding(ORIX.Space.sm)341 }342 ForEach(model.runs) { r in runRow(r, live: true); Divider().overlay(ORIX.Palette.hairline) }343 PaneHeader(title: "Recent runs") { Text("\(model.recentRuns.count)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary) }344 if model.recentRuns.isEmpty {345 Text("No automation has finished yet.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).padding(ORIX.Space.sm)346 }347 ForEach(model.recentRuns.reversed()) { r in runRow(r, live: false); Divider().overlay(ORIX.Palette.hairline) }348 }349 }350 .frame(maxWidth: .infinity, maxHeight: .infinity)351 .background(ORIX.Palette.surface)352 .accessibilityIdentifier("automation-monitor-runs")353 Divider().overlay(ORIX.Palette.hairline)354 ScrollView {355 VStack(alignment: .leading, spacing: 8) {356 HStack {357 SectionLabel("Scheduler (measured)")358 Spacer()359 StudioIconButton(title: "Reset", symbol: "arrow.counterclockwise", showsTitle: true) { model.host.resetStats(); model.refreshNow() }360 .accessibilityIdentifier("automation-monitor-reset")361 }362 LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8, alignment: .leading), count: 2), alignment: .leading, spacing: 8) {363 stat("Ticks", "\(s.ticks)")364 stat("Average tick", String(format: "%.1f µs", s.averageTickMicros))365 stat("Longest tick", String(format: "%.1f µs", s.maxTickMicros))366 stat("Largest tick gap", String(format: "%.2f ms", s.maxTickGapMillis))367 stat("Active automations", "\(s.activeAutomations)")368 stat("Pending tasks", "\(s.pendingTasks)")369 stat("Active ramps", "\(s.activeRamps)")370 stat("Started / finished", "\(s.started) / \(s.finished)")371 stat("Runtime errors", "\(s.runtimeErrors)", warn: s.runtimeErrors > 0)372 stat("Validation errors", "\(s.validationErrors)", warn: s.validationErrors > 0)373 stat("Timed commands", "\(s.trackedEvents)")374 stat("Late commands", "\(s.lateEvents)", warn: s.lateEvents > 0)375 stat("Worst lateness", "\(s.maxLateSamples) smp · " + String(format: "%.2f ms", rate > 0 ? Double(s.maxLateSamples) / rate * 1000 : 0), warn: s.maxLateSamples > 0)376 stat("Mean lateness", String(format: "%.2f smp", s.meanLateSamples))377 stat("Dropped control events", "\(s.droppedControlEvents)", warn: s.droppedControlEvents > 0)378 }379 Text(verbatim: "Lateness is converted at the engine sample rate, \(Int(rate)) Hz.").font(.system(size: 10)).foregroundStyle(ORIX.Palette.textTertiary)380 }381 .padding(ORIX.Space.sm)382 }383 .frame(width: 320)384 .background(ORIX.Palette.surface)385 .accessibilityIdentifier("automation-monitor-stats")386 }387 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-monitor")388 }389}390