SPB Git

Repository Public

AutomationStudioState.swift 27.0 KB 645 lines swift

1// ORIX DJ2// File: App/Sources/Features/AutomationStudio/AutomationStudioState.swift3// Description: State of the Automation Studio: validation results, breakpoints, simulation settings and results, the4//              debugger session, editor controllers and the studio's launch options. Slow work runs off the main thread.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AppKit9import ORIXDJCore10import SwiftUI1112enum StudioMode: String, CaseIterable, Identifiable, Sendable {13    case editor, presets, builder14    var id: String { rawValue }15    var title: LocalizedStringKey {16        switch self {17        case .editor: "Editor"18        case .presets: "Presets"19        case .builder: "Visual Builder"20        }21    }22    var symbol: String {23        switch self {24        case .editor: "chevron.left.forwardslash.chevron.right"25        case .presets: "square.grid.2x2"26        case .builder: "rectangle.connected.to.line.below"27        }28    }29}3031enum StudioTab: String, CaseIterable, Identifiable, Sendable {32    case console, simulator, debugger, problems, log, monitor33    var id: String { rawValue }34    var title: LocalizedStringKey {35        switch self {36        case .console: "Console"37        case .simulator: "Simulator"38        case .debugger: "Debugger"39        case .problems: "Problems"40        case .log: "Log"41        case .monitor: "Monitor"42        }43    }44    var symbol: String {45        switch self {46        case .console: "terminal"47        case .simulator: "chart.xyaxis.line"48        case .debugger: "ant"49        case .problems: "exclamationmark.triangle"50        case .log: "list.bullet.rectangle"51        case .monitor: "gauge.with.dots.needle.67percent"52        }53    }54}5556struct SimTrigger: Identifiable, Equatable, Sendable {57    var id = UUID()58    var beat: Double59    var number: Int60}6162/// What the simulated rig looks like when Simulate or Debug starts.63struct SimSettings: Equatable, Sendable {64    var bpm = 128.065    var deckLoaded = [true, true, false, false]66    var deckPlaying = [true, false, false, false]67    var maxBeats = 256.068    var triggers: [SimTrigger] = []6970    var config: SimulationConfig {71        var c = SimulationConfig()72        c.bpm = bpm73        c.maxBeats = maxBeats74        c.decks = (0 ..< ScriptSchema.deckCount).map { d in75            SimulatedDeckConfig(loaded: deckLoaded[d], playing: deckLoaded[d] && deckPlaying[d], bpm: bpm, title: deckLoaded[d] ? "Track \(deckLetters[d])" : "")76        }77        c.triggers = triggers.map { (beat: $0.beat, number: $0.number) }78        return c79    }80}8182struct ScriptValidation: Sendable {83    var source: String84    var result: CompileResult85}8687/// One finished simulation.88struct SimulationRun: Sendable {89    var docID: UUID?90    var title: String91    var automation: String92    var source: String93    var settings: SimSettings94    var result: SimulationResult95    var lengthBeats: Double?96}9798/// Everything the debugger panel shows while a session is paused or over.99struct DebugSnapshot: Sendable {100    var pausedLine: Int?101    var beat: Double102    var startBeat: Double103    var state: AutomationState104    var timedOut: Bool105    var isOver: Bool106    var variables: [VariableSnapshot]107    var tasks: [TaskSnapshot]108    var ramps: [RampSnapshot]109    var handlers: [String]110    var trace: [TraceEvent]111    var stats: AutomationStats112}113114/// Owns a `DebugSession` on a private queue. The session is single-threaded; nothing else touches it.115final class DebugController: @unchecked Sendable {116    private let queue = DispatchQueue(label: "ai.spboucher.orix.dj.debugger", qos: .userInitiated)117    private var session: DebugSession?118119    private func snapshot(_ s: DebugSession) -> DebugSnapshot {120        let i = s.instance121        return DebugSnapshot(pausedLine: s.isOver ? nil : i.pausedAtLine, beat: s.beat, startBeat: i.startBeat, state: i.state, timedOut: s.timedOut, isOver: s.isOver,122                             variables: i.variables, tasks: i.taskSnapshots, ramps: i.rampSnapshots, handlers: i.handlerDescriptions, trace: s.trace, stats: i.stats)123    }124125    private func perform(_ work: @escaping @Sendable (DebugSession) -> Void) async -> DebugSnapshot? {126        await withCheckedContinuation { continuation in127            queue.async {128                guard let s = self.session else { continuation.resume(returning: nil); return }129                work(s)130                continuation.resume(returning: self.snapshot(s))131            }132        }133    }134135    /// Starts a session and runs to the first breakpoint, or pauses on the first statement when there is none.136    func start(program: Program, automation: CompiledAutomation, config: SimulationConfig, breakpoints: Set<Int>) async -> DebugSnapshot {137        await withCheckedContinuation { continuation in138            queue.async {139                let s = DebugSession(program: program, automation: automation, config: config)140                s.instance.breakpoints = breakpoints141                s.instance.stepping = breakpoints.isEmpty142                self.session = s143                s.run()144                continuation.resume(returning: self.snapshot(s))145            }146        }147    }148149    func resume(breakpoints: Set<Int>) async -> DebugSnapshot? { await perform { $0.instance.breakpoints = breakpoints; $0.resume() } }150    func step(breakpoints: Set<Int>) async -> DebugSnapshot? { await perform { $0.instance.breakpoints = breakpoints; $0.stepOver() } }151    func end() { queue.async { self.session = nil } }152}153154struct DebugState {155    var docID: UUID156    var title: String157    var automation: String158    var source: String159    var settings: SimSettings160    var snapshot: DebugSnapshot161}162163/// A live run waiting for the user's confirmation because a deck is playing.164struct PendingLiveRun: Identifiable {165    var id = UUID()166    var source: String167    var automation: String?168    var title: String169    var origin: String170}171172@MainActor @Observable173final class AutomationStudioState {174    var mode: StudioMode = .editor175    var tab: StudioTab = .console176    var showExplorer = true177    var showInspector = true178179    var validations: [UUID: ScriptValidation] = [:]180    var validating: Set<UUID> = []181    var breakpoints: [UUID: Set<Int>] = [:]182    /// Automation chosen for Run, Simulate and Debug when a script defines several.183    var selectedAutomation: [UUID: String] = [:]184185    var settings = SimSettings()186    var simulation: SimulationRun?187    var simulationBusy = false188    var simulationMessage: String?189190    var debug: DebugState?191    var debugBusy = false192    var debugMessage: String?193194    var caretPath: String?195    var caretLine = 1196    var caretColumn = 1197    var hoverPath: String?198199    var pendingRun: PendingLiveRun?200    var closeRequest: UUID?201    var saveAsRequest = false202    var saveAsName = ""203204    /// Lines with an id at or below this are hidden by the Log tab's Clear button.205    var logClearedThroughID = 0206207    let builder = VisualBuilderState()208209    @ObservationIgnored private var editors: [UUID: CodeEditorController] = [:]210    @ObservationIgnored private var validationTasks: [UUID: Task<Void, Never>] = [:]211    @ObservationIgnored private let debugger = DebugController()212    @ObservationIgnored private var launchOptionsApplied = false213214    // MARK: Editors215216    func editor(for doc: ScriptDocument, model: AppModel) -> CodeEditorController {217        if let e = editors[doc.id] { return e }218        let e = CodeEditorController(docID: doc.id, source: doc.source)219        let id = doc.id220        e.onTextChange = { [weak self, weak model] text in221            guard let self, let model, let i = model.documents.firstIndex(where: { $0.id == id }) else { return }222            if model.documents[i].source != text { model.documents[i].source = text }223            self.scheduleValidation(id: id, source: text)224        }225        e.onCaret = { [weak self] path, line, column in226            guard let self else { return }227            if self.caretPath != path { self.caretPath = path }228            if self.caretLine != line { self.caretLine = line }229            if self.caretColumn != column { self.caretColumn = column }230        }231        e.onHover = { [weak self] path in if self?.hoverPath != path { self?.hoverPath = path } }232        e.onBreakpointsChange = { [weak self] set in self?.breakpoints[id] = set }233        e.onCommand = { [weak self, weak model] command in234            guard let self, let model else { return }235            self.perform(command, model: model)236        }237        editors[doc.id] = e238        return e239    }240241    func existingEditor(_ id: UUID?) -> CodeEditorController? { id.flatMap { editors[$0] } }242243    /// Drops editors and results of documents that were closed.244    func prune(openDocuments: [ScriptDocument]) {245        let open = Set(openDocuments.map(\.id))246        for id in editors.keys where !open.contains(id) { editors[id] = nil; validations[id] = nil; breakpoints[id] = nil; validationTasks[id]?.cancel(); validationTasks[id] = nil }247    }248249    func jump(to line: Int, column: Int = 1, in docID: UUID?, model: AppModel) {250        guard let docID, model.documents.contains(where: { $0.id == docID }) else { return }251        mode = .editor252        model.activeDocumentID = docID253        // The editor of a tab that was not shown yet is created by the next layout pass.254        Task { @MainActor in self.editors[docID]?.reveal(line: line, column: column) }255    }256257    func selectLine(_ line: Int, in docID: UUID?, model: AppModel) {258        guard line > 0, let docID, model.documents.contains(where: { $0.id == docID }) else { return }259        mode = .editor260        model.activeDocumentID = docID261        Task { @MainActor in self.editors[docID]?.selectLine(line) }262    }263264    // MARK: Validation265266    /// Validates ~300 ms after the last change, off the main thread.267    func scheduleValidation(id: UUID, source: String, delay: Duration = .milliseconds(300)) {268        if validations[id]?.source == source { return }269        validationTasks[id]?.cancel()270        validating.insert(id)271        validationTasks[id] = Task { [weak self] in272            try? await Task.sleep(for: delay)273            if Task.isCancelled { return }274            let result = await Task.detached(priority: .userInitiated) { ScriptCompiler.compile(source) }.value275            if Task.isCancelled { return }276            self?.validations[id] = ScriptValidation(source: source, result: result)277            self?.validating.remove(id)278        }279    }280281    /// Validates now and waits for the result.282    @discardableResult283    func validate(id: UUID, source: String) async -> CompileResult {284        if let v = validations[id], v.source == source { return v.result }285        validationTasks[id]?.cancel()286        validating.insert(id)287        let result = await Task.detached(priority: .userInitiated) { ScriptCompiler.compile(source) }.value288        validations[id] = ScriptValidation(source: source, result: result)289        validating.remove(id)290        return result291    }292293    func diagnostics(for doc: ScriptDocument?) -> [Diagnostic] { doc.flatMap { validations[$0.id]?.result.diagnostics } ?? [] }294295    func automationName(for docID: UUID, program: Program) -> String? {296        if let chosen = selectedAutomation[docID], program.automation(named: chosen) != nil { return chosen }297        return program.automations.first?.name298    }299300    // MARK: Commands301302    func perform(_ command: EditorCommand, model: AppModel) {303        switch command {304        case .save: save(model: model)305        case .saveAs: beginSaveAs(model: model)306        case .run: requestRunActive(model: model)307        case .stop: stopActiveScript(model: model)308        case .validate: validateActive(model: model)309        case .simulate: simulateActive(model: model)310        case .format: formatActive(model: model)311        }312    }313314    func save(model: AppModel) {315        guard let doc = model.activeDocument else { return }316        if doc.recordID == nil { beginSaveAs(model: model) } else { model.saveActiveDocument() }317    }318319    func beginSaveAs(model: AppModel) {320        guard let doc = model.activeDocument else { return }321        // Propose the automation's own name for a script that was never saved.322        let declared = Parser.parse(doc.source).file.automations.first?.name323        saveAsName = doc.recordID == nil ? (declared ?? doc.name) : doc.name + " copy"324        saveAsRequest = true325    }326327    func confirmSaveAs(model: AppModel) {328        let name = saveAsName.trimmingCharacters(in: .whitespacesAndNewlines)329        guard !name.isEmpty else { return }330        if model.saveActiveDocument(as: name) { saveAsRequest = false }331    }332333    func duplicateActive(model: AppModel) {334        guard let doc = model.activeDocument else { return }335        model.newDocument(name: doc.name + " copy", source: doc.source, origin: .user)336    }337338    func formatActive(model: AppModel) {339        guard let doc = model.activeDocument else { return }340        let formatted = ScriptFormatter.format(doc.source)341        guard formatted != doc.source else { model.show(notice: "Already formatted"); return }342        if let e = editors[doc.id] { e.replaceAll(with: formatted, undoable: true) }343        else if let i = model.documents.firstIndex(where: { $0.id == doc.id }) { model.documents[i].source = formatted }344    }345346    func validateActive(model: AppModel) {347        guard let doc = model.activeDocument else { return }348        Task {349            let result = await validate(id: doc.id, source: doc.source)350            if result.diagnostics.isEmpty { model.show(notice: "\"\(doc.name)\" is valid") }351            else {352                tab = .problems353                model.show(notice: "\(result.errors.count) error\(result.errors.count == 1 ? "" : "s"), \(result.warnings.count) warning\(result.warnings.count == 1 ? "" : "s")")354            }355        }356    }357358    // MARK: Live runs359360    func requestRunActive(model: AppModel) {361        guard let doc = model.activeDocument else { return }362        Task {363            let result = await validate(id: doc.id, source: doc.source)364            guard let program = result.program else {365                model.host.noteValidationError()366                tab = .problems367                if let first = result.errors.first { model.show(notice: "Line \(first.location.line): \(first.message)") }368                return369            }370            requestRun(source: doc.source, automation: automationName(for: doc.id, program: program), title: doc.name, origin: "editor", model: model)371        }372    }373374    /// Starts a script on the live engine, asking first when a deck is playing.375    func requestRun(source: String, automation: String?, title: String, origin: String, model: AppModel) {376        let run = PendingLiveRun(source: source, automation: automation, title: title, origin: origin)377        if model.decks.contains(where: { $0.playing }) { pendingRun = run } else { start(run, model: model) }378    }379380    func start(_ run: PendingLiveRun, model: AppModel) {381        pendingRun = nil382        let result = ScriptCompiler.compile(run.source)383        guard let program = result.program else {384            model.host.noteValidationError()385            if let first = result.errors.first { model.show(notice: "Line \(first.location.line): \(first.message)") }386            return387        }388        if let name = run.automation, name != program.automations.first?.name {389            // `model.run` starts the first automation of a script; another one is started on the same host.390            if model.host.start(program, automation: name, origin: run.origin) != nil { model.show(notice: "Automation \"\(name)\" started") }391            model.refreshNow()392        } else {393            _ = model.run(source: run.source, origin: run.origin)394        }395    }396397    /// Stops the runs started from the active script; when none is running, stops every automation.398    func stopActiveScript(model: AppModel) {399        let names = model.activeDocument.flatMap { validations[$0.id]?.result.program?.automations.map(\.name) } ?? []400        let mine = model.runs.filter { names.contains($0.name) }401        if mine.isEmpty { model.host.stopAll() } else { for r in mine { model.host.stop(run: r.id) } }402        model.refreshNow()403    }404405    // MARK: Simulation406407    func simulateActive(model: AppModel) {408        guard let doc = model.activeDocument else { return }409        simulate(source: doc.source, title: doc.name, docID: doc.id, automation: selectedAutomation[doc.id])410    }411412    func simulate(source: String, title: String, docID: UUID?, automation: String? = nil) {413        tab = .simulator414        simulationBusy = true415        simulationMessage = nil416        let settings = settings417        Task {418            let outcome: (SimulationRun?, String?) = await Task.detached(priority: .userInitiated) {419                let compiled = ScriptCompiler.compile(source)420                guard let program = compiled.program else {421                    let first = compiled.errors.first422                    return (nil, first.map { "The script does not compile. Line \($0.location.line): \($0.message)" } ?? "The script does not compile.")423                }424                guard let chosen = automation.flatMap({ program.automation(named: $0) }) ?? program.automations.first,425                      let result = Simulator.run(program, automation: chosen.name, config: settings.config) else { return (nil, "The script defines no automation.") }426                return (SimulationRun(docID: docID, title: title, automation: chosen.name, source: source, settings: settings, result: result, lengthBeats: chosen.requirements.lengthBeats), nil)427            }.value428            simulationBusy = false429            if let run = outcome.0 { simulation = run }430            simulationMessage = outcome.1431        }432    }433434    // MARK: Debugger435436    func debugActive(model: AppModel) {437        guard let doc = model.activeDocument else { return }438        tab = .debugger439        debugBusy = true440        debugMessage = nil441        let settings = settings442        let points = breakpoints[doc.id] ?? []443        let chosen = selectedAutomation[doc.id]444        Task {445            let result = await validate(id: doc.id, source: doc.source)446            guard let program = result.program, let automation = chosen.flatMap({ program.automation(named: $0) }) ?? program.automations.first else {447                debugBusy = false448                debug = nil449                debugMessage = result.errors.first.map { "The script does not compile. Line \($0.location.line): \($0.message)" } ?? "The script defines no automation."450                return451            }452            let snapshot = await debugger.start(program: program, automation: automation, config: settings.config, breakpoints: points)453            debug = DebugState(docID: doc.id, title: doc.name, automation: automation.name, source: doc.source, settings: settings, snapshot: snapshot)454            debugBusy = false455        }456    }457458    func debugContinue() { advanceDebugger(step: false) }459    func debugStep() { advanceDebugger(step: true) }460461    private func advanceDebugger(step: Bool) {462        guard let current = debug, !current.snapshot.isOver, !debugBusy else { return }463        debugBusy = true464        let points = breakpoints[current.docID] ?? []465        Task {466            let snapshot = step ? await debugger.step(breakpoints: points) : await debugger.resume(breakpoints: points)467            if let snapshot, debug?.docID == current.docID { debug?.snapshot = snapshot }468            debugBusy = false469        }470    }471472    func debugStop() {473        debugger.end()474        debug = nil475        debugMessage = nil476    }477478    /// Line highlighted in the editor of `docID` while the debugger is paused there.479    func pausedLine(for docID: UUID) -> Int? {480        guard let d = debug, d.docID == docID else { return nil }481        return d.snapshot.pausedLine482    }483484    // MARK: Launch options485486    /// `-ORIXAutomationTab`, `-ORIXAutomationMode`, `-ORIXAutomationPreset`, `-ORIXAutomationSourceFile`,487    /// `-ORIXAutomationBreakpoints`, `-ORIXConsoleScript`, `-ORIXAutomationBuilderImport`, `-ORIXBuilderSelfCheck`.488    func applyLaunchOptions(model: AppModel) {489        guard !launchOptionsApplied else { return }490        launchOptionsApplied = true491        let defaults = UserDefaults.standard492        if let t = defaults.string(forKey: "ORIXAutomationTab").flatMap(StudioTab.init(rawValue:)) { tab = t }493        if let m = defaults.string(forKey: "ORIXAutomationMode").flatMap(StudioMode.init(rawValue:)) { mode = m }494        var opened = false495        if let name = defaults.string(forKey: "ORIXAutomationPreset"), let preset = PresetLibrary.preset(named: name) {496            model.newDocument(name: preset.name, source: preset.source, origin: .preset)497            opened = true498        } else if let path = defaults.string(forKey: "ORIXAutomationSourceFile"), let text = try? String(contentsOfFile: path, encoding: .utf8) {499            model.newDocument(name: URL(fileURLWithPath: path).deletingPathExtension().lastPathComponent, source: text)500            opened = true501        }502        if let doc = model.activeDocument {503            if let list = defaults.string(forKey: "ORIXAutomationBreakpoints") {504                breakpoints[doc.id] = Set(list.split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) })505            }506            scheduleValidation(id: doc.id, source: doc.source, delay: .zero)507            if opened {508                if tab == .simulator { simulateActive(model: model) }509                if tab == .debugger { debugActive(model: model) }510            }511            if defaults.bool(forKey: "ORIXAutomationBuilderImport") { builder.importScript(doc.source, model: model) }512        }513        if let actions = defaults.string(forKey: "ORIXAutomationEditorActions") {514            Task {515                try? await Task.sleep(for: .seconds(2))516                self.existingEditor(model.activeDocumentID)?.perform(actions: actions)517            }518        }519        if let script = defaults.string(forKey: "ORIXConsoleScript") {520            // The demo decks load asynchronously; give them a moment so the commands see a real rig.521            Task {522                try? await Task.sleep(for: .seconds(3))523                for line in script.split(separator: ";") { model.runConsole(String(line)) }524            }525        }526        #if DEBUG527        if defaults.bool(forKey: "ORIXBuilderSelfCheck") {528            let results = VBRoundTrip.runAll()529            for r in results { print("ORIX-BUILDER-CHECK \(r.passed ? "PASS" : "FAIL") \(r.name): \(r.detail)") }530            print("ORIX-BUILDER-CHECK SUMMARY \(results.filter(\.passed).count)/\(results.count) passed")531            fflush(stdout)532        }533        #endif534    }535}536537// MARK: - Shared formatting538539enum StudioFormat {540    static func number(_ x: Double, decimals: Int = 2) -> String {541        if x == x.rounded(), abs(x) < 1e9 { return String(Int(x)) }542        var s = String(format: "%.\(decimals)f", locale: Locale(identifier: "en_US_POSIX"), x)543        while s.hasSuffix("0") { s.removeLast() }544        if s.hasSuffix(".") { s.removeLast() }545        return s546    }547548    /// "32 beats (8 bars)".549    static func length(_ beats: Double) -> String {550        let bars = beats / ORIXScriptLanguage.beatsPerBar551        return "\(number(beats)) beat\(beats == 1 ? "" : "s") (\(number(bars)) bar\(bars == 1 ? "" : "s"))"552    }553554    /// "bar 3 · beat 2" for a zero-based beat offset.555    static func position(_ beat: Double) -> String {556        let b = max(0, beat)557        let bar = Int(b / 4) + 1558        return "bar \(bar) · beat \(number(b - Double(bar - 1) * 4 + 1))"559    }560561    /// A scalar of a parameter in its own unit ("-12 dB", "1.2 kHz").562    static func value(_ scalar: Double, of address: ParamAddress) -> String {563        guard let def = ScriptSchema.definition(for: address) else { return number(scalar) }564        switch def.type {565        case .gain: return Value.gain(scalar).display()566        case .frequency: return Value.frequency(scalar).display()567        case .bool: return scalar >= 0.5 ? "on" : "off"568        case .duration: return def.durationUnit == .beats ? Value.duration(.beats(scalar)).display() : Value.duration(.seconds(scalar)).display()569        default: return Value.number(scalar).display(unit: def.unit)570        }571    }572573    static func state(_ state: AutomationState, timedOut: Bool = false) -> (text: String, symbol: String, color: Color) {574        if timedOut, state.isAlive { return ("Timed out", "clock.badge.exclamationmark", ORIX.Palette.warning) }575        switch state {576        case .running: return ("Running", "play.fill", ORIX.Palette.success)577        case .paused: return ("Paused", "pause.fill", ORIX.Palette.warning)578        case .finished: return ("Finished", "checkmark.circle.fill", ORIX.Palette.success)579        case .stopped: return ("Stopped", "stop.circle.fill", ORIX.Palette.textSecondary)580        case .failed: return ("Failed", "xmark.octagon.fill", ORIX.Palette.danger)581        }582    }583584    static func trace(_ kind: TraceKind) -> (symbol: String, color: Color) {585        switch kind {586        case .start: ("flag", ORIX.Palette.textSecondary)587        case .write: ("slider.horizontal.3", ORIX.Palette.accentSecondary)588        case .action: ("bolt.fill", ORIX.Palette.accent)589        case .wait: ("hourglass", ORIX.Palette.textTertiary)590        case .spawn: ("arrow.triangle.branch", ORIX.Palette.textSecondary)591        case .ramp: ("line.diagonal.arrow", ORIX.Palette.accentSecondary)592        case .rampEnd: ("arrow.right.to.line", ORIX.Palette.textTertiary)593        case .handler, .event: ("antenna.radiowaves.left.and.right", ORIX.Palette.accent)594        case .print: ("text.bubble", ORIX.Palette.textPrimary)595        case .warning: ("exclamationmark.triangle.fill", ORIX.Palette.warning)596        case .error: ("xmark.octagon.fill", ORIX.Palette.danger)597        case .finish: ("flag.checkered", ORIX.Palette.success)598        case .breakpoint: ("pause.circle", ORIX.Palette.warning)599        }600    }601}602603/// Small header used by every pane.604struct PaneHeader<Trailing: View>: View {605    var title: LocalizedStringKey606    @ViewBuilder var trailing: Trailing607608    var body: some View {609        HStack(spacing: ORIX.Space.xs) {610            SectionLabel(title)611            Spacer(minLength: 4)612            trailing613        }614        .padding(.horizontal, ORIX.Space.sm)615        .frame(height: 30)616        .background(ORIX.Palette.surface)617    }618}619620/// Icon button used in the studio's toolbars.621struct StudioIconButton: View {622    var title: LocalizedStringKey623    var symbol: String624    var tint: Color = ORIX.Palette.textPrimary625    var showsTitle = false626    var action: () -> Void627628    var body: some View {629        Button(action: action) {630            HStack(spacing: 4) {631                Image(systemName: symbol).font(.system(size: 11, weight: .semibold))632                if showsTitle { Text(title).font(.system(size: 11, weight: .medium)).lineLimit(1).fixedSize() }633            }634            .padding(.horizontal, showsTitle ? 8 : 6).frame(minWidth: 26, minHeight: 24)635            .foregroundStyle(tint)636            .background(ORIX.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous))637            .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.chip, style: .continuous).strokeBorder(ORIX.Palette.hairline))638            .contentShape(Rectangle())639        }640        .buttonStyle(.plain)641        .help(title)642        .accessibilityLabel(title)643    }644}645
Files main
Menu

Theme