Repository Public
1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/SimulatorPanel.swift3// Description: Simulator and debugger panels: the simulation timeline (play spans, parameter curves, action markers),4// the event trace, and the step debugger that drives a DebugSession in the simulated rig.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011/// Rows of an event trace: beat, kind, text, line. Clicking a row selects its line in the editor.12struct TraceTable: View {13 var trace: [TraceEvent]14 var onSelect: (Int) -> Void1516 var body: some View {17 LazyVStack(spacing: 0) {18 HStack(spacing: 8) {19 Text("Beat").frame(width: 52, alignment: .trailing)20 Text("Kind").frame(width: 98, alignment: .leading)21 Text("Event").frame(maxWidth: .infinity, alignment: .leading)22 Text("Line").frame(width: 40, alignment: .trailing)23 }24 .font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textSecondary)25 .padding(.horizontal, ORIX.Space.sm).frame(height: 20)26 .background(ORIX.Palette.surfaceRaised)27 ForEach(Array(trace.enumerated()), id: \.offset) { _, e in28 let t = StudioFormat.trace(e.kind)29 Button { onSelect(e.line) } label: {30 HStack(alignment: .firstTextBaseline, spacing: 8) {31 Text(verbatim: String(format: "%.2f", e.beat)).frame(width: 52, alignment: .trailing).foregroundStyle(ORIX.Palette.textSecondary)32 HStack(spacing: 4) { Image(systemName: t.symbol).frame(width: 14); Text(verbatim: e.kind.rawValue).lineLimit(1) }.foregroundStyle(t.color).frame(width: 98, alignment: .leading)33 Text(verbatim: e.text).foregroundStyle(ORIX.Palette.textPrimary).frame(maxWidth: .infinity, alignment: .leading)34 Text(verbatim: e.line > 0 ? "\(e.line)" : "–").frame(width: 40, alignment: .trailing).foregroundStyle(ORIX.Palette.textSecondary)35 }36 .font(ORIX.Typeface.mono)37 .padding(.horizontal, ORIX.Space.sm).padding(.vertical, 2)38 .contentShape(Rectangle())39 }40 .buttonStyle(.plain)41 .disabled(e.line <= 0)42 .accessibilityLabel(Text(verbatim: "Beat \(String(format: "%.2f", e.beat)), \(e.kind.rawValue): \(e.text)" + (e.line > 0 ? ", line \(e.line)" : "")))43 }44 }45 }46}4748/// The simulation timeline drawn with Canvas.49struct SimulationTimeline: View {50 var run: SimulationRun51 @State private var hover: CGFloat?5253 private let labelWidth: CGFloat = 17854 private let rulerHeight: CGFloat = 2255 private let deckHeight: CGFloat = 1856 private let curveHeight: CGFloat = 4657 private let markerHeight: CGFloat = 225859 private var totalBeats: Double { max(4, (run.result.beats / 4).rounded(.up) * 4) }60 private var decks: [Int] { (0 ..< run.result.playSpans.count).filter { !run.result.playSpans[$0].isEmpty || run.settings.deckLoaded[$0] } }61 private var curves: [(address: ParamAddress, points: [CurvePoint])] {62 run.result.curves.map { (address: $0.key, points: $0.value.sorted { $0.beat < $1.beat }) }.sorted { $0.address.description < $1.address.description }63 }64 private var markers: [TraceEvent] { run.result.trace.filter { [.action, .print, .warning, .error, .handler].contains($0.kind) } }6566 private var height: CGFloat { rulerHeight + CGFloat(decks.count) * deckHeight + CGFloat(curves.count) * curveHeight + markerHeight + 6 }6768 static func value(at beat: Double, in points: [CurvePoint]) -> Double? { points.last { $0.beat <= beat + 1e-9 }?.value }6970 var body: some View {71 let curves = curves, decks = decks, markers = markers, total = totalBeats72 Canvas { context, size in73 let plot = CGRect(x: labelWidth, y: 0, width: max(10, size.width - labelWidth - 8), height: size.height)74 func x(_ beat: Double) -> CGFloat { plot.minX + plot.width * CGFloat(beat / total) }75 let secondary = ORIX.Palette.textSecondary, tertiary = ORIX.Palette.textTertiary76 // Ruler: bars are numbered, beats are ticks. Long simulations thin the labels out.77 let bars = Int(total / 4)78 let labelStep = max(1, Int((Double(bars) / Double(max(1, plot.width / 44))).rounded(.up)))79 for beat in 0 ... Int(total) {80 let isBar = beat % 4 == 081 let px = x(Double(beat))82 if isBar || plot.width / CGFloat(total) > 5 {83 context.fill(Path(CGRect(x: px, y: isBar ? 10 : 16, width: 1, height: isBar ? size.height - 10 : 6)), with: .color(isBar ? ORIX.Palette.hairline : tertiary.opacity(0.5)))84 }85 if isBar, beat < Int(total), (beat / 4) % labelStep == 0 {86 context.draw(Text(verbatim: "\(beat / 4 + 1)").font(.system(size: 9, weight: .semibold).monospacedDigit()).foregroundStyle(secondary), at: CGPoint(x: px + 3, y: 6), anchor: .leading)87 }88 }89 context.draw(Text("BAR").font(.system(size: 9, weight: .semibold)).foregroundStyle(tertiary), at: CGPoint(x: labelWidth - 8, y: 6), anchor: .trailing)90 var y = rulerHeight91 // Deck lanes: play spans.92 for d in decks {93 context.draw(Text(verbatim: "Deck \(deckLetters[d]) playing").font(.system(size: 10, weight: .medium)).foregroundStyle(secondary), at: CGPoint(x: 8, y: y + deckHeight / 2), anchor: .leading)94 context.fill(Path(roundedRect: CGRect(x: plot.minX, y: y + 3, width: plot.width, height: deckHeight - 6), cornerRadius: 3), with: .color(ORIX.Palette.well))95 for span in run.result.playSpans[d] {96 let r = CGRect(x: x(span.lowerBound), y: y + 3, width: max(2, x(min(span.upperBound, total)) - x(span.lowerBound)), height: deckHeight - 6)97 context.fill(Path(roundedRect: r, cornerRadius: 3), with: .color(ORIX.deck(d)))98 if r.width > 16 { context.draw(Text(verbatim: deckLetters[d]).font(.system(size: 9, weight: .heavy)).foregroundStyle(Color.black.opacity(0.85)), at: CGPoint(x: r.minX + 5, y: r.midY), anchor: .leading) }99 }100 y += deckHeight101 }102 // Parameter lanes: one curve each, scaled to its own range.103 for (address, points) in curves {104 let values = points.map(\.value)105 let lo = values.min() ?? 0, hi = values.max() ?? 1106 let span = hi - lo107 let lane = CGRect(x: plot.minX, y: y + 5, width: plot.width, height: curveHeight - 10)108 func py(_ v: Double) -> CGFloat { span > 0 ? lane.maxY - lane.height * CGFloat((v - lo) / span) : lane.midY }109 context.draw(Text(verbatim: address.description).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textPrimary), at: CGPoint(x: 8, y: y + 12), anchor: .leading)110 let range = span > 0 ? "\(StudioFormat.value(lo, of: address)) … \(StudioFormat.value(hi, of: address))" : StudioFormat.value(lo, of: address)111 context.draw(Text(verbatim: range).font(.system(size: 9).monospacedDigit()).foregroundStyle(tertiary), at: CGPoint(x: 8, y: y + 28), anchor: .leading)112 context.fill(Path(roundedRect: lane.insetBy(dx: 0, dy: -3), cornerRadius: 3), with: .color(ORIX.Palette.well))113 var path = Path()114 for (i, p) in points.enumerated() {115 let point = CGPoint(x: x(p.beat), y: py(p.value))116 if i == 0 { path.move(to: point); continue }117 // Samples arrive every 1/16 beat while a value moves; a longer gap is a held value, then a step.118 if p.beat - points[i - 1].beat > 0.2 { path.addLine(to: CGPoint(x: point.x, y: py(points[i - 1].value))) }119 path.addLine(to: point)120 }121 if let last = points.last { path.addLine(to: CGPoint(x: x(max(last.beat, run.result.beats)), y: py(last.value))) }122 context.stroke(path, with: .color(address.deck.map { ORIX.deck($0) } ?? ORIX.Palette.accent), style: StrokeStyle(lineWidth: 1.6, lineJoin: .round))123 y += curveHeight124 }125 // Event markers: diamond = action, square = print, triangle = warning or error, circle = handler.126 context.draw(Text("Actions and prints").font(.system(size: 10, weight: .medium)).foregroundStyle(secondary), at: CGPoint(x: 8, y: y + markerHeight / 2), anchor: .leading)127 for e in markers {128 let c = CGPoint(x: x(min(e.beat, total)), y: y + markerHeight / 2)129 var shape = Path()130 switch e.kind {131 case .action: shape.move(to: CGPoint(x: c.x, y: c.y - 5)); shape.addLine(to: CGPoint(x: c.x + 5, y: c.y)); shape.addLine(to: CGPoint(x: c.x, y: c.y + 5)); shape.addLine(to: CGPoint(x: c.x - 5, y: c.y)); shape.closeSubpath()132 case .print: shape.addRect(CGRect(x: c.x - 4, y: c.y - 4, width: 8, height: 8))133 case .handler: shape.addEllipse(in: CGRect(x: c.x - 4, y: c.y - 4, width: 8, height: 8))134 default: shape.move(to: CGPoint(x: c.x, y: c.y - 5)); shape.addLine(to: CGPoint(x: c.x + 5, y: c.y + 4)); shape.addLine(to: CGPoint(x: c.x - 5, y: c.y + 4)); shape.closeSubpath()135 }136 context.fill(shape, with: .color(StudioFormat.trace(e.kind).color))137 }138 // End of the automation.139 let endX = x(run.result.beats)140 context.fill(Path(CGRect(x: endX, y: rulerHeight - 4, width: 1.5, height: size.height - rulerHeight + 4)), with: .color(ORIX.Palette.textSecondary))141 // Hover: a cursor and the value of every lane at that beat.142 if let hover, hover >= plot.minX, hover <= plot.maxX {143 let beat = Double((hover - plot.minX) / plot.width) * total144 context.fill(Path(CGRect(x: hover, y: 0, width: 1, height: size.height)), with: .color(ORIX.Palette.textPrimary))145 let flip = hover > plot.maxX - 120146 var ly = rulerHeight + CGFloat(decks.count) * deckHeight147 context.draw(Text(verbatim: "beat \(StudioFormat.number(beat)) · " + StudioFormat.position(beat)).font(.system(size: 9, weight: .semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.textPrimary),148 at: CGPoint(x: hover + (flip ? -4 : 4), y: 16), anchor: flip ? .trailing : .leading)149 for (address, points) in curves {150 if let v = Self.value(at: beat, in: points) {151 let label = Text(verbatim: StudioFormat.value(v, of: address)).font(.system(size: 10, weight: .semibold).monospacedDigit()).foregroundStyle(ORIX.Palette.textPrimary)152 let resolved = context.resolve(label)153 let measured = resolved.measure(in: CGSize(width: 200, height: 20))154 let origin = CGPoint(x: hover + (flip ? -6 - measured.width : 6), y: ly + curveHeight / 2 - measured.height / 2)155 context.fill(Path(roundedRect: CGRect(origin: origin, size: measured).insetBy(dx: -3, dy: -1), cornerRadius: 3), with: .color(ORIX.Palette.surfaceRaised))156 context.draw(resolved, at: origin, anchor: .topLeading)157 }158 ly += curveHeight159 }160 }161 }162 .frame(height: height)163 .onContinuousHover { phase in164 switch phase {165 case let .active(p): hover = p.x166 case .ended: hover = nil167 }168 }169 .accessibilityElement(children: .ignore)170 .accessibilityLabel("Simulation timeline")171 .accessibilityValue(Text(verbatim: "\(StudioFormat.length(run.result.beats)), \(curves.count) parameter curves: " + curves.map { c in172 "\(c.address.description) from \(StudioFormat.value(c.points.first?.value ?? 0, of: c.address)) to \(StudioFormat.value(c.points.last?.value ?? 0, of: c.address))"173 }.joined(separator: "; ")))174 .accessibilityIdentifier("automation-simulator-timeline")175 }176}177178struct AutomationSimulatorPanel: View {179 @Environment(AppModel.self) private var model180 let studio: AutomationStudioState181182 private func statChip(_ title: LocalizedStringKey, _ value: String) -> some View {183 HStack(spacing: 3) {184 Text(title).foregroundStyle(ORIX.Palette.textTertiary)185 Text(verbatim: value).foregroundStyle(ORIX.Palette.textPrimary).monospacedDigit()186 }187 .font(.system(size: 11)).lineLimit(1).fixedSize()188 .accessibilityElement(children: .combine)189 }190191 var body: some View {192 VStack(spacing: 0) {193 HStack(spacing: ORIX.Space.sm) {194 StudioIconButton(title: "Simulate", symbol: "play.rectangle", showsTitle: true) { studio.simulateActive(model: model) }195 .accessibilityIdentifier("automation-simulator-run")196 if studio.simulationBusy { ProgressView().controlSize(.small) }197 if let run = studio.simulation {198 let r = run.result199 let s = StudioFormat.state(r.state, timedOut: r.timedOut)200 Text(verbatim: "\"\(run.automation)\"").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)201 Label { Text(verbatim: s.text) } icon: { Image(systemName: s.symbol) }.font(.system(size: 11, weight: .semibold)).foregroundStyle(s.color)202 .accessibilityIdentifier("automation-simulator-state")203 if let e = r.error {204 Text(verbatim: e.message + (e.location.map { " (line \($0.line))" } ?? "")).font(.system(size: 11)).foregroundStyle(ORIX.Palette.danger).lineLimit(1)205 .help(Text(verbatim: e.description))206 } else if r.timedOut {207 Text(verbatim: "still running after \(StudioFormat.number(run.settings.maxBeats)) beats").font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).lineLimit(1)208 }209 Spacer(minLength: 4)210 statChip("Length", StudioFormat.number(r.beats) + " beats")211 statChip("Operations", "\(r.stats.operations)")212 statChip("Writes", "\(r.stats.writes)")213 statChip("Ramp writes", "\(r.stats.rampWrites)")214 statChip("Clamped", "\(r.stats.clampedValues)")215 statChip("Peak tasks", "\(r.stats.peakTasks)")216 } else { Spacer() }217 }218 .padding(.horizontal, ORIX.Space.sm).frame(height: 32)219 Divider().overlay(ORIX.Palette.hairline)220 if let message = studio.simulationMessage {221 HStack(spacing: 6) {222 Image(systemName: "xmark.octagon.fill").foregroundStyle(ORIX.Palette.danger)223 Text(verbatim: message).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textPrimary)224 Spacer()225 }226 .padding(ORIX.Space.xs).background(ORIX.Palette.danger.opacity(0.1))227 }228 if let run = studio.simulation {229 ScrollView {230 VStack(spacing: 0) {231 if run.docID != nil, let doc = model.documents.first(where: { $0.id == run.docID }), doc.source != run.source {232 Text("The script changed since this simulation. Simulate again to refresh it.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning)233 .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, ORIX.Space.sm).padding(.top, 4)234 }235 SimulationTimeline(run: run).padding(.top, 4)236 Divider().overlay(ORIX.Palette.hairline)237 TraceTable(trace: run.result.trace) { line in studio.selectLine(line, in: run.docID, model: model) }238 .accessibilityIdentifier("automation-simulator-trace")239 }240 }241 .background(ORIX.Palette.surface)242 } else if studio.simulationMessage == nil {243 EmptyState(symbol: "chart.xyaxis.line", title: "No simulation yet", message: "Simulate runs the active script in a simulated rig, with the settings of the inspector. Nothing reaches the audio engine.",244 actionTitle: "Simulate", action: { studio.simulateActive(model: model) })245 } else { Spacer() }246 }247 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-simulator")248 }249}250251// MARK: - Debugger252253struct AutomationDebuggerPanel: View {254 @Environment(AppModel.self) private var model255 let studio: AutomationStudioState256257 private func column<Content: View>(_ title: LocalizedStringKey, count: Int, @ViewBuilder content: () -> Content) -> some View {258 VStack(alignment: .leading, spacing: 0) {259 HStack { SectionLabel(title); Spacer(); Text(verbatim: "\(count)").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary) }260 .padding(.horizontal, ORIX.Space.xs).frame(height: 22).background(ORIX.Palette.surfaceRaised)261 content()262 }263 }264265 private func row(_ left: String, _ right: String) -> some View {266 HStack(alignment: .firstTextBaseline, spacing: 6) {267 Text(verbatim: left).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)268 Spacer(minLength: 4)269 Text(verbatim: right).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)270 }271 .font(ORIX.Typeface.mono).padding(.horizontal, ORIX.Space.xs).padding(.vertical, 2)272 .accessibilityElement(children: .combine)273 }274275 private func none(_ text: LocalizedStringKey) -> some View {276 Text(text).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary).padding(.horizontal, ORIX.Space.xs).padding(.vertical, 4)277 }278279 var body: some View {280 let session = studio.debug281 let over = session?.snapshot.isOver ?? true282 VStack(spacing: 0) {283 HStack(spacing: 6) {284 StudioIconButton(title: session == nil ? "Start Debugging" : "Restart", symbol: session == nil ? "ant" : "arrow.counterclockwise", showsTitle: true) { studio.debugActive(model: model) }285 .accessibilityIdentifier("automation-debugger-restart")286 StudioIconButton(title: "Continue", symbol: "play.fill", tint: ORIX.Palette.success, showsTitle: true) { studio.debugContinue() }287 .disabled(over || studio.debugBusy).accessibilityIdentifier("automation-debugger-continue")288 StudioIconButton(title: "Step", symbol: "arrow.turn.down.right", showsTitle: true) { studio.debugStep() }289 .disabled(over || studio.debugBusy).accessibilityIdentifier("automation-debugger-step")290 StudioIconButton(title: "Stop", symbol: "stop.fill", tint: ORIX.Palette.danger, showsTitle: true) { studio.debugStop() }291 .disabled(session == nil).accessibilityIdentifier("automation-debugger-stop")292 if studio.debugBusy { ProgressView().controlSize(.small) }293 Spacer(minLength: 4)294 if let session {295 let snap = session.snapshot296 let rel = max(0, snap.beat - snap.startBeat)297 if let line = snap.pausedLine {298 Label { Text(verbatim: "Paused at line \(line)") } icon: { Image(systemName: "pause.circle.fill") }299 .font(.system(size: 11, weight: .semibold)).foregroundStyle(ORIX.Palette.warning)300 .accessibilityIdentifier("automation-debugger-state")301 } else {302 let s = StudioFormat.state(snap.state, timedOut: snap.timedOut)303 Label { Text(verbatim: s.text) } icon: { Image(systemName: s.symbol) }.font(.system(size: 11, weight: .semibold)).foregroundStyle(s.color)304 .accessibilityIdentifier("automation-debugger-state")305 }306 Text(verbatim: "beat \(StudioFormat.number(rel)) · " + StudioFormat.position(rel)).font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)307 }308 }309 .padding(.horizontal, ORIX.Space.sm).frame(height: 32)310 Label("Debugging runs in the simulator with the inspector's simulation settings. It never pauses or changes live audio.", systemImage: "info.circle")311 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)312 .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, ORIX.Space.sm).padding(.bottom, 5)313 .accessibilityIdentifier("automation-debugger-notice")314 Divider().overlay(ORIX.Palette.hairline)315 if let message = studio.debugMessage {316 HStack(spacing: 6) {317 Image(systemName: "xmark.octagon.fill").foregroundStyle(ORIX.Palette.danger)318 Text(verbatim: message).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textPrimary)319 Spacer()320 }321 .padding(ORIX.Space.xs).background(ORIX.Palette.danger.opacity(0.1))322 }323 if let session {324 let snap = session.snapshot325 if let doc = model.documents.first(where: { $0.id == session.docID }), doc.source != session.source {326 Text("The script changed since this session started; line numbers refer to the version being debugged. Restart to debug the current text.")327 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, ORIX.Space.sm).padding(.vertical, 3)328 }329 if case let .failed(e) = snap.state {330 Text(verbatim: e.description).font(.system(size: 11)).foregroundStyle(ORIX.Palette.danger).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, ORIX.Space.sm).padding(.vertical, 3)331 }332 HStack(alignment: .top, spacing: 0) {333 ScrollView {334 VStack(alignment: .leading, spacing: 0) {335 column("Variables", count: snap.variables.count) {336 if snap.variables.isEmpty { none("No variable in scope.") }337 ForEach(Array(snap.variables.enumerated()), id: \.offset) { _, v in row(v.name, v.value.display()) }338 }339 column("Handlers", count: snap.handlers.count) {340 if snap.handlers.isEmpty { none("No event handler registered.") }341 ForEach(Array(snap.handlers.enumerated()), id: \.offset) { _, h in row(h, "") }342 }343 column("Pending tasks", count: snap.tasks.count) {344 if snap.tasks.isEmpty { none("No pending task.") }345 ForEach(Array(snap.tasks.enumerated()), id: \.offset) { _, t in346 row("#\(t.id)" + (t.isHandler ? " handler" : "") + (t.line > 0 ? " · line \(t.line)" : ""), "wakes at beat \(StudioFormat.number(max(0, t.wakeBeat - snap.startBeat)))")347 }348 }349 column("Active ramps", count: snap.ramps.count) {350 if snap.ramps.isEmpty { none("No ramp in progress.") }351 ForEach(Array(snap.ramps.enumerated()), id: \.offset) { _, r in352 VStack(alignment: .leading, spacing: 0) {353 row(r.address.description, r.curve.rawValue)354 row(" \(StudioFormat.value(r.from, of: r.address)) → \(StudioFormat.value(r.to, of: r.address))",355 "beats \(StudioFormat.number(r.startBeat - snap.startBeat)) – \(StudioFormat.number(r.endBeat - snap.startBeat))")356 }357 }358 }359 }360 }361 .frame(width: 290)362 Divider().overlay(ORIX.Palette.hairline)363 ScrollViewReader { proxy in364 ScrollView {365 TraceTable(trace: snap.trace) { line in studio.selectLine(line, in: session.docID, model: model) }366 Color.clear.frame(height: 1).id("end")367 }368 .onChange(of: snap.trace.count) { _, _ in proxy.scrollTo("end", anchor: .bottom) }369 }370 .frame(maxWidth: .infinity)371 .accessibilityIdentifier("automation-debugger-trace")372 }373 .background(ORIX.Palette.surface)374 } else if studio.debugMessage == nil {375 EmptyState(symbol: "ant", title: "No debug session", message: "Click the gutter of the editor to set breakpoints, then start. Without a breakpoint the session pauses on the first statement.",376 actionTitle: "Start Debugging", action: { studio.debugActive(model: model) })377 } else { Spacer() }378 }379 .accessibilityElement(children: .contain).accessibilityIdentifier("automation-debugger")380 }381}382