diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 884a356a5d..6be566f3f8 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -89,8 +89,8 @@ file, and one that stops must not hide another's server from the stdio bridge. `GUI_App::on_init_inner()` starts the service once AppConfig is loaded. That is before the first startup dialog, such as the TLS prompt or the setup wizard, so an agent can answer those dialogs. -`--mcp` or the `mcp_enabled` preference opens the endpoint, while `--mcp-script` alone only builds -the catalog. `get_state.ready` stays false until `post_init()` calls `mark_ready()`, the Prepare +`--mcp` or the `mcp_enabled` preference opens the endpoint, while `--mcp-script` alone, or opening the +Run Script dialog, only builds the catalog. `get_state.ready` stays false until `post_init()` calls `mark_ready()`, the Prepare canvas has loaded OpenGL and the main window has built its tab pages, and tools that need the main window fail with "still starting". Starting on Home, the canvas loads OpenGL at idle after `post_init()` (MainFrame's GL prebuild), and before that a 3MF save would draw its thumbnail with no @@ -1773,12 +1773,25 @@ at once and stores it under `save_as`, so later steps can answer a dialog it ope `wait` for it. `expect` maps JSON pointers into the result to matchers (`eq ne gt ge lt le contains regex exists empty`). A failed step or expectation stops the run unless the step is `optional`. Auto-answer rules registered by a script end with it. `vars` passed to `run_script` override the -script's. A step naming an unknown tool makes the script invalid before anything runs. The result, -also written to `/result.json`, is -`{passed, name, failed_step, steps: [{index, tool, args, ok, result | error, expect_failure}], -out_dir, result_file}`. A script file's `out_dir` defaults to ` + + + + +
+
+ + + +
+ +
+
+ +
+
+

Open a script file or paste one to see what it will do.

+
+ + +
+
+ +
+
+ +
+ + +
+
+ +
+
+ + +
+ + + + +
+
+ + diff --git a/resources/web/dialog/ScriptRunner/script_runner.js b/resources/web/dialog/ScriptRunner/script_runner.js new file mode 100644 index 0000000000..86009d359e --- /dev/null +++ b/resources/web/dialog/ScriptRunner/script_runner.js @@ -0,0 +1,468 @@ +// Script runner page. The host (ScriptRunnerDialog) parses, describes and runs scripts and words what +// it reports; this page shows the steps as a rail that fills in as the script runs, and asks. + +const FLAG_LABELS = { + writes_file: ["flag_writes_file", "Writes a file"], + changes_presets: ["flag_changes_presets", "Changes presets"], + replaces_project: ["flag_replaces_project", "Replaces the project"], + sends_to_printer: ["flag_sends_to_printer", "Sends to a printer"], +}; + +const state = { + ready: false, + origin: "", // "file" or "paste" + fileName: "", + loadedText: null, // the opened file's text, to tell when the source is edited + parseSeq: 0, + parseTimer: 0, + parsed: null, // the host's last description: {ok, error, name, steps, count_text} + stale: false, // the text has changed since the host described it; Run waits for the new description + pending: false, // Run was pressed and the host hasn't started or refused the run yet + running: false, + single: null, // the step of a single-step run + total: 0, + started: new Map(), // step index -> start time of a running step + results: new Map(), // step index -> what the host reported when it finished + skipped: new Set(), + open: new Set(), // step indexes opened to their details + outcome: null, // the last run's {kind, text, detail} + outDir: "", + hasRun: false, + message: null, // a refusal or error to show in the footer: {kind, text, detail} +}; + +const rows = new Map(); // step index -> its
  • +let ticker = 0; + +function $(id) { return document.getElementById(id); } + +function send(command, extra) { + SendWXMessage(JSON.stringify(Object.assign({ command }, extra || {}))); +} + +function el(tag, className, text) { + const node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined && text !== null) node.textContent = text; + return node; +} + +function seconds(ms) { return T("seconds", "%s s", (ms / 1000).toFixed(1)); } + +// ---- source ----------------------------------------------------------------------------------- + +function sourceText() { return $("source").value; } + +function scheduleParse(delay) { + clearTimeout(state.parseTimer); + // Numbered now, so a description of the text before this change is not taken for this one. + const seq = ++state.parseSeq; + state.stale = true; + state.parseTimer = setTimeout(() => { + const text = sourceText(); + if (!text.trim()) { + onParsed({ seq, ok: false, empty: true }); + return; + } + send("parse", { text, seq }); + }, delay); +} + +function onSource(msg) { + state.origin = msg.origin; + state.fileName = msg.file_name || ""; + state.loadedText = msg.origin === "file" ? msg.text : null; + $("source").value = msg.text; + if (msg.origin === "paste") setSectionOpen("source-section", true); + resetRun(); + scheduleParse(0); +} + +function onSourceInput() { + if (!state.origin) state.origin = "paste"; + scheduleParse(250); + render(); +} + +function renderChip() { + const text = sourceText(); + const shown = state.origin === "file" || text.trim() !== ""; + $("chip").hidden = !shown; + if (!shown) return; + $("chip-name").textContent = state.origin === "file" ? state.fileName : T("pasted_script", "Pasted script"); + $("chip-edited").hidden = !(state.origin === "file" && state.loadedText !== null && text !== state.loadedText); +} + +// ---- sections --------------------------------------------------------------------------------- + +function setSectionOpen(id, open) { + const section = $(id); + section.classList.toggle("is-open", open); + const head = section.querySelector(".section-head"); + head.setAttribute("aria-expanded", String(open)); + $(head.getAttribute("aria-controls")).hidden = !open; +} + +function toggleSection(id) { setSectionOpen(id, !$(id).classList.contains("is-open")); } + +// ---- the step list ---------------------------------------------------------------------------- + +function onParsed(msg) { + if (msg.seq !== state.parseSeq) return; // an answer to text that has changed since + // Run waits for the latest description and the text is frozen from the click on, so no answer can + // arrive for a run's script; none may reset a run's log either way. + if (busy()) return; + state.stale = false; + state.parsed = msg; + resetRun(); + buildRail(); + render(); +} + +function resetRun() { + state.results.clear(); + state.skipped.clear(); + state.started.clear(); + state.open.clear(); + state.outcome = null; + state.message = null; + state.hasRun = false; +} + +function buildRail() { + const rail = $("steps"); + rail.textContent = ""; + rows.clear(); + const steps = state.parsed && state.parsed.ok ? state.parsed.steps : []; + for (const step of steps) { + const row = makeRow(step); + rows.set(step.index, row); + rail.appendChild(row); + } +} + +function makeRow(step) { + const row = el("li", "step is-wait"); + row.dataset.index = step.index; + + row.appendChild(el("span", "dot", String(step.index))); + + const main = el("div", "step-main"); + const head = el("button", "step-head"); + head.type = "button"; + head.setAttribute("aria-expanded", "false"); + head.appendChild(el("span", "step-title", step.title)); + if (step.what_text) head.appendChild(el("span", "step-what", step.what_text)); + if (step.param_text) head.appendChild(el("span", "step-param", step.param_text)); + const tags = el("span", "step-tags"); + for (const id of step.flags || []) { + const label = FLAG_LABELS[id]; + if (label) tags.appendChild(el("span", "tag", T(label[0], label[1]))); + } + if (step.checks_result) tags.appendChild(el("span", "tag is-check", T("checks_result", "Checks the result"))); + if (tags.childNodes.length) head.appendChild(tags); + head.addEventListener("click", () => toggleStep(step.index)); + main.appendChild(head); + + const detail = el("div", "step-detail"); + detail.hidden = true; + main.appendChild(detail); + row.appendChild(main); + + const side = el("div", "step-side"); + side.appendChild(el("span", "time")); + const play = el("button", "play", "▷"); + play.type = "button"; + play.title = T("run_this_step", "Run this step"); + play.setAttribute("aria-label", play.title); + play.addEventListener("click", () => runStep(step.index)); + side.appendChild(play); + row.appendChild(side); + return row; +} + +function stepOf(index) { + return state.parsed && state.parsed.ok ? state.parsed.steps.find((s) => s.index === index) : null; +} + +function toggleStep(index) { + if (state.open.has(index)) state.open.delete(index); + else state.open.add(index); + renderRow(index); +} + +function renderRow(index) { + const row = rows.get(index); + const step = stepOf(index); + if (!row || !step) return; + const result = state.results.get(index); + let status = "wait"; + if (state.started.has(index)) status = "running"; + else if (result) status = result.cancelled ? "stopped" : !result.ok ? "fail" : result.warning_text ? "warn" : "done"; + else if (state.skipped.has(index)) status = "skip"; + row.className = "step is-" + status + (state.open.has(index) ? " is-open" : ""); + + const dot = row.querySelector(".dot"); + dot.textContent = status === "done" ? "✓" : status === "fail" || status === "stopped" || status === "warn" ? "!" : String(index); + + const time = row.querySelector(".time"); + if (status === "running") time.textContent = seconds(Date.now() - state.started.get(index)); + else if (result) time.textContent = seconds(result.duration_ms || 0); + else if (status === "skip") time.textContent = T("skipped", "Skipped"); + else time.textContent = ""; + + row.querySelector(".play").disabled = !canRun(); + const head = row.querySelector(".step-head"); + head.setAttribute("aria-expanded", String(state.open.has(index))); + const detail = row.querySelector(".step-detail"); + detail.hidden = !state.open.has(index); + if (!detail.hidden) fillDetail(detail, step, result); +} + +function fillDetail(detail, step, result) { + detail.textContent = ""; + const args = step.args || {}; + const keys = Object.keys(args); + if (keys.length) { + const dl = el("dl", "args"); + for (const key of keys) { + dl.appendChild(el("dt", "", key)); + const value = args[key]; + dl.appendChild(el("dd", "", typeof value === "string" ? value : JSON.stringify(value))); + } + detail.appendChild(dl); + } + if (step.checks && step.checks.length) { + // A failed check is told in the failure box; after a pass, each one is marked as met. + const checks = el("ul", "checks"); + for (const text of step.checks) checks.appendChild(el("li", result && result.ok ? "is-met" : "", text)); + detail.appendChild(checks); + } + if (result) { + const problem = result.failure_text || result.warning_text; + if (problem) { + const box = el("div", "failure", problem); + const more = result.failure_detail || result.warning_detail; + if (more) box.appendChild(el("span", "failure-detail", more)); + detail.appendChild(box); + } + for (const line of result.result_lines || []) detail.appendChild(el("div", "result-line", line)); + if (result.thumbnail || (result.files && result.files.length)) { + const files = el("div", "files"); + if (result.thumbnail && result.files && result.files.length) { + const img = el("img", "thumb"); + img.src = result.thumbnail; + img.alt = result.files[0].name; + img.addEventListener("click", () => send("open_image", { path: result.files[0].path })); + files.appendChild(img); + } + for (const file of result.files || []) { + const link = el("button", "link", file.name); + link.type = "button"; + link.title = T("show_in_folder", "Show in folder"); + link.addEventListener("click", () => send("open_location", { path: file.path })); + files.appendChild(link); + } + detail.appendChild(files); + } + } + const actions = el("div", "actions"); + const run = el("button", "btn small", "▷ " + T("run_this_step", "Run this step")); + run.type = "button"; + run.disabled = !canRun(); + run.addEventListener("click", () => runStep(step.index)); + actions.appendChild(run); + if (result && result.raw) { + const raw = el("pre", "raw", JSON.stringify(result.raw, null, 2)); + raw.hidden = true; + const toggle = el("button", "link", T("show_raw", "Show raw result")); + toggle.type = "button"; + toggle.addEventListener("click", () => { + raw.hidden = !raw.hidden; + toggle.textContent = raw.hidden ? T("show_raw", "Show raw result") : T("hide_raw", "Hide raw result"); + }); + actions.appendChild(toggle); + detail.appendChild(actions); + detail.appendChild(raw); + } else { + detail.appendChild(actions); + } +} + +// ---- running ---------------------------------------------------------------------------------- + +function busy() { return state.pending || state.running; } + +function canRun() { return state.ready && !busy() && !state.stale && state.parsed && state.parsed.ok; } + +function requestRun(extra) { + if (!canRun()) return; + // Frozen at once: the host may ask about unsaved changes first, and the script must not change meanwhile. + state.pending = true; + send("run", Object.assign({ text: sourceText() }, extra)); + render(); +} + +function runAll() { requestRun({}); } + +function runStep(index) { requestRun({ step: index }); } + +function onRunStarted(msg) { + state.pending = false; + state.running = true; + state.single = msg.step || null; + state.total = state.parsed && state.parsed.ok ? state.parsed.steps.length : 0; + state.message = null; + if (state.single) { + state.results.delete(state.single); + state.skipped.delete(state.single); + } else { + state.results.clear(); + state.skipped.clear(); + state.outcome = null; + } + clearInterval(ticker); + ticker = setInterval(() => state.started.forEach((_, index) => renderRow(index)), 200); + render(); +} + +function onStepStarted(msg) { + state.started.set(msg.index, Date.now()); + renderRow(msg.index); + renderFooter(); + const row = rows.get(msg.index); + if (row) row.scrollIntoView({ block: "nearest" }); +} + +function onStepFinished(msg) { + state.started.delete(msg.index); + state.results.set(msg.index, msg); + if (!msg.ok || msg.warning_text) state.open.add(msg.index); + renderRow(msg.index); +} + +function onRunFinished(msg) { + state.pending = false; + state.running = false; + state.started.clear(); + clearInterval(ticker); + state.outDir = msg.out_dir || state.outDir; + if (!msg.single) { + state.hasRun = true; + // A run that ended early leaves the steps after it unrun. + if (!msg.passed && state.parsed && state.parsed.ok) + for (const step of state.parsed.steps) + if (!state.results.has(step.index)) state.skipped.add(step.index); + } + if (msg.outcome_text) state.outcome = { kind: msg.outcome_kind, text: msg.outcome_text, detail: msg.error_detail || "" }; + render(); +} + +function onRunRefused(msg) { + state.pending = false; + state.running = false; + clearInterval(ticker); + state.message = msg.message ? { kind: "fail", text: msg.message, detail: msg.detail || "" } : null; + render(); +} + +// ---- footer and header -------------------------------------------------------------------------- + +function render() { + const text = sourceText(); + const hasSteps = state.parsed && state.parsed.ok; + $("empty").hidden = text.trim() !== ""; + $("steps").hidden = !hasSteps; + renderChip(); + rows.forEach((_, index) => renderRow(index)); + renderSummary(); + renderFooter(); + + for (const id of ["open-file", "paste", "empty-open", "empty-paste"]) $(id).disabled = busy(); + $("source").readOnly = busy(); +} + +function runningText() { + const index = [...state.started.keys()].pop() || state.single || state.results.size + 1; + return state.single ? T("running_one", "Running step %s", index) : T("running_step", "Running step %s of %s", index, state.total); +} + +function renderSummary() { + const summary = $("steps-summary"); + summary.classList.remove("is-error"); + if (state.running) summary.textContent = runningText(); + else if (state.outcome) summary.textContent = state.outcome.text; + else if (state.parsed && state.parsed.ok) summary.textContent = state.parsed.count_text || ""; + else if (state.parsed && !state.parsed.empty && state.parsed.error) { + summary.textContent = state.parsed.error; + summary.classList.add("is-error"); + } else summary.textContent = ""; +} + +function renderFooter() { + const outcome = $("outcome"); + const detail = $("outcome-detail"); + let shown = null; + if (!state.ready) shown = { kind: "quiet", text: T("starting", "OrcaSlicer is still starting…"), detail: "" }; + else if (state.running) shown = { kind: "quiet", text: runningText(), detail: T("hands_off", "Don't use OrcaSlicer until the script finishes.") }; + else if (state.message) shown = state.message; + else if (state.outcome) shown = state.outcome; + outcome.className = shown ? "is-" + shown.kind : ""; + outcome.textContent = shown ? shown.text : ""; + detail.textContent = shown ? shown.detail : ""; + detail.title = detail.textContent; + + $("run").hidden = state.running; + $("run").disabled = !canRun(); + $("run").textContent = state.hasRun ? T("run_again", "Run again") : T("run", "Run"); + $("stop").hidden = !state.running; + $("open-output").hidden = state.running || !state.outDir; + renderSummary(); +} + +// ---- host messages ------------------------------------------------------------------------------ + +function HandleStudio(msg) { + switch (msg.command) { + case "service": + state.ready = !!msg.ready; + render(); + break; + case "source": onSource(msg); break; + case "parsed": onParsed(msg); break; + case "run_started": onRunStarted(msg); break; + case "step_started": onStepStarted(msg); break; + case "step_finished": onStepFinished(msg); break; + case "run_finished": onRunFinished(msg); break; + case "run_refused": onRunRefused(msg); break; + case "error": + state.pending = false; + state.message = { kind: "fail", text: msg.message, detail: "" }; + render(); + break; + } +} + +function OnInit() { + TranslatePage(); + $("open-file").addEventListener("click", () => send("open_file")); + $("empty-open").addEventListener("click", () => send("open_file")); + $("paste").addEventListener("click", () => send("paste")); + $("empty-paste").addEventListener("click", () => send("paste")); + $("run").addEventListener("click", runAll); + $("stop").addEventListener("click", () => send("stop")); + $("close").addEventListener("click", () => send("close_page")); + $("open-output").addEventListener("click", () => send("open_output")); + for (const id of ["steps-section", "source-section"]) + $(id).querySelector(".section-head").addEventListener("click", () => toggleSection(id)); + const source = $("source"); + source.addEventListener("input", onSourceInput); + source.addEventListener("keydown", (e) => { + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + runAll(); + } + }); + render(); + send("init"); +} diff --git a/resources/web/dialog/ScriptRunner/style.css b/resources/web/dialog/ScriptRunner/style.css new file mode 100644 index 0000000000..bc7fd70f0c --- /dev/null +++ b/resources/web/dialog/ScriptRunner/style.css @@ -0,0 +1,326 @@ +/* Script runner. Colours come from the host theme contract (--orca-*) and theme.css's status roles, + * so the page follows the app in light and dark. The one distinctive element is the step rail: an + * accent thread that fills down the list as steps pass. Everything else stays quiet and host-native. */ + +:root { + --sr-bg: var(--orca-bg, #ffffff); + --sr-fg: var(--orca-fg, #262e30); + --sr-muted: var(--orca-muted, #6b7478); + --sr-rule: var(--border, #dcdfe1); + --sr-accent: var(--orca-accent, #009688); + --sr-accent-fg: var(--orca-accent-fg, #ffffff); + --sr-pass: var(--plugin-status-ok, #137333); + --sr-fail: var(--plugin-status-danger, #b42318); + --sr-fail-bg: var(--plugin-status-danger-bg, rgba(180, 35, 24, 0.12)); + --sr-warn: var(--plugin-status-warn, #a15c00); + --sr-warn-bg: var(--plugin-status-warn-bg, rgba(199, 122, 22, 0.12)); + --sr-hover: var(--row-hover, #f7f9fb); + --sr-footer: var(--footer-bg, #fafafa); + --sr-btn-bg: var(--btn-bg, #ffffff); + --sr-btn-border: var(--btn-border, #cccccc); + --sr-btn-hover: var(--btn-hover, #f0f0f0); + --sr-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12)); + --sr-ring: rgba(0, 150, 136, 0.25); + --sr-ring-soft: rgba(0, 150, 136, 0.1); + --sr-mono: "Cascadia Code", Consolas, "SF Mono", Menlo, "DejaVu Sans Mono", monospace; + --sr-dot: 20px; +} + +* { box-sizing: border-box; } + +html, body { + height: 100%; + margin: 0; + overflow: hidden; + background: var(--sr-bg); + color: var(--sr-fg); + font-family: var(--orca-font, "Segoe UI", system-ui, sans-serif); + font-size: 13px; + line-height: 1.4; +} + +[hidden] { display: none !important; } + +.runner { display: flex; flex-direction: column; height: 100%; } + +/* ---- buttons ---- */ +.btn { + font: inherit; + color: var(--sr-fg); + background: var(--sr-btn-bg); + border: 1px solid var(--sr-btn-border); + border-radius: 4px; + padding: 4px 14px; + cursor: pointer; + white-space: nowrap; +} +.btn:hover:not(:disabled) { background: var(--sr-btn-hover); } +.btn.primary { color: var(--sr-accent-fg); background: var(--sr-accent); border-color: var(--sr-accent); } +.btn.primary:hover:not(:disabled) { background: var(--sr-accent); filter: brightness(1.08); } +.btn.small { padding: 2px 10px; font-size: 12px; } +.btn:disabled { opacity: 0.45; cursor: default; } +.link { + font: inherit; + font-size: 12px; + color: var(--sr-accent); + background: none; + border: 0; + padding: 0; + cursor: pointer; + text-decoration: underline; + text-underline-offset: 2px; +} +button:focus-visible, textarea:focus-visible { outline: 2px solid var(--sr-accent); outline-offset: 1px; } + +/* ---- source bar ---- */ +.source-bar { + flex: none; + display: flex; + align-items: center; + gap: 6px; + padding: 10px 12px; + border-bottom: 1px solid var(--sr-rule); +} +.chip { + margin-left: 6px; + min-width: 0; + display: inline-flex; + align-items: baseline; + gap: 6px; + padding: 2px 8px; + border-radius: 4px; + background: var(--sr-accent-tint); + color: var(--sr-fg); + overflow: hidden; +} +#chip-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.chip-note { color: var(--sr-muted); white-space: nowrap; } + +/* ---- foldable sections ---- */ +.sections { flex: 1; min-height: 0; display: flex; flex-direction: column; } +.section { display: flex; flex-direction: column; min-height: 0; } +.section + .section { border-top: 1px solid var(--sr-rule); } +.section.is-open { flex: 1 1 0; } +#steps-section.is-open { flex-grow: 3; } +#source-section.is-open { flex-grow: 2; } +.section-head { + flex: none; + display: flex; + align-items: center; + gap: 8px; + width: 100%; + padding: 7px 12px; + font: inherit; + font-weight: 600; + color: var(--sr-fg); + background: none; + border: 0; + border-bottom: 1px solid transparent; + text-align: left; + cursor: pointer; +} +.section.is-open .section-head { border-bottom-color: var(--sr-rule); } +.section-head:hover { background: var(--sr-hover); } +.chevron { + width: 0; + height: 0; + border-style: solid; + border-width: 4px 0 4px 6px; + border-color: transparent transparent transparent var(--sr-muted); + transition: transform 120ms ease; +} +.section.is-open .chevron { transform: rotate(90deg); } +.section-summary { margin-left: auto; font-weight: 400; font-size: 12px; color: var(--sr-muted); } +.section-summary.is-error { color: var(--sr-fail); } +.section-body { flex: 1; min-height: 0; overflow: auto; } + +/* ---- empty state ---- */ +.empty { + height: 100%; + min-height: 140px; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 12px; + padding: 24px; + text-align: center; +} +.empty p { margin: 0; max-width: 34ch; } +.empty-actions { display: flex; gap: 8px; } + +/* ---- the step rail ---- */ +.rail { list-style: none; margin: 0; padding: 6px 0 10px; } +.step { + position: relative; + display: grid; + grid-template-columns: var(--sr-dot) minmax(0, 1fr) auto; + column-gap: 10px; + padding: 0 12px 0 14px; +} +/* The thread from this step's dot down to the next one; it takes the accent once the step passed. */ +.step::before { + content: ""; + position: absolute; + left: calc(14px + var(--sr-dot) / 2 - 1px); + top: calc(6px + var(--sr-dot)); + bottom: -6px; + width: 2px; + background: var(--sr-rule); + transition: background-color 240ms ease; +} +.step:last-child::before { display: none; } +.step.is-done::before, .step.is-warn::before { background: var(--sr-accent); } +.dot { + margin-top: 6px; + width: var(--sr-dot); + height: var(--sr-dot); + border-radius: 50%; + border: 1.5px solid var(--sr-rule); + background: var(--sr-bg); + color: var(--sr-muted); + display: flex; + align-items: center; + justify-content: center; + font-size: 11px; + font-variant-numeric: tabular-nums; + position: relative; + z-index: 1; +} +.step.is-done .dot { background: var(--sr-accent); border-color: var(--sr-accent); color: var(--sr-accent-fg); } +.step.is-warn .dot { background: var(--sr-warn); border-color: var(--sr-warn); color: #ffffff; } +.step.is-fail .dot, .step.is-stopped .dot { background: var(--sr-fail); border-color: var(--sr-fail); color: #ffffff; } +.step.is-skip .dot { border-style: dashed; } +.step.is-running .dot { border-color: var(--sr-accent); color: var(--sr-accent); animation: sr-ring 1.4s ease-in-out infinite; } +@keyframes sr-ring { + 0%, 100% { box-shadow: 0 0 0 2px var(--sr-ring); } + 50% { box-shadow: 0 0 0 5px var(--sr-ring-soft); } +} + +.step-main { min-width: 0; } +.step-head { + display: block; + width: 100%; + padding: 6px 4px 6px 0; + font: inherit; + color: inherit; + background: none; + border: 0; + text-align: left; + cursor: pointer; +} +.step-title { font-weight: 600; } +.step.is-wait .step-title, .step.is-skip .step-title { font-weight: 400; color: var(--sr-muted); } +.step-what, .step-param { display: block; color: var(--sr-muted); font-size: 12px; overflow-wrap: anywhere; } +.step-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 3px; } +.tag { + font-size: 11px; + line-height: 16px; + padding: 0 6px; + border-radius: 3px; + color: var(--sr-warn); + background: var(--sr-warn-bg); +} +.tag.is-check { color: var(--sr-muted); background: none; border: 1px solid var(--sr-rule); } + +.step-side { display: flex; align-items: flex-start; gap: 6px; padding-top: 7px; } +.time { font-size: 12px; color: var(--sr-muted); font-variant-numeric: tabular-nums; white-space: nowrap; } +.step.is-running .time { color: var(--sr-accent); } +.play { + width: 20px; + height: 20px; + padding: 0; + font-size: 10px; + line-height: 1; + color: var(--sr-accent); + background: none; + border: 1px solid transparent; + border-radius: 50%; + cursor: pointer; + opacity: 0; +} +.step:hover .play:not(:disabled), .play:focus-visible { opacity: 1; border-color: var(--sr-rule); } + +/* ---- an opened step ---- */ +.step-detail { padding: 2px 0 10px; font-size: 12px; } +.step.is-open { background: var(--sr-hover); } +.args { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 2px 12px; margin: 0 0 6px; } +.args dt { color: var(--sr-muted); } +.args dd { margin: 0; font-family: var(--sr-mono); font-size: 11.5px; overflow-wrap: anywhere; white-space: pre-wrap; } +.result-line { margin: 2px 0; } +.checks { list-style: none; margin: 0 0 6px; padding: 0; color: var(--sr-muted); } +.checks li { margin: 2px 0; overflow-wrap: anywhere; } +.checks li.is-met::before { content: "\2713\00a0"; color: var(--sr-pass); } +.failure { + margin: 4px 0 6px; + padding: 6px 8px; + border-left: 2px solid var(--sr-fail); + border-radius: 0 3px 3px 0; + background: var(--sr-fail-bg); +} +.step.is-warn .failure { border-left-color: var(--sr-warn); background: var(--sr-warn-bg); } +.failure-detail { display: block; margin-top: 3px; color: var(--sr-muted); overflow-wrap: anywhere; } +.files { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin: 4px 0; } +.thumb { + display: block; + width: 160px; + max-width: 100%; + border: 1px solid var(--sr-rule); + border-radius: 3px; + cursor: zoom-in; +} +.actions { display: flex; gap: 12px; align-items: center; margin-top: 6px; } +.raw { + margin: 6px 0 0; + max-height: 220px; + overflow: auto; + padding: 6px 8px; + border: 1px solid var(--sr-rule); + border-radius: 3px; + font-family: var(--sr-mono); + font-size: 11px; + white-space: pre; + user-select: text; +} + +/* ---- source ---- */ +#source-body { display: flex; padding: 8px 12px; } +#source { + flex: 1; + min-height: 80px; + resize: none; + padding: 6px 8px; + font-family: var(--sr-mono); + font-size: 12px; + line-height: 1.5; + color: var(--sr-fg); + background: var(--sr-bg); + border: 1px solid var(--sr-rule); + border-radius: 4px; + tab-size: 2; +} +#source:focus { outline: none; border-color: var(--sr-accent); } +#source[readonly] { color: var(--sr-muted); } + +/* ---- footer ---- */ +.foot { + flex: none; + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-top: 1px solid var(--sr-rule); + background: var(--sr-footer); +} +.outcome { flex: 1; min-width: 0; display: flex; flex-direction: column; } +#outcome { font-weight: 600; } +#outcome.is-pass { color: var(--sr-pass); } +#outcome.is-fail { color: var(--sr-fail); } +#outcome.is-warn { color: var(--sr-warn); } +#outcome.is-quiet { font-weight: 400; color: var(--sr-muted); } +.outcome-detail { font-size: 12px; color: var(--sr-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +@media (prefers-reduced-motion: reduce) { + .step.is-running .dot { animation: none; box-shadow: 0 0 0 2px var(--sr-ring); } + .step::before, .chevron { transition: none; } +} diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 9f2ffa3e42..8ba9f29ecb 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -128,6 +128,8 @@ set(SLIC3R_GUI_SOURCES GUI/PluginsDialog.hpp GUI/Shortcuts.cpp GUI/Shortcuts.hpp + GUI/ScriptRunnerDialog.cpp + GUI/ScriptRunnerDialog.hpp GUI/SpeedDialDialog.cpp GUI/SpeedDialDialog.hpp GUI/ColorPickerDialog.cpp @@ -155,6 +157,10 @@ set(SLIC3R_GUI_SOURCES GUI/Mcp/McpOptions.hpp GUI/Mcp/McpScript.cpp GUI/Mcp/McpScript.hpp + GUI/Mcp/McpScriptRun.cpp + GUI/Mcp/McpScriptRun.hpp + GUI/Mcp/McpScriptSummary.cpp + GUI/Mcp/McpScriptSummary.hpp GUI/Mcp/McpService.cpp GUI/Mcp/McpService.hpp GUI/Mcp/McpServicePtr.hpp diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 0b6e21a7a6..6acf7f98bf 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -85,6 +85,7 @@ #include "3DScene.hpp" #include "ParamsDialog.hpp" #include "PrintHostDialogs.hpp" +#include "ScriptRunnerDialog.hpp" #include "libslic3r_version.h" #include "wxExtensions.hpp" #include "GUI_ObjectList.hpp" @@ -3201,6 +3202,9 @@ void MainFrame::init_menubar_as_editor() append_submenu(fileMenu, export_menu, wxID_ANY, _L("Export"), ""); + append_menu_item(fileMenu, wxID_ANY, _L("Run Script") + dots, _L("Open or paste a script and run its steps"), + [this](wxCommandEvent&) { show_script_runner(); }, "", nullptr, []() { return true; }, this); + fileMenu->AppendSeparator(); #ifndef __APPLE__ @@ -4029,6 +4033,14 @@ struct ConfigsOverwriteConfirmDialog : MessageDialog } }; +void MainFrame::show_script_runner() +{ + if (!m_script_runner) + m_script_runner = new ScriptRunnerDialog(this); + m_script_runner->Show(); + m_script_runner->Raise(); +} + void MainFrame::export_config() { ExportConfigsDialog export_configs_dlg(nullptr); diff --git a/src/slic3r/GUI/MainFrame.hpp b/src/slic3r/GUI/MainFrame.hpp index 748b92a836..4845280f07 100644 --- a/src/slic3r/GUI/MainFrame.hpp +++ b/src/slic3r/GUI/MainFrame.hpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include #ifdef __APPLE__ #include #endif // __APPLE__ @@ -418,6 +420,8 @@ public: void reslice_now(); void export_config(); + // Shows the Run Script dialog, creating it the first time and raising the open one after. + void show_script_runner(); // Query user for the config file and open it. void load_config_file(); // Import preset files (.json, .zip, .orca_printer, .orca_filament, .orca_bundle) as the Import Configs @@ -513,6 +517,8 @@ public: Input_Shaping_Freq_Test_Dlg* m_IS_freq_calib_dlg{ nullptr }; Input_Shaping_Damp_Test_Dlg* m_IS_damp_calib_dlg{ nullptr }; Cornering_Test_Dlg* m_cornering_calib_dlg{ nullptr }; + // Modeless and owned by this frame; the weak ref clears when it is destroyed. + wxWeakRef m_script_runner; // BBS. Replace title bar and menu bar with top bar. BBLTopbar* m_topbar{ nullptr }; diff --git a/src/slic3r/GUI/Mcp/JobRegistry.cpp b/src/slic3r/GUI/Mcp/JobRegistry.cpp index c400f4b1ae..c45d56463a 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -24,6 +25,11 @@ std::string JobRegistry::create(const std::string& tool, const std::string& pare job.tool = tool; job.parent = parent; job.created = std::chrono::steady_clock::now(); + if (!parent.empty()) { + job.ancestors.push_back(parent); + if (auto it = m_jobs.find(parent); it != m_jobs.end()) + job.ancestors.insert(job.ancestors.end(), it->second.ancestors.begin(), it->second.ancestors.end()); + } m_jobs.emplace(id, std::move(job)); return id; } @@ -71,27 +77,50 @@ std::optional JobRegistry::wait(const std::string& id, std::chrono:: return it->second.result; } -std::set JobRegistry::lineage(const std::string& id) const +std::optional JobRegistry::wait(const std::string& id, std::chrono::milliseconds timeout, const std::function& stop) +{ + constexpr std::chrono::milliseconds slice{500}; + const auto deadline = std::chrono::steady_clock::now() + timeout; + for (;;) { + const auto left = std::chrono::duration_cast(deadline - std::chrono::steady_clock::now()); + if (auto done = wait(id, std::clamp(left, std::chrono::milliseconds(0), slice))) + return done; + if (left <= slice || stop()) + return std::nullopt; + std::lock_guard lock(m_mutex); + if (m_woken) + return std::nullopt; + } +} + +void JobRegistry::request_stop(const std::string& id) { std::lock_guard lock(m_mutex); - std::set out; - std::string cur = id; - while (!cur.empty() && out.insert(cur).second) { - auto it = m_jobs.find(cur); - cur = it == m_jobs.end() ? std::string() : it->second.parent; - } - return out; + m_stop_requests.insert(id); +} + +bool JobRegistry::stop_requested(const std::string& id) const +{ + const std::vector chain = ancestry(id); + std::lock_guard lock(m_mutex); + return std::any_of(chain.begin(), chain.end(), [this](const std::string& job) { return m_stop_requests.count(job) != 0; }); +} + +std::set JobRegistry::lineage(const std::string& id) const +{ + const std::vector chain = ancestry(id); + return {chain.begin(), chain.end()}; } std::vector JobRegistry::ancestry(const std::string& id) const { std::lock_guard lock(m_mutex); std::vector out; - for (std::string cur = id; !cur.empty() && std::find(out.begin(), out.end(), cur) == out.end();) { - out.push_back(cur); - auto it = m_jobs.find(cur); - cur = it == m_jobs.end() ? std::string() : it->second.parent; - } + if (id.empty()) + return out; + out.push_back(id); + if (auto it = m_jobs.find(id); it != m_jobs.end()) + out.insert(out.end(), it->second.ancestors.begin(), it->second.ancestors.end()); return out; } diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index 32f3a08d69..0ab4bfa24d 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -36,11 +37,20 @@ public: // The job's result once it has finished; nullopt when it is still running after `timeout` or // the registry was woken for shutdown. Throws ToolFailure for an unknown id. std::optional wait(const std::string& id, std::chrono::milliseconds timeout); + // The same, but gives up early once `stop` is true, which it checks every half second. It looks + // at the job at least once, so a zero timeout still returns a finished job's result. + std::optional wait(const std::string& id, std::chrono::milliseconds timeout, const std::function& stop); // `id` followed by its parent chain. std::set lineage(const std::string& id) const; // The same chain in order: `id`, its parent, its parent's parent, ... std::vector ancestry(const std::string& id) const; + // A stop asked for `id` reaches every call it and its descendants make (ToolContext::cancelled). + // Requests are kept for the session: ids are never reused, and a descendant may still run after + // its root has finished. + void request_stop(const std::string& id); + // True when a stop was asked for `id` or one of its ancestors. + bool stop_requested(const std::string& id) const; // True when a running job exists that is not in `excluded`. bool any_running_except(const std::set& excluded) const; // Operation admission: a job marked as an operation holds the project until it finishes. @@ -59,6 +69,9 @@ private: { std::string tool; std::string parent; + // The parent chain, nearest first, recorded at creation: a finished ancestor may be forgotten + // while this job still runs, and the chain must still reach the root (a stop asked for it). + std::vector ancestors; bool finished = false; bool operation = false; ToolResult result; @@ -69,6 +82,7 @@ private: std::condition_variable m_cv; std::map m_jobs; std::deque m_finished_order; + std::set m_stop_requests; uint64_t m_next = 1; bool m_woken = false; }; diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index 530b0b9f13..36d2b155fd 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -68,7 +68,10 @@ public: }); } const std::string& job_id() const override { return m_job; } - bool cancelled() const override { return m_core.ui().is_shutdown(); } + bool cancelled() const override + { + return m_core.ui().is_shutdown() || m_core.jobs().stop_requested(m_job.empty() ? m_parent : m_job); + } ToolResult call_child(const std::string& tool, const nlohmann::json& args) override { diff --git a/src/slic3r/GUI/Mcp/McpScript.cpp b/src/slic3r/GUI/Mcp/McpScript.cpp index 7ed683d7b5..af5ebaba7a 100644 --- a/src/slic3r/GUI/Mcp/McpScript.cpp +++ b/src/slic3r/GUI/Mcp/McpScript.cpp @@ -3,6 +3,8 @@ #include "McpTypes.hpp" #include +#include +#include #include #include #include @@ -51,16 +53,43 @@ std::optional resolve_placeholder(const std::string& key, const Script& sc return std::nullopt; } -json substitute_value(const json& value, const Script& script, const ScriptContext& ctx, std::string& err, int depth) +// How a substitution went: in lenient mode an unresolvable placeholder is kept as written; otherwise +// the first one fails the substitution and is recorded here, so run_script can say why. +struct Substitution +{ + bool lenient = false; + std::string err; + std::string failed; // the placeholder's body, e.g. "jobs.prefs" +}; + +// The 1-based index of the step that saves its job as `name`, or 0. +std::size_t step_saving(const Script& script, const std::string& name) +{ + for (std::size_t i = 0; i < script.steps.size(); ++i) + if (script.steps[i].save_as == name) + return i + 1; + return 0; +} + +void fail_placeholder(Substitution& sub, const std::string& key, const std::string& text, const Script& script) +{ + sub.failed = key; + sub.err = "unknown placeholder " + text; + if (key.rfind("jobs.", 0) == 0) + if (const std::size_t saver = step_saving(script, key.substr(5)); saver != 0) + sub.err += ": no job is saved as " + key.substr(5) + " yet; step " + std::to_string(saver) + " saves it"; +} + +json substitute_value(const json& value, const Script& script, const ScriptContext& ctx, Substitution& sub, int depth) { if (depth > 8) { - err = "variable substitution nests too deeply"; + sub.err = "variable substitution nests too deeply"; return value; } if (value.is_array() || value.is_object()) { json out = value; for (auto it = out.begin(); it != out.end(); ++it) - *it = substitute_value(*it, script, ctx, err, depth); + *it = substitute_value(*it, script, ctx, sub, depth); return out; } if (!value.is_string()) @@ -71,30 +100,50 @@ json substitute_value(const json& value, const Script& script, const ScriptConte if (std::regex_match(text, whole, placeholder)) { auto v = resolve_placeholder(whole[1].str(), script, ctx); if (!v) { - err = "unknown placeholder " + text; + if (!sub.lenient) + fail_placeholder(sub, whole[1].str(), text, script); return value; } // A var may itself contain placeholders (e.g. "${script_dir}/part.stl"). - return substitute_value(*v, script, ctx, err, depth + 1); + return substitute_value(*v, script, ctx, sub, depth + 1); } std::string out; auto begin = std::sregex_iterator(text.begin(), text.end(), placeholder); std::size_t last = 0; for (auto it = begin; it != std::sregex_iterator(); ++it) { out.append(text, last, std::size_t(it->position()) - last); + last = std::size_t(it->position() + it->length()); auto v = resolve_placeholder((*it)[1].str(), script, ctx); if (!v) { - err = "unknown placeholder " + it->str(); - return value; + if (!sub.lenient) { + fail_placeholder(sub, (*it)[1].str(), it->str(), script); + return value; + } + out += it->str(); + continue; } - const json resolved = substitute_value(*v, script, ctx, err, depth + 1); + const json resolved = substitute_value(*v, script, ctx, sub, depth + 1); out += resolved.is_string() ? resolved.get() : resolved.dump(); - last = std::size_t(it->position() + it->length()); } out.append(text, last, std::string::npos); return json(out); } +// "line L, column C" of a 1-based byte offset into `text`, as nlohmann's parse errors give it. +std::string text_position(const std::string& text, std::size_t byte) +{ + const std::size_t end = std::min(byte, text.size()); + std::size_t line = 1, column = 1; + for (std::size_t i = 0; i + 1 < end; ++i) { + if (text[i] == '\n') { + ++line; + column = 1; + } else + ++column; + } + return "line " + std::to_string(line) + ", column " + std::to_string(column); +} + bool numeric(const json& v) { return v.is_number(); } std::optional check_matcher(const std::string& pointer, const json& actual, bool exists, const std::string& op, @@ -149,12 +198,18 @@ std::optional check_matcher(const std::string& pointer, const json& std::optional