diff --git a/.claude/skills/orca-wxwidgets/references/windows-dialogs.md b/.claude/skills/orca-wxwidgets/references/windows-dialogs.md index 392da46b47..48fb104da5 100644 --- a/.claude/skills/orca-wxwidgets/references/windows-dialogs.md +++ b/.claude/skills/orca-wxwidgets/references/windows-dialogs.md @@ -507,7 +507,7 @@ name — for any other window call `window_pos_save/restore` with its own name. A `WebViewHostDialog` subclass calls the inherited `restore_z_order()` after each such modal, on every outcome including Cancel. Cite: 0a0d59b76b (`PluginsDialog`: also passed as the `restore` callback of - `detail::run_off_thread_with_progress`); `ScriptRunnerDialog::open_file`. + `detail::run_off_thread_with_progress`); `ActionReplayDialog::open_file`. - **Rule:** On macOS, when a secondary dialog raises the main window on purpose (to give it the keyboard focus for work that acts on it) and must stay in sight meanwhile, attach it as a Cocoa child window of the main window for that span — `keep_window_above(GetHandle(), mainframe->GetHandle(), true)` @@ -518,7 +518,7 @@ name — for any other window call `window_pos_save/restore` with its own name. it also moves with its parent, so attach it only for the span. wx detaches it on `Hide()` and in the window's destructor (`src/osx/cocoa/nonownedwnd.mm:767-768, 990-991`), so closing the dialog midway needs no extra step. - Cite: `ScriptRunnerDialog::run` (a run's progress and Stop button; the dialog takes the focus back with + Cite: `ActionReplayDialog::run` (a run's progress and Stop button; the dialog takes the focus back with `restore_z_order()` when the run finishes). - **Rule:** Never position windows by absolute coordinates on Wayland, and never expect `SetIcon` to show on macOS or Wayland. diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 674b91387a..adaa4d7a0a 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -116,8 +116,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, or opening the -Run Script dialog, 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 +Action Replay or the Run Script panel, 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 @@ -2149,7 +2149,8 @@ OrcaSlicer's windows only gives what the screen shows of them in the client area backing scale, in sRGB: the window, web views and 3D views included, and over it our dialogs, wx popups, AppKit's menus and tooltips, but no other application's window, so a covered window captures whole. The filter names the application rather than its windows, so a menu or tooltip that opens later -is in it too. It leaves out the shown windows hidden from automation (the script runner), their wx +is in it too. It leaves out the shown windows hidden from automation (Action Replay, a floating Run Script +panel), their wx popups, and AppKit's windows over them: AppKit does not say which window opened a menu or tooltip, so each of our windows that is not wx's goes with the topmost wx window below it that it overlaps, as on Windows. The window behind such a window shows through. `SCScreenshotManager` takes one image per @@ -2263,7 +2264,7 @@ result's `note` is the last frame's: which of these applies, then what that fram approximated, so a macOS recording that fell back to drawing views says so. `capture_frame()` stores it under the recorder's mutex, since `stop_recording` reports from another thread while a tick may be capturing. The `canvas` target is `shown_canvas()`. A recording captures with -`CaptureOptions::hide_covering` off, so X11 never hides and re-shows the script runner at each frame. +`CaptureOptions::hide_covering` off, so X11 never hides and re-shows Action Replay at each frame. The costly part is a 3D view: `render_and_capture()` draws a frame, after any extra frames a change asked for, and reads it back. A recording @@ -2334,8 +2335,8 @@ that would encode without an ffmpeg is refused rather than recording unencoded. recording's file is closed (`McpRecorder::wait_closed()`), so it can be cancelled like any encode. No reply names the job, which only exists once the file is closed: an agent finds it in `get_state.jobs` and waits for it by its id, as the command's description says. -Start Recording starts the service without its endpoint when the server is off, as the Run Script dialog -does. The person's recording has its own owner (`kPersonOwner`), so neither a script's end nor the +Start Recording starts the service without its endpoint when the server is off, as Action Replay and the +Run Script panel do. The person's recording has its own owner (`kPersonOwner`), so neither a script's end nor the endpoint closing ends it. Whatever ends it tells the person where it went, in a notification whose button opens the folder: Stop Recording itself, which stops any recording, an agent's too, ending it as `stopped_in_app`; or `RecordingOptions::ended`, which the recorder runs on the UI thread when an agent's @@ -2537,7 +2538,7 @@ file's `out_dir` defaults to ` + + + + + - +
- + @@ -40,7 +46,7 @@
@@ -49,19 +55,7 @@
-
-
- -
- - - -
-
-
+
@@ -73,14 +67,10 @@
- + - diff --git a/resources/web/dialog/ActionReplay/script_editor.js b/resources/web/dialog/ActionReplay/script_editor.js new file mode 100644 index 0000000000..d1773189eb --- /dev/null +++ b/resources/web/dialog/ActionReplay/script_editor.js @@ -0,0 +1,271 @@ +// The replay editor's language: a replay's highlighting (the orca_replay mode), and suggestions for its keys, tool +// names, a tool's args and their allowed values, and ${…} placeholders, with what accepting one and Return write. The +// editor is Ace, set up by ../js/code_editor.js; the pure functions here are also loaded by script_editor.test.js. + +// The keys of a script and of a step, with the JSON type of their values. Accepting a key writes a +// value of that type after its colon (an empty string, object or array with the caret inside, or true), +// or the item's own `then`; for a number the caret waits after the colon. +const ROOT_KEYS = [ + { label: "orca_script", detail: "integer", then: "1" }, + { label: "name", detail: "string" }, + { label: "vars", detail: "object" }, + { label: "steps", detail: "array" }, +]; +const STEP_KEYS = [ + { label: "tool", detail: "string" }, + { label: "args", detail: "object" }, + { label: "expect", detail: "object" }, + { label: "optional", detail: "boolean" }, + { label: "await", detail: "boolean" }, + { label: "save_as", detail: "string" }, + { label: "timeout_s", detail: "integer" }, +]; +const EMPTY_VALUES = { string: '""', object: "{}", array: "[]", boolean: "true" }; +const MATCHERS = ["eq", "ne", "gt", "ge", "lt", "le", "contains", "regex", "exists", "empty"]; + +// Comments, strings (opening quote and body, then the closing quote; an unclosed one ends with its +// line), numbers, literals and punctuation: what the reader walks. +const TOKEN = /(\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$))|("(?:[^"\\\n]|\\.)*)("?)|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b|([{}[\],:])/g; + +const ed = { + tools: new Map(), // tool name -> {title, args: {name: {type, enum}}}, from the host + editor: null, // the Ace editor, once initEditor() made it +}; + +// ---- highlighting --------------------------------------------------------------------------------- + +// Ace's JSON mode with a replay's own highlighting: // and /* */ comments, keys (a string a colon follows on its line), +// strings, ${…} inside keys and strings, numbers, true/false/null and punctuation, coloured by code_editor.css. +function defineReplayMode() { + ace.define("ace/mode/orca_replay_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text_highlight_rules"], + (require, exports) => { + const oop = require("ace/lib/oop"); + const TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules; + function ReplayHighlightRules() { + const placeholder = { token: "orca_var", regex: /\$\{[^}"]*\}/ }; + this.$rules = { + start: [ + { token: "comment", regex: /\/\/.*$/ }, + { token: "comment", regex: /\/\*/, next: "comment" }, + { token: "variable", regex: /"(?=(?:[^"\\]|\\.)*"\s*:)/, next: "key" }, + { token: "string", regex: /"/, next: "string" }, + { token: "constant.numeric", regex: /-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/ }, + { token: "constant.language", regex: /\b(?:true|false|null)\b/ }, + { token: "paren.lparen", regex: /[[{]/ }, + { token: "paren.rparen", regex: /[\]}]/ }, + { token: "punctuation", regex: /[,:]/ }, + ], + key: [placeholder, { token: "variable", regex: /\\./ }, { token: "variable", regex: /"|$/, next: "start" }, { defaultToken: "variable" }], + string: [placeholder, { token: "string", regex: /\\./ }, { token: "string", regex: /"|$/, next: "start" }, { defaultToken: "string" }], + comment: [{ token: "comment", regex: /\*\//, next: "start" }, { defaultToken: "comment" }], + }; + } + oop.inherits(ReplayHighlightRules, TextHighlightRules); + exports.ReplayHighlightRules = ReplayHighlightRules; + }); + ace.define("ace/mode/orca_replay", ["require", "exports", "module", "ace/lib/oop", "ace/mode/json", "ace/mode/orca_replay_highlight_rules"], + (require, exports) => { + const oop = require("ace/lib/oop"); + const JsonMode = require("ace/mode/json").Mode; + function Mode() { + JsonMode.call(this); + this.HighlightRules = require("ace/mode/orca_replay_highlight_rules").ReplayHighlightRules; + } + oop.inherits(Mode, JsonMode); + Mode.prototype.$id = "ace/mode/orca_replay"; + // A replay is JSON with comments: JSON's worker would flag them. + Mode.prototype.createWorker = () => null; + exports.Mode = Mode; + }); +} + +// ---- reading the structure -------------------------------------------------------------------- + +// Walks the tokens before `at` keeping a frame per open object ({key, colon, keys, tool}) and +// array ({array, index}). Returns the frames, the string `at` is in (after its opening quote) if +// any, and the vars and saved job names seen; null when `at` is in a comment. +function readScript(text, at) { + const frames = []; + const vars = new Set(); + const jobs = new Set(); + let m; + TOKEN.lastIndex = 0; + while ((m = TOKEN.exec(text)) && m.index < at) { + const end = TOKEN.lastIndex; + const top = frames[frames.length - 1]; + if (m[1] !== undefined) { + if (end > at || (end === at && !m[1].endsWith("*/"))) return null; + continue; + } + if (m[2] !== undefined) { + const closed = m[3] === '"'; + if (at < end || (at === end && !closed)) + return { frames, vars, jobs, string: { start: m.index, end, closed } }; + const value = m[2].slice(1); + if (top && !top.array) { + if (!top.colon) { + top.key = value; + top.keys.add(value); + if (frames.length === 2 && frames[0].key === "vars") vars.add(value); + } else if (top.key === "tool") top.tool = value; + else if (top.key === "save_as") jobs.add(value); + } + continue; + } + switch (m[6]) { + case "{": frames.push({ array: false, key: null, colon: false, keys: new Set(), tool: null }); break; + case "[": frames.push({ array: true, index: 0 }); break; + case "}": case "]": frames.pop(); break; + case ":": if (top && !top.array) top.colon = true; break; + case ",": + if (top && top.array) top.index++; + else if (top) { top.key = null; top.colon = false; } + break; + } + } + return { frames, vars, jobs, string: null }; +} + +// The step a path inside steps[] belongs to, as its frame: frames are root, steps, step, ... +function stepTool(frames) { + const step = frames[2]; + return step && !step.array ? ed.tools.get(step.tool) : null; +} + +function typeText(type) { return Array.isArray(type) ? type.join(" | ") : type || ""; } + +function keyItems(frames, path) { + const top = frames[frames.length - 1]; + let items = []; + if (path.length === 0) items = ROOT_KEYS; + else if (path.length === 2 && path[0] === "steps") items = STEP_KEYS; + else if (path.length === 3 && path[0] === "steps" && path[2] === "args") { + const tool = stepTool(frames); + if (tool) + items = Object.entries(tool.args).map(([name, arg]) => ({ + label: name, + detail: typeText(arg.type), + info: arg.enum ? arg.enum.join(" | ") : "", + })); + } else if (path.length === 4 && path[0] === "steps" && path[2] === "expect") + items = MATCHERS.map((label) => ({ label })); + return items.filter((item) => !top.keys.has(item.label)); +} + +function valueItems(frames, path) { + if (path.length === 3 && path[0] === "steps" && path[2] === "tool") + return [...ed.tools.values()].map((tool) => { + const args = Object.keys(tool.args); + return { label: tool.name, detail: tool.title, info: args.length ? "args: " + args.join(", ") : "" }; + }); + if (path.length === 4 && path[0] === "steps" && path[2] === "args") { + const tool = stepTool(frames); + const arg = tool && tool.args[path[3]]; + if (arg && arg.enum) return arg.enum.filter((v) => typeof v === "string").map((label) => ({ label })); + } + return []; +} + +// What can go at `at`: the range a suggestion replaces, how it is written there, and the candidates. +// Inside a string that is a key or a value, or after an unclosed ${ in a string; elsewhere only when +// asked (`explicit`), at a key or value position. +function suggestionsAt(text, at, explicit) { + const read = readScript(text, at); + if (!read || !read.frames.length) return null; + const { frames, string } = read; + const top = frames[frames.length - 1]; + const path = frames.slice(0, -1).map((f) => (f.array ? f.index : f.key)); + const wordEnd = at + /^[\w.-]*/.exec(text.slice(at))[0].length; + if (string) { + const typed = text.slice(string.start + 1, at); + const open = typed.lastIndexOf("${"); + if (open >= 0 && typed.indexOf("}", open) < 0) { + const items = ["script_dir", "out_dir", ...[...read.vars].map((k) => "vars." + k), ...[...read.jobs].map((k) => "jobs." + k)]; + return { kind: "var", from: string.start + 3 + open, to: wordEnd, items: items.map((label) => ({ label })) }; + } + } else if (!explicit) return null; + // A suggestion replaces what was typed and, in a closed string, the rest of it up to the quote. + const found = string + ? { quoted: true, from: string.start + 1, to: string.closed ? string.end : wordEnd } + : { quoted: false, from: at - /[\w.-]*$/.exec(text.slice(0, at))[0].length, to: wordEnd }; + // Unquoted, only where a key or value can start, not right after one. + if (!string && !/(^|[{[,:])\s*$/.test(text.slice(0, found.from))) return null; + if (!top.array && !top.colon) return Object.assign(found, { kind: "key", items: keyItems(frames, path) }); + const value = [...path, top.array ? top.index : top.key]; + return Object.assign(found, { kind: "value", items: valueItems(frames, value) }); +} + +// ---- suggestions ----------------------------------------------------------------------------------- + +// What accepting `item` of what suggestionsAt() `found` writes: [from, to) replaced with `insert`, the +// caret `back` characters before its end, and whether the suggestions open again there. A key gets its +// colon and an empty value of its type (unless a colon follows already), with the caret inside a +// string, object or array; a ${…} gets its closing brace. +function acceptEdit(text, found, item) { + if (found.kind === "var") + return { from: found.from, to: text[found.to] === "}" ? found.to + 1 : found.to, insert: item.label + "}", back: 0, reopen: false }; + let insert = (found.quoted ? "" : '"') + item.label + '"'; + let back = 0; + let then = ""; + if (found.kind === "key" && !/^\s*:/.test(text.slice(found.to))) { + then = item.then !== undefined ? item.then : EMPTY_VALUES[item.detail] || ""; + insert += ": " + then; + back = then.length === 2 ? 1 : 0; + } + return { from: found.from, to: found.to, insert, back, reopen: then === '""' }; +} + +// What Return writes for the selection [start, end): the line's indent, one level more after an +// opening bracket; between a pair of brackets the closing one goes on its own line, the caret `back` +// characters before the end on the line between. +function newlineEdit(text, start, end) { + const lineStart = text.lastIndexOf("\n", start - 1) + 1; + const indent = /^[ \t]*/.exec(text.slice(lineStart, start))[0]; + const opens = /[{[]\s*$/.test(text.slice(lineStart, start)); + const closes = /^[ \t]*[}\]]/.test(text.slice(end)); + if (opens && closes) return { from: start, to: end, insert: "\n" + indent + " \n" + indent, back: indent.length + 1 }; + return { from: start, to: end, insert: "\n" + indent + (opens ? " " : ""), back: 0 }; +} + +// ---- the editor ------------------------------------------------------------------------------------ + +function setEditorTools(tools) { + ed.tools = new Map(tools.map((tool) => [tool.name, tool])); +} + +// What the replay editor suggests: the word Ace filters by is the text from where a suggestion starts to the caret, so +// it takes the characters of a tool name, a key and vars.x; typing a quote or a brace (of ${) opens the list. +const replayCompleter = { + suggestionsAt, + acceptEdit, + identifierRegexps: [/[\w.-]/], + triggerCharacters: ['"', "{"], +}; + +// Makes the editor in #editor: `onChange(text)` for every edit, and the page's `commands` (Run, Save, Save as) beside +// Return, which writes newlineEdit()'s edit, since Ace's own brace handling splits only {}. +function initEditor(onChange, commands) { + defineReplayMode(); + const newlineCommand = { + name: "replayNewline", + bindKey: { win: "Return", mac: "Return" }, + exec: (editor) => { + const range = editor.getSelectionRange(); + const doc = editor.session.doc; + applyEditorEdit(editor, newlineEdit(editor.getValue(), doc.positionToIndex(range.start), doc.positionToIndex(range.end))); + }, + }; + ed.editor = createCodeEditor(document.getElementById("editor"), { + mode: "ace/mode/orca_replay", + tabSize: 2, + placeholder: T("source_placeholder", "Write a replay here, or open one."), + completer: replayCompleter, + onChange, + commands: [newlineCommand, ...commands], + }); + return ed.editor; +} + +// The language's pure functions, for the page's tests (node --test), which load this file as a module. +if (typeof module === "object" && module.exports) + module.exports = { readScript, suggestionsAt, acceptEdit, newlineEdit, setEditorTools }; diff --git a/resources/web/dialog/ActionReplay/script_editor.test.js b/resources/web/dialog/ActionReplay/script_editor.test.js new file mode 100644 index 0000000000..466b5bc73e --- /dev/null +++ b/resources/web/dialog/ActionReplay/script_editor.test.js @@ -0,0 +1,117 @@ +"use strict"; +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const editor = require("./script_editor.js"); + +// Two tools, as the host's catalog lists them: one taking a plain number, one an enum and a nullable number. +editor.setEditorTools([ + { name: "slice", title: "Slice", args: { plate: { type: "integer" } } }, + { name: "set_view", title: "Set the view", args: { view: { type: "string", enum: ["top", "front"] }, zoom: { type: ["number", "null"] } } }, +]); + +// What suggestionsAt() finds with the caret at the end of `text`. +function at(text, explicit) { return editor.suggestionsAt(text, text.length, !!explicit); } +function labels(found) { return found.items.map((item) => item.label); } + +test("a script's root keys are suggested in a key's string", () => { + const found = at('{\n "'); + assert.equal(found.kind, "key"); + assert.equal(found.from, 5); + assert.equal(found.to, 5); + assert.deepEqual(labels(found), ["orca_script", "name", "vars", "steps"]); +}); + +test("a step's keys are suggested inside steps[], leaving out the ones it has", () => { + const found = at('{"steps": [{"tool": "slice", "'); + assert.equal(found.kind, "key"); + assert.deepEqual(labels(found), ["args", "expect", "optional", "await", "save_as", "timeout_s"]); +}); + +test("a step's tool is suggested from the catalog with its title and arguments", () => { + const text = '{"steps": [{"tool": "sl'; + const found = at(text); + assert.equal(found.kind, "value"); + assert.equal(found.from, text.length - 2); + assert.equal(found.to, text.length); + assert.deepEqual(found.items, [ + { label: "slice", detail: "Slice", info: "args: plate" }, + { label: "set_view", detail: "Set the view", info: "args: view, zoom" }, + ]); +}); + +test("a tool's arguments are suggested in its args with their types and allowed values", () => { + const found = at('{"steps": [{"tool": "set_view", "args": {"'); + assert.equal(found.kind, "key"); + assert.deepEqual(found.items, [ + { label: "view", detail: "string", info: "top | front" }, + { label: "zoom", detail: "number | null", info: "" }, + ]); +}); + +test("an argument's allowed values are suggested as its value", () => { + const found = at('{"steps": [{"tool": "set_view", "args": {"view": "'); + assert.equal(found.kind, "value"); + assert.deepEqual(labels(found), ["top", "front"]); +}); + +test("a placeholder suggests the folders, the vars and the saved jobs", () => { + const text = '{"vars": {"part": 1}, "steps": [{"tool": "slice", "save_as": "s1"}, {"tool": "set_view", "args": {"view": "${'; + const found = at(text); + assert.equal(found.kind, "var"); + assert.equal(found.from, text.length); + assert.equal(found.to, text.length); + assert.deepEqual(labels(found), ["script_dir", "out_dir", "vars.part", "jobs.s1"]); +}); + +test("nothing is suggested outside a string unless asked for, nor in a comment", () => { + assert.equal(at('{"steps": [{'), null); + const asked = at('{"steps": [{', true); + assert.equal(asked.kind, "key"); + assert.equal(asked.quoted, false); + assert.equal(at('// "'), null); +}); + +test("an accepted key gets its colon and an empty value with the caret inside", () => { + const text = '{"'; + const found = at(text); + const steps = found.items.find((item) => item.label === "steps"); + assert.deepEqual(editor.acceptEdit(text, found, steps), { from: 2, to: 2, insert: 'steps": []', back: 1, reopen: false }); + // A string's value opens the suggestions again inside its quotes. + const name = found.items.find((item) => item.label === "name"); + assert.deepEqual(editor.acceptEdit(text, found, name), { from: 2, to: 2, insert: 'name": ""', back: 1, reopen: true }); + // A number waits after the colon. + const version = found.items.find((item) => item.label === "orca_script"); + assert.deepEqual(editor.acceptEdit(text, found, version), { from: 2, to: 2, insert: 'orca_script": 1', back: 0, reopen: false }); +}); + +test("a key accepted before an existing colon replaces only the key", () => { + const text = '{"na": 1}'; + const found = editor.suggestionsAt(text, 4, false); + const name = found.items.find((item) => item.label === "name"); + assert.deepEqual(editor.acceptEdit(text, found, name), { from: 2, to: 5, insert: 'name"', back: 0, reopen: false }); +}); + +test("a value accepted in a closed string replaces it up to its quote", () => { + const text = '{"steps": [{"tool": "sl"}]}'; + const caret = text.indexOf('sl"') + 2; + const found = editor.suggestionsAt(text, caret, false); + assert.equal(found.from, caret - 2); + assert.equal(found.to, caret + 1); + assert.deepEqual(editor.acceptEdit(text, found, { label: "slice" }), { from: caret - 2, to: caret + 1, insert: 'slice"', back: 0, reopen: false }); +}); + +test("an accepted placeholder closes its brace, over one already typed", () => { + const text = '{"vars": {"part": 1}, "steps": [{"tool": "x", "args": {"p": "${va}"}}]}'; + const caret = text.indexOf("${va") + 4; + const found = editor.suggestionsAt(text, caret, false); + assert.equal(found.kind, "var"); + assert.deepEqual(editor.acceptEdit(text, found, { label: "vars.part" }), { from: caret - 2, to: caret + 1, insert: "vars.part}", back: 0, reopen: false }); +}); + +test("Return keeps the indent, adds a level after an opening bracket and splits a pair", () => { + assert.deepEqual(editor.newlineEdit("{", 1, 1), { from: 1, to: 1, insert: "\n ", back: 0 }); + assert.deepEqual(editor.newlineEdit("{}", 1, 1), { from: 1, to: 1, insert: "\n \n", back: 1 }); + assert.deepEqual(editor.newlineEdit(" []", 3, 3), { from: 3, to: 3, insert: "\n \n ", back: 3 }); + const line = ' "a": 1,'; + assert.deepEqual(editor.newlineEdit(line, line.length, line.length), { from: line.length, to: line.length, insert: "\n ", back: 0 }); +}); diff --git a/resources/web/dialog/ScriptRunner/style.css b/resources/web/dialog/ActionReplay/style.css similarity index 72% rename from resources/web/dialog/ScriptRunner/style.css rename to resources/web/dialog/ActionReplay/style.css index e1a30c293a..582695470c 100644 --- a/resources/web/dialog/ScriptRunner/style.css +++ b/resources/web/dialog/ActionReplay/style.css @@ -1,4 +1,4 @@ -/* Script runner. Colours come from the host theme contract (--orca-*) and theme.css's status roles, +/* Action Replay. 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. */ @@ -22,29 +22,8 @@ --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-mono: var(--code-font); --sr-dot: 20px; - /* The editor's syntax colours, set apart from the status colours so a string never reads as a warning. */ - --sr-syn-key: #00796b; - --sr-syn-string: #8a4b08; - --sr-syn-number: #6639ba; - --sr-syn-punct: #8a9397; - --sr-syn-comment: #7d8589; - --sr-gutter: #f6f7f8; - --sr-pop-bg: var(--ctx-bg, #ffffff); - --sr-pop-border: var(--ctx-border, #cccccc); - --sr-pop-shadow: 0 6px 20px rgba(20, 30, 35, 0.16); - --sr-selection: rgba(0, 150, 136, 0.22); -} -:root[data-orca-theme="dark"] { - --sr-syn-key: #4db6ac; - --sr-syn-string: #d9a35f; - --sr-syn-number: #b79af0; - --sr-syn-punct: #7f858b; - --sr-syn-comment: #858a90; - --sr-gutter: #28282c; - --sr-pop-shadow: 0 6px 20px rgba(0, 0, 0, 0.45); - --sr-selection: rgba(0, 150, 136, 0.35); } * { box-sizing: border-box; } @@ -309,104 +288,18 @@ button:focus-visible, textarea:focus-visible { outline: 2px solid var(--sr-accen } /* ---- source editor ---- - * A textarea over a highlighted copy of its text. The textarea keeps typing, selection, undo and input - * methods and draws only the caret and the selection; the copy beneath paints the text. Both sit in one - * scroller and the textarea is sized to the copy, so it never scrolls on its own and the two can't - * drift apart. */ + * Ace (../js/code_editor.js), filling the section; code_editor.css colours what is inside it. */ #source-body { display: flex; padding: 8px 12px; } .editor { flex: 1; min-width: 0; min-height: 80px; - overflow: auto; border: 1px solid var(--sr-rule); border-radius: 4px; - background: var(--sr-bg); - font-family: var(--sr-mono); - font-size: 12px; - line-height: 18px; -} -.editor:focus-within { border-color: var(--sr-accent); } -.lines { display: flex; width: max-content; min-width: 100%; min-height: 100%; } -.gutter { - position: sticky; - left: 0; - z-index: 1; - flex: none; - min-width: 36px; - padding: 6px 8px 6px 4px; - text-align: right; - white-space: pre; - color: var(--sr-muted); - background: var(--sr-gutter); - border-right: 1px solid var(--sr-rule); - user-select: none; -} -.code { position: relative; flex: 1 0 auto; } -#highlight, #source, .measure { - margin: 0; - padding: 6px 8px; - border: 0; - font: inherit; - line-height: inherit; - white-space: pre; - tab-size: 2; -} -#highlight { color: var(--sr-fg); } -#source { - position: absolute; - inset: 0; - width: 100%; - height: 100%; - overflow: hidden; - resize: none; - outline: none; - color: transparent; - background: transparent; - caret-color: var(--sr-fg); -} -#source::selection { color: transparent; background: var(--sr-selection); } -#source::placeholder { color: var(--sr-muted); } -.editor.is-readonly #highlight { opacity: 0.6; } -/* While an input method composes, the textarea shows its own text: the copy can't show what is being composed. */ -.editor.is-composing #source { color: var(--sr-fg); } -.editor.is-composing #highlight { visibility: hidden; } -.measure { position: absolute; top: 0; left: 0; padding: 0; visibility: hidden; } -.t-key { color: var(--sr-syn-key); } -.t-str { color: var(--sr-syn-string); } -.t-num { color: var(--sr-syn-number); } -.t-punct { color: var(--sr-syn-punct); } -.t-com { color: var(--sr-syn-comment); font-style: italic; } -.t-var { color: var(--sr-accent); background: var(--sr-accent-tint); border-radius: 2px; } - -/* ---- suggestions ---- */ -.suggest { - position: fixed; - z-index: 10; - width: 380px; - max-width: calc(100vw - 16px); - background: var(--sr-pop-bg); - border: 1px solid var(--sr-pop-border); - border-radius: 6px; - box-shadow: var(--sr-pop-shadow); - overflow: hidden; font-size: 12px; } -.suggest ul { list-style: none; margin: 0; padding: 4px 0; max-height: 180px; overflow: auto; } -.suggest li { display: flex; align-items: baseline; gap: 12px; padding: 3px 10px; cursor: default; } -.suggest li.is-active { background: var(--sr-accent-tint); } -.s-name { font-family: var(--sr-mono); white-space: nowrap; } -.s-name b { color: var(--sr-accent); font-weight: 600; } -.s-detail { margin-left: auto; min-width: 0; color: var(--sr-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } -.suggest-detail { - margin: 0; - padding: 6px 10px 7px; - border-top: 1px solid var(--sr-rule); - color: var(--sr-muted); - font-family: var(--sr-mono); - font-size: 11.5px; - overflow-wrap: anywhere; -} +.editor.ace_focus { border-color: var(--sr-accent); } +.editor.is-readonly .ace_content { opacity: 0.6; } /* ---- footer ---- */ .foot { diff --git a/resources/web/dialog/RunScript/index.html b/resources/web/dialog/RunScript/index.html new file mode 100644 index 0000000000..fcecf3d742 --- /dev/null +++ b/resources/web/dialog/RunScript/index.html @@ -0,0 +1,136 @@ + + + + + + Run Script + + + + + + + + + + + + + + + +
+
+ + + + + + + + + + + + + + + + + +
+ +
+ +
+
+ +
+ +
+
+
+
+ + +
+
+ + +
+ +
+ + +
+ + diff --git a/resources/web/dialog/RunScript/python_editor.js b/resources/web/dialog/RunScript/python_editor.js new file mode 100644 index 0000000000..31d69c9828 --- /dev/null +++ b/resources/web/dialog/RunScript/python_editor.js @@ -0,0 +1,78 @@ +// The Run Script editor's Python: Ace's Python mode, with a line that starts a cell (`# %%`) as its own token and +// Return's indent from pythonNextIndent(), and the suggestions for this build's tools and the orca.host API. The editor is +// set up by ../js/code_editor.js; the logic is run_script_model.js's. + +// `linesBefore(line)` gives the text before the line Return splits (`line`, its part before the caret), for the +// triple-quoted string open where that line starts. +function definePythonMode(linesBefore) { + ace.define("ace/mode/orca_python_highlight_rules", + ["require", "exports", "module", "ace/lib/oop", "ace/mode/python_highlight_rules"], (require, exports) => { + const oop = require("ace/lib/oop"); + const PythonHighlightRules = require("ace/mode/python_highlight_rules").PythonHighlightRules; + function OrcaPythonHighlightRules() { + PythonHighlightRules.call(this); + // Before Python's own comment rule, which would take the line. + this.$rules.start.unshift({ token: "cell-marker", regex: "^# %%.*$" }); + } + oop.inherits(OrcaPythonHighlightRules, PythonHighlightRules); + exports.OrcaPythonHighlightRules = OrcaPythonHighlightRules; + }); + ace.define("ace/mode/orca_python", + ["require", "exports", "module", "ace/lib/oop", "ace/mode/python", "ace/mode/orca_python_highlight_rules"], (require, exports) => { + const oop = require("ace/lib/oop"); + const PythonMode = require("ace/mode/python").Mode; + function Mode() { + PythonMode.call(this); + this.HighlightRules = require("ace/mode/orca_python_highlight_rules").OrcaPythonHighlightRules; + } + oop.inherits(Mode, PythonMode); + Mode.prototype.$id = "ace/mode/orca_python"; + Mode.prototype.getNextLineIndent = (state, line, tab) => + RunScriptModel.pythonNextIndent(line, tab, RunScriptModel.openQuote(linesBefore(line))); + // pythonNextIndent() already outdents after a statement that ends a block. + Mode.prototype.checkOutdent = () => false; + exports.Mode = Mode; + }); +} + +// A tool's arguments for the detail line: each name, with its allowed values when it has some. +function toolArgsText(tool) { + return Object.entries(tool.args || {}) + .map(([name, arg]) => (arg.enum ? name + ": " + arg.enum.join(" | ") : name)) + .join(", "); +} + +// The completer the editor gets (code_editor.js's shape): the tools inside tools.call("…"), with their titles and +// arguments, and the API one level below an orca.host path, with signatures and summaries. `source` holds the catalog +// ({tools}) and the API's entries ({api}) as the host sends them. +function pythonCompleter(source) { + return { + suggestionsAt(text, at) { + const lineStart = text.lastIndexOf("\n", at - 1) + 1; + const quote = RunScriptModel.openQuote(text.slice(0, Math.max(0, lineStart - 1))); + const context = RunScriptModel.suggestContext(text.slice(lineStart, at), quote); + if (!context) return null; + const from = lineStart + context.from; + const to = at + /^\w*/.exec(text.slice(at))[0].length; + if (context.kind === "tool") + return { kind: "tool", from, to, quote: text[from - 1], + items: source.tools.map((tool) => ({ label: tool.name, detail: tool.title, info: toolArgsText(tool) })) }; + const prefix = context.path + "."; + const items = []; + for (const entry of source.api) { + if (!entry.name.startsWith(prefix)) continue; + const rest = entry.name.slice(prefix.length); + if (!rest || rest.includes(".")) continue; + items.push({ label: rest, detail: entry.kind, info: entry.signature + (entry.summary ? "\n" + entry.summary : "") }); + } + return { kind: "api", from, to, items }; + }, + // A tool's name closes its string when nothing does yet. + acceptEdit(text, found, item) { + const closes = found.kind === "tool" && found.quote && text[found.to] !== found.quote; + return { from: found.from, to: found.to, insert: item.label + (closes ? found.quote : ""), back: 0, reopen: false }; + }, + identifierRegexps: [/\w/], + triggerCharacters: ['"', "'", "."], + }; +} diff --git a/resources/web/dialog/RunScript/run_script.js b/resources/web/dialog/RunScript/run_script.js new file mode 100644 index 0000000000..fbc59a3df7 --- /dev/null +++ b/resources/web/dialog/RunScript/run_script.js @@ -0,0 +1,1054 @@ +// The Run Script panel's page. The host (RunScriptPanel) keeps the script, its file and the session, and runs what this +// page asks for; this page edits the script, draws the margin and the console, and reports every edit as it happens, so +// the host's copy is never behind. + +const S = { + python: true, + ready: false, + none: true, // no script open + fileName: "", + savedText: "", // the text as opened or saved; null while the host says it's edited and the page never saw it saved + session: "none", // none | idle | working | threads | ending + pending: null, // a run asked for, until the host starts or refuses it + run: null, // the run going: {kind, cells, text, cell, reported, runningCell, block, cellBlock} + toggleChord: "", + recent: [], + rail: new Map(), // cell index -> {state: "ran" | "failed", text: the cell's text as it ran} + cellsRun: new Set(), // the cells that ran in this session + counts: null, // {cells_text, variables_text} from the host + message: null, // a refusal or an error, shown in the status line until the next run + cellView: RunScriptModel.cellView(), // how the editor shows cells: {style, highlight}, from the Cells menu + layout: RunScriptModel.paneLayout(), // {split: the editor's share of the width, hidden: "" | "editor" | "console"} + news: "", // what the hidden console's strip shows: "" | running | fresh | failed +}; +// What the editor suggests: the host's tool catalog and the orca.host API's entries. +const source = { tools: [], api: [] }; +const CONSOLE_LIMIT = 2 * 1024 * 1024; + +let editor = null; +let railFrame = 0; +let railDecorations = []; +let railMarkers = []; +let consoleSize = 0; +let outputBlock = null; // the newest block, where output goes + +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)); } + +// ---- the script --------------------------------------------------------------------------------------------------- + +function scriptText() { return editor.getValue(); } + +function isEdited() { return !S.none && (S.savedText === null || scriptText() !== S.savedText); } + +function cellText(cell, lines) { return lines.slice(cell.start - 1, cell.end).join("\n"); } + +function applyScript(script) { + S.none = !!script.none; + S.fileName = S.none ? "" : script.file_name || ""; + closeEditorSuggestions(editor); + setEditorText(editor, S.none ? "" : script.text || ""); + S.savedText = S.none ? "" : script.edited ? null : RunScriptModel.editorText(script.text || ""); + resetSessionMarks(); + render(); +} + +function resetSessionMarks() { + S.rail.clear(); + S.cellsRun.clear(); + S.counts = null; + scheduleRail(); +} + +function onEdit(text) { + send("edit", { text, edited: isEdited() }); + scheduleRail(); + renderChip(); +} + +function save(pick) { + if (!S.none) send("save", { pick }); +} + +// ---- the margin ----------------------------------------------------------------------------------------------------- + +function scheduleRail() { + if (!railFrame) railFrame = requestAnimationFrame(drawRail); +} + +function cellState(cell, lines) { + if (S.run && S.run.runningCell === cell.index) return "running"; + const mark = S.rail.get(cell.index); + if (!mark) return "idle"; + if (mark.state === "ran" && RunScriptModel.edited(cellText(cell, lines), mark.text)) return "edited"; + return mark.state; +} + +// The cells of the rows on screen, at most once a frame: a bar per cell in the margin, in its state (wider for the cell at +// the cursor while the highlight is on), and the rows the Cells menu's view marks behind the text. +function drawRail() { + railFrame = 0; + const session = editor.session; + for (const [row, cls] of railDecorations) session.removeGutterDecoration(row, cls); + for (const id of railMarkers) session.removeMarker(id); + railDecorations = []; + railMarkers = []; + editor.container.classList.toggle("cells-bands", S.cellView.style === "bands"); + drawEditorStrip(); + if (S.none) return; + const text = scriptText(); + const lines = text.split("\n"); + const first = editor.renderer.getFirstVisibleRow(); + const last = Math.min(editor.renderer.getLastVisibleRow() + 1, lines.length - 1); + const add = (row, cls) => { + session.addGutterDecoration(row, cls); + railDecorations.push([row, cls]); + }; + const cells = RunScriptModel.splitCells(text); + const current = S.cellView.highlight ? RunScriptModel.cellAt(cells, editor.getCursorPosition().row + 1) : null; + const shown = []; + for (const cell of cells) { + if (cell.end - 1 < first || cell.start - 1 > last) continue; + shown.push(cell); + const cls = "rail-" + cellState(cell, lines); + for (let row = Math.max(cell.start - 1, first); row <= Math.min(cell.end - 1, last); ++row) { + add(row, cls); + if (row === cell.start - 1) add(row, "rail-first"); + if (row === cell.end - 1) add(row, "rail-last"); + if (cell === current) add(row, "rail-current"); + } + } + // Each marker ends past the end of its last line, so it covers every screen row of a line that wraps. + const Range = ace.require("ace/range").Range; + for (const mark of RunScriptModel.cellMarks(shown, lines, S.cellView, current ? current.index : 0)) + railMarkers.push(session.addMarker(new Range(mark.from, 0, mark.to, Infinity), mark.cls, "fullLine", false)); +} + +// ---- Add a cell ----------------------------------------------------------------------------------------------------- + +// The + in the margin a row below the last line, which adds a cell at the end; hovering it shows where. Ace has no cells, +// so the page places it after each render. Hidden while the editor can't be edited or the row is off screen. +let addButton = null; +let addHint = null; + +function setUpAddCell() { + addButton = el("button", "add-cell", "+"); + addButton.type = "button"; + addButton.title = T("add_cell_tip", "Add a cell at the end of the script"); + addButton.setAttribute("aria-label", T("add_cell", "Add a cell")); + addHint = el("div", "add-hint", T("add_cell", "Add a cell")); + addHint.setAttribute("aria-hidden", "true"); + editor.container.append(addButton, addHint); + // Ace would move the caret on the press before the click; the page's own outside-press handler doesn't see it then, + // so the press closes the menus itself. + addButton.addEventListener("mousedown", (e) => { + e.stopPropagation(); + closeMenus(); + }); + addButton.addEventListener("click", addCell); + editor.renderer.on("afterRender", placeAddButton); + // Room below the last line for the + when the script is longer than the editor. + editor.renderer.setScrollMargin(0, 24, 0, 0); +} + +function placeAddButton() { + if (!addButton) return; + const r = editor.renderer; + const box = editor.container.getBoundingClientRect(); + const top = r.textToScreenCoordinates(editor.session.getLength() - 1, Infinity).pageY - box.top + r.lineHeight; + const shown = !S.none && !editor.getReadOnly() && top >= 0 && top + r.lineHeight <= box.height; + addButton.hidden = addHint.hidden = !shown; + if (!shown) return; + addButton.style.top = top + Math.round((r.lineHeight - addButton.offsetHeight) / 2) + "px"; + addHint.style.top = top + "px"; + addHint.style.height = r.lineHeight + "px"; + addHint.style.left = r.textToScreenCoordinates(0, 0).pageX - box.left + "px"; +} + +function addCell() { + if (S.none || editor.getReadOnly()) return; + const edit = RunScriptModel.addCellEdit(editor.session.getDocument().getAllLines()); + editor.session.insert(edit.at, edit.text); + editor.clearSelection(); + editor.moveCursorTo(edit.caret.row, edit.caret.column); + editor.scrollToLine(edit.caret.row + 1, false, true); + editor.focus(); +} + +// ---- the divider and the hidden sides ------------------------------------------------------------------------------ + +// The divider dragged: the share it had when the drag started, which a side the drag hides comes back at, and the side +// the drag would hide if it ended now. +let splitDrag = null; + +const NEWS_TIPS = { + "": ["show_console", "Show the console"], + running: ["show_console_running", "Show the console: a script is running"], + fresh: ["show_console_new", "Show the console: it has new output"], + failed: ["show_console_failed", "Show the console: the last run failed"], +}; + +// Whether the side right of the divider shows the console, rather than the start page or the note that Python is off. +function consoleShown() { return !S.none && S.python; } + +function renderLayout() { + const panes = $("panes"); + const hidden = RunScriptModel.hiddenSide(S.layout.hidden, consoleShown()); + panes.style.setProperty("--split", S.layout.split * 100 + "%"); + panes.dataset.hidden = hidden; + $("hide-console").hidden = !consoleShown(); + $("split").setAttribute("aria-valuenow", String(Math.round(S.layout.split * 100))); + const tip = T(...NEWS_TIPS[S.news]); + $("console-strip").title = tip; + $("console-strip").setAttribute("aria-label", tip); + $("console-news").className = "news " + S.news; + if (hidden === "editor") scheduleRail(); + else if (!S.none) editor.resize(); +} + +// The hidden editor's strip: a bar per cell, in the margin's states. +function drawEditorStrip() { + const bars = $("editor-strip-cells"); + bars.textContent = ""; + if (S.layout.hidden !== "editor" || S.none) return; + const text = scriptText(); + const lines = text.split("\n"); + for (const cell of RunScriptModel.splitCells(text)) bars.append(el("i", cellState(cell, lines))); +} + +// Sets the layout, and has the host keep it unless `save` is false (a drag keeps it when it ends). The console's strip +// starts blank, or running while a run goes. +function setLayout(layout, save) { + if (layout.hidden !== S.layout.hidden) S.news = layout.hidden === "console" && S.run ? "running" : ""; + S.layout = layout; + renderLayout(); + if (save !== false) send("pane_layout", layout); +} + +// Hides a side, the divider coming back at `split`, and leaves the focus on the strip that brings it back. +function hideSide(side, split) { + setLayout({ split: split === undefined ? S.layout.split : split, hidden: side }); + $(side + "-strip").focus(); +} + +// Brings the hidden side back, with the focus in it: the editor, or the console's prompt line while it takes a line. +function showBothSides() { + const was = S.layout.hidden; + setLayout({ split: S.layout.split, hidden: "" }); + if (was === "editor" && !S.none) editor.focus(); + else if (was === "console" && !$("console").hidden && !$("prompt-input").disabled) $("prompt-input").focus(); + else $("split").focus(); +} + +// What the hidden console's strip shows after a run starts or ends, or output comes. +function noteConsole(event) { + if (RunScriptModel.hiddenSide(S.layout.hidden, consoleShown()) !== "console") return; + const news = RunScriptModel.consoleNews(S.news, event); + if (news === S.news) return; + S.news = news; + renderLayout(); +} + +function setUpSplit() { + const split = $("split"); + split.addEventListener("pointerdown", (e) => { + if (e.button !== 0 || e.target.closest("button")) return; + e.preventDefault(); + split.setPointerCapture(e.pointerId); + splitDrag = { from: S.layout.split, hide: "" }; + $("panes").classList.add("dragging"); + }); + split.addEventListener("pointermove", (e) => { + if (!splitDrag) return; + const box = $("panes").getBoundingClientRect(); + const to = RunScriptModel.dragSplit(e.clientX - box.left, box.width); + splitDrag.hide = RunScriptModel.hiddenSide(to.hide, consoleShown()); + $("panes").dataset.pending = splitDrag.hide; + setLayout({ split: to.split, hidden: "" }, false); + }); + const endDrag = () => { + if (!splitDrag) return; + const { from, hide } = splitDrag; + splitDrag = null; + $("panes").classList.remove("dragging"); + $("panes").dataset.pending = ""; + if (hide) hideSide(hide, from); + else send("pane_layout", S.layout); + }; + split.addEventListener("pointerup", endDrag); + split.addEventListener("lostpointercapture", endDrag); + split.addEventListener("dblclick", (e) => { + if (!e.target.closest("button")) setLayout({ split: RunScriptModel.paneLayout().split, hidden: "" }); + }); + // A window splitter's keys; Enter hides the console while the side shows it. The grip's buttons take their own. + split.addEventListener("keydown", (e) => { + if (e.target !== split) return; + if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) { + e.preventDefault(); + if (consoleShown()) hideSide("console"); + return; + } + const to = RunScriptModel.splitByKey(S.layout.split, e.key, $("panes").getBoundingClientRect().width); + if (to === null) return; + e.preventDefault(); + setLayout({ split: to, hidden: "" }); + }); + $("hide-editor").addEventListener("click", () => hideSide("editor")); + $("hide-console").addEventListener("click", () => hideSide("console")); + $("editor-strip").addEventListener("click", showBothSides); + $("console-strip").addEventListener("click", showBothSides); +} + +// ---- running ------------------------------------------------------------------------------------------------------ + +function busy() { return !!S.pending || !!S.run || S.session === "working"; } + +function canRun() { return S.python && S.ready && !S.none && !busy() && S.session !== "ending"; } + +function runAll() { + closeEditorSuggestions(editor); + if (!canRun()) return; + const text = scriptText(); + const cells = RunScriptModel.splitCells(text); + S.pending = { kind: "file", cells, text }; + S.message = null; + send("run", { kind: "file", text, cell_starts: cells.map((cell) => cell.start) }); + render(); +} + +function runCell() { + closeEditorSuggestions(editor); + if (!canRun()) return; + const text = scriptText(); + const cells = RunScriptModel.splitCells(text); + const cell = RunScriptModel.cellAt(cells, editor.getCursorPosition().row + 1); + const code = cellText(cell, text.split("\n")); + S.pending = { kind: "cell", cells, text, cell, code }; + S.message = null; + send("run", { kind: "cell", text, first_line: cell.start, last_line: cell.end, code }); + render(); +} + +function runConsole() { + const input = $("prompt-input"); + const code = input.value; + if (!code.trim() || !S.python || !S.ready || busy() || S.session === "ending") return; + input.value = ""; + S.pending = { kind: "console", code }; + S.message = null; + send("run", { kind: "console", text: S.none ? "" : scriptText(), code }); + render(); +} + +function onRunStarted(msg) { + const asked = S.pending || { kind: msg.kind }; + S.pending = null; + S.run = Object.assign({ reported: [], runningCell: null }, asked, { kind: msg.kind, started: Date.now() }); + if (msg.kind === "file" && !S.run.cells) { + // A run the page didn't ask for in this load (it was rebuilt meanwhile): the cells are the editor's. + S.run.text = scriptText(); + S.run.cells = RunScriptModel.splitCells(S.run.text); + } + if (msg.kind === "file") { + // Run all runs in a session of its own. + if (S.session !== "none") addDivider(T("session_restarted", "Session restarted for Run all")); + resetSessionMarks(); + S.run.block = newRunAllBlock(); + } else if (msg.kind === "cell") { + S.run.runningCell = asked.cell.index; + S.run.block = newBlock(T("cell_n", "Cell %s", asked.cell.index), asked.cell.title); + } else + S.run.block = newBlock(null, null, ">>> " + asked.code); + editor.setReadOnly(true); + noteConsole("start"); + scheduleRail(); + render(); +} + +function onCell(msg) { + const run = S.run; + if (!run || run.kind !== "file" || !run.cells) return; + const cell = run.cells[msg.index]; + if (!cell) return; + const lines = run.text.split("\n"); + // The cell before it has run. + if (run.reported.length) { + const before = run.cells[run.reported[run.reported.length - 1]]; + S.rail.set(before.index, { state: "ran", text: cellText(before, lines) }); + if (run.cellBlock) finishBlock(run.cellBlock, Date.now() - run.cellBlock.started, false); + } + run.reported.push(msg.index); + run.runningCell = cell.index; + run.cellBlock = newCellRow(run.block, cell); + scheduleRail(); + renderStatus(); +} + +function onRunFinished(msg) { + const run = S.run || Object.assign({ reported: [] }, S.pending || {}); + S.pending = null; + S.run = null; + const failed = msg.status !== "finished"; + if (run.cellBlock) finishBlock(run.cellBlock, Date.now() - run.cellBlock.started, failed); + const block = run.block || outputBlock || newBlock(T("run_all", "Run all")); + finishBlock(block, msg.duration_ms, failed); + // How it ended goes under what ran last: Run all's last cell, or the run's own block. + const last = run.cellBlock || block; + if (msg.status === "refused") { + S.message = msg.message || ""; + appendLine(last, msg.message || "", "err"); + } else if (msg.status === "raised") + appendTraceback(last, msg.traceback || msg.message || "", msg.script_file); + else if (msg.status_text) + appendLine(last, msg.status_text, failed ? "err" : "muted"); + if (!last.printed && !failed && run.kind !== "file") appendLine(last, T("no_output", "(no output)"), "muted"); + // The cell Run all stopped in opens, so its error shows. + if (failed && run.cellBlock) { + setRowOpen(run.cellBlock, true); + renderExpandAll(run.block); + } + revealLog(true); + + const lines = (run.text || "").split("\n"); + if (run.kind === "cell" && msg.status !== "refused" && msg.status !== "unavailable") { + S.rail.set(run.cell.index, { state: failed ? "failed" : "ran", text: run.code }); + S.cellsRun.add(run.cell.index); + } else if (run.kind === "file" && run.cells && msg.status !== "refused") { + RunScriptModel.railAfterFile(run.cells, run.reported, msg).forEach((state, i) => { + if (state === "idle") return; + S.rail.set(i + 1, { state, text: cellText(run.cells[i], lines) }); + S.cellsRun.add(i + 1); + }); + } + if (msg.status !== "refused") send("counts", { cells: S.cellsRun.size, variables: msg.variables || 0 }); + editor.setReadOnly(S.none); + scheduleRail(); + render(); + noteConsole(failed ? "failed" : "finished"); + // The prompt was off while its line ran; the next line goes in it. + if (run.kind === "console" && !$("prompt-input").disabled) $("prompt-input").focus(); +} + +function onRunRefused(msg) { + S.pending = null; + S.message = msg.message || ""; + render(); +} + +// ---- the console ------------------------------------------------------------------------------------------------ + +function newBlock(head, title, code) { + const block = el("div", "block"); + const top = el("div", "run-head busy"); + if (head) top.append(el("b", "", head)); + if (title) top.append(el("span", "t", title)); + if (code) top.append(el("span", "code", code)); + const duration = el("span", "d"); + top.append(duration); + block.append(top); + block.head = top; + block.duration = duration; + block.size = 0; + block.started = Date.now(); + $("log").append(block); + outputBlock = block; + revealLog(true); + return block; +} + +// Run all's block: a row for each cell the run reaches, folded, and Expand all in its heading once there is one. +function newRunAllBlock() { + const block = newBlock(T("run_all", "Run all")); + const all = el("button", "expand-all"); + all.type = "button"; + all.hidden = true; + all.addEventListener("click", () => { + const open = !allRowsOpen(block); + for (const row of block.cells.children) setRowOpen(row, open); + renderExpandAll(block); + }); + block.head.insertBefore(all, block.duration); + block.expandAll = all; + block.cells = el("div", "cells"); + block.append(block.cells); + return block; +} + +// The row of the cell Run all runs now, in `group`, the run's block. Folded, its heading shows what the cell showed last +// (a line it printed, its result or its error), and a click opens it. Output goes in it, as in a block. +function newCellRow(group, cell) { + const row = el("div", "cell-row running"); + const head = el("button", "cell-head busy"); + head.type = "button"; + head.append(el("span", "chev"), el("b", "", T("cell_n", "Cell %s", cell.index))); + if (cell.title) head.append(el("span", "t", cell.title)); + const peek = el("span", "peek"); + const duration = el("span", "d"); + head.append(peek, duration); + const body = el("div", "cell-body"); + row.append(head, body); + Object.assign(row, { head, peek, duration, body, group, size: 0, started: Date.now(), tail: "" }); + setRowOpen(row, false); + head.addEventListener("click", () => { + setRowOpen(row, body.hidden); + renderExpandAll(group); + }); + group.cells.append(row); + renderExpandAll(group); + outputBlock = row; + revealLog(true); + return row; +} + +function setRowOpen(row, open) { + row.body.hidden = !open; + row.classList.toggle("open", open); + row.head.setAttribute("aria-expanded", String(open)); +} + +function allRowsOpen(group) { return [...group.cells.children].every((row) => !row.body.hidden); } + +function renderExpandAll(group) { + group.expandAll.hidden = !group.cells.children.length; + group.expandAll.textContent = allRowsOpen(group) ? T("collapse_all", "Collapse all") : T("expand_all", "Expand all"); +} + +// What a folded row shows: `text` on one line, in the error colour for an error. Empty text leaves what it showed. +function setPeek(row, text, err) { + if (!text) return; + row.peek.textContent = text.slice(0, 500); + row.peek.classList.toggle("err", !!err); +} + +// Where a block's output goes: a row's body, or the block itself. +function contentOf(block) { return block.body || block; } + +function finishBlock(block, ms, failed) { + block.head.classList.remove("busy"); + block.head.classList.toggle("failed", !!failed); + if (ms !== undefined && ms !== null) block.duration.textContent = seconds(ms); + if (block.peek) { + block.classList.remove("running"); + block.classList.toggle("failed", !!failed); + if (!block.printed) setPeek(block, T("no_output", "(no output)")); + } +} + +function addDivider(text) { $("log").append(el("div", "divider", text)); } + +function logAtBottom() { + const log = $("log"); + return log.scrollHeight - log.scrollTop - log.clientHeight < 24; +} + +function revealLog(force) { + const log = $("log"); + if (force || logAtBottom()) log.scrollTop = log.scrollHeight; +} + +// Empties the console and leaves the session alone. A run going keeps its heading, emptied, and its output goes on under it; +// in Run all, that is the run's block with the row of the cell it runs now. +function clearConsole() { + const kept = RunScriptModel.keptByClear(S.run); + const log = $("log"); + log.textContent = ""; + consoleSize = 0; + for (const block of kept) { + if (block.cells) { + block.cells.replaceChildren(); + block.replaceChildren(block.head, block.cells); + } else if (block.body) { + block.body.replaceChildren(); + block.tail = ""; + block.peek.textContent = ""; + } else + block.replaceChildren(block.head); + block.size = 0; + (block.group ? block.group.cells : log).append(block); + } + if (kept.length && kept[0].cells) renderExpandAll(kept[0]); + outputBlock = kept.length ? kept[kept.length - 1] : null; +} + +// `size` is what the block holds now, for the console's limit, a row's counted in its run's block too; `printed`, +// whether it ever showed output, Clear or not. +function count(block, n) { + block.size += n; + block.printed = true; + if (block.group) block.group.size += n; + consoleSize += n; + // The console keeps its last 2 MiB, dropping its oldest blocks. + const log = $("log"); + while (consoleSize > CONSOLE_LIMIT && log.children.length > 1) { + const oldest = log.firstElementChild; + consoleSize -= oldest.size || 0; + oldest.remove(); + } +} + +// The output a row keeps to find its last line, which a long line can't push out. +const PEEK_TAIL = 4096; + +function appendOutput(text) { + const atBottom = logAtBottom(); + const block = outputBlock || newBlock(null); + const box = contentOf(block); + let out = box.lastElementChild; + if (!out || !out.classList.contains("out") || out.classList.length > 1) { + out = el("div", "out"); + box.append(out); + } + out.append(document.createTextNode(text)); + count(block, text.length); + if (block.peek) { + block.tail = (block.tail + text).slice(-PEEK_TAIL); + setPeek(block, RunScriptModel.lastLine(block.tail)); + } + if (atBottom) revealLog(true); + noteConsole("output"); +} + +// A result JSON holds, as the host sends it: laid out to read, in the editor's JSON colours. A folded row shows it as it +// came, on one line. +function appendResult(text) { + const atBottom = logAtBottom(); + const block = outputBlock || newBlock(null); + const out = el("div", "out json"); + const shown = RunScriptModel.formatJson(text); + const tokens = RunScriptModel.jsonTokens(shown); + if (!tokens) out.textContent = shown; + else + for (const token of tokens) + out.append(token.type === "space" ? document.createTextNode(token.text) : el("span", "j-" + token.type, token.text)); + contentOf(block).append(out); + // The layout is what the console holds. + count(block, shown.length); + if (block.peek) { + block.tail = ""; + setPeek(block, text); + } + if (atBottom) revealLog(true); + noteConsole("output"); +} + +function appendLine(block, text, cls) { + contentOf(block).append(el("div", "out " + cls, text)); + count(block, text.length); + if (block.peek) setPeek(block, RunScriptModel.lastLine(text), cls === "err"); + revealLog(false); +} + +// A traceback whose lines in the script are links that move the cursor there. +function appendTraceback(block, traceback, scriptFile) { + const out = el("div", "out err"); + let at = 0; + for (const link of RunScriptModel.tracebackLinks(traceback, scriptFile || "")) { + out.append(document.createTextNode(traceback.slice(at, link.start))); + const a = el("a", "link", traceback.slice(link.start, link.end)); + a.href = "#"; + a.addEventListener("click", (e) => { + e.preventDefault(); + goToLine(link.line); + }); + out.append(a); + at = link.end; + } + out.append(document.createTextNode(traceback.slice(at))); + contentOf(block).append(out); + count(block, traceback.length); + if (block.peek) setPeek(block, RunScriptModel.lastLine(traceback), true); + revealLog(false); +} + +function goToLine(line) { + editor.gotoLine(line, 0, true); + editor.scrollToLine(line - 1, true, true); + editor.focus(); +} + +// ---- rendering ----------------------------------------------------------------------------------------------------- + +function renderChip() { + $("file-chip").hidden = S.none; + $("file-name").textContent = S.fileName || T("untitled_script", "Untitled script"); + $("file-edited").hidden = !isEdited(); + $("editor-strip-name").textContent = S.none ? "" : $("file-name").textContent; +} + +function sessionItem(text, cls) { return el("span", "item" + (cls ? " " + cls : ""), text); } + +// The session line: its items apart, since one sentence can't hold two counts. +function renderSession() { + const box = $("session"); + box.textContent = ""; + box.className = "session"; + box.append(el("span", "dot")); + if (S.session === "ending") return box.append(sessionItem(T("session_ending", "Ending the session…"))); + if (busy()) { + box.classList.add("busy"); + return box.append(sessionItem(T("running", "Running"), "lead")); + } + if (S.session === "none") return box.append(sessionItem(T("no_session", "No session yet"))); + box.classList.add("live"); + box.append(sessionItem(T("session", "Session"), "lead")); + if (S.counts) { + box.append(sessionItem(S.counts.cells_text)); + box.append(sessionItem(S.counts.variables_text)); + } + if (S.session === "threads") box.append(sessionItem(T("threads_running", "Threads are running"))); +} + +function runningText() { + const run = S.run; + if (!run) return ""; + if (run.runningCell && run.cells) return T("running_cell", "Running cell %s of %s", run.runningCell, run.cells.length); + if (run.kind === "file") return T("running_file", "Running the file"); + return T("running", "Running"); +} + +function renderStatus() { + const bar = $("status"); + bar.classList.remove("is-error"); + if (S.run) { + $("status-main").textContent = runningText(); + $("status-detail").textContent = T("hands_off", "Don't use OrcaSlicer until the script finishes."); + } else if (S.message) { + bar.classList.add("is-error"); + $("status-main").textContent = S.message; + $("status-detail").textContent = ""; + } else if (S.python && !S.ready) { + $("status-main").textContent = T("starting", "OrcaSlicer is still starting…"); + $("status-detail").textContent = ""; + } else { + bar.hidden = true; + return; + } + bar.hidden = false; +} + +function render() { + renderChip(); + const working = busy(); + const ending = S.session === "ending"; + $("new").disabled = working; + $("open").disabled = working; + $("close-script").disabled = working || S.none; + $("save").disabled = S.none; + $("run-all").disabled = !canRun(); + $("run-cell").disabled = !canRun(); + $("stop").disabled = !(working || S.session === "threads"); + $("restart").disabled = S.session === "none" || working || ending; + const promptOff = !S.python || !S.ready || working || ending; + $("prompt-input").disabled = promptOff; + $("prompt-input").closest(".prompt-line").classList.toggle("off", promptOff); + + $("editor").hidden = S.none; + $("editor-empty").hidden = !S.none; + editor.setReadOnly(S.none || !!S.run); + $("editor").classList.toggle("is-readonly", !!S.run); + $("start").hidden = !S.none; + $("off").hidden = S.none || S.python; + $("console").hidden = S.none || !S.python; + renderLayout(); + placeAddButton(); + renderSession(); + renderStatus(); +} + +function renderRecent() { + const menu = $("open-recent"); + const list = $("start-recent"); + menu.textContent = ""; + list.textContent = ""; + for (const item of S.recent) { + const entry = el("button", "menu-item"); + entry.type = "button"; + entry.setAttribute("role", "menuitem"); + entry.append(el("span", "f", item.name), el("span", "d", item.folder)); + entry.addEventListener("click", () => { + closeMenus(); + send("open_recent", { path: item.path }); + }); + menu.append(entry); + const row = el("li"); + const button = el("button"); + button.type = "button"; + button.append(el("span", "f", item.name), el("span", "d", item.folder)); + button.addEventListener("click", () => send("open_recent", { path: item.path })); + row.append(button); + list.append(row); + } + menu.hidden = !S.recent.length; + $("start-no-recent").hidden = !!S.recent.length; +} + +// ---- the toolbar's menus: Open and Cells ---------------------------------------------------------------------------- + +// Each menu, by the id of the button that opens it. +const MENUS = { open: "open-menu", cells: "cells-menu" }; + +// Opens the menu of `button`, closing the other, and focuses `item`. A menu that would run past the page's right edge +// opens leftwards from its button instead. +function openMenu(button, item) { + closeMenus(); + const menu = $(MENUS[button]); + menu.classList.remove("right"); + menu.hidden = false; + $(button).setAttribute("aria-expanded", "true"); + if (menu.getBoundingClientRect().right > document.documentElement.clientWidth) menu.classList.add("right"); + if (item) item.focus(); +} + +function closeMenus() { + for (const [button, menu] of Object.entries(MENUS)) { + $(menu).hidden = true; + $(button).setAttribute("aria-expanded", "false"); + } +} + +function menuOpen() { return Object.values(MENUS).some((menu) => !$(menu).hidden); } + +function renderCellsMenu() { + for (const item of document.querySelectorAll("#cells-menu [data-style]")) + item.setAttribute("aria-checked", String(item.dataset.style === S.cellView.style)); + $("cells-highlight").setAttribute("aria-checked", String(S.cellView.highlight)); +} + +// A pick in the Cells menu, drawn at once and saved by the host. The menu stays open, so the styles can be compared. +function setCellView(view) { + S.cellView = view; + renderCellsMenu(); + scheduleRail(); + send("cell_view", view); +} + +// ---- keys ----------------------------------------------------------------------------------------------------------- + +const EVENT_KEY_NAMES = { Enter: "Enter", Escape: "Esc", " ": "Space", Backspace: "Backspace", Delete: "Del", Insert: "Ins", + PageUp: "PgUp", PageDown: "PgDn", ArrowLeft: "Left", ArrowRight: "Right", ArrowUp: "Up", ArrowDown: "Down", + Tab: "Tab", Home: "Home", End: "End" }; + +// A key event as KeyChord::to_string() writes a chord: Ctrl (⌘ on macOS), Shift, Alt, RawCtrl, then the key. +function chordOfEvent(e) { + let key = ""; + if (/^Key[A-Z]$/.test(e.code)) key = e.code.slice(3); + else if (/^Digit\d$/.test(e.code)) key = e.code.slice(5); + else if (EVENT_KEY_NAMES[e.key]) key = EVENT_KEY_NAMES[e.key]; + else if (/^F\d+$/.test(e.key)) key = e.key; + else if (e.key.length === 1) key = e.key.toUpperCase(); + if (!key) return ""; + const mods = []; + if (IS_MAC ? e.metaKey : e.ctrlKey) mods.push("Ctrl"); + if (e.shiftKey) mods.push("Shift"); + if (e.altKey) mods.push("Alt"); + if (IS_MAC && e.ctrlKey) mods.push("RawCtrl"); + return mods.map((m) => m + "+").join("") + key; +} + +function markOwnKey(name) { editor.$orcaOwnAt[name] = Date.now(); } + +// The editor's commands: Run all, Run cell, Save, Save as, the panel's toggle, and Ctrl+R, which does nothing. None +// edits the text, so all work while the editor is read-only. +function pageCommands() { + const commands = [ + { name: "runAll", bindKey: { win: "Ctrl-Return", mac: "Command-Return" }, exec: () => runAll(), readOnly: true }, + { name: "runCell", bindKey: { win: "Shift-Return", mac: "Shift-Return" }, exec: () => runCell(), readOnly: true }, + { name: "save", bindKey: { win: "Ctrl-S", mac: "Command-S" }, exec: () => save(false), readOnly: true }, + { name: "saveAs", bindKey: { win: "Ctrl-Shift-S", mac: "Command-Shift-S" }, exec: () => save(true), readOnly: true }, + { name: "noReload", bindKey: { win: "Ctrl-R", mac: "Command-R" }, exec: () => {}, readOnly: true }, + ]; + if (S.toggleChord) commands.push(toggleCommand()); + return commands; +} + +function toggleCommand() { return { name: "togglePanel", bindKey: aceKey(S.toggleChord), exec: () => send("toggle"), readOnly: true }; } + +function setToggleChord(chord) { + S.toggleChord = chord || ""; + editor.commands.removeCommand("togglePanel"); + if (S.toggleChord) { + editor.commands.addCommand(toggleCommand()); + editor.$orcaCommands.add("togglePanel"); + } +} + +// Keys elsewhere on the page; the editor's own commands take them in the editor. +function onDocumentKey(e) { + if (isEditorText(editor, e.target)) return; + const chord = chordOfEvent(e); + if (!chord) return; + const act = (fn) => { + e.preventDefault(); + fn(); + }; + if (chord === S.toggleChord) act(() => send("toggle")); + else if (chord === "Ctrl+S") act(() => (markOwnKey("save"), save(false))); + else if (chord === "Ctrl+Shift+S") act(() => (markOwnKey("saveAs"), save(true))); + else if (chord === "Ctrl+Enter") act(runAll); + else if (chord === "Shift+Enter") act(runCell); + else if (chord === "Ctrl+R") act(() => {}); + else if (chord === "Esc" && menuOpen()) act(closeMenus); +} + +// A key the host forwards from its menus while the panel has the focus, unless the page took the same press itself. +function onForwardedKey(action) { + if (action === "save" || action === "save_as") { + const name = action === "save" ? "save" : "saveAs"; + if (!ownKeyRan(editor, name)) save(action === "save_as"); + } else + runEditorAction(editor, action); +} + +// ---- host messages ---------------------------------------------------------------------------------------------- + +function HandleStudio(msg) { + switch (msg.command) { + case "state": + S.python = !!msg.python_on; + S.ready = !!msg.ready; + S.recent = msg.recent || []; + S.session = msg.session || "none"; + setToggleChord(msg.toggle_key && msg.toggle_key.chord); + S.cellView = RunScriptModel.cellView(msg.cell_view); + S.layout = RunScriptModel.paneLayout(msg.pane_layout); + renderCellsMenu(); + applyScript(msg.script || { none: true }); + renderRecent(); + break; + case "service": + S.ready = !!msg.ready; + render(); + break; + case "catalog": source.tools = msg.tools || []; break; + case "api": source.api = msg.entries || []; break; + case "script": applyScript(msg); break; + case "saved": + S.fileName = msg.file_name; + S.savedText = RunScriptModel.editorText(msg.text); + onEdit(scriptText()); + break; + case "recent": + S.recent = msg.items || []; + renderRecent(); + break; + case "error": + S.message = msg.message; + render(); + break; + case "run_started": onRunStarted(msg); break; + case "run_refused": onRunRefused(msg); break; + case "output": appendOutput(msg.text); break; + case "result": appendResult(msg.text); break; + case "cell": onCell(msg); break; + case "run_finished": onRunFinished(msg); break; + case "session": + S.session = msg.state; + // A session that ended takes what ran in it along: every cell is grey again. + if (S.session === "none" && !S.run) resetSessionMarks(); + render(); + break; + case "counts": + S.counts = msg; + render(); + break; + case "key": onForwardedKey(msg.action); break; + case "shortcuts": setToggleChord(msg.toggle_key && msg.toggle_key.chord); break; + case "python": + S.python = !!msg.on; + render(); + break; + } +} + +function OnInit() { + TranslatePage(); + // Ace has already split the line when it asks for the next line's indent, so the line is the one above the caret. + definePythonMode((line) => { + let row = editor.getCursorPosition().row; + if (row > 0 && editor.session.getLine(row - 1) === line) --row; + return editor.session.getLines(0, row - 1).join("\n"); + }); + editor = createCodeEditor($("editor"), { + mode: "ace/mode/orca_python", + tabSize: 4, + completer: pythonCompleter(source), + onChange: onEdit, + commands: pageCommands(), + }); + editor.session.on("changeScrollTop", scheduleRail); + editor.renderer.on("resize", scheduleRail); + editor.session.on("changeFold", scheduleRail); + editor.selection.on("changeCursor", () => { + if (S.cellView.highlight) scheduleRail(); + }); + setUpAddCell(); + setUpSplit(); + + const runAllKey = T("key_run_all", "Ctrl+Enter"); + const runCellKey = T("key_run_cell", "Shift+Enter"); + $("run-all-key").textContent = runAllKey; + $("run-cell-key").textContent = runCellKey; + $("run-all").title = T("run_all_tip", "Restart the session and run every cell (%s)", runAllKey); + $("run-cell").title = T("run_cell_tip", "Run the cell at the cursor (%s)", runCellKey); + $("save").title = T("save_tip", "Save the script (%s)", T("key_save", "Ctrl+S")); + $("new").title = T("new_tip", "Start a new script"); + $("open").title = T("open_tip", "Open a Python script"); + $("stop").title = T("stop_tip", "Interrupt the code that runs now and the threads the session started"); + $("restart").title = T("restart_tip", "End the session: its variables, imports and threads go"); + $("clear").title = T("clear_tip", "Clear the console: the session and its variables stay"); + $("cells").title = T("cells_tip", "How the editor shows the script's cells"); + renderCellsMenu(); + AppendTemplate($("start-text"), T("start_script_text", + "A Python script runs inside OrcaSlicer and can call every tool an AI agent can, plus the whole orca.host API. Split it into cells with %s and try one cell at a time."), + el("code", "", "# %%")); + + $("new").addEventListener("click", () => send("new")); + $("start-new").addEventListener("click", () => send("new")); + $("start-open").addEventListener("click", () => send("open")); + $("open").addEventListener("click", () => ($("open-menu").hidden ? openMenu("open", $("open-file")) : closeMenus())); + $("open-file").addEventListener("click", () => { + closeMenus(); + send("open"); + }); + $("close-script").addEventListener("click", () => { + closeMenus(); + send("close_script"); + }); + $("cells").addEventListener("click", () => + ($("cells-menu").hidden ? openMenu("cells", $("cells-menu").querySelector('[aria-checked="true"]')) : closeMenus())); + for (const item of document.querySelectorAll("#cells-menu [data-style]")) + item.addEventListener("click", () => setCellView({ style: item.dataset.style, highlight: S.cellView.highlight })); + $("cells-highlight").addEventListener("click", () => setCellView({ style: S.cellView.style, highlight: !S.cellView.highlight })); + document.addEventListener("mousedown", (e) => { + if (menuOpen() && !e.target.closest(".menu-wrap")) closeMenus(); + }); + $("save").addEventListener("click", () => save(false)); + $("run-all").addEventListener("click", runAll); + $("run-cell").addEventListener("click", runCell); + $("stop").addEventListener("click", () => send("stop")); + $("restart").addEventListener("click", () => send("restart")); + $("clear").addEventListener("click", clearConsole); + $("turn-on").addEventListener("click", () => send("turn_on_python")); + $("prompt-input").addEventListener("keydown", (e) => { + if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) { + e.preventDefault(); + runConsole(); + } + }); + document.addEventListener("keydown", onDocumentKey); + + render(); + send("init"); + // The keys the editor takes, which the host keeps from its menus while the panel has the focus. + send("editor_keys", { chords: editorChords(editor) }); +} diff --git a/resources/web/dialog/RunScript/run_script.test.js b/resources/web/dialog/RunScript/run_script.test.js new file mode 100644 index 0000000000..206f871a33 --- /dev/null +++ b/resources/web/dialog/RunScript/run_script.test.js @@ -0,0 +1,317 @@ +"use strict"; +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const model = require("./run_script_model.js"); + +test("a file without a marker is one cell", () => { + assert.deepEqual(model.splitCells("x = 1\ny = 2\n"), [{ index: 1, start: 1, end: 3, title: "" }]); +}); + +test("a marker on line 1 starts the first cell, and its text is the cell's title", () => { + assert.deepEqual(model.splitCells("# %% Load\nx = 1\n# %%Slice \ny = 2"), [ + { index: 1, start: 1, end: 2, title: "Load" }, + { index: 2, start: 3, end: 4, title: "Slice" }, + ]); +}); + +test("lines before the first marker are cell 1, and an indented marker is a comment", () => { + assert.deepEqual(model.splitCells("import os\n\n# %% A\nif True:\n # %% not a cell\n x = 1"), [ + { index: 1, start: 1, end: 2, title: "" }, + { index: 2, start: 3, end: 6, title: "A" }, + ]); +}); + +test("the cell at a line is the one whose lines hold it", () => { + const cells = model.splitCells("a\n# %% B\nb\n# %% C\nc"); + assert.equal(model.cellAt(cells, 1).index, 1); + assert.equal(model.cellAt(cells, 3).index, 2); + assert.equal(model.cellAt(cells, 5).index, 3); +}); + +test("Return indents after a colon or an opening bracket, outdents after a statement that ends a block", () => { + const tab = " "; + assert.equal(model.pythonNextIndent("def f(): # c", tab), " "); + assert.equal(model.pythonNextIndent("x = 1", tab), ""); + assert.equal(model.pythonNextIndent(" return x", tab), ""); + assert.equal(model.pythonNextIndent(" pass", tab), ""); + assert.equal(model.pythonNextIndent("foo(", tab), " "); + assert.equal(model.pythonNextIndent('x = "a:"', tab), ""); + assert.equal(model.pythonNextIndent("# a:", tab), ""); + assert.equal(model.pythonNextIndent("return", tab), ""); + assert.equal(model.pythonNextIndent(" if x:", tab), " "); + assert.equal(model.pythonNextIndent(" returned = 1", tab), " "); +}); + +test("suggestions come inside tools.call's string and after orca.host., never inside another string", () => { + assert.deepEqual(model.suggestContext('tools.call("sl'), { kind: "tool", from: 12, typed: "sl" }); + assert.deepEqual(model.suggestContext("orca.host.tools.call('"), { kind: "tool", from: 22, typed: "" }); + assert.deepEqual(model.suggestContext("orca.host.ui.me"), { kind: "api", path: "orca.host.ui", from: 13, typed: "me" }); + assert.deepEqual(model.suggestContext("x = orca.host."), { kind: "api", path: "orca.host", from: 14, typed: "" }); + assert.equal(model.suggestContext('x = "tools.call("'), null); + assert.equal(model.suggestContext("# orca.host.ui"), null); +}); + +test("a traceback's lines in the script are links, other files' and the console's are not", () => { + const script = "C:\\scripts\\demo.py"; + const traceback = 'Traceback (most recent call last):\n' + + ' File "C:\\scripts\\demo.py", line 7, in \n' + + ' File "C:\\lib\\helper.py", line 3, in f\n' + + ' File "", line 1, in \n' + + ' File "C:\\scripts\\demo.py", line 12\n' + + "SyntaxError: invalid syntax\n"; + const links = model.tracebackLinks(traceback, script); + assert.deepEqual(links.map((l) => l.line), [7, 12]); + for (const link of links) + assert.match(traceback.slice(link.start, link.end), /^File "C:\\scripts\\demo\.py", line \d+$/); +}); + +test("Run all's margin: every cell ran when it finished", () => { + const cells = model.splitCells("a\n# %% b\nb\n# %% c\nc"); + assert.deepEqual(model.railAfterFile(cells, [0, 1, 2], { status: "finished", error_line: 0, executed: true, cells_reported: true }), + ["ran", "ran", "ran"]); +}); + +test("Run all's margin: a raise at a line marks the cells before it ran, its own failed, the rest not run", () => { + const cells = model.splitCells("a\n# %% b\nb\n# %% c\nc"); + const raised = { status: "raised", error_line: 3, executed: true }; + assert.deepEqual(model.railAfterFile(cells, [0, 1], Object.assign({ cells_reported: true }, raised)), ["ran", "failed", "idle"]); + assert.deepEqual(model.railAfterFile(cells, [], Object.assign({ cells_reported: false }, raised)), ["ran", "failed", "idle"]); +}); + +test("Run all's margin: a syntax error marks its cell failed and none ran", () => { + const cells = model.splitCells("a\n# %% b\nb(\n# %% c\nc"); + assert.deepEqual(model.railAfterFile(cells, [], { status: "raised", error_line: 3, executed: false, cells_reported: false }), + ["idle", "failed", "idle"]); + assert.deepEqual(model.railAfterFile(cells, [], { status: "raised", error_line: 0, executed: false, cells_reported: false }), + ["idle", "idle", "idle"]); +}); + +test("Run all's margin: a stop marks the last reported cell, and none without reports", () => { + const cells = model.splitCells("a\n# %% b\nb\n# %% c\nc"); + assert.deepEqual(model.railAfterFile(cells, [0, 1], { status: "cancelled", error_line: 0, executed: true, cells_reported: true }), + ["ran", "failed", "idle"]); + assert.deepEqual(model.railAfterFile(cells, [], { status: "cancelled", error_line: 0, executed: true, cells_reported: false }), + ["idle", "idle", "idle"]); +}); + +test("a cell is edited when its text differs from the text that ran", () => { + assert.equal(model.edited("x = 1\n", "x = 1\n"), false); + assert.equal(model.edited("x = 2\n", "x = 1\n"), true); +}); + +test("a script's text is compared with the line breaks the editor holds", () => { + assert.equal(model.editorText("a = 1\r\nb = 2\r\n"), "a = 1\nb = 2\n"); + assert.equal(model.editorText("a = 1\rb = 2\n"), "a = 1\nb = 2\n"); + assert.equal(model.editorText("a = 1\nb = 2\n"), "a = 1\nb = 2\n"); +}); + +test("a triple-quoted string open at a line's start is found from the lines before it", () => { + assert.equal(model.openQuote('def f():\n """Doc:'), '"""'); + assert.equal(model.openQuote("s = '''a\nb"), "'''"); + assert.equal(model.openQuote('s = """a"""\n# """'), null); + assert.equal(model.openQuote('s = "a"\nt = 1'), null); +}); + +test("Return inside a multi-line string keeps the indent, and code after the string closes is read as code", () => { + const tab = " "; + assert.equal(model.pythonNextIndent(' """Doc:', tab), " "); + assert.equal(model.pythonNextIndent(" return the value", tab, '"""'), " "); + assert.equal(model.pythonNextIndent(' return the value"""', tab, '"""'), " "); + assert.equal(model.pythonNextIndent(' """ + f(', tab, '"""'), " "); +}); + +test("no suggestions inside a multi-line string, and suggestions again after it closes", () => { + assert.equal(model.suggestContext('tools.call("', '"""'), null); + assert.equal(model.suggestContext("orca.host.", "'''"), null); + assert.equal(model.suggestContext('"""; tools.call("', '"""').kind, "tool"); +}); + +test("Clear keeps only the blocks a run still writes to: its own and the cell it runs now", () => { + assert.deepEqual(model.keptByClear(null), []); + assert.deepEqual(model.keptByClear({ kind: "cell", block: "Cell 2" }), ["Cell 2"]); + assert.deepEqual(model.keptByClear({ kind: "console", block: ">>> x" }), [">>> x"]); + assert.deepEqual(model.keptByClear({ kind: "file", block: "Run all" }), ["Run all"]); + assert.deepEqual(model.keptByClear({ kind: "file", block: "Run all", cellBlock: "Cell 3" }), ["Run all", "Cell 3"]); +}); + +test("the cell view is the saved one, and Dividers with the cell at the cursor highlighted when nothing usable is saved", () => { + assert.deepEqual(model.cellView(undefined), { style: "dividers", highlight: true }); + assert.deepEqual(model.cellView({ style: "", highlight: true }), { style: "dividers", highlight: true }); + assert.deepEqual(model.cellView({ style: "zebra", highlight: true }), { style: "dividers", highlight: true }); + assert.deepEqual(model.cellView({ style: "bands", highlight: false }), { style: "bands", highlight: false }); + for (const style of ["margin", "dividers", "bands", "shaded"]) assert.equal(model.cellView({ style }).style, style); +}); + +test("Dividers draw a line above every cell but one starting on the first line", () => { + const marks = (text) => model.cellMarks(model.splitCells(text), text.split("\n"), { style: "dividers", highlight: false }, 0); + assert.deepEqual(marks("x = 1\n# %% B\ny\n# %% C\nz"), [ + { from: 1, to: 1, cls: "cell-divider" }, + { from: 3, to: 3, cls: "cell-divider" }, + ]); + assert.deepEqual(marks("# %% A\nx\n# %% B\ny"), [{ from: 2, to: 2, cls: "cell-divider" }]); + assert.deepEqual(marks("x = 1\ny = 2"), []); +}); + +test("Header bands mark each cell's # %% line, not the lines before the first marker", () => { + const marks = (text) => model.cellMarks(model.splitCells(text), text.split("\n"), { style: "bands", highlight: false }, 0); + assert.deepEqual(marks("import os\n# %% B\ny"), [{ from: 1, to: 1, cls: "cell-band" }]); + assert.deepEqual(marks("# %% A\nx\n# %%\ny"), [ + { from: 0, to: 0, cls: "cell-band" }, + { from: 2, to: 2, cls: "cell-band" }, + ]); +}); + +test("Shaded cells shade every second cell, and Margin bars only marks no rows", () => { + const text = "# %% A\na\n# %% B\nb\n# %% C\nc\n# %% D\nd"; + const marks = (style) => model.cellMarks(model.splitCells(text), text.split("\n"), { style, highlight: false }, 0); + assert.deepEqual(marks("shaded"), [ + { from: 2, to: 3, cls: "cell-shade" }, + { from: 6, to: 7, cls: "cell-shade" }, + ]); + assert.deepEqual(marks("margin"), []); +}); + +test("the highlight covers the cell at the cursor in every style, under the style's own lines", () => { + const text = "# %% A\na\n# %% B\nb1\nb2\n# %% C\nc"; + const marks = (style, highlight, current) => + model.cellMarks(model.splitCells(text), text.split("\n"), { style, highlight }, current); + assert.deepEqual(marks("margin", true, 2), [{ from: 2, to: 4, cls: "cell-current" }]); + assert.deepEqual(marks("dividers", true, 2), [ + { from: 2, to: 4, cls: "cell-current" }, + { from: 2, to: 2, cls: "cell-divider" }, + { from: 5, to: 5, cls: "cell-divider" }, + ]); + assert.deepEqual(marks("shaded", true, 2), [ + { from: 2, to: 4, cls: "cell-shade" }, + { from: 2, to: 4, cls: "cell-current" }, + ]); + assert.deepEqual(marks("margin", false, 2), []); + assert.deepEqual(marks("margin", true, 0), []); +}); + +test("a JSON result splits into the tokens its highlight colours, each as Python wrote it", () => { + const tokens = model.jsonTokens('{"a": [1.0, true, null, "x, y: z"]}').map((t) => [t.type, t.text]); + assert.deepEqual(tokens, [ + ["punct", "{"], ["key", '"a"'], ["punct", ":"], ["space", " "], ["punct", "["], ["number", "1.0"], ["punct", ","], + ["space", " "], ["literal", "true"], ["punct", ","], ["space", " "], ["literal", "null"], ["punct", ","], ["space", " "], + ["string", '"x, y: z"'], ["punct", "]"], ["punct", "}"], + ]); +}); + +test("a JSON result keeps an array or object on one line while it fits the width", () => { + assert.equal(model.formatJson('{"offset": [128, 128, 0], "mirrored": false}'), '{"offset": [128, 128, 0], "mirrored": false}'); +}); + +test("a JSON result past the width takes a line per member, two spaces a level, keeping members that fit whole", () => { + const text = '{"objects": [{"index": 0, "name": "3DBenchy", "offset": [128, 128, 0], "rotation": [0, 0, 0]}], "total": 1}'; + assert.equal(model.formatJson(text, 40), [ + "{", + ' "objects": [', + " {", + ' "index": 0,', + ' "name": "3DBenchy",', + ' "offset": [128, 128, 0],', + ' "rotation": [0, 0, 0]', + " }", + " ],", + ' "total": 1', + "}", + ].join("\n")); +}); + +test("a JSON result's numbers, strings and empty members stay as Python wrote them", () => { + const text = '[1.0, 12345678901234567890123, -1e-07, "a \\"b\\" [c], {d}: e", "\u00e9", [], {}]'; + assert.equal(model.formatJson(text, 20), [ + "[", + " 1.0,", + " 12345678901234567890123,", + " -1e-07,", + ' "a \\"b\\" [c], {d}: e",', + ' "\u00e9",', + " [],", + " {}", + "]", + ].join("\n")); +}); + +test("text that isn't JSON is shown as it is", () => { + assert.equal(model.formatJson("{'a': 1}"), "{'a': 1}"); + assert.equal(model.formatJson('{"a": [1, 2}'), '{"a": [1, 2}'); +}); + +test("a folded cell shows the last line it printed that has text", () => { + assert.equal(model.lastLine("slicing plate 1\nslicing plate 2\n\n"), "slicing plate 2"); + assert.equal(model.lastLine("a\r\nb\r\n"), "b"); + assert.equal(model.lastLine("\n \n"), ""); +}); + +test("Add a cell puts a marker after a blank line at the end, with the caret where its title goes", () => { + // The script ends with a newline, so its last line is empty. + assert.deepEqual(model.addCellEdit(["x = 1", ""]), { at: { row: 1, column: 0 }, text: "\n# %% \n", caret: { row: 2, column: 5 } }); + assert.deepEqual(model.addCellEdit(["x = 1", "", ""]), { at: { row: 2, column: 0 }, text: "# %% \n", caret: { row: 2, column: 5 } }); + assert.deepEqual(model.addCellEdit(["x = 1"]), { at: { row: 0, column: 5 }, text: "\n\n# %% \n", caret: { row: 2, column: 5 } }); + assert.deepEqual(model.addCellEdit(["x = 1", " "]), { at: { row: 1, column: 4 }, text: "\n# %% \n", caret: { row: 2, column: 5 } }); + assert.deepEqual(model.addCellEdit([""]), { at: { row: 0, column: 0 }, text: "# %% \n", caret: { row: 0, column: 5 } }); +}); + +test("a JSON result whose layout would grow past four times its length stays on one line", () => { + // Nested past the width at every level, its layout is mostly indentation. + let text = '"' + "x".repeat(80) + '"'; + for (let level = 0; level < 60; ++level) text = '{"a": ' + text + "}"; + assert.equal(model.formatJson(text), text); +}); + +test("the panel's split and hidden side come back as it kept them, and anything else as the default", () => { + assert.deepEqual(model.paneLayout(undefined), { split: 0.6, hidden: "" }); + assert.deepEqual(model.paneLayout({ split: "0.35", hidden: "console" }), { split: 0.35, hidden: "console" }); + assert.deepEqual(model.paneLayout({ split: 0.7, hidden: "editor" }), { split: 0.7, hidden: "editor" }); + for (const split of ["", "x", 0, 1, -0.2, 1.5, NaN, null, undefined]) assert.equal(model.paneLayout({ split }).split, 0.6); + assert.equal(model.paneLayout({ split: 0.5, hidden: "both" }).hidden, ""); +}); + +test("the divider leaves the editor 220 px and the console 200 px, or their shares of a pane too narrow for both", () => { + assert.equal(model.clampSplit(0.1, 1000), 0.22); + assert.equal(model.clampSplit(0.9, 1000), 0.8); + assert.equal(model.clampSplit(0.5, 1000), 0.5); + assert.equal(model.clampSplit(0.1, 300), 0.5238); + assert.equal(model.clampSplit(0.9, 300), 0.5238); +}); + +test("dragging the divider 48 px past a side's smallest width hides that side", () => { + assert.deepEqual(model.dragSplit(500, 1000), { split: 0.5, hide: "" }); + assert.deepEqual(model.dragSplit(172, 1000), { split: 0.22, hide: "" }); + assert.deepEqual(model.dragSplit(171, 1000), { split: 0.22, hide: "editor" }); + assert.deepEqual(model.dragSplit(848, 1000), { split: 0.8, hide: "" }); + assert.deepEqual(model.dragSplit(849, 1000), { split: 0.8, hide: "console" }); + // A pane too narrow for both: each side hides 48 px past the point the divider stops at. + assert.equal(model.dragSplit(157, 300).hide, ""); + assert.equal(model.dragSplit(100, 300).hide, "editor"); + assert.equal(model.dragSplit(210, 300).hide, "console"); +}); + +test("the divider's arrows move it a twentieth of the pane, Home and End to a side's smallest width", () => { + assert.equal(model.splitByKey(0.6, "ArrowLeft", 1000), 0.55); + assert.equal(model.splitByKey(0.6, "ArrowRight", 1000), 0.65); + assert.equal(model.splitByKey(0.78, "ArrowRight", 1000), 0.8); + assert.equal(model.splitByKey(0.6, "Home", 1000), 0.22); + assert.equal(model.splitByKey(0.6, "End", 1000), 0.8); + assert.equal(model.splitByKey(0.6, "a", 1000), null); +}); + +test("the console's strip shows a run going, then new output, and a failed run until the next one", () => { + assert.equal(model.consoleNews("", "output"), "fresh"); + assert.equal(model.consoleNews("", "start"), "running"); + assert.equal(model.consoleNews("running", "output"), "running"); + assert.equal(model.consoleNews("running", "finished"), "fresh"); + assert.equal(model.consoleNews("running", "failed"), "failed"); + assert.equal(model.consoleNews("failed", "output"), "failed"); + assert.equal(model.consoleNews("failed", "start"), "running"); +}); + +test("the console's side hides only while it shows the console, not the start page or the note that Python is off", () => { + assert.equal(model.hiddenSide("console", true), "console"); + assert.equal(model.hiddenSide("console", false), ""); + assert.equal(model.hiddenSide("editor", false), "editor"); + assert.equal(model.hiddenSide("editor", true), "editor"); + assert.equal(model.hiddenSide("", true), ""); +}); diff --git a/resources/web/dialog/RunScript/run_script_model.js b/resources/web/dialog/RunScript/run_script_model.js new file mode 100644 index 0000000000..b9369cee8c --- /dev/null +++ b/resources/web/dialog/RunScript/run_script_model.js @@ -0,0 +1,380 @@ +// The Run Script page's pure logic: cells, Python's Return indent, where suggestions go, a traceback's links, the +// margin after Run all, what Clear keeps, the rows each cell style marks, a JSON result's tokens and layout, a folded +// cell's line, the edit Add a cell makes, and the divider between the editor and the console. Loaded by the page as a +// script and by run_script.test.js as a module. +(function (root, factory) { + "use strict"; + const api = factory(); + if (typeof module === "object" && module.exports) module.exports = api; + else root.RunScriptModel = api; +})(typeof globalThis === "object" ? globalThis : this, function () { + "use strict"; + + // A line that starts a cell: "# %%" in the first column; the rest of the line is the cell's title. + const CELL_MARKER = /^# %%(.*)$/; + + // The cells of `text`, 1-based lines: [{index, start, end, title}]. The lines before the first marker are cell 1. + function splitCells(text) { + const cells = []; + let current = null; + text.split("\n").forEach((raw, i) => { + const line = i + 1; + const marker = CELL_MARKER.exec(raw.replace(/\r$/, "")); + if (marker) { + if (current) current.end = line - 1; + current = { index: cells.length + 1, start: line, end: line, title: marker[1].trim() }; + cells.push(current); + } else if (!current) { + current = { index: 1, start: 1, end: line, title: "" }; + cells.push(current); + } else current.end = line; + }); + return cells; + } + + // The cell whose lines hold `line`; the last cell for a line past the end. + function cellAt(cells, line) { + for (const cell of cells) + if (line >= cell.start && line <= cell.end) return cell; + return cells.length ? cells[cells.length - 1] : null; + } + + // Where `line` stands at `end`: in a string (its quote), in a comment, or in code. `quote` is the triple-quoted string + // open when the line starts (openQuote()), if any. + function stateAt(line, end, quote = null) { + for (let i = 0; i < end; ++i) { + if (quote) { + if (line[i] === "\\") ++i; + else if (line.startsWith(quote, i)) { + i += quote.length - 1; + quote = null; + } + continue; + } + const c = line[i]; + if (c === "#") return { quote: null, comment: true, at: i }; + if (c === '"' || c === "'") { + quote = line.startsWith(c.repeat(3), i) ? c.repeat(3) : c; + i += quote.length - 1; + } + } + return { quote, comment: false, at: end }; + } + + // The line's code: what comes before a comment that isn't inside a string. + function codeOf(line) { + const state = stateAt(line, line.length); + return state.comment ? line.slice(0, state.at) : line; + } + + // The triple-quoted string open at the end of `text` (the lines before the caret's line), or null: only such a string + // runs on past its line. + function openQuote(text) { + let quote = null; + for (const line of text.split("\n")) { + const state = stateAt(line, line.length, quote); + quote = state.quote && state.quote.length === 3 ? state.quote : null; + } + return quote; + } + + // Where the string `quote` that `line` starts inside closes: the index after its closing quote, or the line's length. + function closeOf(line, quote) { + for (let i = 0; i < line.length; ++i) { + if (line[i] === "\\") ++i; + else if (line.startsWith(quote, i)) return i + quote.length; + } + return line.length; + } + + // The indent Return gives the next line: the line's own, one level (`tab`) more when its code ends with a colon or an + // opening bracket, one level less (not below none) when its statement ends a block (return, pass, raise, break, + // continue). `quote` is the triple-quoted string open when the line starts: its text up to where it closes isn't code, + // and a line that ends inside one keeps its indent. + function pythonNextIndent(lineBeforeCaret, tab, quote = null) { + const indent = /^\s*/.exec(lineBeforeCaret)[0]; + const end = stateAt(lineBeforeCaret, lineBeforeCaret.length, quote); + if (end.quote && end.quote.length === 3) return indent; + const code = codeOf(quote ? lineBeforeCaret.slice(closeOf(lineBeforeCaret, quote)) : lineBeforeCaret).trimEnd(); + if (/[:([{]$/.test(code)) return indent + tab; + if (/^(return|pass|raise|break|continue)\b/.test(code.trim())) return indent.slice(0, Math.max(0, indent.length - tab.length)); + return indent; + } + + // What suggestions go at the end of `lineBeforeCaret`: the tools inside the string tools.call( opens, or the API one + // level below an orca.host path; null in another string, in a comment or anywhere else. `quote` is the triple-quoted + // string open when the line starts. + function suggestContext(lineBeforeCaret, quote = null) { + const tool = /((?:\w+\.)*tools\.call\(\s*)(["'])(\w*)$/.exec(lineBeforeCaret); + if (tool) { + const state = stateAt(lineBeforeCaret, tool.index, quote); + if (state.quote || state.comment) return null; + return { kind: "tool", from: lineBeforeCaret.length - tool[3].length, typed: tool[3] }; + } + const api = /\b(orca\.host(?:\.\w+)*)\.(\w*)$/.exec(lineBeforeCaret); + if (api) { + const state = stateAt(lineBeforeCaret, api.index, quote); + if (state.quote || state.comment) return null; + return { kind: "api", path: api[1], from: lineBeforeCaret.length - api[2].length, typed: api[2] }; + } + return null; + } + + // The spans of `traceback` that name a line of the script (File "", line N), with that line. + function tracebackLinks(traceback, scriptFile) { + const links = []; + const pattern = /File "([^"]*)", line (\d+)/g; + let m; + while ((m = pattern.exec(traceback))) + if (m[1] === scriptFile) links.push({ start: m.index, end: m.index + m[0].length, line: Number(m[2]) }); + return links; + } + + // The margin after Run all, one state per cell ("ran", "failed", "idle"), from the cells the run reported (0-based + // indexes, in order) and how it ended. Finished: every cell ran. Raised at a line once the code started: the cells + // before that line's cell ran, it failed. Raised before the code started (a syntax error, dependencies that didn't + // install): only a syntax error's cell is marked, failed. Stopped, or raised at no line of the file: the cells before the + // last one reported ran, that one failed; none without reports. + function railAfterFile(cells, reportedCells, outcome) { + const states = cells.map(() => "idle"); + if (outcome.status === "finished") return states.fill("ran"); + if (outcome.status === "raised") { + const at = outcome.error_line > 0 ? cellAt(cells, outcome.error_line) : null; + if (!outcome.executed) { + if (at) states[at.index - 1] = "failed"; + return states; + } + if (at) { + for (let i = 0; i < at.index - 1; ++i) states[i] = "ran"; + states[at.index - 1] = "failed"; + return states; + } + } else if (outcome.status !== "cancelled" && outcome.status !== "timed_out") return states; + if (reportedCells.length) { + const last = Math.min(reportedCells[reportedCells.length - 1], states.length - 1); + for (let i = 0; i < last; ++i) states[i] = "ran"; + states[last] = "failed"; + } + return states; + } + + // Whether a cell's text has changed since it ran. + function edited(cellText, ranText) { return cellText !== ranText; } + + // A script's text with the line breaks the editor holds (LF), whatever the file has, so a CRLF file isn't edited as + // it opens. + function editorText(text) { return text.replace(/\r\n?/g, "\n"); } + + // The console blocks Clear keeps, in order: the ones the run going still writes to, its own block and, in Run all, the + // block of the cell it runs now. None when nothing runs. + function keptByClear(run) { return run ? [run.block, run.cellBlock].filter(Boolean) : []; } + + // How the editor shows cells, from the Cells menu: a style, and whether the cell at the cursor is highlighted. + const CELL_STYLES = ["margin", "dividers", "bands", "shaded"]; + + // The cell view to draw from what the host saved: a missing or unknown style is Dividers, and the highlight is on unless + // it was turned off. + function cellView(saved) { + const style = saved && CELL_STYLES.includes(saved.style) ? saved.style : "dividers"; + return { style, highlight: !saved || saved.highlight !== false }; + } + + // The rows `view` marks behind the text of `cells` (0-based, inclusive, one class each), in the order they are drawn: + // Shaded cells' shade on every second cell, the highlight on cell `current` (its index, 0 for none), then the style's + // lines on top, a divider above each cell that doesn't start the file or a band on each cell's "# %%" line. + function cellMarks(cells, lines, view, current) { + const marks = []; + const add = (from, to, cls) => marks.push({ from, to, cls }); + if (view.style === "shaded") + for (const cell of cells) if (cell.index % 2 === 0) add(cell.start - 1, cell.end - 1, "cell-shade"); + if (view.highlight) + for (const cell of cells) if (cell.index === current) add(cell.start - 1, cell.end - 1, "cell-current"); + for (const cell of cells) { + const row = cell.start - 1; + if (view.style === "dividers" && row > 0) add(row, row, "cell-divider"); + else if (view.style === "bands" && CELL_MARKER.test((lines[row] || "").replace(/\r$/, ""))) add(row, row, "cell-band"); + } + return marks; + } + + // ---- a result that is JSON: the host sends it compact, as json.dumps writes it ------------------------------------- + + const JSON_TOKEN = /\s+|"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|true|false|null|[{}[\],:]/y; + + // `text`'s tokens, {type: "key" | "string" | "number" | "literal" | "punct" | "space", text}, each as written, so a + // number keeps every digit Python wrote; null when something in it is no JSON token. + function jsonTokens(text) { + const tokens = []; + const re = new RegExp(JSON_TOKEN.source, "y"); + for (let at = 0; at < text.length;) { + re.lastIndex = at; + const match = re.exec(text); + if (!match) return null; + const t = match[0]; + const first = t[0]; + const type = /\s/.test(first) ? "space" : first === '"' ? "string" : first === "-" || (first >= "0" && first <= "9") ? "number" + : first >= "a" && first <= "z" ? "literal" : "punct"; + tokens.push({ type, text: t }); + at += t.length; + } + // A string before a colon is a key. + for (let i = 0; i < tokens.length; ++i) { + if (tokens[i].type !== "string") continue; + let next = i + 1; + while (tokens[next] && tokens[next].type === "space") ++next; + if (tokens[next] && tokens[next].text === ":") tokens[i].type = "key"; + } + return tokens; + } + + // How much longer than the host's one-line JSON its layout may be: deep nesting is mostly indentation, which would hold + // the console far past what the runner's output allowance counted. + const JSON_MAX_GROWTH = 4; + + // `text` laid out to read: an array or object whose one-line form fits in `width` with its indent stays on one line, + // any other takes a line per member, indented two spaces a level. Numbers and strings stay as written. Text that isn't + // one JSON value, or whose layout would be more than JSON_MAX_GROWTH times as long, comes back as it is. + function formatJson(text, width = 72) { + const tokens = jsonTokens(text); + if (!tokens) return text; + const items = tokens.filter((t) => t.type !== "space"); + let at = 0; + // A value: a scalar's text, or {open, close, members: [{key, value}]}, with key null in an array. + const value = () => { + const t = items[at++]; + if (!t || t.type === "key" || (t.type === "punct" && t.text !== "{" && t.text !== "[")) throw new SyntaxError(); + if (t.type !== "punct") return t.text; + const node = { open: t.text, close: t.text === "{" ? "}" : "]", members: [] }; + if (items[at] && items[at].text === node.close) return ++at, node; + for (;;) { + let key = null; + if (node.open === "{") { + key = items[at++]; + if (!key || key.type !== "key" || !items[at] || items[at++].text !== ":") throw new SyntaxError(); + key = key.text; + } + node.members.push({ key, value: value() }); + const next = items[at++]; + if (next && next.text === node.close) return node; + if (!next || next.text !== ",") throw new SyntaxError(); + } + }; + let root; + try { + root = value(); + } catch (e) { + return text; + } + if (at !== items.length) return text; + const lead = (member) => (member.key === null ? "" : member.key + ": "); + // The length of a value's one-line form, kept on the node. + const size = (node) => { + if (typeof node === "string") return node.length; + if (node.size === undefined) + node.size = 2 + node.members.reduce((n, m, i) => n + (i ? 2 : 0) + lead(m).length + size(m.value), 0); + return node.size; + }; + const flat = (node) => (typeof node === "string" ? node : node.open + node.members.map((m) => lead(m) + flat(m.value)).join(", ") + node.close); + const lay = (node, indent, before) => { + if (typeof node === "string" || indent.length + before.length + size(node) <= width) return flat(node); + const inner = indent + " "; + return node.open + "\n" + node.members.map((m) => inner + lead(m) + lay(m.value, inner, lead(m))).join(",\n") + "\n" + indent + node.close; + }; + const laid = lay(root, "", ""); + return laid.length > JSON_MAX_GROWTH * text.length ? text : laid; + } + + // ---- Run all's folded cells and Add a cell -------------------------------------------------------------------------- + + // The last line of `text` that has more than spaces, without its line break: what a folded cell shows. + function lastLine(text) { + const lines = text.split("\n"); + for (let i = lines.length - 1; i >= 0; --i) { + const line = lines[i].replace(/\r$/, ""); + if (line.trim()) return line; + } + return ""; + } + + // The edit Add a cell makes to the editor's `lines`: a "# %% " line at the end, a blank line before it unless the script + // is empty, the file still ending with a line break, and the caret after the marker, where the cell's title goes. + function addCellEdit(lines) { + const last = lines.length - 1; + const line = lines[last]; + const before = last > 0 ? lines[last - 1] : ""; + let text; + if (line === "") text = last === 0 || !before.trim() ? "# %% \n" : "\n# %% \n"; + else text = line.trim() ? "\n\n# %% \n" : "\n# %% \n"; + const breaks = text.indexOf("#"); + return { at: { row: last, column: line.length }, text, caret: { row: last + breaks, column: 5 } }; + } + + // ---- the divider between the editor and the console ---------------------------------------------------------------- + + // The editor's share of the panel's width, which the panel keeps as a share so a pane resized keeps its proportions; + // the smallest widths the divider leaves each side; and how far past one a drag goes to hide that side. + const SPLIT_DEFAULT = 0.6; + const MIN_EDITOR = 220; + const MIN_CONSOLE = 200; + const HIDE_PAST = 48; + const HIDDEN_SIDES = ["editor", "console"]; + + // The layout the panel kept, {split, hidden}: a split that is not a share strictly between 0 and 1 is the default, and + // a hidden side that is neither side is none. The host keeps the split as text. + function paneLayout(saved) { + const split = saved && saved.split !== null && saved.split !== "" ? Number(saved.split) : NaN; + return { + split: split > 0 && split < 1 ? split : SPLIT_DEFAULT, + hidden: saved && HIDDEN_SIDES.includes(saved.hidden) ? saved.hidden : "", + }; + } + + // Where the divider can be in a panel `width` px wide, as shares: from the editor's smallest width to the console's. + // A panel too narrow for both stops the divider where the two smallest widths' shares meet. + function splitBounds(width) { + const low = MIN_EDITOR / width, high = (width - MIN_CONSOLE) / width; + if (low <= high) return { low, high }; + const meet = MIN_EDITOR / (MIN_EDITOR + MIN_CONSOLE); + return { low: meet, high: meet }; + } + + // `split` within the bounds, to four places: the value the host keeps. + function clampSplit(split, width) { + const { low, high } = splitBounds(width); + return Math.round(Math.min(Math.max(split, low), high) * 10000) / 10000; + } + + // The divider dragged to `x` px from the panel's left: where it goes, and the side to hide when the drag ends there, + // which is the one it went more than HIDE_PAST px past the bound of. + function dragSplit(x, width) { + const { low, high } = splitBounds(width); + const hide = x < low * width - HIDE_PAST ? "editor" : x > high * width + HIDE_PAST ? "console" : ""; + return { split: clampSplit(x / width, width), hide }; + } + + // The divider's keys, as a window splitter's: the arrows move it a twentieth of the width, Home and End to a bound. + // Null for any other key. + function splitByKey(split, key, width) { + const to = { ArrowLeft: split - 0.05, ArrowRight: split + 0.05, Home: 0, End: 1 }[key]; + return to === undefined ? null : clampSplit(to, width); + } + + // The side hidden as the panel draws it, from the side the layout hides. The console's side hides only while it shows + // the console (`consoleShown`): with no script open or Python off it holds the start page or the note about Python, + // which stay in sight. + function hiddenSide(hidden, consoleShown) { return hidden === "console" && !consoleShown ? "" : hidden; } + + // What the hidden console's strip shows after `event` (start, output, finished, failed), from what it shows now + // (nothing, running, fresh, failed): a run going, then that there is output not seen, red from a failed run until the + // next run starts. Output while a run goes or after one failed changes nothing. + function consoleNews(news, event) { + if (event === "start") return "running"; + if (event === "finished") return "fresh"; + if (event === "failed") return "failed"; + return news || "fresh"; + } + + return { splitCells, cellAt, pythonNextIndent, suggestContext, tracebackLinks, railAfterFile, edited, stateAt, editorText, + openQuote, keptByClear, cellView, cellMarks, jsonTokens, formatJson, lastLine, addCellEdit, paneLayout, clampSplit, + dragSplit, splitByKey, hiddenSide, consoleNews }; +}); diff --git a/resources/web/dialog/RunScript/style.css b/resources/web/dialog/RunScript/style.css new file mode 100644 index 0000000000..2f37197cd1 --- /dev/null +++ b/resources/web/dialog/RunScript/style.css @@ -0,0 +1,417 @@ +/* The Run Script panel. 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 editor's own colours are code_editor.css's. The distinctive element is + * the margin: a bar per cell beside the line numbers that shows what ran in this session. */ + +:root { + --rs-bg: var(--orca-bg, #ffffff); + --rs-fg: var(--orca-fg, #262e30); + --rs-muted: var(--orca-muted, #6b7478); + --rs-rule: var(--border, #dcdfe1); + --rs-accent: var(--orca-accent, #009688); + --rs-accent-fg: var(--orca-accent-fg, #ffffff); + --rs-accent-text: #00796b; + --rs-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12)); + --rs-ring: rgba(0, 150, 136, 0.25); + --rs-ring-soft: rgba(0, 150, 136, 0.08); + --rs-fail: var(--plugin-status-danger, #b42318); + --rs-warn: var(--plugin-status-warn, #a15c00); + --rs-chrome: var(--footer-bg, #f3f4f5); + --rs-console: #fbfcfc; + --rs-btn-bg: var(--btn-bg, #ffffff); + --rs-btn-border: var(--btn-border, #cccccc); + --rs-btn-hover: var(--btn-hover, #f0f0f0); + --rs-pop-bg: var(--ctx-bg, #ffffff); + --rs-pop-shadow: 0 6px 20px rgba(20, 30, 35, 0.16); + --rs-mono: var(--code-font); + /* The Cells menu's styles, drawn behind the editor's text. */ + --rs-cell-divider: #c3c9cc; + --rs-cell-current: rgba(0, 150, 136, 0.07); + --rs-cell-band: #eef1f2; + --rs-cell-shade: rgba(38, 46, 48, 0.04); +} +:root[data-orca-theme="dark"] { + --rs-accent-text: #4db6ac; + --rs-accent-tint: rgba(0, 150, 136, 0.22); + --rs-ring: rgba(0, 150, 136, 0.45); + --rs-ring-soft: rgba(0, 150, 136, 0.15); + --rs-console: #262629; + --rs-pop-shadow: 0 6px 20px rgba(0, 0, 0, 0.45); + --rs-cell-divider: #55555d; + --rs-cell-current: rgba(0, 150, 136, 0.14); + --rs-cell-band: #36363b; + --rs-cell-shade: rgba(255, 255, 255, 0.04); +} + +* { box-sizing: border-box; } +html, body { + height: 100%; + margin: 0; + overflow: hidden; + background: var(--rs-bg); + color: var(--rs-fg); + font: 13px/1.45 var(--orca-font, "Segoe UI", system-ui, sans-serif); +} +[hidden] { display: none !important; } +:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: 1px; } + +.panel { height: 100%; display: flex; flex-direction: column; min-height: 0; } + +/* ---- toolbar ---- */ +.toolbar { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--rs-rule); flex-wrap: wrap; flex: none; } +.btn { + font: 12.5px var(--orca-font, "Segoe UI", system-ui, sans-serif); + color: var(--rs-fg); + background: var(--rs-btn-bg); + border: 1px solid var(--rs-btn-border); + border-radius: 4px; + padding: 3px 11px; + white-space: nowrap; + display: inline-flex; + align-items: center; + gap: 6px; + cursor: pointer; +} +.btn:hover:not(:disabled) { background: var(--rs-btn-hover); } +.btn.primary { color: var(--rs-accent-fg); background: var(--rs-accent); border-color: var(--rs-accent); } +.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--rs-accent); } +.btn.stop:not(:disabled) { color: var(--rs-fail); border-color: var(--rs-fail); } +.btn:disabled { opacity: 0.42; cursor: default; } +.btn .key { font-size: 11px; opacity: 0.7; } +.caret-d { width: 0; height: 0; border-top: 4.5px solid currentColor; border-left: 4px solid transparent; border-right: 4px solid transparent; opacity: 0.7; } +.tri { width: 0; height: 0; border-left: 7px solid currentColor; border-top: 4.5px solid transparent; border-bottom: 4.5px solid transparent; } +.sq { width: 8px; height: 8px; background: currentColor; border-radius: 1px; } +.sep { width: 1px; height: 20px; background: var(--rs-rule); margin: 0 3px; } +.chip { display: inline-flex; align-items: center; gap: 6px; padding: 2px 9px; border-radius: 4px; background: var(--rs-accent-tint); font-size: 12px; white-space: nowrap; max-width: 280px; overflow: hidden; text-overflow: ellipsis; } +.chip .edited { color: var(--rs-muted); } + +.menu-wrap { position: relative; display: inline-flex; } +.menu { + position: absolute; + top: calc(100% + 3px); + left: 0; + z-index: 20; + min-width: 240px; + max-width: 420px; + padding: 4px 0; + background: var(--rs-pop-bg); + border: 1px solid var(--rs-rule); + border-radius: 6px; + box-shadow: var(--rs-pop-shadow); +} +.menu-item { + display: flex; + width: 100%; + gap: 10px; + align-items: baseline; + padding: 4px 12px; + border: 0; + background: none; + color: var(--rs-fg); + font: inherit; + text-align: left; + cursor: pointer; +} +.menu-item:hover, .menu-item:focus-visible { background: var(--rs-accent-tint); outline: none; } +.menu-item:disabled { opacity: 0.42; cursor: default; } +.menu-item .d { color: var(--rs-muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.menu-label { padding: 6px 12px 2px; font-size: 11.5px; color: var(--rs-muted); } +.menu-rule { height: 1px; margin: 4px 0; background: var(--rs-rule); } +.menu.right { left: auto; right: 0; } +/* The Cells menu: a dot on the style in use, a check on the highlight. */ +.menu-item[role="menuitemradio"]::before, .menu-item[role="menuitemcheckbox"]::before { + content: ""; + flex: none; + width: 12px; + text-align: center; + color: var(--rs-accent); + font-weight: 700; +} +.menu-item[role="menuitemradio"][aria-checked="true"]::before { content: "●"; font-size: 9px; } +.menu-item[role="menuitemcheckbox"][aria-checked="true"]::before { content: "✓"; } +.cells-glyph { + width: 12px; + height: 11px; + flex: none; + border-top: 2px solid currentColor; + border-bottom: 2px solid currentColor; + background: linear-gradient(currentColor, currentColor) center / 100% 1.5px no-repeat; + opacity: 0.75; +} + +/* The session line: its items, each on its own, apart. */ +.session { margin-left: auto; display: inline-flex; align-items: center; gap: 7px; font-size: 12px; color: var(--rs-muted); white-space: nowrap; } +.session .dot { width: 8px; height: 8px; border-radius: 50%; border: 1.5px solid var(--rs-muted); flex: none; } +.session.live .dot { border: 0; background: var(--rs-accent); box-shadow: 0 0 0 3px var(--rs-accent-tint); } +.session.busy { color: var(--rs-accent); } +.session.busy .dot { border: 0; background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; } +.session .item + .item { padding-left: 7px; border-left: 1px solid var(--rs-rule); } +.session .item.lead { color: var(--rs-fg); } + +/* ---- body: editor and console side by side, the editor's share of the width set by the divider ---- */ +.body { flex: 1; display: flex; min-height: 0; } +.col { display: flex; flex-direction: column; min-width: 0; min-height: 0; } +.editor-col { flex: 0 0 var(--split, 60%); } +.side { flex: 1 1 0; } +.body.dragging { cursor: col-resize; user-select: none; } +/* Dragged far enough past a side's smallest width, the side fades: the drag ending there hides it. */ +.body[data-pending="editor"] .editor-col, .body[data-pending="console"] .side { opacity: 0.35; } + +/* The divider: a line, a strip either side of it to grab, the accent while it can be dragged. */ +.split { position: relative; z-index: 8; flex: none; width: 1px; background: var(--rs-rule); cursor: col-resize; touch-action: none; } +.split:focus-visible { outline: none; } +.split::before { content: ""; position: absolute; top: 0; bottom: 0; left: -4px; right: -4px; } +.split::after { + content: ""; + position: absolute; + top: 0; + bottom: 0; + left: -1px; + width: 3px; + background: var(--rs-accent); + opacity: 0; + transition: opacity 0.1s 0.15s; + pointer-events: none; +} +.split:hover::after, .split:focus-visible::after, .body.dragging .split::after { opacity: 1; transition-delay: 0s; } +/* Its grip: each arrow pushes the divider over the side it points at, which hides. */ +.grip { + position: absolute; + z-index: 1; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + display: flex; + flex-direction: column; + gap: 2px; + padding: 3px 1px; + background: var(--rs-bg); + border: 1px solid var(--rs-rule); + border-radius: 9px; + cursor: default; +} +.grip button { width: 16px; height: 18px; padding: 0; border: 0; border-radius: 6px; display: grid; place-items: center; background: none; color: var(--rs-muted); cursor: pointer; } +.grip button:hover, .grip button:focus-visible { background: var(--rs-accent); color: var(--rs-accent-fg); outline: none; } +.grip path, .strip-chev path { fill: none; stroke: currentColor; stroke-width: 1.6; stroke-linecap: round; stroke-linejoin: round; } + +/* A hidden side leaves a strip at its edge, which brings it back. */ +.strip { + flex: none; + width: 28px; + display: none; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 6px 0 10px; + overflow: hidden; + border: 0; + background: var(--rs-chrome); + color: var(--rs-muted); + font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif); + cursor: pointer; +} +.strip-editor { border-right: 1px solid var(--rs-rule); } +.strip-console { border-left: 1px solid var(--rs-rule); } +.strip:hover { color: var(--rs-fg); } +.strip:focus-visible { outline-offset: -2px; } +.strip-chev { flex: none; width: 20px; height: 20px; border-radius: 4px; display: grid; place-items: center; } +.strip:hover .strip-chev, .strip:focus-visible .strip-chev { background: var(--rs-accent); color: var(--rs-accent-fg); } +/* Read from the panel's edge inwards: up the left strip, down the right one. */ +.strip-label { writing-mode: vertical-rl; white-space: nowrap; min-height: 0; overflow: hidden; text-overflow: ellipsis; } +.strip-editor .strip-label { transform: rotate(180deg); } +.body[data-hidden="editor"] .strip-editor, .body[data-hidden="console"] .strip-console { display: flex; } +.body[data-hidden="editor"] .editor-col, .body[data-hidden="editor"] .split, +.body[data-hidden="console"] .side, .body[data-hidden="console"] .split { display: none; } +.body[data-hidden="console"] .editor-col { flex: 1 1 0; } +/* The hidden editor's strip: a bar per cell in the margin's colours, so what ran and what failed stays in sight. */ +.strip-cells { flex: none; display: flex; flex-direction: column; gap: 3px; max-height: 50%; overflow: hidden; } +.strip-cells i { flex: none; width: 4px; height: 12px; border-radius: 2px; background: var(--rs-rule); } +.strip-cells i.ran { background: var(--rs-accent); } +.strip-cells i.edited { background: repeating-linear-gradient(180deg, var(--rs-accent) 0 4px, transparent 4px 7px); } +.strip-cells i.failed { background: var(--rs-fail); } +.strip-cells i.running { background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; } +/* The hidden console's strip: a dot while a run goes, for output not seen, red after a run failed. */ +.news { flex: none; width: 8px; height: 8px; border-radius: 50%; } +.news.running { background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; } +.news.fresh { background: var(--rs-accent); box-shadow: 0 0 0 3px var(--rs-accent-tint); } +.news.failed { background: var(--rs-fail); box-shadow: 0 0 0 3px rgba(180, 35, 24, 0.18); } +.editor { flex: 1; min-height: 0; font-size: 12.5px; } +.editor.is-readonly .ace_content { opacity: 0.6; } +.placeholder-text { margin: 0; color: var(--rs-muted); padding: 14px 18px; } + +/* The margin: one bar per cell, drawn on the gutter rows of its lines. */ +.editor .ace_gutter-cell { padding-left: 12px; } +.editor .ace_gutter-cell[class*="rail-"]::before { + content: ""; + position: absolute; + left: 4px; + top: 0; + bottom: 0; + width: 4px; + background: var(--rs-rule); +} +.editor .ace_gutter-cell.rail-first::before { top: 3px; border-top-left-radius: 2px; border-top-right-radius: 2px; } +.editor .ace_gutter-cell.rail-last::before { bottom: 3px; border-bottom-left-radius: 2px; border-bottom-right-radius: 2px; } +.editor .ace_gutter-cell.rail-ran::before { background: var(--rs-accent); } +.editor .ace_gutter-cell.rail-edited::before { background: repeating-linear-gradient(180deg, var(--rs-accent) 0 5px, transparent 5px 9px); } +.editor .ace_gutter-cell.rail-failed::before { background: var(--rs-fail); } +.editor .ace_gutter-cell.rail-running::before { background: var(--rs-accent); animation: pulse 1.4s ease-in-out infinite; } +.editor .ace_gutter-cell.rail-current::before { left: 3px; width: 6px; } +.editor .ace_cell-marker { color: var(--code-comment); font-weight: 600; } + +/* The Cells menu's styles: full-line markers behind the text (RunScriptModel.cellMarks()). */ +.editor .ace_marker-layer .cell-divider { position: absolute; border-top: 1px solid var(--rs-cell-divider); } +.editor .ace_marker-layer .cell-band { position: absolute; background: var(--rs-cell-band); border-top: 1px solid var(--rs-cell-divider); } +.editor .ace_marker-layer .cell-shade { position: absolute; background: var(--rs-cell-shade); } +.editor .ace_marker-layer .cell-current { position: absolute; background: var(--rs-cell-current); } +.editor.cells-bands .ace_cell-marker { color: var(--rs-fg); } + +/* Add a cell: the + in the margin a row below the last line, and on hover where the cell goes. Drawn in the accent as + * text, which the dark theme lightens to read on its background. */ +.editor .add-cell { + position: absolute; + z-index: 6; + left: 3px; + width: 18px; + height: 18px; + padding: 0; + border: 0; + border-radius: 4px; + display: grid; + place-items: center; + background: none; + color: var(--rs-accent-text); + font: 700 16px/1 var(--orca-font, "Segoe UI", system-ui, sans-serif); + cursor: pointer; +} +.editor .add-cell:hover, .editor .add-cell:focus-visible { background: var(--rs-accent); color: var(--rs-accent-fg); } +.editor .add-hint { + position: absolute; + z-index: 6; + right: 12px; + display: flex; + align-items: center; + gap: 8px; + pointer-events: none; + visibility: hidden; + font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif); + color: var(--rs-accent-text); +} +.editor .add-hint::after { content: ""; flex: 1; border-top: 1px dashed var(--rs-accent-text); opacity: 0.6; } +.editor .add-cell:hover + .add-hint, .editor .add-cell:focus-visible + .add-hint { visibility: visible; } +@keyframes pulse { 0%, 100% { box-shadow: 0 0 0 1px var(--rs-ring); } 50% { box-shadow: 0 0 0 4px var(--rs-ring-soft); } } + +/* ---- console ---- */ +.console { flex: 1; min-height: 0; display: flex; flex-direction: column; font: 12px/1.55 var(--rs-mono); background: var(--rs-console); } +.log { flex: 1; min-height: 0; overflow: auto; padding: 4px 0; } +.block + .block { margin-top: 4px; border-top: 1px dashed var(--rs-rule); } +.run-head { display: flex; gap: 8px; align-items: baseline; font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif); padding: 5px 12px 2px; } +.run-head b { font-weight: 600; } +.run-head .t { color: var(--rs-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.run-head .code { font-family: var(--rs-mono); color: var(--rs-muted); white-space: pre; overflow: hidden; text-overflow: ellipsis; } +.run-head .d { margin-left: auto; color: var(--rs-muted); white-space: nowrap; } +.run-head.failed b { color: var(--rs-fail); } +.run-head.busy b, .run-head.busy .d { color: var(--rs-accent); } +.out { padding: 0 12px; white-space: pre-wrap; overflow-wrap: anywhere; } +.out.muted { color: var(--rs-muted); } +.out.err { color: var(--rs-fail); } +.out a.link { color: var(--rs-fail); text-decoration: underline; text-underline-offset: 2px; cursor: pointer; } +/* Run all's block: a row per cell, folded to its heading, which shows what the cell showed last. The bar at a row's left + * is the cell's bar in the margin, in the same state. */ +.run-head .expand-all { + font: inherit; + font-size: 11.5px; + color: var(--rs-muted); + background: none; + border: 0; + padding: 0; + cursor: pointer; + text-decoration: underline dotted; + text-underline-offset: 2px; +} +.run-head .expand-all:hover { color: var(--rs-fg); text-decoration-style: solid; } +.cells { padding-bottom: 4px; } +.cell-row { position: relative; } +.cell-row::before { content: ""; position: absolute; left: 14px; top: 4px; bottom: 4px; width: 3px; border-radius: 2px; background: var(--rs-accent); } +.cell-row.failed::before { background: var(--rs-fail); } +.cell-row.running::before { animation: pulse 1.4s ease-in-out infinite; } +.cell-head { + display: flex; + align-items: baseline; + gap: 8px; + width: 100%; + padding: 3px 12px 3px 24px; + border: 0; + background: none; + color: var(--rs-fg); + font: 12px var(--orca-font, "Segoe UI", system-ui, sans-serif); + text-align: left; + cursor: pointer; +} +.cell-head:hover { background: var(--rs-cell-current); } +.cell-head .chev { + flex: none; + align-self: center; + width: 0; + height: 0; + border-left: 5px solid currentColor; + border-top: 3.5px solid transparent; + border-bottom: 3.5px solid transparent; + opacity: 0.55; + transition: transform 0.12s; +} +.cell-row.open .chev { transform: rotate(90deg); } +.cell-head b { flex: none; font-weight: 600; } +.cell-head .t { flex: 0 1 auto; max-width: 45%; color: var(--rs-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cell-head .peek { flex: 1 1 0; min-width: 0; font: 11.5px var(--rs-mono); color: var(--rs-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cell-head .peek.err { color: var(--rs-fail); } +.cell-row.open .peek { visibility: hidden; } +.cell-head .d { flex: none; margin-left: auto; color: var(--rs-muted); white-space: nowrap; } +.cell-head.busy b, .cell-head.busy .d { color: var(--rs-accent); } +.cell-head.failed b { color: var(--rs-fail); } +.cell-body { padding: 1px 0 5px; } +.cell-body .out { padding-left: 37px; } +/* A result JSON holds, in the editor's own JSON colours. */ +.out.json .j-key { color: var(--code-key); } +.out.json .j-string { color: var(--code-string); } +.out.json .j-number { color: var(--code-number); } +.out.json .j-literal { color: var(--code-keyword); } +.out.json .j-punct { color: var(--code-punct); } +.divider { margin: 6px 12px; font: 11.5px var(--orca-font, "Segoe UI", system-ui, sans-serif); color: var(--rs-muted); display: flex; align-items: center; gap: 8px; } +.divider::before, .divider::after { content: ""; flex: 1; height: 1px; background: var(--rs-rule); } +/* The prompt line, with Clear at its end; Clear stays usable while the line is off. */ +.prompt { display: flex; align-items: center; border-top: 1px solid var(--rs-rule); background: var(--rs-bg); flex: none; } +.prompt-line { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; padding: 5px 12px; } +.prompt .p { color: var(--rs-accent); font-weight: 700; } +.prompt input { flex: 1; min-width: 0; border: 0; outline: none; background: transparent; color: var(--rs-fg); font: 12px var(--rs-mono); } +.prompt input::placeholder { color: var(--rs-muted); font-family: var(--orca-font, "Segoe UI", system-ui, sans-serif); } +.prompt-line:focus-within { box-shadow: inset 0 0 0 1px var(--rs-accent); } +.prompt-line.off { opacity: 0.5; } +.btn.small { font-size: 12px; padding: 1px 9px; margin-right: 8px; } + +/* ---- the side's other views: no script, Python off ---- */ +.side-msg { flex: 1; padding: 18px 20px; overflow: auto; } +.side-msg h3 { font-size: 14px; font-weight: 600; margin: 0 0 6px; } +.side-msg p { margin: 0 0 12px; color: var(--rs-muted); max-width: 52ch; } +.side-msg code { font: 12px var(--rs-mono); background: var(--rs-accent-tint); border-radius: 3px; padding: 0 4px; } +.side-msg .row { display: flex; gap: 8px; margin-bottom: 18px; } +.recent { list-style: none; margin: 0; padding: 0; border-top: 1px solid var(--rs-rule); } +.recent li { border-bottom: 1px solid var(--rs-rule); } +.recent button { display: flex; width: 100%; gap: 10px; align-items: baseline; padding: 6px 2px; border: 0; background: none; color: var(--rs-fg); font: inherit; text-align: left; cursor: pointer; } +.recent button:hover { background: var(--rs-accent-tint); } +.recent .f { font-weight: 600; white-space: nowrap; } +.recent .d { color: var(--rs-muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.label-sm { font-size: 12px; color: var(--rs-muted); margin: 0 0 6px; } +.off-note { border-left: 3px solid var(--rs-warn); padding: 2px 0 2px 12px; margin-bottom: 14px; } + +/* ---- status line, while a run goes ---- */ +.statusline { display: flex; align-items: center; gap: 10px; padding: 4px 10px; border-top: 1px solid var(--rs-rule); background: var(--rs-chrome); font-size: 12px; color: var(--rs-muted); flex: none; } +#status-main { font-weight: 600; color: var(--rs-accent); } +.statusline.is-error #status-main { color: var(--rs-fail); } + +@media (prefers-reduced-motion: reduce) { + .session.busy .dot, .editor .ace_gutter-cell.rail-running::before, .cell-row.running::before, .strip-cells i.running, .news.running { + animation: none; + box-shadow: 0 0 0 2px var(--rs-ring); + } + .cell-head .chev, .split::after { transition: none; } +} diff --git a/resources/web/dialog/ScriptRunner/script_editor.js b/resources/web/dialog/ScriptRunner/script_editor.js deleted file mode 100644 index 99f414f752..0000000000 --- a/resources/web/dialog/ScriptRunner/script_editor.js +++ /dev/null @@ -1,436 +0,0 @@ -// The script editor: a textarea over a highlighted copy of its text (style.css says why), a line -// gutter, and suggestions for the script's keys, tool names, a tool's args and their allowed values, -// and ${…} placeholders. The textarea's value is the script; everything here reads it. - -// The copy's padding and line height, as style.css sets them for #highlight and #source. -const PAD_X = 8; -const PAD_Y = 6; -const LINE = 18; - -// The keys of a script and of a step, with the JSON type of their values. Accepting a key writes a -// value of that type after its colon (an empty string, object or array with the caret inside, or true), -// or the item's own `then`; for a number the caret waits after the colon. -const ROOT_KEYS = [ - { label: "orca_script", detail: "integer", then: "1" }, - { label: "name", detail: "string" }, - { label: "vars", detail: "object" }, - { label: "steps", detail: "array" }, -]; -const STEP_KEYS = [ - { label: "tool", detail: "string" }, - { label: "args", detail: "object" }, - { label: "expect", detail: "object" }, - { label: "optional", detail: "boolean" }, - { label: "await", detail: "boolean" }, - { label: "save_as", detail: "string" }, - { label: "timeout_s", detail: "integer" }, -]; -const EMPTY_VALUES = { string: '""', object: "{}", array: "[]", boolean: "true" }; -const MATCHERS = ["eq", "ne", "gt", "ge", "lt", "le", "contains", "regex", "exists", "empty"]; - -// Comments, strings (opening quote and body, then the closing quote; an unclosed one ends with its -// line), numbers, literals and punctuation: what the highlighter paints and the reader walks. -const TOKEN = /(\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$))|("(?:[^"\\\n]|\\.)*)("?)|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)|\b(true|false|null)\b|([{}[\],:])/g; - -const ed = { - tools: new Map(), // tool name -> {title, args: {name: {type, enum}}}, from the host - lineCount: 0, - composing: false, - inserting: false, - pop: null, // the open suggestions: what suggestionsAt() found, filtered, and the active item -}; - -function escapeHtml(text) { return text.replace(/&/g, "&").replace(//g, ">"); } - -function span(cls, html) { return '' + html + ""; } - -// ---- highlighting ------------------------------------------------------------------------------- - -function highlightHtml(text) { - const colon = /\s*:/y; - let out = ""; - let last = 0; - let m; - TOKEN.lastIndex = 0; - while ((m = TOKEN.exec(text))) { - out += escapeHtml(text.slice(last, m.index)); - last = TOKEN.lastIndex; - const tok = escapeHtml(m[0]); - if (m[1] !== undefined) out += span("t-com", tok); - else if (m[2] !== undefined) { - colon.lastIndex = last; - out += span(colon.test(text) ? "t-key" : "t-str", tok.replace(/\$\{[^}"]*\}/g, (v) => span("t-var", v))); - } else if (m[4] !== undefined || m[5] !== undefined) out += span("t-num", tok); - else out += span("t-punct", tok); - } - return out + escapeHtml(text.slice(last)); -} - -function refreshEditor() { - const source = $("source"); - const text = source.value; - // A last empty line has no height in the copy, where the textarea gives it one. - $("highlight").innerHTML = highlightHtml(text) + (text === "" || text.endsWith("\n") ? " " : ""); - const lines = text.split("\n").length; - if (lines !== ed.lineCount) { - ed.lineCount = lines; - $("gutter").textContent = Array.from({ length: lines }, (_, i) => i + 1).join("\n"); - } - // Sized to the copy, the textarea never needs to scroll; what the browser scrolled to show the - // caret before the copy grew is undone, and the editor's own scroller shows it instead. - source.scrollTop = 0; - source.scrollLeft = 0; -} - -// Where the character at `index` starts, in pixels from the top left of .code. -function offsetAt(index) { - const text = $("source").value; - const lineStart = text.lastIndexOf("\n", index - 1) + 1; - const measure = $("measure"); - measure.textContent = text.slice(lineStart, index); - const line = text.slice(0, lineStart).split("\n").length - 1; - return { x: PAD_X + measure.getBoundingClientRect().width, y: PAD_Y + line * LINE }; -} - -function revealCaret() { - const editor = $("editor"); - const source = $("source"); - const gutter = $("gutter").offsetWidth; - // The end of a selection that moves, which is its start when it was made backwards. - const at = offsetAt(source.selectionDirection === "backward" ? source.selectionStart : source.selectionEnd); - if (at.y - PAD_Y < editor.scrollTop) editor.scrollTop = at.y - PAD_Y; - else if (at.y + LINE + PAD_Y > editor.scrollTop + editor.clientHeight) editor.scrollTop = at.y + LINE + PAD_Y - editor.clientHeight; - const x = gutter + at.x; - if (x - PAD_X < editor.scrollLeft + gutter) editor.scrollLeft = Math.max(0, x - PAD_X - gutter); - else if (x + PAD_X > editor.scrollLeft + editor.clientWidth) editor.scrollLeft = x + PAD_X - editor.clientWidth; -} - -// ---- reading the structure -------------------------------------------------------------------- - -// Walks the tokens before `at` keeping a frame per open object ({key, colon, keys, tool}) and -// array ({array, index}). Returns the frames, the string `at` is in (after its opening quote) if -// any, and the vars and saved job names seen; null when `at` is in a comment. -function readScript(text, at) { - const frames = []; - const vars = new Set(); - const jobs = new Set(); - let m; - TOKEN.lastIndex = 0; - while ((m = TOKEN.exec(text)) && m.index < at) { - const end = TOKEN.lastIndex; - const top = frames[frames.length - 1]; - if (m[1] !== undefined) { - if (end > at || (end === at && !m[1].endsWith("*/"))) return null; - continue; - } - if (m[2] !== undefined) { - const closed = m[3] === '"'; - if (at < end || (at === end && !closed)) - return { frames, vars, jobs, string: { start: m.index, end, closed } }; - const value = m[2].slice(1); - if (top && !top.array) { - if (!top.colon) { - top.key = value; - top.keys.add(value); - if (frames.length === 2 && frames[0].key === "vars") vars.add(value); - } else if (top.key === "tool") top.tool = value; - else if (top.key === "save_as") jobs.add(value); - } - continue; - } - switch (m[6]) { - case "{": frames.push({ array: false, key: null, colon: false, keys: new Set(), tool: null }); break; - case "[": frames.push({ array: true, index: 0 }); break; - case "}": case "]": frames.pop(); break; - case ":": if (top && !top.array) top.colon = true; break; - case ",": - if (top && top.array) top.index++; - else if (top) { top.key = null; top.colon = false; } - break; - } - } - return { frames, vars, jobs, string: null }; -} - -// The step a path inside steps[] belongs to, as its frame: frames are root, steps, step, ... -function stepTool(frames) { - const step = frames[2]; - return step && !step.array ? ed.tools.get(step.tool) : null; -} - -function typeText(type) { return Array.isArray(type) ? type.join(" | ") : type || ""; } - -function keyItems(frames, path) { - const top = frames[frames.length - 1]; - let items = []; - if (path.length === 0) items = ROOT_KEYS; - else if (path.length === 2 && path[0] === "steps") items = STEP_KEYS; - else if (path.length === 3 && path[0] === "steps" && path[2] === "args") { - const tool = stepTool(frames); - if (tool) - items = Object.entries(tool.args).map(([name, arg]) => ({ - label: name, - detail: typeText(arg.type), - info: arg.enum ? arg.enum.join(" | ") : "", - })); - } else if (path.length === 4 && path[0] === "steps" && path[2] === "expect") - items = MATCHERS.map((label) => ({ label })); - return items.filter((item) => !top.keys.has(item.label)); -} - -function valueItems(frames, path) { - if (path.length === 3 && path[0] === "steps" && path[2] === "tool") - return [...ed.tools.values()].map((tool) => { - const args = Object.keys(tool.args); - return { label: tool.name, detail: tool.title, info: args.length ? "args: " + args.join(", ") : "" }; - }); - if (path.length === 4 && path[0] === "steps" && path[2] === "args") { - const tool = stepTool(frames); - const arg = tool && tool.args[path[3]]; - if (arg && arg.enum) return arg.enum.filter((v) => typeof v === "string").map((label) => ({ label })); - } - return []; -} - -// What can go at `at`: the range a suggestion replaces, how it is written there, and the candidates. -// Inside a string that is a key or a value, or after an unclosed ${ in a string; elsewhere only when -// asked (`explicit`), at a key or value position. -function suggestionsAt(text, at, explicit) { - const read = readScript(text, at); - if (!read || !read.frames.length) return null; - const { frames, string } = read; - const top = frames[frames.length - 1]; - const path = frames.slice(0, -1).map((f) => (f.array ? f.index : f.key)); - const wordEnd = at + /^[\w.-]*/.exec(text.slice(at))[0].length; - if (string) { - const typed = text.slice(string.start + 1, at); - const open = typed.lastIndexOf("${"); - if (open >= 0 && typed.indexOf("}", open) < 0) { - const items = ["script_dir", "out_dir", ...[...read.vars].map((k) => "vars." + k), ...[...read.jobs].map((k) => "jobs." + k)]; - return { kind: "var", from: string.start + 3 + open, to: wordEnd, items: items.map((label) => ({ label })) }; - } - } else if (!explicit) return null; - // A suggestion replaces what was typed and, in a closed string, the rest of it up to the quote. - const found = string - ? { quoted: true, from: string.start + 1, to: string.closed ? string.end : wordEnd } - : { quoted: false, from: at - /[\w.-]*$/.exec(text.slice(0, at))[0].length, to: wordEnd }; - // Unquoted, only where a key or value can start, not right after one. - if (!string && !/(^|[{[,:])\s*$/.test(text.slice(0, found.from))) return null; - if (!top.array && !top.colon) return Object.assign(found, { kind: "key", items: keyItems(frames, path) }); - const value = [...path, top.array ? top.index : top.key]; - return Object.assign(found, { kind: "value", items: valueItems(frames, value) }); -} - -// ---- suggestions ------------------------------------------------------------------------------ - -// Items starting with what was typed come first, then those containing it. -function filterItems(items, typed) { - const needle = typed.toLowerCase(); - const starts = []; - const contains = []; - for (const item of items) { - const pos = item.label.toLowerCase().indexOf(needle); - if (pos === 0) starts.push(Object.assign({ match: 0 }, item)); - else if (pos > 0) contains.push(Object.assign({ match: pos }, item)); - } - return starts.concat(contains); -} - -function updateSuggest(explicit) { - const source = $("source"); - if (source.readOnly || source.selectionStart !== source.selectionEnd) return closeSuggest(); - const at = source.selectionEnd; - const found = suggestionsAt(source.value, at, explicit); - if (!found) return closeSuggest(); - const typed = source.value.slice(found.from, at); - const items = filterItems(found.items, typed); - if (!items.length) return closeSuggest(); - const was = ed.pop && ed.pop.items[ed.pop.active].label; - ed.pop = Object.assign(found, { items, typed, active: Math.max(0, items.findIndex((item) => item.label === was)) }); - renderSuggest(); -} - -function closeSuggest() { - if (!ed.pop) return; - ed.pop = null; - $("suggest").hidden = true; - const source = $("source"); - source.setAttribute("aria-expanded", "false"); - source.removeAttribute("aria-activedescendant"); -} - -function renderSuggest() { - const pop = ed.pop; - const list = $("suggest-list"); - list.textContent = ""; - pop.items.forEach((item, i) => { - const li = el("li", i === pop.active ? "is-active" : ""); - li.id = "suggest-" + i; - li.setAttribute("role", "option"); - li.setAttribute("aria-selected", String(i === pop.active)); - const name = el("span", "s-name"); - const n = pop.typed.length; - name.append(item.label.slice(0, item.match)); - if (n) name.appendChild(el("b", "", item.label.slice(item.match, item.match + n))); - name.append(item.label.slice(item.match + n)); - li.appendChild(name); - if (item.detail) li.appendChild(el("span", "s-detail", item.detail)); - // Keeps the caret in the editor; the click itself accepts. - li.addEventListener("mousedown", (e) => { - e.preventDefault(); - acceptSuggest(i); - }); - list.appendChild(li); - }); - const active = pop.items[pop.active]; - $("suggest-detail").hidden = !active.info; - $("suggest-detail").textContent = active.info || ""; - const source = $("source"); - source.setAttribute("aria-expanded", "true"); - source.setAttribute("aria-activedescendant", "suggest-" + pop.active); - const box = $("suggest"); - box.hidden = false; - placeSuggest(); - $("suggest-" + pop.active).scrollIntoView({ block: "nearest" }); -} - -// Under the caret's line with the names starting under what was typed; above the line when the -// space below is too small. -function placeSuggest() { - if (!ed.pop) return; - const box = $("suggest"); - const code = document.querySelector(".code").getBoundingClientRect(); - const at = offsetAt(ed.pop.from); - const left = code.left + at.x - 11; - const top = code.top + at.y; - box.style.left = Math.max(8, Math.min(left, innerWidth - box.offsetWidth - 8)) + "px"; - const below = top + LINE + 3; - box.style.top = (below + box.offsetHeight <= innerHeight - 8 ? below : Math.max(8, top - box.offsetHeight - 3)) + "px"; -} - -function moveSuggest(step) { - const pop = ed.pop; - pop.active = (pop.active + step + pop.items.length) % pop.items.length; - renderSuggest(); -} - -// Replaces [from, to) with `text` through the editing commands, so undo takes it back, and puts the -// caret `back` characters before the end of what was inserted. -function insertText(from, to, text, back) { - const source = $("source"); - source.setSelectionRange(from, to); - ed.inserting = true; - if (!document.execCommand("insertText", false, text)) { - source.setRangeText(text, from, to, "end"); - source.dispatchEvent(new Event("input")); - } - ed.inserting = false; - const caret = from + text.length - (back || 0); - source.setSelectionRange(caret, caret); -} - -function acceptSuggest(index) { - const pop = ed.pop; - const item = pop.items[index === undefined ? pop.active : index]; - const text = $("source").value; - closeSuggest(); - if (pop.kind === "var") { - insertText(pop.from, text[pop.to] === "}" ? pop.to + 1 : pop.to, item.label + "}"); - return; - } - let insert = (pop.quoted ? "" : '"') + item.label + '"'; - let back = 0; - let then = ""; - if (pop.kind === "key" && !/^\s*:/.test(text.slice(pop.to))) { - then = item.then !== undefined ? item.then : EMPTY_VALUES[item.detail] || ""; - insert += ": " + then; - back = then.length === 2 ? 1 : 0; - } - insertText(pop.from, pop.to, insert, back); - if (then === '""') updateSuggest(false); -} - -// Return keeps the line's indent, one level more after an opening bracket; between a pair of -// brackets the closing one goes on its own line. -function newline() { - const source = $("source"); - const text = source.value; - const start = source.selectionStart; - const lineStart = text.lastIndexOf("\n", start - 1) + 1; - const indent = /^[ \t]*/.exec(text.slice(lineStart, start))[0]; - const opens = /[{[]\s*$/.test(text.slice(lineStart, start)); - const closes = /^[ \t]*[}\]]/.test(text.slice(source.selectionEnd)); - if (opens && closes) insertText(start, source.selectionEnd, "\n" + indent + " \n" + indent, indent.length + 1); - else insertText(start, source.selectionEnd, "\n" + indent + (opens ? " " : "")); -} - -// ---- events ----------------------------------------------------------------------------------- - -function onEditorInput(e) { - refreshEditor(); - revealCaret(); - if (ed.inserting || ed.composing) return; - const type = e.inputType || ""; - if (type === "insertText" || (ed.pop && type.startsWith("delete"))) updateSuggest(false); - else closeSuggest(); -} - -function onEditorKey(e) { - if (e.isComposing || e.keyCode === 229) return; - // Ctrl/Cmd+Enter runs the script (script_runner.js). - if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) return; - if (ed.pop) { - switch (e.key) { - case "ArrowDown": moveSuggest(1); break; - case "ArrowUp": moveSuggest(-1); break; - case "PageDown": moveSuggest(Math.min(6, ed.pop.items.length - 1 - ed.pop.active)); break; - case "PageUp": moveSuggest(-Math.min(6, ed.pop.active)); break; - case "Enter": case "Tab": acceptSuggest(); break; - case "Escape": closeSuggest(); break; - // Moving the caret leaves what the suggestions would replace; the key itself goes on. - case "ArrowLeft": case "ArrowRight": case "Home": case "End": closeSuggest(); return; - default: return; - } - e.preventDefault(); - return; - } - if (e.code === "Space" && e.ctrlKey && !e.metaKey && !e.altKey) { - e.preventDefault(); - updateSuggest(true); - } else if (e.key === "Enter" && !e.shiftKey && !e.altKey && !e.target.readOnly) { - e.preventDefault(); - newline(); - } -} - -function setEditorTools(tools) { - ed.tools = new Map(tools.map((tool) => [tool.name, tool])); -} - -function initEditor() { - const source = $("source"); - source.addEventListener("input", onEditorInput); - source.addEventListener("keydown", onEditorKey); - source.addEventListener("keyup", (e) => { - if (/^(Arrow|Page|Home|End)/.test(e.key)) revealCaret(); - }); - source.addEventListener("blur", closeSuggest); - source.addEventListener("mousedown", closeSuggest); - source.addEventListener("scroll", () => { - source.scrollTop = 0; - source.scrollLeft = 0; - }); - source.addEventListener("compositionstart", () => { - ed.composing = true; - closeSuggest(); - $("editor").classList.add("is-composing"); - }); - source.addEventListener("compositionend", () => { - ed.composing = false; - $("editor").classList.remove("is-composing"); - refreshEditor(); - }); - $("editor").addEventListener("scroll", placeSuggest); - window.addEventListener("resize", closeSuggest); - refreshEditor(); -} diff --git a/resources/web/dialog/js/code_editor.css b/resources/web/dialog/js/code_editor.css new file mode 100644 index 0000000000..ede8547dc0 --- /dev/null +++ b/resources/web/dialog/js/code_editor.css @@ -0,0 +1,127 @@ +/* The code editors' theme, ace-orca (code_editor.js applies it as an object, so Ace loads no theme file). Its colours + * come from the host theme contract (--orca-*) and the tokens below, which follow the app into dark mode through + * theme.css's data-orca-theme, as the rest of a page does. The syntax colours stay apart from the status colours, so a + * string never reads as a warning. A page sets the editor's size and border; this sets what is inside it. */ + +:root { + --code-bg: var(--orca-bg, #ffffff); + --code-fg: var(--orca-fg, #262e30); + --code-muted: var(--orca-muted, #6b7478); + --code-rule: var(--border, #dcdfe1); + --code-accent: var(--orca-accent, #009688); + --code-accent-tint: var(--plugin-source-mine-bg, rgba(0, 150, 136, 0.12)); + --code-gutter: #f6f7f8; + --code-selection: rgba(0, 150, 136, 0.22); + --code-font: "Cascadia Code", Consolas, "SF Mono", Menlo, "DejaVu Sans Mono", monospace; + --code-key: #00796b; + --code-string: #8a4b08; + --code-number: #6639ba; + --code-punct: #8a9397; + --code-comment: #7d8589; + --code-keyword: #1f5f99; + --code-builtin: #00796b; + --code-pop-bg: var(--ctx-bg, #ffffff); + --code-pop-border: var(--ctx-border, #cccccc); + --code-pop-shadow: 0 6px 20px rgba(20, 30, 35, 0.16); +} +:root[data-orca-theme="dark"] { + --code-gutter: #28282c; + --code-selection: rgba(0, 150, 136, 0.35); + --code-key: #4db6ac; + --code-string: #d9a35f; + --code-number: #b79af0; + --code-punct: #7f858b; + --code-comment: #858a90; + --code-keyword: #7cb4f0; + --code-builtin: #4db6ac; + --code-pop-shadow: 0 6px 20px rgba(0, 0, 0, 0.45); +} + +.ace-orca { + background: var(--code-bg); + color: var(--code-fg); + font-family: var(--code-font); +} +.ace-orca .ace_gutter { + background: var(--code-gutter); + color: var(--code-muted); + border-right: 1px solid var(--code-rule); +} +.ace-orca .ace_gutter-active-line { background: transparent; } +.ace-orca .ace_cursor { color: var(--code-fg); } +.ace-orca .ace_marker-layer .ace_selection { background: var(--code-selection); } +.ace-orca .ace_marker-layer .ace_selected-word { border: 1px solid var(--code-selection); } +/* The bracket matching the one at the caret. */ +.ace-orca .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid var(--code-accent); } +.ace-orca .ace_placeholder { color: var(--code-muted); font-family: inherit; } +.ace-orca .ace_fold { background: var(--code-accent-tint); border-color: var(--code-accent); } +.ace-orca .ace_indent-guide { background: none; box-shadow: inset -1px 0 0 var(--code-rule); } +.ace-orca .ace_invisible { color: var(--code-rule); } + +/* Tokens: a replay's keys, strings, ${…}, numbers and literals; Python's keywords and built-ins. */ +.ace-orca .ace_comment { color: var(--code-comment); font-style: italic; } +.ace-orca .ace_variable { color: var(--code-key); } +.ace-orca .ace_string { color: var(--code-string); } +.ace-orca .ace_orca_var { color: var(--code-accent); background: var(--code-accent-tint); border-radius: 2px; } +.ace-orca .ace_constant.ace_numeric, +.ace-orca .ace_constant.ace_language { color: var(--code-number); } +.ace-orca .ace_paren, +.ace-orca .ace_punctuation, +.ace-orca .ace_keyword.ace_operator { color: var(--code-punct); } +.ace-orca .ace_keyword { color: var(--code-keyword); } +.ace-orca .ace_support.ace_function { color: var(--code-builtin); } + +/* The suggestion list and its detail, which Ace draws with the editor's theme. */ +.ace-orca.ace_autocomplete { + background: var(--code-pop-bg); + color: var(--code-fg); + border: 1px solid var(--code-pop-border); + border-radius: 6px; + box-shadow: var(--code-pop-shadow); +} +.ace-orca.ace_autocomplete .ace_marker-layer .ace_active-line, +.ace-orca.ace_autocomplete .ace_selected { background: var(--code-accent-tint); } +.ace-orca.ace_autocomplete .ace_line-hover { background: var(--code-accent-tint); border: 0; } +.ace-orca.ace_autocomplete .ace_completion-highlight { color: var(--code-accent); font-weight: 600; text-shadow: none; } +.ace-orca.ace_autocomplete .ace_completion-meta { color: var(--code-muted); opacity: 1; } +.ace_tooltip.ace_doc-tooltip { + background: var(--code-pop-bg); + color: var(--code-muted); + border: 1px solid var(--code-pop-border); + border-radius: 6px; + box-shadow: var(--code-pop-shadow); + font-family: var(--code-font); + font-size: 11.5px; +} + +/* The search box (Ctrl+F). */ +.ace-orca .ace_search { + background: var(--code-pop-bg); + color: var(--code-fg); + border-color: var(--code-pop-border); + box-shadow: var(--code-pop-shadow); +} +.ace-orca .ace_search_field { + background: var(--code-bg); + color: var(--code-fg); + border-color: var(--code-rule); +} +.ace-orca .ace_search_field:focus, +.ace-orca .ace_searchbtn:focus-visible, +.ace-orca .ace_button:focus-visible { outline: 2px solid var(--code-accent); outline-offset: -1px; } +.ace-orca .ace_searchbtn, +.ace-orca .ace_button { + background: var(--code-bg); + color: var(--code-fg); + border-color: var(--code-rule); +} +.ace-orca .ace_searchbtn:hover, +.ace-orca .ace_button:hover { background: var(--code-accent-tint); } +.ace-orca .ace_button.checked { border-color: var(--code-accent); color: var(--code-accent); opacity: 1; } +.ace-orca .ace_search_counter { color: var(--code-muted); } +.ace-orca .ace_searchbtn_close { filter: none; } +:root[data-orca-theme="dark"] .ace-orca .ace_searchbtn_close { filter: invert(0.8); } + +@media (prefers-reduced-motion: reduce) { + .ace-orca .ace_cursor { animation: none !important; transition: none !important; } +} diff --git a/resources/web/dialog/js/code_editor.js b/resources/web/dialog/js/code_editor.js new file mode 100644 index 0000000000..b99f28ee33 --- /dev/null +++ b/resources/web/dialog/js/code_editor.js @@ -0,0 +1,268 @@ +// The code editor of the bundled pages: Ace, vendored unmodified in resources/web/include/ace and loaded before this +// file by script tags, since the pages are file:// URLs. Everything an editor uses is vendored, so nothing here may make +// Ace fetch a file: workers are off, snippets are off, completers are passed as arrays (`true` would add Ace's snippet and +// keyword completers), the theme is an object (code_editor.css holds its colours), modes are objects, and the default +// commands that would load an extension the repo doesn't vendor are removed. Ace's own text (the search box, the +// suggestion list, the read-only note, folding, the ARIA labels) comes from the page's strings under "code_editor" +// (WebViewHostDialog::code_editor_strings()). + +// Ace's default commands that load a file the repo doesn't vendor (the settings menu, the error marker, the prompt behind +// Go to line, the command palette and the mode list). +const UNVENDORED_COMMANDS = ["showSettingsMenu", "goToNextError", "goToPreviousError", "gotoline", "openCommandPalette", + "openCommandPallete", "modeSelect"]; + +// How long after Ace's own undo, redo or select all the same action forwarded by the host is the same key press. +const FORWARDED_KEY_WINDOW_MS = 150; + +const IS_MAC = typeof navigator !== "undefined" && /Mac/.test(navigator.platform || navigator.userAgent); + +let codeEditorConfigured = false; + +// Ace's messages from the page's strings: each %s, in order, becomes Ace's $0, $1. +function configureCodeEditor() { + if (codeEditorConfigured) return; + codeEditorConfigured = true; + const strings = typeof ORCA_UI_STRINGS !== "undefined" && ORCA_UI_STRINGS && ORCA_UI_STRINGS.code_editor; + if (!strings) return; + const messages = {}; + for (const [key, text] of Object.entries(strings)) { + let n = 0; + messages[key] = String(text).replace(/%s/g, () => "$" + n++); + } + ace.config.setMessages(messages); +} + +function pageIsDark() { return document.documentElement.getAttribute("data-orca-theme") === "dark"; } + +function setEditorDark(editor, dark) { editor.setTheme({ cssClass: "ace-orca", isDark: !!dark, cssText: "" }); } + +// A position in the text as an offset, and back. +function indexOf(editor, pos) { return editor.session.doc.positionToIndex(pos); } +function positionOf(editor, index) { return editor.session.doc.indexToPosition(index); } + +// Writes `edit` ({from, to, insert, back}, offsets in the text) as one change, the caret `back` characters before the end +// of what was inserted. +function applyEditorEdit(editor, edit) { + const Range = ace.require("ace/range").Range; + const start = positionOf(editor, edit.from); + const end = positionOf(editor, edit.to); + editor.session.replace(new Range(start.row, start.column, end.row, end.column), edit.insert); + editor.selection.moveToPosition(positionOf(editor, edit.from + edit.insert.length - (edit.back || 0))); + editor.renderer.scrollCursorIntoView(); +} + +// A page's completer ({suggestionsAt, acceptEdit, identifierRegexps, triggerCharacters}) as an Ace completer. The list +// shows what suggestionsAt() finds at the caret, in its order; accepting an item finds the range again at the caret, +// since Ace keeps the list open and filters it while more is typed without asking again, and writes acceptEdit()'s edit. +function aceCompleter(completer) { + const adapted = { + identifierRegexps: completer.identifierRegexps, + triggerCharacters: completer.triggerCharacters, + getCompletions(editor, session, pos, prefix, callback) { + // Ctrl+Space opens the list as asked for; typing opens it on its own (autoShown). + const explicit = !(editor.completer && editor.completer.autoShown); + const found = completer.suggestionsAt(editor.getValue(), indexOf(editor, pos), explicit); + if (!found || !found.items.length) return callback(null, []); + const count = found.items.length; + // Each completion names its completer, whose insertMatch() Ace then calls. + callback(null, found.items.map((item, i) => ({ caption: item.label, value: item.label, meta: item.detail || "", score: count - i, item, + completer: adapted }))); + }, + getDocTooltip(completion) { + if (completion.item && completion.item.info && !completion.docText) completion.docText = completion.item.info; + }, + insertMatch(editor, data) { + const text = editor.getValue(); + const found = completer.suggestionsAt(text, indexOf(editor, editor.getCursorPosition()), true); + if (!found) return; + const edit = completer.acceptEdit(text, found, data.item); + applyEditorEdit(editor, edit); + // After the list has closed for this acceptance. + if (edit.reopen) setTimeout(() => editor.execCommand("startAutocomplete"), 0); + }, + }; + return adapted; +} + +// An editor in `element`: options = {mode (an Ace mode id), tabSize, placeholder, completer, onChange(text), commands}. +// Each command is {name, bindKey: {win, mac}, exec(editor), readOnly}; one that doesn't edit the text is readOnly, since +// Ace refuses any other in a read-only editor. onChange runs once per batch of changes, from the session's change event, +// so the host's copy is never behind (Ace's own input event comes later). +function createCodeEditor(element, options) { + configureCodeEditor(); + const completers = options.completer ? [aceCompleter(options.completer)] : false; + const editor = ace.edit(element, { + useWorker: false, + enableSnippets: false, + enableBasicAutocompletion: completers, + enableLiveAutocompletion: completers, + useSoftTabs: true, + tabSize: options.tabSize || 2, + showPrintMargin: false, + fixedWidthGutter: true, + highlightActiveLine: false, + fontSize: "12px", + placeholder: options.placeholder || "", + }); + editor.session.setNewLineMode("unix"); + const Mode = ace.require(options.mode).Mode; + editor.session.setMode(new Mode()); + setEditorDark(editor, pageIsDark()); + new MutationObserver(() => setEditorDark(editor, pageIsDark())) + .observe(document.documentElement, { attributes: true, attributeFilter: ["data-orca-theme"] }); + + for (const name of UNVENDORED_COMMANDS) editor.commands.removeCommand(name); + // Shift+Enter is the page's (Run cell) even while the suggestion list is open. + if (completers) ace.require("ace/autocomplete").Autocomplete.for(editor).keyboardHandler.removeCommand("Shift-Return"); + editor.$orcaCommands = new Set(); + for (const command of options.commands || []) { + editor.commands.addCommand(command); + editor.$orcaCommands.add(command.name); + } + + editor.$orcaOwnAt = {}; + editor.commands.on("afterExec", (e) => { + if (!editor.$orcaForwarding) editor.$orcaOwnAt[e.command.name] = Date.now(); + }); + document.addEventListener("keydown", (e) => recordFieldKey(editor, e), true); + let reported = false; + editor.session.on("change", () => { + if (editor.$orcaQuiet || reported || !options.onChange) return; + reported = true; + queueMicrotask(() => { + reported = false; + options.onChange(editor.getValue()); + }); + }); + return editor; +} + +// Replaces the text without reporting it as an edit, with no undo history and the caret at the start. +function setEditorText(editor, text) { + editor.$orcaQuiet = true; + try { + editor.session.setValue(text); + } finally { + editor.$orcaQuiet = false; + } + editor.session.getUndoManager().reset(); + editor.clearSelection(); + editor.moveCursorTo(0, 0); + editor.renderer.scrollToRow(0); +} + +function closeEditorSuggestions(editor) { + if (editor.completer && editor.completer.activated) editor.completer.detach(); +} + +// ---- keys ------------------------------------------------------------------------------------------------------- + +// KeyChord::to_string()'s special key names and Ace's. +const CHORD_TO_ACE_KEYS = { Backspace: "Backspace", Tab: "Tab", Enter: "Return", Esc: "Esc", Space: "Space", Del: "Delete", + Ins: "Insert", Home: "Home", End: "End", PgUp: "PageUp", PgDn: "PageDown", Left: "Left", + Right: "Right", Up: "Up", Down: "Down" }; +const ACE_TO_CHORD_KEYS = { backspace: "Backspace", tab: "Tab", return: "Enter", enter: "Enter", esc: "Esc", escape: "Esc", + space: "Space", delete: "Del", del: "Del", insert: "Ins", home: "Home", end: "End", + pageup: "PgUp", pagedown: "PgDn", left: "Left", right: "Right", up: "Up", down: "Down" }; + +// A chord in KeyChord::to_string()'s canonical form ("Ctrl+Shift+R", Ctrl being ⌘ on macOS) in Ace's ("Ctrl-Shift-R" off +// macOS, "Command-Shift-R" on it). Never the translated text the menus show. +function aceKey(chord) { + const parts = chord.length > 1 && chord.endsWith("+") ? [...chord.slice(0, -2).split("+").filter(Boolean), "+"] : chord.split("+"); + const key = parts.pop(); + const name = CHORD_TO_ACE_KEYS[key] || key; + const win = []; + const mac = []; + for (const modifier of parts) { + if (modifier === "Ctrl") { win.push("Ctrl"); mac.push("Command"); } + else if (modifier === "Shift") { win.push("Shift"); mac.push("Shift"); } + else if (modifier === "Alt") { win.push("Alt"); mac.push("Option"); } + else if (modifier === "RawCtrl") mac.push("Ctrl"); + } + return { win: [...win, name].join("-"), mac: [...mac, name].join("-") }; +} + +// An Ace key binding on this platform ("Ctrl-Shift-K", "Command-Alt-Up") in KeyChord's canonical form, or "" for one it +// can't name (a key chain, a numpad key). +function chordOf(binding) { + if (/\s/.test(binding)) return ""; + const parts = binding.endsWith("--") ? [...binding.slice(0, -2).split("-").filter(Boolean), "-"] : binding.split("-"); + const key = parts.pop(); + const mods = new Set(); + for (const part of parts) { + const p = part.toLowerCase(); + const control = p === "ctrl" || p === "control"; + // Ace's Ctrl is the Control key on macOS, where KeyChord's Ctrl is Command. + if (p === "command" || p === "cmd" || (control && !IS_MAC)) mods.add("Ctrl"); + else if (control) mods.add("RawCtrl"); + else if (p === "shift") mods.add("Shift"); + else if (p === "alt" || p === "option") mods.add("Alt"); + else return ""; + } + const name = ACE_TO_CHORD_KEYS[key.toLowerCase()] || (/^f\d+$/i.test(key) ? key.toUpperCase() : key.length === 1 ? key.toUpperCase() : ""); + if (!name) return ""; + return ["Ctrl", "Shift", "Alt", "RawCtrl"].filter((m) => mods.has(m)).map((m) => m + "+").join("") + name; +} + +// The chords Ace's own commands bind on this platform, in KeyChord's canonical form, leaving out the page's commands +// (Save, Run, the toggle are the app's): what the host disables in its menus while the editor has the focus. Ace's own +// bindings never change, so the list doesn't change with a rebinding. +function editorChords(editor) { + const platform = editor.commands.platform; + const chords = new Set(); + for (const [name, command] of Object.entries(editor.commands.commands)) { + if (editor.$orcaCommands.has(name) || !command.bindKey) continue; + const binding = typeof command.bindKey === "string" ? command.bindKey : command.bindKey[platform]; + if (!binding) continue; + for (const one of binding.split("|")) { + const chord = chordOf(one.trim()); + if (chord) chords.add(chord); + } + } + return [...chords]; +} + +// The editor's own text input, where its commands take the keys. Ace's search box sits inside the editor too, but its +// fields are text fields of their own. +function isEditorText(editor, el) { return !!el && el === editor.textInput.getElement(); } + +// A text field other than the editor's text (a console prompt, Ace's search fields), which does its own undo, redo and +// select all. +function isOtherTextField(editor, el) { + return !!el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA") && !isEditorText(editor, el); +} + +// Whether the page's own `name` command (an editor command, or a key the page handled itself) ran within +// FORWARDED_KEY_WINDOW_MS: the same key press the host then forwards from its menu. +function ownKeyRan(editor, name) { return Date.now() - (editor.$orcaOwnAt[name] || 0) < FORWARDED_KEY_WINDOW_MS; } + +// A key pressed in such a field: its undo, redo or select all is recorded as the editor's own commands are, so the same +// press forwarded by the host's menu does nothing more. +function recordFieldKey(editor, e) { + if (!isOtherTextField(editor, e.target) || !(IS_MAC ? e.metaKey : e.ctrlKey) || e.altKey) return; + const key = (e.key || "").toLowerCase(); + const name = key === "a" && !e.shiftKey ? "selectall" : key === "z" ? (e.shiftKey ? "redo" : "undo") : key === "y" && !e.shiftKey ? "redo" : ""; + if (name) editor.$orcaOwnAt[name] = Date.now(); +} + +// Runs a forwarded "undo", "redo" or "select_all" (the host's Edit menu) unless the same action ran by its own key within +// FORWARDED_KEY_WINDOW_MS, so one press acts once whichever way it reached the page. A focused text field outside the +// editor takes it; otherwise the editor does. +function runEditorAction(editor, action) { + const name = { undo: "undo", redo: "redo", select_all: "selectall" }[action]; + if (!name || ownKeyRan(editor, name)) return; + const field = document.activeElement; + if (isOtherTextField(editor, field)) { + if (name === "selectall") field.select(); + else document.execCommand(name); + return; + } + editor.$orcaForwarding = true; + try { + editor.execCommand(name); + } finally { + editor.$orcaForwarding = false; + } +} + +if (typeof module !== "undefined") module.exports = { runEditorAction, recordFieldKey, ownKeyRan, isEditorText }; diff --git a/resources/web/dialog/js/code_editor.test.js b/resources/web/dialog/js/code_editor.test.js new file mode 100644 index 0000000000..544e45778d --- /dev/null +++ b/resources/web/dialog/js/code_editor.test.js @@ -0,0 +1,85 @@ +// The shared code editor's forwarded actions, run with `node --test`. Ace isn't loaded: the editor and the page are +// stand-ins with the parts these functions touch. +const { test } = require("node:test"); +const assert = require("node:assert/strict"); +const { runEditorAction, recordFieldKey, ownKeyRan, isEditorText } = require("./code_editor.js"); + +function page() { + const editorText = { tagName: "TEXTAREA" }; // Ace's hidden textarea, inside the editor + const prompt = { tagName: "INPUT", selected: 0, select() { this.selected++; } }; + const button = { tagName: "BUTTON" }; + // Ace's search box sits inside the editor's container, but its fields are text fields of their own. + const search = { tagName: "INPUT", selected: 0, select() { this.selected++; } }; + const editor = { + container: { contains: (el) => el === editorText || el === search }, + textInput: { getElement: () => editorText }, + $orcaOwnAt: {}, + ran: [], + execCommand(name) { this.ran.push(name); }, + }; + const doc = { activeElement: editorText, ran: [], execCommand(name) { this.ran.push(name); return true; } }; + global.document = doc; + return { editor, doc, editorText, prompt, button, search }; +} + +test("a forwarded undo or redo with a text field focused acts on the field, not the script", () => { + const p = page(); + p.doc.activeElement = p.prompt; + runEditorAction(p.editor, "undo"); + runEditorAction(p.editor, "redo"); + assert.deepEqual(p.doc.ran, ["undo", "redo"]); + assert.deepEqual(p.editor.ran, []); +}); + +test("a forwarded select all with a text field focused selects the field's text", () => { + const p = page(); + p.doc.activeElement = p.prompt; + runEditorAction(p.editor, "select_all"); + assert.equal(p.prompt.selected, 1); + assert.deepEqual(p.editor.ran, []); +}); + +test("a forwarded action with the editor or a button focused acts on the script", () => { + const p = page(); + runEditorAction(p.editor, "undo"); + p.doc.activeElement = p.button; + runEditorAction(p.editor, "select_all"); + assert.deepEqual(p.editor.ran, ["undo", "selectall"]); + assert.deepEqual(p.doc.ran, []); +}); + +test("a field's own undo key is recorded, so the same press forwarded by the host does nothing more", () => { + const p = page(); + p.doc.activeElement = p.prompt; + recordFieldKey(p.editor, { target: p.prompt, key: "z", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false }); + runEditorAction(p.editor, "undo"); + assert.deepEqual(p.doc.ran, []); + assert.deepEqual(p.editor.ran, []); +}); + +test("a key in the editor is left to the editor's own commands", () => { + const p = page(); + recordFieldKey(p.editor, { target: p.editorText, key: "z", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false }); + assert.deepEqual(p.editor.$orcaOwnAt, {}); +}); + +test("Ace's search field takes the forwarded actions itself, as a field outside the editor does", () => { + const p = page(); + p.doc.activeElement = p.search; + runEditorAction(p.editor, "undo"); + runEditorAction(p.editor, "select_all"); + assert.deepEqual(p.doc.ran, ["undo"]); + assert.equal(p.search.selected, 1); + assert.deepEqual(p.editor.ran, []); + assert.equal(isEditorText(p.editor, p.search), false); + assert.equal(isEditorText(p.editor, p.editorText), true); +}); + +test("a forwarded Save right after the page's own is the same key press", () => { + const p = page(); + p.editor.$orcaOwnAt.save = Date.now(); + assert.equal(ownKeyRan(p.editor, "save"), true); + p.editor.$orcaOwnAt.save = Date.now() - 1000; + assert.equal(ownKeyRan(p.editor, "save"), false); + assert.equal(ownKeyRan(p.editor, "saveAs"), false); +}); diff --git a/src/slic3r/CMakeLists.txt b/src/slic3r/CMakeLists.txt index 70a960c9d8..1db651f9a4 100644 --- a/src/slic3r/CMakeLists.txt +++ b/src/slic3r/CMakeLists.txt @@ -134,14 +134,17 @@ set(SLIC3R_GUI_SOURCES GUI/RecordingDialog.hpp GUI/RecordingIndicator.cpp GUI/RecordingIndicator.hpp - GUI/ScriptRunnerDialog.cpp - GUI/ScriptRunnerDialog.hpp + GUI/RunScriptPanel.cpp + GUI/RunScriptPanel.hpp + GUI/CodeEditorWindow.hpp GUI/SpeedDialDialog.cpp GUI/SpeedDialDialog.hpp GUI/ColorPickerDialog.cpp GUI/ColorPickerDialog.hpp GUI/ActionRegistry.cpp GUI/ActionRegistry.hpp + GUI/ActionReplayDialog.cpp + GUI/ActionReplayDialog.hpp GUI/NativeCommands.cpp GUI/NativeCommands.hpp GUI/SyntheticInput.cpp @@ -773,6 +776,8 @@ set(SLIC3R_GUI_SOURCES plugin/PythonRunScope.hpp plugin/PythonScriptRunner.cpp plugin/PythonScriptRunner.hpp + plugin/PythonSession.cpp + plugin/PythonSession.hpp plugin/PyPluginPackage.hpp plugin/PluginBindingUtils.hpp plugin/host/PluginHost.cpp diff --git a/src/slic3r/GUI/ScriptRunnerDialog.cpp b/src/slic3r/GUI/ActionReplayDialog.cpp similarity index 75% rename from src/slic3r/GUI/ScriptRunnerDialog.cpp rename to src/slic3r/GUI/ActionReplayDialog.cpp index 3fd1ddd39f..3a30f5fa83 100644 --- a/src/slic3r/GUI/ScriptRunnerDialog.cpp +++ b/src/slic3r/GUI/ActionReplayDialog.cpp @@ -1,4 +1,4 @@ -#include "ScriptRunnerDialog.hpp" +#include "ActionReplayDialog.hpp" #include "GLCanvas3D.hpp" #include "GUI.hpp" @@ -8,15 +8,15 @@ #include "MsgDialog.hpp" #include "NativeCommands.hpp" #include "Plater.hpp" +#include "RunScriptPanel.hpp" #include "format.hpp" #include "Mcp/McpPaths.hpp" #include "Mcp/McpScript.hpp" #include "Mcp/McpScriptRun.hpp" #include "Mcp/McpScriptSummary.hpp" #include "Mcp/McpService.hpp" +#include "Mcp/McpTools.hpp" #include "Mcp/McpTypes.hpp" -#include "Mcp/PythonScriptsDialog.hpp" -#include "slic3r/plugin/PythonScriptRunner.hpp" #include "Widgets/WebViewHostDialog.hpp" #include "libslic3r/Utils.hpp" #ifdef __APPLE__ @@ -35,12 +35,18 @@ #include #include #include +#include #include #include #include #include #include #include +#include + +#ifdef _WIN32 +#include +#endif #include #include @@ -75,7 +81,7 @@ std::string timestamp() return buf; } -// The file name a new script is first offered under: the script's name, with the characters file +// The file name a new replay is first offered under: the replay's name, with the characters file // systems refuse replaced. std::string file_name_for(const std::string& text) { @@ -83,10 +89,12 @@ std::string file_name_for(const std::string& text) const auto script = Mcp::parse_script(text, err); std::string name = script ? sanitize_filename(script->name) : std::string(); boost::trim_if(name, boost::is_any_of(" .")); - return (name.empty() ? std::string("script") : name) + ".json"; + return (name.empty() ? std::string("replay") : name) + ".json"; } -wxString script_wildcard() { return format_wxstr("%1% (*.json;*.py)|*.json;*.py", _L("Script files")); } +wxString replay_wildcard() { return format_wxstr("%1% (*.json)|*.json|%2% (*.*)|*.*", _L("Replay files"), _L("All files")); } + +bool is_replay_file(const fs::path& path) { return boost::iequals(path.extension().string(), ".json"); } bool is_python_file(const fs::path& path) { return boost::iequals(path.extension().string(), ".py"); } @@ -146,12 +154,12 @@ std::pair what_text(const json& what) return {}; } -// One check of a step's expect in a sentence; the pointer and operand are the script's data. +// One check of a step's expect in a sentence; the pointer and operand are the replay's data. std::string check_text(const std::string& pointer, const std::string& op, const json& operand) { const std::string value = value_text(operand); - // TRN In these messages %1% names the field of a step's result that the script checks (a JSON - // pointer such as /plates/0/outcome) and %2% the value the script compares it with. + // TRN In these messages %1% names the field of a step's result that the replay checks (a JSON + // pointer such as /plates/0/outcome) and %2% the value the replay compares it with. if (op == "eq") return format(_u8L("Checks that %1% is %2%."), pointer, value); if (op == "ne") @@ -172,7 +180,7 @@ std::string check_text(const std::string& pointer, const std::string& op, const return operand == false ? format(_u8L("Checks that %1% is missing."), pointer) : format(_u8L("Checks that %1% is there."), pointer); if (op == "empty") return operand == false ? format(_u8L("Checks that %1% is not empty."), pointer) : format(_u8L("Checks that %1% is empty."), pointer); - // A matcher this version doesn't know, which the run reports: the script's own words. + // A matcher this version doesn't know, which the run reports: the replay's own words. return pointer + ": " + op + " " + value; } @@ -190,7 +198,7 @@ json checks_view(const json& expect) return out; } -// A failed expectation in a sentence; the pointer and values are the script's data. +// A failed expectation in a sentence; the pointer and values are the replay's data. std::string expect_text(const json& r) { const std::string pointer = r.value("pointer", ""); @@ -198,17 +206,17 @@ std::string expect_text(const json& r) const std::string actual = value_text(r.value("actual", json())); const std::string expected = value_text(r.value("expected", json())); const bool exists = r.value("exists", false); - // TRN In these messages %1% names the field of a step's result that the script checked (a JSON - // pointer such as /plates/0/outcome), %2% the value it had and %3% the value the script expected. + // TRN In these messages %1% names the field of a step's result that the replay checked (a JSON + // pointer such as /plates/0/outcome), %2% the value it had and %3% the value the replay expected. if (op == "exists") return r.value("expected", json(true)) == true ? format(_u8L("The step finished, but %1% was missing."), pointer) : - format(_u8L("The step finished, but %1% was there, which the script did not expect."), pointer); + format(_u8L("The step finished, but %1% was there, which the replay did not expect."), pointer); if (!exists) return format(_u8L("The step finished, but %1% was missing."), pointer); if (op == "eq") return format(_u8L("The step finished, but %1% was %2%, not %3%."), pointer, actual, expected); if (op == "ne") - return format(_u8L("The step finished, but %1% was %2%, which the script did not expect."), pointer, actual); + return format(_u8L("The step finished, but %1% was %2%, which the replay did not expect."), pointer, actual); if (op == "gt") return format(_u8L("The step finished, but %1% was %2%, not more than %3%."), pointer, actual, expected); if (op == "ge") @@ -244,34 +252,13 @@ std::string thumbnail(const std::string& path) return "data:image/png;base64," + into_u8(wxBase64Encode(bytes.data(), bytes.size())); } -// What the editor suggests for each tool: its name, title and arguments with their types and allowed -// values. The argument descriptions are written for agents, in English, and stay out. -json tool_catalog(const Mcp::ToolRegistry& registry) -{ - json tools = json::array(); - for (const Mcp::ToolDef& def : registry.tools()) { - json args = json::object(); - const auto properties = def.input_schema.find("properties"); - if (properties != def.input_schema.end()) - for (const auto& [name, schema] : properties->items()) { - json arg = json::object(); - for (const char* key : {"type", "enum"}) - if (schema.contains(key)) - arg[key] = schema[key]; - args[name] = std::move(arg); - } - tools.push_back({{"name", def.name}, {"title", _u8L(def.title.c_str())}, {"args", std::move(args)}}); - } - return tools; -} - } // namespace -ScriptRunnerDialog::ScriptRunnerDialog(wxWindow* parent) : WebViewHostDialog(parent) +ActionReplayDialog::ActionReplayDialog(wxWindow* parent) : WebViewHostDialog(parent) { - // Scripts drive the main window through the MCP tools; the dialog keeps out of their sight. + // Replays drive the main window through the MCP tools; the dialog keeps out of their sight. SetName(Mcp::kHiddenFromAutomation); - // The script runner needs the MCP service's tools and jobs, never its network endpoint. + // Replaying needs the MCP service's tools and jobs, never its network endpoint. if (service() == nullptr) wxGetApp().start_mcp_service(false); @@ -281,11 +268,17 @@ ScriptRunnerDialog::ScriptRunnerDialog(wxWindow* parent) : WebViewHostDialog(par m_ready_timer.Stop(); send_service_state(); }); - Bind(wxEVT_CLOSE_WINDOW, &ScriptRunnerDialog::on_close, this); - create_webview("web/dialog/ScriptRunner/index.html", _L("Run Script"), wxSize(760, 720), wxSize(560, 480)); + Bind(wxEVT_CLOSE_WINDOW, &ActionReplayDialog::on_close, this); + static const char page[] = "web/dialog/ActionReplay/index.html"; + m_page = wxFileName(from_path(fs::path(resources_dir()) / page)); + if (create_webview(page, _L("Action Replay"), wxSize(760, 720), wxSize(560, 480))) { + // No reload: it would put the page back to its draft while the host keeps the file it replaces. + browser()->EnableBrowserAcceleratorKeys(false); + browser()->Bind(wxEVT_WEBVIEW_NAVIGATING, &ActionReplayDialog::on_navigating, this); + } } -ScriptRunnerDialog::~ScriptRunnerDialog() +ActionReplayDialog::~ActionReplayDialog() { m_alive->store(false); m_ready_timer.Stop(); @@ -296,9 +289,24 @@ ScriptRunnerDialog::~ScriptRunnerDialog() } } -bool ScriptRunnerDialog::running() const { return m_run && m_run->running(); } +bool ActionReplayDialog::running() const { return m_run && m_run->running(); } -nlohmann::json ScriptRunnerDialog::localized_strings() const +bool ActionReplayDialog::owns_focus(const wxWindow* focus) const +{ + for (const wxWindow* w = focus; w != nullptr; w = w->GetParent()) + if (w == this) + return true; +#ifdef _WIN32 + // WebView2 keeps the focus in windows of its own, which wx doesn't know. + if (const HWND native = ::GetFocus(); native != nullptr && ::IsChild(static_cast(GetHWND()), native)) + return true; +#endif + return false; +} + +void ActionReplayDialog::forward_action(const std::string& action) { call_web_handler({{"command", "key"}, {"action", action}}); } + +nlohmann::json ActionReplayDialog::localized_strings() const { // Shortcuts as the menus write them (⌘+S, Ctrl+S). The editor's suggestion key is Control+Space on // every platform, which the Mac writes ⌃. @@ -313,30 +321,30 @@ nlohmann::json ScriptRunnerDialog::localized_strings() const {"key_run", ctrl + enter}, {"key_save", ctrl + "S"}, {"key_save_as", ctrl + shortkey_shift_prefix() + "S"}, - {"open_script", _u8L("Open script…")}, + {"open_script", _u8L("Open replay…")}, {"save", _u8L("Save")}, - // TRN Saves a new script: the button opens a file dialog. + // TRN Saves a new replay file: the button opens a file dialog. {"save_new", _u8L("Save…")}, {"save_as", _u8L("Save as…")}, - // TRN Shown for a moment after a script is saved. + // TRN Shown for a moment after a replay file is saved. {"saved", _u8L("Saved")}, {"edited", _u8L("(edited)")}, - // TRN The name a new script starts with, in the editor of the Run Script dialog. - {"untitled_script", _u8L("Untitled script")}, + // TRN The name a new replay starts with, in the editor of the Action Replay window. + {"untitled_script", _u8L("Untitled replay")}, {"steps", _u8L("Steps")}, {"steps_hint", _u8L("Steps appear here as you write them.")}, - {"script_source", _u8L("Script source")}, - {"source_placeholder", _u8L("Write a script here, or open one.")}, - // TRN The first comment line a new script starts with. MCP is the protocol AI agents use to drive OrcaSlicer. - {"draft_about", _u8L("A script runs OrcaSlicer's tools in order, the way an AI agent does through MCP.")}, - // TRN A comment line a new script starts with. "tool", "args" and "expect" are the script's keys and stay in English. + {"script_source", _u8L("Replay file")}, + {"source_placeholder", _u8L("Write a replay here, or open one.")}, + // TRN The first comment line a new replay starts with. MCP is the protocol AI agents use to drive OrcaSlicer. + {"draft_about", _u8L("A replay file runs OrcaSlicer's tools in order, the way an AI agent does through MCP.")}, + // TRN A comment line a new replay starts with. "tool", "args" and "expect" are the file's keys and stay in English. {"draft_steps", _u8L("Each step names a \"tool\" and its \"args\"; \"expect\" checks the result before the next step.")}, - // TRN %s is the placeholder ${out_dir}, written as is in the script. + // TRN %s is the placeholder ${out_dir}, written as is in the replay file. {"draft_out_dir", _u8L("%s is this run's output folder.")}, // TRN The first %s is a key such as Ctrl+Space, the second one such as Ctrl+Enter. - {"draft_keys", _u8L("%s shows suggestions, %s runs the script.")}, - {"run", _u8L("Run")}, - {"run_again", _u8L("Run again")}, + {"draft_keys", _u8L("%s shows suggestions, %s replays the file.")}, + {"run", _u8L("Replay")}, + {"run_again", _u8L("Replay again")}, {"stop", _u8L("Stop")}, {"close", _u8L("Close")}, {"open_output", _u8L("Open output folder")}, @@ -356,12 +364,13 @@ nlohmann::json ScriptRunnerDialog::localized_strings() const {"running_one", _u8L("Running step %s")}, // TRN The first %s is the number of the step that is running, the second how many steps there are. {"running_step", _u8L("Running step %s of %s")}, - {"hands_off", _u8L("Don't use OrcaSlicer until the script finishes.")}, + {"hands_off", _u8L("Don't use OrcaSlicer until the replay finishes.")}, {"starting", _u8L("OrcaSlicer is still starting…")}, + {"code_editor", code_editor_strings()}, }; } -void ScriptRunnerDialog::on_script_message(const nlohmann::json& payload) +void ActionReplayDialog::on_script_message(const nlohmann::json& payload) { // Out of the web view's message callback: window work on its stack (file dialogs, prompts, // closing) is a crash class on GTK and macOS. @@ -371,7 +380,7 @@ void ScriptRunnerDialog::on_script_message(const nlohmann::json& payload) }); } -void ScriptRunnerDialog::handle(const nlohmann::json& payload) +void ActionReplayDialog::handle(const nlohmann::json& payload) { const std::string command = payload.value("command", ""); try { @@ -382,6 +391,11 @@ void ScriptRunnerDialog::handle(const nlohmann::json& payload) else if (command == "edit") { m_text = payload.value("text", ""); m_edited = payload.value("edited", false); + } else if (command == "editor_keys") { + m_editor_keys.clear(); + for (const json& chord : payload.value("chords", json::array())) + if (chord.is_string()) + m_editor_keys.insert(chord.get()); } else if (command == "save") save(payload.value("pick", false)); else if (command == "parse") @@ -404,7 +418,7 @@ void ScriptRunnerDialog::handle(const nlohmann::json& payload) } } -void ScriptRunnerDialog::send_service_state() +void ActionReplayDialog::send_service_state() { Mcp::McpService* s = service(); const bool ready = s != nullptr && s->ready(); @@ -412,22 +426,31 @@ void ScriptRunnerDialog::send_service_state() m_ready_timer.Start(500); json msg{{"command", "service"}, {"ready", ready}}; if (ready) - msg["tools"] = tool_catalog(s->registry()); + msg["tools"] = Mcp::editor_tool_catalog(s->registry()); call_web_handler(msg); } -void ScriptRunnerDialog::open_file() +void ActionReplayDialog::open_file() { if (!confirm_unsaved()) return; - wxFileDialog dialog(this, _L("Open a script"), wxEmptyString, wxEmptyString, script_wildcard(), wxFD_OPEN | wxFD_FILE_MUST_EXIST); + wxFileDialog dialog(this, _L("Open a replay file"), wxEmptyString, wxEmptyString, replay_wildcard(), wxFD_OPEN | wxFD_FILE_MUST_EXIST, + wxDefaultPosition, wxDefaultSize, Mcp::kHiddenFromAutomation); const int result = dialog.ShowModal(); if (!m_alive->load()) return; restore_z_order(); if (result != wxID_OK) return; - const fs::path path = into_path(dialog.GetPath()); + const fs::path path = into_path(dialog.GetPath()); + if (is_python_file(path)) + offer_run_script(path); + else + load_file(path); +} + +void ActionReplayDialog::load_file(const fs::path& path) +{ boost::nowide::ifstream in(Mcp::path_to_utf8(path).c_str(), std::ios::binary); if (!in) { call_web_handler({{"command", "error"}, {"message", format(_u8L("Can't read %1%."), Mcp::path_to_utf8(path))}}); @@ -435,35 +458,66 @@ void ScriptRunnerDialog::open_file() } std::ostringstream text; text << in.rdbuf(); - std::string source = text.str(); - std::string encoding = "utf-8"; - if (is_python_file(path)) { - // The page edits UTF-8 text: the file is decoded as Python reads it, and saved back in its encoding. - std::string decoded, error; - if (!decode_python_source(source, decoded, encoding, error)) { - // TRN %1% is a script's file name, %2% why it can't be read. - call_web_handler({{"command", "error"}, - {"message", format(_u8L("%1% can't be read as Python source: %2%"), Mcp::path_to_utf8(path.filename()), error)}}); - return; - } - source = std::move(decoded); + m_file = path; + m_jobs = json::object(); + call_web_handler({{"command", "source"}, {"file_name", Mcp::path_to_utf8(path.filename())}, {"text", text.str()}}); +} + +// The page goes nowhere but its own loads. A file dropped on it is a navigation to that file, handled after this event. +void ActionReplayDialog::on_navigating(wxWebViewEvent& event) +{ + if (own_page_navigation(event.GetURL(), m_page)) { + event.Skip(); + return; } - m_python_encoding = encoding; - m_file = path; - m_python = is_python_file(path); - m_jobs = json::object(); - call_web_handler({{"command", "source"}, {"file_name", Mcp::path_to_utf8(path.filename())}, {"text", source}}); + event.Veto(); + fs::path path = dropped_file(event.GetURL()); + if (path.empty()) + return; + wxGetApp().CallAfter([this, alive = m_alive, path = std::move(path)] { + if (alive->load()) + dropped(path); + }); +} + +void ActionReplayDialog::dropped(const fs::path& path) +{ + // As Open, which is unavailable while a replay runs. + if (running()) + return; + if (is_python_file(path)) + offer_run_script(path); + else if (is_replay_file(path) && confirm_unsaved()) + load_file(path); +} + +void ActionReplayDialog::offer_run_script(const fs::path& path) +{ + // TRN %1% is a file name. + MessageDialog dialog(this, format_wxstr(_L("%1% is a Python script. Python scripts run in the Run Script panel."), from_path(path.filename())), + _L("Action Replay"), wxOK | wxCANCEL | wxICON_INFORMATION); + // The person's own question: no auto-answer rule answers it. + dialog.SetName(Mcp::kHiddenFromAutomation); + dialog.SetButtonLabel(wxID_OK, _L("Open in Run Script")); + const int answer = dialog.ShowModal(); + if (!m_alive->load()) + return; + if (answer == wxID_OK) + wxGetApp().run_script_panel().open_file(path); + else + restore_z_order(); } // Writes the source to its file, or to one the person picks when it has none or `pick` asks for another. // False when nothing was written: the person cancelled, or the file can't be written. -bool ScriptRunnerDialog::save(bool pick) +bool ActionReplayDialog::save(bool pick) { fs::path path = m_file; if (pick || path.empty()) { const wxString name = path.empty() ? from_u8(file_name_for(m_text)) : from_path(path.filename()); - wxFileDialog dialog(this, _L("Save the script"), path.empty() ? wxString() : from_path(path.parent_path()), name, - script_wildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); + wxFileDialog dialog(this, _L("Save the replay file"), path.empty() ? wxString() : from_path(path.parent_path()), name, + replay_wildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition, wxDefaultSize, + Mcp::kHiddenFromAutomation); const int result = dialog.ShowModal(); if (!m_alive->load()) return false; @@ -472,13 +526,13 @@ bool ScriptRunnerDialog::save(bool pick) return false; path = into_path(dialog.GetPath()); // GTK's file dialog doesn't add the filter's extension, so it never asked about the file adding it names. - const char* extension = m_python ? ".py" : ".json"; - if (!boost::iequals(path.extension().string(), extension)) { - path += extension; + if (!is_replay_file(path)) { + path += ".json"; boost::system::error_code ec; if (fs::exists(path, ec)) { MessageDialog confirm(this, wxString::Format(_L("The file %s already exists.\nDo you want to replace it?"), from_path(path)), _L("Confirm Save As"), wxYES_NO | wxICON_WARNING); + confirm.SetName(Mcp::kHiddenFromAutomation); const int answer = confirm.ShowModal(); if (!m_alive->load() || answer != wxID_YES) return false; @@ -487,21 +541,10 @@ bool ScriptRunnerDialog::save(bool pick) } // Written beside the file, then renamed over it. Unlike write_file_atomically() nothing is ever written // in place, so a save that fails (a full disk, a folder that refuses new files) leaves the file as it was. - const std::string target = Mcp::path_to_utf8(path); - // A Python script goes back in the encoding it was read in. - std::string contents = m_text; - if (m_python) { - std::string error; - if (!encode_python_source(m_text, m_python_encoding, contents, error)) { - // TRN %1% is a file name, %2% the text encoding it is in (such as cp1252), %3% why the text doesn't fit it. - call_web_handler({{"command", "error"}, - {"message", format(_u8L("Can't save %1% in its encoding, %2%: %3%"), target, m_python_encoding, error)}}); - return false; - } - } - const std::string temp = target + ".saving"; + const std::string target = Mcp::path_to_utf8(path); + const std::string temp = target + ".saving"; boost::nowide::ofstream out(temp.c_str(), std::ios::binary | std::ios::trunc); - out << contents; + out << m_text; out.close(); const bool written = bool(out); if (!written || rename_file(temp, target)) { @@ -512,7 +555,7 @@ bool ScriptRunnerDialog::save(bool pick) call_web_handler({{"command", "error"}, {"message", format(_u8L("Can't save %1%."), target)}}); return false; } - // Saved somewhere new, the script is that file's: ${script_dir} and the output folder follow it. + // Saved somewhere new, the replay is that file's: ${script_dir} and the output folder follow it. const bool moved = path != m_file; m_file = path; m_edited = false; @@ -522,14 +565,16 @@ bool ScriptRunnerDialog::save(bool pick) // Asks whether to save an edited source before it is closed or replaced. False to keep it: the person // cancelled, or chose to save and nothing was saved. -bool ScriptRunnerDialog::confirm_unsaved() +bool ActionReplayDialog::confirm_unsaved() { if (!m_edited) return true; - const wxString question = m_file.empty() ? _L("Save this script?\nIf you don't, your changes are lost.") : - // TRN %1% is a script's file name. + const wxString question = m_file.empty() ? _L("Save this replay file?\nIf you don't, your changes are lost.") : + // TRN %1% is a replay file's name. format_wxstr(_L("Save the changes to %1%?\nIf you don't, your changes are lost."), from_path(m_file.filename())); - MessageDialog dialog(this, question, _L("Run Script"), wxYES_NO | wxCANCEL | wxICON_QUESTION); + MessageDialog dialog(this, question, _L("Action Replay"), wxYES_NO | wxCANCEL | wxICON_QUESTION); + // The person's own question: no auto-answer rule answers it. + dialog.SetName(Mcp::kHiddenFromAutomation); dialog.SetButtonLabel(wxID_YES, _L("Save")); dialog.SetButtonLabel(wxID_NO, _L("Don't save")); const int answer = dialog.ShowModal(); @@ -538,9 +583,9 @@ bool ScriptRunnerDialog::confirm_unsaved() return answer == wxID_YES ? save(false) : answer == wxID_NO; } -// A file's runs write next to it, into .out; a new script's into one folder of the session's +// A file's runs write next to it, into .out; a new replay's into one folder of the session's // output, named when first needed. -fs::path ScriptRunnerDialog::out_dir() const +fs::path ActionReplayDialog::out_dir() const { if (!m_file.empty()) { fs::path dir = m_file.parent_path() / m_file.stem(); @@ -552,7 +597,7 @@ fs::path ScriptRunnerDialog::out_dir() const return m_draft_out_dir; } -Mcp::ScriptContext ScriptRunnerDialog::context() const +Mcp::ScriptContext ActionReplayDialog::context() const { Mcp::ScriptContext ctx; ctx.out_dir = out_dir(); @@ -561,7 +606,7 @@ Mcp::ScriptContext ScriptRunnerDialog::context() const return ctx; } -json ScriptRunnerDialog::describe(const Mcp::Script& script) const +json ActionReplayDialog::describe(const Mcp::Script& script) const { Mcp::McpService* s = service(); // ${jobs.NAME} stays as written: a full run starts from no saved jobs and a single step uses the @@ -595,39 +640,21 @@ json ScriptRunnerDialog::describe(const Mcp::Script& script) const return steps; } -void ScriptRunnerDialog::parse(const nlohmann::json& payload) +void ActionReplayDialog::parse(const nlohmann::json& payload) { json reply{{"command", "parsed"}, {"seq", payload.value("seq", 0)}, {"ok", false}}; - if (m_python && !Mcp::python_scripts_allowed(*wxGetApp().app_config)) { - // The page keeps Run off while a script doesn't parse, and says why. - reply["error"] = _u8L("Python scripts are off. You can turn them on in Preferences > AI features > Python scripts."); - call_web_handler(reply); - return; - } - if (m_python) { - // Python is checked when it runs; the page shows it as one step that runs the whole file. - json step{{"index", 1}, {"tool", "run_python"}, {"title", _u8L("Run Python code")}, {"flags", json::array()}, - {"checks_result", false}, {"optional", false}, {"args", json::object()}, {"expect", json::object()}, - {"checks", json::array()}}; - reply.update({{"ok", true}, - {"name", Mcp::path_to_utf8(m_file.stem())}, - {"steps", json::array({std::move(step)})}, - {"count_text", _u8L("Python script")}}); - call_web_handler(reply); - return; - } try { Mcp::McpService* s = service(); std::string err; const auto script = Mcp::parse_script(m_text, err); if (s == nullptr) - reply["error"] = _u8L("Scripts can't run while OrcaSlicer is starting or closing."); + reply["error"] = _u8L("Replays can't run while OrcaSlicer is starting or closing."); else if (!script) reply["error"] = err; else { for (std::size_t i = 0; i < script->steps.size() && !reply.contains("error"); ++i) if (s->registry().lookup(script->steps[i].tool) == nullptr) - // TRN %1% is a step number, %2% the name of the tool the script asks for. + // TRN %1% is a step number, %2% the name of the tool the replay asks for. reply["error"] = format(_u8L("Step %1% uses a tool this version of OrcaSlicer doesn't have: %2%"), i + 1, script->steps[i].tool); if (!reply.contains("error")) { @@ -644,35 +671,31 @@ void ScriptRunnerDialog::parse(const nlohmann::json& payload) call_web_handler(reply); } -void ScriptRunnerDialog::refuse(const std::string& message, const std::string& detail) +void ActionReplayDialog::refuse(const std::string& message, const std::string& detail) { call_web_handler({{"command", "run_refused"}, {"message", message}, {"detail", detail}}); } -void ScriptRunnerDialog::run(const nlohmann::json& payload) +void ActionReplayDialog::run(const nlohmann::json& payload) { if (running()) return; Mcp::McpService* s = service(); if (s == nullptr || !s->ready()) { - refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); - return; - } - if (m_python) { - run_python(); + refuse(_u8L("Replays can't run while OrcaSlicer is starting or closing.")); return; } std::string err; auto script = Mcp::parse_script(m_text, err); if (!script) { - refuse(_u8L("The script could not run."), err); + refuse(_u8L("The replay could not run."), err); return; } std::optional only; if (payload.contains("step") && payload["step"].is_number_unsigned()) { only = payload["step"].get(); if (*only < 1 || *only > script->steps.size()) { - refuse(_u8L("The script could not run.")); + refuse(_u8L("The replay could not run.")); return; } } @@ -682,7 +705,7 @@ void ScriptRunnerDialog::run(const nlohmann::json& payload) ctx.jobs = json::object(); // The runner asks about unsaved changes only before replacements it can answer for (steps that - // check them themselves), or ones the script may answer the app's own question for. + // check them themselves), or ones the replay may answer the app's own question for. bool checked = false, app_asked = false, answers = false; for (std::size_t i = only ? *only - 1 : 0; i < (only ? *only : script->steps.size()); ++i) { const Mcp::StepDescription d = Mcp::describe_step(script->steps[i], *script, ctx); @@ -693,8 +716,9 @@ void ScriptRunnerDialog::run(const nlohmann::json& payload) bool discard = false; Plater* plater = wxGetApp().plater(); if (plater != nullptr && plater->is_project_dirty() && (checked || (app_asked && answers))) { - MessageDialog dialog(this, _L("This script replaces the current project, which has unsaved changes. Save them before running the script?"), - _L("Run Script"), wxYES_NO | wxCANCEL | wxICON_QUESTION); + MessageDialog dialog(this, _L("This replay replaces the current project, which has unsaved changes. Save them before replaying it?"), + _L("Action Replay"), wxYES_NO | wxCANCEL | wxICON_QUESTION); + dialog.SetName(Mcp::kHiddenFromAutomation); const int answer = dialog.ShowModal(); if (!m_alive->load()) return; @@ -714,7 +738,7 @@ void ScriptRunnerDialog::run(const nlohmann::json& payload) } } - // Steps act on the main window, and keys a script sends without a target go where the focus is. + // Steps act on the main window, and keys a replay sends without a target go where the focus is. if (MainFrame* frame = wxGetApp().mainframe) { frame->Raise(); if (plater != nullptr) @@ -750,7 +774,7 @@ void ScriptRunnerDialog::run(const nlohmann::json& payload) m_started = std::chrono::steady_clock::now(); m_run = s->start_script_run(std::move(*script), ctx, only, discard, std::move(events)); if (!m_run) { - refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); + refuse(_u8L("Replays can't run while OrcaSlicer is starting or closing.")); return; } #ifdef __APPLE__ @@ -767,7 +791,7 @@ void ScriptRunnerDialog::run(const nlohmann::json& payload) call_web_handler(started); } -json ScriptRunnerDialog::step_view(const json& entry) const +json ActionReplayDialog::step_view(const json& entry) const { const std::string tool = entry.value("tool", ""); json view{{"command", "step_finished"}, @@ -785,21 +809,21 @@ json ScriptRunnerDialog::step_view(const json& entry) const const int s = reason.value("seconds", 0); view["failure_text"] = format(_L_PLURAL("The step didn't finish within %1% second.", "The step didn't finish within %1% seconds.", s), s); } else if (kind == "expect") { - view["failure_text"] = _u8L("The step's result was not what the script expected."); + view["failure_text"] = _u8L("The step's result was not what the replay expected."); const std::string text = expect_text(reason); view["failure_detail"] = text.empty() ? entry.value("expect_failure", "") : text; } else if (kind == "expect_invalid") { - view["failure_text"] = _u8L("The script's check of this step's result isn't valid."); + view["failure_text"] = _u8L("The replay's check of this step's result isn't valid."); view["failure_detail"] = entry.value("expect_failure", ""); } else if (kind == "placeholder") - // TRN %1% is a placeholder such as ${vars.model} that the script uses. - view["failure_text"] = format(_u8L("The script refers to %1%, which has no value."), reason.value("text", "")); + // TRN %1% is a placeholder such as ${vars.model} that the replay uses. + view["failure_text"] = format(_u8L("The replay refers to %1%, which has no value."), reason.value("text", "")); else if (kind == "missing_job") { if (reason.contains("saved_by") && reason["saved_by"].is_number()) // TRN %1% is the number of the step that saves the job this step needs. view["failure_text"] = format(_u8L("This step needs the job saved by step %1%. Run that step first."), reason["saved_by"].get()); else - view["failure_text"] = _u8L("This step needs a job that no step of this script saves."); + view["failure_text"] = _u8L("This step needs a job that no step of this replay saves."); } else if (kind == "python") { const std::string status = reason.value("status", ""); view["failure_text"] = status == "cancelled" ? _u8L("The script was stopped.") : @@ -860,59 +884,11 @@ json ScriptRunnerDialog::step_view(const json& entry) const return view; } -void ScriptRunnerDialog::run_python() -{ - if (!Mcp::python_scripts_allowed(*wxGetApp().app_config)) { - refuse(_u8L("Python scripts are off. You can turn them on in Preferences > AI features > Python scripts.")); - return; - } - // The script acts on the main window, as a JSON script's steps do. - if (MainFrame* frame = wxGetApp().mainframe) - frame->Raise(); - - Mcp::ScriptRun::Events events; - auto alive = m_alive; - events.finished = [this, alive](const json& result, const json&) { - if (!alive->load()) - return; - // The run's outcome as the one step it is shown as. - json entry{{"index", 1}, {"tool", "run_python"}, {"duration_ms", - std::chrono::duration_cast(std::chrono::steady_clock::now() - m_started).count()}}; - const bool ok = !result.contains("error") && result.value("status", "") == "finished"; - entry["ok"] = ok; - if (result.contains("error")) - entry.update({{"error", result["error"]}, {"reason", {{"kind", "tool"}}}}); - else { - entry["result"] = result; - if (!ok) - entry.update({{"error", result.value("message", std::string())}, - {"reason", {{"kind", "python"}, {"status", result.value("status", "")}}}, - {"cancelled", result.value("status", "") == "cancelled"}}); - } - call_web_handler(step_view(entry)); - json script_result{{"passed", ok}, {"steps", json::array({entry})}}; - if (!ok) - script_result["failed_step"] = 1; - call_web_handler(finished_view(script_result)); - restore_z_order(); - }; - m_single = std::nullopt; - m_total = 1; - m_started = std::chrono::steady_clock::now(); - m_run = service()->start_python_run(m_text, m_file, std::move(events)); - if (!m_run) { - refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); - return; - } - call_web_handler({{"command", "run_started"}, {"total", 1}}); - call_web_handler({{"command", "step_started"}, {"index", 1}}); -} - -json ScriptRunnerDialog::finished_view(const json& result) const +json ActionReplayDialog::finished_view(const json& result) const { json view{{"command", "run_finished"}, {"single", m_single.has_value()}, {"out_dir", Mcp::path_to_utf8(out_dir())}}; if (result.contains("error")) { - view.update({{"passed", false}, {"outcome_kind", "fail"}, {"outcome_text", _u8L("The script could not run.")}, {"error_detail", value_text(result["error"])}}); + view.update({{"passed", false}, {"outcome_kind", "fail"}, {"outcome_text", _u8L("The replay could not run.")}, {"error_detail", value_text(result["error"])}}); return view; } const bool passed = result.value("passed", false); @@ -930,11 +906,11 @@ json ScriptRunnerDialog::finished_view(const json& result) const view["failed_step"] = failed; if (stopped) view.update({{"outcome_kind", "warn"}, - // TRN %1% is the step the run stopped at, %2% how many steps the script has. + // TRN %1% is the step the run stopped at, %2% how many steps the replay has. {"outcome_text", m_single ? _u8L("Stopped.") : format(_u8L("Stopped at step %1% of %2%"), failed, total)}}); else if (!passed) view.update({{"outcome_kind", "fail"}, - // TRN %1% is the step that failed, %2% how many steps the script has. + // TRN %1% is the step that failed, %2% how many steps the replay has. {"outcome_text", m_single ? _u8L("The step failed.") : format(_u8L("Failed at step %1% of %2%"), failed, total)}}); else if (nested_failed) view.update({{"outcome_kind", "warn"}, {"outcome_text", _u8L("Finished, but a nested script failed.")}}); @@ -949,11 +925,12 @@ json ScriptRunnerDialog::finished_view(const json& result) const return view; } -void ScriptRunnerDialog::on_close(wxCloseEvent& event) +void ActionReplayDialog::on_close(wxCloseEvent& event) { if (event.CanVeto()) { if (running()) { - MessageDialog dialog(this, _L("A script is running. Stop it and close this window?"), _L("Run Script"), wxYES_NO | wxICON_QUESTION); + MessageDialog dialog(this, _L("A replay is running. Stop it and close this window?"), _L("Action Replay"), wxYES_NO | wxICON_QUESTION); + dialog.SetName(Mcp::kHiddenFromAutomation); if (dialog.ShowModal() != wxID_YES) { event.Veto(); return; diff --git a/src/slic3r/GUI/ScriptRunnerDialog.hpp b/src/slic3r/GUI/ActionReplayDialog.hpp similarity index 54% rename from src/slic3r/GUI/ScriptRunnerDialog.hpp rename to src/slic3r/GUI/ActionReplayDialog.hpp index dabe156d9e..89076dded5 100644 --- a/src/slic3r/GUI/ScriptRunnerDialog.hpp +++ b/src/slic3r/GUI/ActionReplayDialog.hpp @@ -1,5 +1,6 @@ #pragma once +#include "CodeEditorWindow.hpp" #include "Widgets/WebViewHostDialog.hpp" #include @@ -10,12 +11,15 @@ #include #include #include +#include #include #include +#include #include class wxCloseEvent; +class wxWebViewEvent; class wxWindow; namespace Slic3r { namespace GUI { @@ -26,19 +30,28 @@ struct Script; struct ScriptContext; } // namespace Mcp -// The Run Script dialog: a person opens or writes an MCP script (orca_script), saves it, reads its -// steps and runs it, whole or one step at a time, watching each step's outcome. The page -// (resources/web/dialog/ScriptRunner) shows; this host parses, describes, words and runs, through the -// MCP service's script runner without opening its endpoint. Modeless, one at a time -// (MainFrame::show_script_runner), and invisible to the MCP GUI tools, so a script can't act on it. -class ScriptRunnerDialog : public WebViewHostDialog +// The Action Replay window: a person opens or writes a replay file (an orca_script, the JSON list of tool calls an +// agent session exports), saves it, reads its steps and replays it, whole or one step at a time, watching each step's +// outcome. The page (resources/web/dialog/ActionReplay) shows; this host parses, describes, words and runs, through the +// MCP service's script runner without opening its endpoint. A Python script opened or dropped here is offered to the Run +// Script panel instead. Modeless, one at a time (MainFrame::show_action_replay), and invisible to the MCP GUI tools, so +// a replay can't act on it. +class ActionReplayDialog : public WebViewHostDialog, public CodeEditorWindow { public: - explicit ScriptRunnerDialog(wxWindow* parent); - ~ScriptRunnerDialog() override; + explicit ActionReplayDialog(wxWindow* parent); + ~ActionReplayDialog() override; bool running() const; + // Reads a replay file into the editor. Callers ask about unsaved changes first. + void load_file(const boost::filesystem::path& path); + + bool owns_focus(const wxWindow* focus) const override; + void forward_action(const std::string& action) override; + wxWebView* web_view() const override { return browser(); } + const std::set& editor_keys() const override { return m_editor_keys; } + private: void on_script_message(const nlohmann::json& payload) override; nlohmann::json localized_strings() const override; @@ -46,11 +59,14 @@ private: void handle(const nlohmann::json& payload); void send_service_state(); void open_file(); + void on_navigating(wxWebViewEvent& event); + void dropped(const boost::filesystem::path& path); + // A Python script was picked or dropped: offers to open it in the Run Script panel. + void offer_run_script(const boost::filesystem::path& path); bool save(bool pick); bool confirm_unsaved(); void parse(const nlohmann::json& payload); void run(const nlohmann::json& payload); - void run_python(); void refuse(const std::string& message, const std::string& detail = {}); void on_close(wxCloseEvent& event); @@ -66,21 +82,20 @@ private: // a dialog that is gone by then. std::shared_ptr> m_alive = std::make_shared>(true); wxTimer m_ready_timer; + // The page's file, which its own loads navigate to; a navigation to any other file is a drop. + wxFileName m_page; + // The chords the page's editor binds, as it reported them. + std::set m_editor_keys; // The source: its text as the page last reported it, whether that differs from what was opened or - // saved last (for a new script, from the draft it started as), the file it was opened from or saved - // to (empty for a new script), and the output folder a new script's runs write to. + // saved last (for a new replay, from the draft it started as), the file it was opened from or saved + // to (empty for a new replay), and the output folder a new replay's runs write to. std::string m_text; bool m_edited = false; boost::filesystem::path m_file; mutable boost::filesystem::path m_draft_out_dir; nlohmann::json m_jobs = nlohmann::json::object(); // jobs earlier runs saved - // The source is a Python script (a .py file), run as one run_python step, not a JSON script. - bool m_python = false; - // The codec a .py was read in and is saved back in: its BOM's or declaration's, else UTF-8. - std::string m_python_encoding = "utf-8"; - std::shared_ptr m_run; std::optional m_single; std::size_t m_total = 0; diff --git a/src/slic3r/GUI/AuiMgr.cpp b/src/slic3r/GUI/AuiMgr.cpp index c4353a95f6..e27cbc339b 100644 --- a/src/slic3r/GUI/AuiMgr.cpp +++ b/src/slic3r/GUI/AuiMgr.cpp @@ -1,6 +1,7 @@ #include "AuiMgr.hpp" #include "GUI_App.hpp" +#include "Mcp/McpTypes.hpp" #ifdef __WXGTK__ #include "LinuxDisplayBackend.hpp" #endif @@ -78,7 +79,12 @@ wxAuiPaneInfo AuiMgr::sidebar_pane_info() wxAuiFloatingFrame* AuiMgr::CreateFloatingFrame(wxWindow* parent, const wxAuiPaneInfo& pane) { - return new FloatFrame(parent, this, pane); + auto* frame = new FloatFrame(parent, this, pane); + // A pane kept from the automation (the Run Script panel) floats in a window kept from it too, which captures then + // leave out as they leave out the person's own dialogs. + if (pane.window != nullptr && pane.window->GetName() == Mcp::kHiddenFromAutomation) + frame->SetName(Mcp::kHiddenFromAutomation); + return frame; } }} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/CodeEditorWindow.hpp b/src/slic3r/GUI/CodeEditorWindow.hpp new file mode 100644 index 0000000000..fc886aec18 --- /dev/null +++ b/src/slic3r/GUI/CodeEditorWindow.hpp @@ -0,0 +1,29 @@ +#pragma once + +#include +#include + +class wxWebView; +class wxWindow; + +namespace Slic3r { namespace GUI { + +// A window whose page has a code editor (the Run Script panel, Action Replay). While it has the focus, the main frame's +// File › Save Project, Save Project as and Edit menu items act on its editor, and its other shortcut menu items whose key +// the editor takes are disabled, so the key reaches the editor (MainFrame::focused_code_editor()). UI thread. +class CodeEditorWindow +{ +public: + virtual ~CodeEditorWindow() = default; + // Whether `focus` (wxWindow::FindFocus()), or the native focus inside the window's web view, is in this window. + virtual bool owns_focus(const wxWindow* focus) const = 0; + // Sends a menu's action to the page: "save", "save_as", "undo", "redo" or "select_all". + virtual void forward_action(const std::string& action) = 0; + // The page's web view, for the clipboard items; nullptr while there is none. + virtual wxWebView* web_view() const = 0; + // The chords the editor's own commands bind on this platform, in KeyChord::to_string()'s form, as the page reported + // them. + virtual const std::set& editor_keys() const = 0; +}; + +}} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/GUI_App.cpp b/src/slic3r/GUI/GUI_App.cpp index 4650d9a3d9..a528d14173 100644 --- a/src/slic3r/GUI/GUI_App.cpp +++ b/src/slic3r/GUI/GUI_App.cpp @@ -194,6 +194,7 @@ #include "3DScene.hpp" #include "MainFrame.hpp" #include "Plater.hpp" +#include "RunScriptPanel.hpp" #include "GLCanvas3D.hpp" #include "EncodedFilament.hpp" #include "GeneratedConfig.hpp" @@ -5116,6 +5117,8 @@ void GUI_App::recreate_GUI(const wxString &msg_name) m_is_recreating_gui = false; if (m_mcp) m_mcp->resume(); + if (m_run_script_panel) + m_run_script_panel->main_window_rebuilt(); BOOST_LOG_TRIVIAL(info) << __FUNCTION__ << "recreate_GUI exit"; } @@ -8578,8 +8581,17 @@ void GUI_App::stop_mcp_service() m_mcp->stop(); } +RunScriptPanel& GUI_App::run_script_panel() +{ + if (!m_run_script_panel) + m_run_script_panel = std::make_unique(); + return *m_run_script_panel; +} + void GUI_App::destroy_mcp_service() { + // The Run Script panel's session is a job of the service: it goes first. + m_run_script_panel.reset(); // Before wxApp::CleanUp(): a timer must not outlive the toolkit. m_mcp_takeover_timer.reset(); // Outside any event loop: the deleter waits for running calls, and leaks a service whose calls diff --git a/src/slic3r/GUI/GUI_App.hpp b/src/slic3r/GUI/GUI_App.hpp index bcdaa02140..c2bfabc444 100644 --- a/src/slic3r/GUI/GUI_App.hpp +++ b/src/slic3r/GUI/GUI_App.hpp @@ -100,6 +100,7 @@ class ObjectSettings; class ObjectList; class ObjectLayers; class Plater; +class RunScriptPanel; class ParamsPanel; class NotificationManager; class Downloader; @@ -386,6 +387,7 @@ private: wxString m_info_dialog_content; std::unique_ptr m_http_server; Mcp::McpServicePtr m_mcp; + std::unique_ptr m_run_script_panel; bool m_mcp_wanted = false; // the endpoint should be open: --mcp, the preference, or Preferences std::unique_ptr m_mcp_takeover_timer; // retries the port another window holds; created on first need bool m_show_gcode_window{true}; @@ -682,6 +684,10 @@ public: // line for the rest of the session: a serving endpoint reopens on it, and a later start opens on it. bool restart_mcp_endpoint(std::string* error = nullptr); Mcp::McpService* mcp_service() { return m_mcp.get(); } + // The Run Script panel's controller, built on first use and kept until the MCP service, whose job hosts its session, + // goes away. + RunScriptPanel& run_script_panel(); + RunScriptPanel* run_script_panel_if_built() { return m_run_script_panel.get(); } void on_show_check_privacy_dlg(int online_login = 0, const std::string& provider = ORCA_CLOUD_PROVIDER); void show_check_privacy_dlg(wxCommandEvent& evt); diff --git a/src/slic3r/GUI/MainFrame.cpp b/src/slic3r/GUI/MainFrame.cpp index 45cb95ffa9..f964445089 100644 --- a/src/slic3r/GUI/MainFrame.cpp +++ b/src/slic3r/GUI/MainFrame.cpp @@ -15,6 +15,7 @@ #include "libslic3r/Preset.hpp" #include #include +#include #include #include #include "slic3r/GUI/Project.hpp" @@ -86,7 +87,9 @@ #include "ParamsDialog.hpp" #include "PrintHostDialogs.hpp" #include "RecordingIndicator.hpp" -#include "ScriptRunnerDialog.hpp" +#include "ActionReplayDialog.hpp" +#include "RunScriptPanel.hpp" +#include "CodeEditorWindow.hpp" #include "NativeCommands.hpp" #include "libslic3r_version.h" #include "wxExtensions.hpp" @@ -712,6 +715,12 @@ DPIFrame(NULL, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, BORDERLESS_FRAME_ return wxGetApp().check_and_save_current_preset_changes(_L("Closing application"), _L("Closing Application while some presets are modified.")); }; + // The Run Script panel's unsaved script is asked about before the project. + if (RunScriptPanel* panel = wxGetApp().run_script_panel_if_built(); event.CanVeto() && panel != nullptr && !panel->confirm_close()) { + event.Veto(); + return; + } + // BBS: close save project int result; if (event.CanVeto() && ((result = m_plater->close_with_confirm(check)) == wxID_CANCEL)) { @@ -822,6 +831,16 @@ DPIFrame(NULL, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, BORDERLESS_FRAME_ } return;} #endif + // A key in the Run Script panel goes to its page, past the global shortcuts, apart from the toggle's. + if (focused_code_editor() != nullptr) { + const KeyChord chord = KeyChord::from_event(evt); + if (chord.valid() && chord == wxGetApp().shortcuts().binding(Shortcut::ToggleRunScript)) { + wxGetApp().run_script_panel().toggle(); + return; + } + evt.Skip(); + return; + } if (!handle_global_shortcut(KeyChord::from_event(evt))) evt.Skip(); }); @@ -917,6 +936,7 @@ bool MainFrame::handle_global_shortcut(const KeyChord& chord) wxPostEvent(m_plater, SimpleEvent(EVT_GLTOOLBAR_EXPORT_SLICED_FILE)); return false; case Shortcut::PrintHostQueue: m_printhost_queue_dlg->Show(); break; + case Shortcut::ToggleRunScript: wxGetApp().run_script_panel().toggle(); break; case Shortcut::SpeedDial: if (!wxGetApp().app_config->get_bool("enable_speed_dial") || (chord == KeyChord{ WXK_SPACE } && focus_keeps_space(wxWindow::FindFocus()))) return false; @@ -1356,6 +1376,8 @@ void MainFrame::shutdown() if (ProjectPanel* project = ProjectPanel::if_built()) project->shutdown(); m_plugin_pages.shutdown(); + if (RunScriptPanel* panel = wxGetApp().run_script_panel_if_built()) + panel->main_window_closing(); if (m_plater != nullptr) m_plater->remove_dock_panes(); #ifdef SLIC3R_CAD @@ -2930,6 +2952,69 @@ void MainFrame::update_shortcut_labels() { for (const ShortcutMenuItem& entry : m_shortcut_menu_items) entry.item->SetItemLabel(shortcut_label(entry.label, entry.shortcut, entry.accelerator)); + if (RunScriptPanel* panel = wxGetApp().run_script_panel_if_built()) + panel->shortcuts_changed(); +} + +CodeEditorWindow* MainFrame::focused_code_editor() const +{ + const wxWindow* focus = wxWindow::FindFocus(); + if (RunScriptPanel* panel = wxGetApp().run_script_panel_if_built(); panel != nullptr && panel->owns_focus(focus)) + return panel; + if (auto* replay = dynamic_cast(m_action_replay.get()); replay != nullptr && replay->owns_focus(focus)) + return replay; + return nullptr; +} + +bool MainFrame::forward_to_editor(const char* action) +{ + CodeEditorWindow* editor = focused_code_editor(); + if (editor == nullptr) + return false; + editor->forward_action(action); + return true; +} + +bool MainFrame::editor_clipboard(char command) +{ + CodeEditorWindow* editor = focused_code_editor(); + if (editor == nullptr) + return false; + // Through the web view, whose clipboard events the editor takes. + if (wxWebView* web = editor->web_view()) { + if (command == 'x') + web->Cut(); + else if (command == 'c') + web->Copy(); + else + web->Paste(); + } + return true; +} + +// While a code editor has the focus, a shortcut menu item whose key the editor takes is disabled, so the key reaches the +// editor: a chord the page reported its editor binds, or a key with no modifier other than Shift. Save, the Edit items the +// editor takes over and File › Run Script stay. The chords are compared, so this follows a rebinding. +void MainFrame::bind_code_editor_menu_rule() +{ + static const std::set kept{Shortcut::SaveProject, Shortcut::SaveProjectAs, Shortcut::Undo, Shortcut::Redo, + Shortcut::Cut, Shortcut::Copy, Shortcut::Paste, Shortcut::SelectAll, + Shortcut::ToggleRunScript}; + for (const ShortcutMenuItem& entry : m_shortcut_menu_items) { + if (kept.count(entry.shortcut) != 0) + continue; + // Bound after the item's own handler, so it runs first; an item it leaves alone goes on to that handler. + Bind(wxEVT_UPDATE_UI, [this, shortcut = entry.shortcut](wxUpdateUIEvent& evt) { + const CodeEditorWindow* editor = focused_code_editor(); + const KeyChord chord = wxGetApp().shortcuts().binding(shortcut); + if (editor != nullptr && chord.valid() && + ((chord.modifiers & ~wxMOD_SHIFT) == 0 || editor->editor_keys().count(chord.to_string()) != 0)) { + evt.Enable(false); + return; + } + evt.Skip(); + }, entry.item->GetId()); + } } wxMenu* MainFrame::generate_help_menu() @@ -3119,22 +3204,22 @@ void MainFrame::init_menubar_as_editor() // BBS: close save project #ifndef __APPLE__ append_shortcut_item(fileMenu, Shortcut::SaveProject, true, _L("Save Project"), _L("Save current project to file"), - [this](wxCommandEvent&) { if (m_plater) m_plater->save_project(); }, "menu_save", nullptr, - [this](){return m_plater != nullptr && can_save(); }, this); + [this](wxCommandEvent&) { if (!forward_to_editor("save") && m_plater) m_plater->save_project(); }, "menu_save", nullptr, + [this](){return focused_code_editor() != nullptr || (m_plater != nullptr && can_save()); }, this); #else append_shortcut_item(fileMenu, Shortcut::SaveProject, true, _L("Save Project"), _L("Save current project to file"), - [this](wxCommandEvent&) { if (m_plater) m_plater->save_project(); }, "", nullptr, - [this](){return m_plater != nullptr && can_save(); }, this); + [this](wxCommandEvent&) { if (!forward_to_editor("save") && m_plater) m_plater->save_project(); }, "", nullptr, + [this](){return focused_code_editor() != nullptr || (m_plater != nullptr && can_save()); }, this); #endif #ifndef __APPLE__ append_shortcut_item(fileMenu, Shortcut::SaveProjectAs, true, _L("Save Project as") + dots, _L("Save current project as"), - [this](wxCommandEvent&) { if (m_plater) m_plater->save_project(true); }, "menu_save", nullptr, - [this](){return m_plater != nullptr && can_save_as(); }, this); + [this](wxCommandEvent&) { if (!forward_to_editor("save_as") && m_plater) m_plater->save_project(true); }, "menu_save", nullptr, + [this](){return focused_code_editor() != nullptr || (m_plater != nullptr && can_save_as()); }, this); #else append_shortcut_item(fileMenu, Shortcut::SaveProjectAs, true, _L("Save Project as") + dots, _L("Save current project as"), - [this](wxCommandEvent&) { if (m_plater) m_plater->save_project(true); }, "", nullptr, - [this](){return m_plater != nullptr && can_save_as(); }, this); + [this](wxCommandEvent&) { if (!forward_to_editor("save_as") && m_plater) m_plater->save_project(true); }, "", nullptr, + [this](){return focused_code_editor() != nullptr || (m_plater != nullptr && can_save_as()); }, this); #endif // BBS: publish @@ -3219,8 +3304,11 @@ 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); + append_shortcut_check_item(fileMenu, Shortcut::ToggleRunScript, _L("Run Script"), _L("Show or hide the Run Script panel"), + [](wxCommandEvent&) { wxGetApp().run_script_panel().toggle(); }, []() { return true; }, + []() { RunScriptPanel* panel = wxGetApp().run_script_panel_if_built(); return panel != nullptr && panel->on_screen(); }); + append_menu_item(fileMenu, wxID_ANY, _L("Action Replay") + dots, _L("Open a replay file and replay its steps"), + [this](wxCommandEvent&) { show_action_replay(); }, "", nullptr, []() { return true; }, this); fileMenu->AppendSeparator(); @@ -3253,11 +3341,15 @@ void MainFrame::init_menubar_as_editor() // BBS undo append_shortcut_item(editMenu, Shortcut::Undo, true, _L("Undo"), _L("Undo"), [this](wxCommandEvent&) { + if (forward_to_editor("undo")) + return; #ifdef SLIC3R_CAD if (DesignPanel* dp = shown_design_panel()) { dp->menu_undo_redo(false); return; } #endif m_plater->undo(); }, "menu_undo", nullptr, [this](){ + if (focused_code_editor() != nullptr) + return true; #ifdef SLIC3R_CAD if (DesignPanel* dp = shown_design_panel()) return dp->menu_can_undo_redo(false); #endif @@ -3265,11 +3357,15 @@ void MainFrame::init_menubar_as_editor() // BBS redo append_shortcut_item(editMenu, Shortcut::Redo, true, _L("Redo"), _L("Redo"), [this](wxCommandEvent&) { + if (forward_to_editor("redo")) + return; #ifdef SLIC3R_CAD if (DesignPanel* dp = shown_design_panel()) { dp->menu_undo_redo(true); return; } #endif m_plater->redo(); }, "menu_redo", nullptr, [this](){ + if (focused_code_editor() != nullptr) + return true; #ifdef SLIC3R_CAD if (DesignPanel* dp = shown_design_panel()) return dp->menu_can_undo_redo(true); #endif @@ -3277,16 +3373,16 @@ void MainFrame::init_menubar_as_editor() editMenu->AppendSeparator(); // BBS Cut TODO append_shortcut_item(editMenu, Shortcut::Cut, true, _L("Cut"), - _L("Cut selection to clipboard"), [this](wxCommandEvent&) {m_plater->cut_selection_to_clipboard(); }, - "menu_cut", nullptr, [this]() {return m_plater->can_copy_to_clipboard(); }, this); + _L("Cut selection to clipboard"), [this](wxCommandEvent&) { if (!editor_clipboard('x')) m_plater->cut_selection_to_clipboard(); }, + "menu_cut", nullptr, [this]() {return focused_code_editor() != nullptr || m_plater->can_copy_to_clipboard(); }, this); // BBS Copy append_shortcut_item(editMenu, Shortcut::Copy, true, _L("Copy"), - _L("Copy selection to clipboard"), [this](wxCommandEvent&) { m_plater->copy_selection_to_clipboard(); }, - "menu_copy", nullptr, [this](){return m_plater->can_copy_to_clipboard(); }, this); + _L("Copy selection to clipboard"), [this](wxCommandEvent&) { if (!editor_clipboard('c')) m_plater->copy_selection_to_clipboard(); }, + "menu_copy", nullptr, [this](){return focused_code_editor() != nullptr || m_plater->can_copy_to_clipboard(); }, this); // BBS Paste append_shortcut_item(editMenu, Shortcut::Paste, true, _L("Paste"), - _L("Paste clipboard"), [this](wxCommandEvent&) { m_plater->paste_from_clipboard(); }, - "menu_paste", nullptr, [this](){return m_plater->can_paste_from_clipboard(); }, this); + _L("Paste clipboard"), [this](wxCommandEvent&) { if (!editor_clipboard('v')) m_plater->paste_from_clipboard(); }, + "menu_paste", nullptr, [this](){return focused_code_editor() != nullptr || m_plater->can_paste_from_clipboard(); }, this); // BBS Delete selected append_shortcut_item(editMenu, Shortcut::DeleteSelected, true, _L("Delete Selected"), _L("Deletes the current selection"),[this](wxCommandEvent&) { m_plater->remove_selected(); }, @@ -3313,6 +3409,8 @@ void MainFrame::init_menubar_as_editor() // BBS undo append_shortcut_item(editMenu, Shortcut::Undo, false, _L("Undo"), _L("Undo"), [this, handle_key_event](wxCommandEvent&) { + if (forward_to_editor("undo")) + return; wxKeyEvent e; e.SetEventType(wxEVT_KEY_DOWN); e.SetControlDown(true); @@ -3325,6 +3423,8 @@ void MainFrame::init_menubar_as_editor() #endif m_plater->undo(); }, "", nullptr, [this](){ + if (focused_code_editor() != nullptr) + return true; #ifdef SLIC3R_CAD if (DesignPanel* dp = shown_design_panel()) return dp->menu_can_undo_redo(false); #endif @@ -3332,6 +3432,8 @@ void MainFrame::init_menubar_as_editor() // BBS redo append_shortcut_item(editMenu, Shortcut::Redo, false, _L("Redo"), _L("Redo"), [this, handle_key_event](wxCommandEvent&) { + if (forward_to_editor("redo")) + return; wxKeyEvent e; e.SetEventType(wxEVT_KEY_DOWN); e.SetControlDown(true); @@ -3344,6 +3446,8 @@ void MainFrame::init_menubar_as_editor() #endif m_plater->redo(); }, "", nullptr, [this](){ + if (focused_code_editor() != nullptr) + return true; #ifdef SLIC3R_CAD if (DesignPanel* dp = shown_design_panel()) return dp->menu_can_undo_redo(true); #endif @@ -3359,8 +3463,9 @@ void MainFrame::init_menubar_as_editor() if (handle_key_event(e)) { return; } - m_plater->cut_selection_to_clipboard(); }, - "", nullptr, [this]() {return m_plater->can_copy_to_clipboard(); }, this); + if (!editor_clipboard('x')) + m_plater->cut_selection_to_clipboard(); }, + "", nullptr, [this]() {return focused_code_editor() != nullptr || m_plater->can_copy_to_clipboard(); }, this); // BBS Copy append_shortcut_item(editMenu, Shortcut::Copy, false, _L("Copy"), _L("Copy selection to clipboard"), [this, handle_key_event](wxCommandEvent&) { @@ -3371,8 +3476,9 @@ void MainFrame::init_menubar_as_editor() if (handle_key_event(e)) { return; } - m_plater->copy_selection_to_clipboard(); }, - "", nullptr, [this](){return m_plater->can_copy_to_clipboard(); }, this); + if (!editor_clipboard('c')) + m_plater->copy_selection_to_clipboard(); }, + "", nullptr, [this](){return focused_code_editor() != nullptr || m_plater->can_copy_to_clipboard(); }, this); // BBS Paste append_shortcut_item(editMenu, Shortcut::Paste, false, _L("Paste"), _L("Paste clipboard"), [this, handle_key_event](wxCommandEvent&) { @@ -3383,8 +3489,9 @@ void MainFrame::init_menubar_as_editor() if (handle_key_event(e)) { return; } - m_plater->paste_from_clipboard(); }, - "", nullptr, [this](){return m_plater->can_paste_from_clipboard(); }, this); + if (!editor_clipboard('v')) + m_plater->paste_from_clipboard(); }, + "", nullptr, [this](){return focused_code_editor() != nullptr || m_plater->can_paste_from_clipboard(); }, this); #if 0 // BBS Delete selected append_shortcut_item(editMenu, Shortcut::DeleteSelected, true, _L("Delete Selected"), @@ -3439,8 +3546,9 @@ void MainFrame::init_menubar_as_editor() if (handle_key_event(e)) { return; } - m_plater->select_all(); }, - "", nullptr, [this](){return can_select(); }, this); + if (!forward_to_editor("select_all")) + m_plater->select_all(); }, + "", nullptr, [this](){return focused_code_editor() != nullptr || can_select(); }, this); // BBS Deslect All append_menu_item(editMenu, wxID_ANY, _L("Deselect All") + sep + _L_CONTEXT("Esc", "Keyboard Shortcut"), _L("Deselects all objects"), [this, handle_key_event](wxCommandEvent&) { @@ -3913,6 +4021,7 @@ void MainFrame::init_menubar_as_editor() }, wxID_EXIT); } #endif // __APPLE__ + bind_code_editor_menu_rule(); } void MainFrame::set_max_recent_count(int max) @@ -4050,12 +4159,12 @@ struct ConfigsOverwriteConfirmDialog : MessageDialog } }; -void MainFrame::show_script_runner() +void MainFrame::show_action_replay() { - if (!m_script_runner) - m_script_runner = new ScriptRunnerDialog(this); - m_script_runner->Show(); - m_script_runner->Raise(); + if (!m_action_replay) + m_action_replay = new ActionReplayDialog(this); + m_action_replay->Show(); + m_action_replay->Raise(); } void MainFrame::export_config() diff --git a/src/slic3r/GUI/MainFrame.hpp b/src/slic3r/GUI/MainFrame.hpp index 35adebcab4..cb8b9f1eea 100644 --- a/src/slic3r/GUI/MainFrame.hpp +++ b/src/slic3r/GUI/MainFrame.hpp @@ -27,11 +27,13 @@ #include #include +#include #include #include "GUI_Utils.hpp" #include "Event.hpp" #include "IdleScheduler.hpp" +#include "wxExtensions.hpp" #include @@ -74,6 +76,7 @@ namespace GUI { class Tab; +class CodeEditorWindow; class PrintHostQueueDialog; class DiffPresetDialog; class ParamsPanel; @@ -282,8 +285,23 @@ class MainFrame : public DPIFrame m_shortcut_menu_items.push_back({ item, shortcut, label, accelerator }); return item; } + // A check item showing the shortcut's key: display-only on macOS, a live accelerator elsewhere. + wxMenuItem* append_shortcut_check_item(wxMenu* menu, Shortcut shortcut, const wxString& label, const wxString& description, + std::function cb, std::function enable, + std::function check) + { + wxMenuItem* item = append_menu_check_item(menu, wxID_ANY, shortcut_label(label, shortcut, false), description, std::move(cb), this, + std::move(enable), std::move(check), this); + m_shortcut_menu_items.push_back({ item, shortcut, label, false }); + return item; + } // Runs the Global shortcut bound to chord; false when the focused control should see the key as well. bool handle_global_shortcut(const KeyChord& chord); + // Sends a Save or Edit menu action to the code editor that has the focus; false when none has it. + bool forward_to_editor(const char* action); + // Cut ('x'), copy ('c') or paste ('v') in the code editor that has the focus; false when none has it. + bool editor_clipboard(char command); + void bind_code_editor_menu_rule(); void add_common_view_menu_items(wxMenu* view_menu, std::function can_change_view); wxMenu* generate_help_menu(); @@ -423,8 +441,10 @@ 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(); + // Shows the Action Replay window, creating it the first time and raising the open one after. + void show_action_replay(); + // The code editor window (the Run Script panel, Action Replay) that has the focus, or nullptr. + CodeEditorWindow* focused_code_editor() const; // 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 @@ -521,7 +541,7 @@ public: 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; + wxWeakRef m_action_replay; // 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 9d23a7c352..9970924532 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.cpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.cpp @@ -92,6 +92,40 @@ std::vector JobRegistry::running_owned_by(const std::string& owner) return out; } +LineageNode::LineageNode(JobRegistry& jobs, std::string tool, std::string parent) + : m_jobs(jobs), m_tool(std::move(tool)), m_parent(std::move(parent)), m_id(make()) +{} + +LineageNode::~LineageNode() +{ + std::lock_guard lock(m_mutex); + m_jobs.finish(m_id, ToolResult::ok()); +} + +std::string LineageNode::make() const +{ + const std::string id = m_jobs.create(m_tool, m_parent); + m_jobs.set_idle(id); + return id; +} + +std::string LineageNode::id() const +{ + std::lock_guard lock(m_mutex); + return m_id; +} + +void LineageNode::renew() +{ + std::string fresh = make(); + std::string old; + { + std::lock_guard lock(m_mutex); + old = std::exchange(m_id, std::move(fresh)); + } + m_jobs.finish(old, ToolResult::ok()); +} + void require_own_job(const ToolContext& ctx, const JobRegistry& jobs, const std::string& job, const char* what) { if (!ctx.caller_plugin().empty() && jobs.owner(job) != ctx.caller_plugin()) diff --git a/src/slic3r/GUI/Mcp/JobRegistry.hpp b/src/slic3r/GUI/Mcp/JobRegistry.hpp index f8a80b67f7..e4479c8382 100644 --- a/src/slic3r/GUI/Mcp/JobRegistry.hpp +++ b/src/slic3r/GUI/Mcp/JobRegistry.hpp @@ -123,6 +123,33 @@ private: bool m_woken = false; }; +// A parent for calls, not a call itself: a running job under `parent`, set idle, so a stop asked for it reaches every +// call made under it, inline ones included, without stopping `parent`. renew() finishes it and makes a fresh one, whose +// calls run again; the destructor finishes it, and nothing else does. A Run Script session's calls hang under one. +// Any thread. +class LineageNode +{ +public: + // Throws ToolFailure as JobRegistry::create() does. + LineageNode(JobRegistry& jobs, std::string tool, std::string parent); + ~LineageNode(); + LineageNode(const LineageNode&) = delete; + LineageNode& operator=(const LineageNode&) = delete; + + std::string id() const; + // Throws ToolFailure as JobRegistry::create() does, keeping the current node. + void renew(); + +private: + std::string make() const; + + JobRegistry& m_jobs; + const std::string m_tool; + const std::string m_parent; + mutable std::mutex m_mutex; + std::string m_id; +}; + // Refuses a plugin's call (ToolContext::caller_plugin()) about a job its own calls did not start: the // session tools act only on a plugin's own jobs. `what` names the action, as in "waits for". void require_own_job(const ToolContext& ctx, const JobRegistry& jobs, const std::string& job, const char* what); diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index 94c5c30086..9249c1e5de 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -101,17 +101,8 @@ public: ToolResult call_child(const std::string& tool, const nlohmann::json& raw_args) override { - std::shared_ptr def = m_core.registry().lookup(tool); - if (def == nullptr) - return ToolResult::error("Unknown tool: " + tool); - nlohmann::json args = raw_args; - normalize_arguments(def->input_schema, args); - if (std::string err = validate_arguments(def->input_schema, args); !err.empty()) - return ToolResult::error("Invalid arguments: " + err); - if (std::string err = resolve_api_call(m_core.registry(), def, args); !err.empty()) - return ToolResult::error(err); // An inline caller has no job of its own; its children are rooted at its parent. - return m_core.call_child(*def, args, m_job.empty() ? m_parent : m_job, m_plugin); + return m_core.call_child_named(tool, raw_args, m_job.empty() ? m_parent : m_job, m_plugin); } const std::string& caller_plugin() const override { return m_plugin; } @@ -215,6 +206,21 @@ ToolResult McpCore::call_child(const ToolDef& def, const nlohmann::json& args, c return run(def, args, parent_job, plugin); } +ToolResult McpCore::call_child_named(const std::string& tool, const nlohmann::json& raw_args, const std::string& parent_job, + const std::string& plugin) +{ + std::shared_ptr def = m_registry.lookup(tool); + if (def == nullptr) + return ToolResult::error("Unknown tool: " + tool); + nlohmann::json args = raw_args; + normalize_arguments(def->input_schema, args); + if (std::string err = validate_arguments(def->input_schema, args); !err.empty()) + return ToolResult::error("Invalid arguments: " + err); + if (std::string err = resolve_api_call(m_registry, def, args); !err.empty()) + return ToolResult::error(err); + return call_child(*def, args, parent_job, plugin); +} + ToolResult McpCore::call_plugin(const ToolDef& def, const nlohmann::json& args, const std::string& plugin_key) { return run(def, args, {}, plugin_key); diff --git a/src/slic3r/GUI/Mcp/McpCore.hpp b/src/slic3r/GUI/Mcp/McpCore.hpp index e0f233fe12..a0ec8ddef8 100644 --- a/src/slic3r/GUI/Mcp/McpCore.hpp +++ b/src/slic3r/GUI/Mcp/McpCore.hpp @@ -80,6 +80,10 @@ public: // `wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out. ToolResult call_child(const ToolDef& def, const nlohmann::json& args, const std::string& parent_job, const std::string& plugin = {}); + // A child call by the tool's name, as ToolContext::call_child() makes one, under any parent: the tool is looked up + // and its arguments normalized, validated and resolved first. Any thread. + ToolResult call_child_named(const std::string& tool, const nlohmann::json& args, const std::string& parent_job, + const std::string& plugin = {}); // A call a plugin's code makes through orca.host.tools: run as a client's call is, its job owned by // `plugin_key` (JobRegistry::owner, ToolContext::caller_plugin), and never journaled, since the journal // is the agent's session. diff --git a/src/slic3r/GUI/Mcp/McpScriptRun.cpp b/src/slic3r/GUI/Mcp/McpScriptRun.cpp index bd62dea876..f0b4264e7b 100644 --- a/src/slic3r/GUI/Mcp/McpScriptRun.cpp +++ b/src/slic3r/GUI/Mcp/McpScriptRun.cpp @@ -1,11 +1,6 @@ #include "McpScriptRun.hpp" -#include "JobRegistry.hpp" -#include "McpCore.hpp" #include "McpService.hpp" -#include "slic3r/GUI/GUI_App.hpp" -#include "slic3r/GUI/Plater.hpp" - #include #include #include @@ -45,12 +40,8 @@ void ScriptRun::stop() if (job.empty() || m_service.stopping()) return; m_service.request_stop(job); - // The step's own operation stops too, as the cancel tool stops it: a background job through the - // worker, a slice or export through the plater. - for (const std::string& op : m_service.jobs().running_operations()) - if (m_service.jobs().lineage(op).count(job) != 0 && !m_service.core().cancel_worker(op)) - if (Plater* plater = wxGetApp().plater()) - plater->cancel_slicing(); + // The step's own operation stops too, as the cancel tool stops it. + m_service.cancel_operations_of(job); } void ScriptRun::detach() { m_detached = true; } diff --git a/src/slic3r/GUI/Mcp/McpService.cpp b/src/slic3r/GUI/Mcp/McpService.cpp index 2655b47558..3356144472 100644 --- a/src/slic3r/GUI/Mcp/McpService.cpp +++ b/src/slic3r/GUI/Mcp/McpService.cpp @@ -25,6 +25,7 @@ #include "slic3r/GUI/Plater.hpp" #include "slic3r/plugin/PluginManager.hpp" #include "slic3r/plugin/PythonScriptRunner.hpp" +#include "slic3r/plugin/PythonSession.hpp" #include "libslic3r/AppConfig.hpp" #include "libslic3r/Utils.hpp" @@ -457,7 +458,7 @@ bool McpService::drain(std::chrono::milliseconds timeout) return m_core->drain(std::max(left, std::chrono::milliseconds(0))); } -std::string McpService::set_auto_answer(std::vector rules, const std::vector& ancestry) +AutoAnswerSet McpService::set_auto_answer(std::vector rules, const std::vector& ancestry) { // A plugin's call is owned by its plugin's scope when no script in its chain is nearer. const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); @@ -465,15 +466,18 @@ std::string McpService::set_auto_answer(std::vector rules, const // The nearest running script in the caller's job chain owns the rules. for (const std::string& job : ancestry) if (auto it = m_script_rule_layers.find(job); it != m_script_rule_layers.end()) { - if (!rules.empty()) - it->second.push_back(m_modals->push_rules(std::move(rules))); - return "script"; + const bool paused = m_paused_scopes.count(job) != 0; + if (rules.empty()) + return {"script", 0, paused}; + it->second.push_back(m_modals->push_rules(std::move(rules), paused)); + return {"script", it->second.back(), paused}; } if (!plugin.empty()) { if (auto it = m_script_rule_layers.find(plugin_scope_key(plugin)); it != m_script_rule_layers.end()) { - if (!rules.empty()) - it->second.push_back(m_modals->push_rules(std::move(rules))); - return "plugin"; + if (rules.empty()) + return {"plugin", 0, false}; + it->second.push_back(m_modals->push_rules(std::move(rules))); + return {"plugin", it->second.back(), false}; } if (m_unloaded_plugins.count(plugin) != 0) throw ToolFailure("The plugin that made this call has been unloaded; its rules were not applied"); @@ -484,7 +488,7 @@ std::string McpService::set_auto_answer(std::vector rules, const if (m_session_rule_layer != 0) m_modals->pop_rules(m_session_rule_layer); m_session_rule_layer = rules.empty() ? 0 : m_modals->push_rules(std::move(rules)); - return "session"; + return {"session", m_session_rule_layer, false}; } void McpService::begin_script_scope(const std::string& job) @@ -508,10 +512,31 @@ void McpService::end_script_scope(const std::string& job, bool wait_recording) for (int layer : it->second) m_modals->pop_rules(layer); m_script_rule_layers.erase(it); + m_paused_scopes.erase(job); } // A recording the script started ends with it, its file closed before the script's call returns. if (m_recorder) m_recorder->end_owned_by(job, "script_ended", wait_recording); + release_script_presses(job); +} + +void McpService::set_script_scope_paused(const std::string& job, bool paused) +{ + std::lock_guard lock(m_rules_mutex); + auto it = m_script_rule_layers.find(job); + if (it == m_script_rule_layers.end()) + return; + if (paused) + m_paused_scopes.insert(job); + else + m_paused_scopes.erase(job); + if (m_modals) + for (int layer : it->second) + m_modals->set_paused(layer, paused); +} + +void McpService::release_script_presses(const std::string& job) +{ // Found again on the UI thread: the service may be gone by the time the closure runs. if (m_dispatcher && !m_stopping) m_dispatcher->post([job] { @@ -522,6 +547,14 @@ void McpService::end_script_scope(const std::string& job, bool wait_recording) }); } +void McpService::cancel_operations_of(const std::string& job) +{ + for (const std::string& op : m_jobs.running_operations()) + if (m_jobs.lineage(op).count(job) != 0 && !m_core->cancel_worker(op)) + if (Plater* plater = wxGetApp().plater()) + plater->cancel_slicing(); +} + std::string McpService::script_owner(const std::vector& ancestry) const { const std::string plugin = ancestry.empty() ? std::string() : m_jobs.owner(ancestry.front()); @@ -960,10 +993,11 @@ std::shared_ptr McpService::start_script_run(Script script, ScriptCon return run; } -std::shared_ptr McpService::start_python_run(std::string code, const fs::path& file, ScriptRun::Events events) +std::shared_ptr McpService::start_python_session(std::shared_ptr session, const fs::path& file, + ScriptRun::Events events) { const ToolDef* run_python = started() ? m_registry.find("run_python") : nullptr; - if (run_python == nullptr || m_stopping) + if (run_python == nullptr || m_stopping || !session) return nullptr; { // Threads whose run has ended are done or about to be; joining them keeps the list short. @@ -978,26 +1012,38 @@ std::shared_ptr McpService::start_python_run(std::string code, const it = m_run_threads.erase(it); } } - auto run = std::make_shared(*this, std::move(events)); + auto run = std::make_shared(*this, std::move(events)); + auto hosted = std::make_shared>(false); + auto filename = file.empty() ? std::string("") : path_to_utf8(file); // run_python's properties, outside the session journal, as a person's run. ToolDef def = as_person(*run_python); def.journal = false; - def.handler = [run, handler = def.handler](const json& args, ToolContext& ctx) { + def.handler = [this, run, session, hosted, filename](const json&, ToolContext& ctx) { run->set_job(ctx.job_id()); - return handler(args, ctx); + hosted->store(true); + // A handler that refuses never hosts the session: it ends here all the same. + struct Ended + { + PythonSession& session; + ~Ended() + { + if (!session.ended()) + session.host_returned(); + } + } ended{*session}; + return run_python_session_job(*this, ctx, *session, filename); }; - // No time limit: the person has the dialog's Stop. - json args{{"code", std::move(code)}, {"timeout_s", 0}}; - if (!file.empty()) - args["filename"] = path_to_utf8(file); std::lock_guard lock(m_runs_mutex); - m_run_threads.push_back({std::thread([this, run, def, args] { - const std::optional r = call_to_end(def, args); + m_run_threads.push_back({std::thread([this, run, def, session, hosted] { + const std::optional r = call_to_end(def, json::object()); run->mark_ended(); - if (!r || m_stopping) + // Refused before its handler ran: the session was never hosted. + if (r && !hosted->load()) + session->host_returned(); + if (!r || m_stopping || !r->is_error) return; - run->post_finished(r->is_error ? json{{"error", r->message}} : r->data, json()); + run->post_finished(json{{"error", r->message}}, json()); }), run}); return run; diff --git a/src/slic3r/GUI/Mcp/McpService.hpp b/src/slic3r/GUI/Mcp/McpService.hpp index e034cfa15a..5871aefa54 100644 --- a/src/slic3r/GUI/Mcp/McpService.hpp +++ b/src/slic3r/GUI/Mcp/McpService.hpp @@ -30,6 +30,10 @@ class wxTimer; +namespace Slic3r { +class PythonSession; +} + namespace Slic3r { namespace GUI { namespace Mcp { class McpHttpServer; @@ -41,6 +45,16 @@ class WebPresses; struct AutoAnswerRule; struct RequestGate; +// Whose a dialog_auto_answer call's rules are ("script", "plugin" or "session"), the tracker layer they went into (0 for +// none), and whether they start paused: a Run Script session's rules registered between its works answer nothing, an open +// dialog included, until its next work. +struct AutoAnswerSet +{ + std::string scope; + int layer = 0; + bool paused = false; +}; + // The MCP server inside the running app: owns the tool catalog, the UI invoker, jobs, the session // journal, the modal-dialog tracker and the HTTP endpoint, and runs a --mcp-script once the app is // ready. Created by GUI_App; started, suspended and stopped on the UI thread. @@ -119,13 +133,22 @@ public: // running script in `ancestry`, the caller's job chain, nearest first) last until that script // ends; a client's rules replace the ones it registered before, and end when the endpoint // closes: with no endpoint open (the server turned off meanwhile), a client's rules are refused. - // Returns "script" or "session". Any thread. - std::string set_auto_answer(std::vector rules, const std::vector& ancestry); + // A script scope that is paused (set_script_scope_paused()) gets them paused. Any thread. + AutoAnswerSet set_auto_answer(std::vector rules, const std::vector& ancestry); // run_script brackets its steps with these. A mouse press the script left held is released // when it ends, and so is a recording it started; `wait_recording` waits for that recording's file, // unless the run already did. void begin_script_scope(const std::string& job); void end_script_scope(const std::string& job, bool wait_recording = true); + // Pauses or resumes every rule layer of `job`'s scope (ModalTracker::set_paused); a layer the scope adds while it + // is paused starts paused. Any thread. + void set_script_scope_paused(const std::string& job, bool paused); + // Releases the mouse presses `job`'s calls left held, on widgets and pages, as the end of its scope does. Any + // thread. + void release_script_presses(const std::string& job); + // Cancels the operations whose lineage holds `job`, as the cancel tool does: a background job through the worker, + // a slice or an export through the plater. UI thread. + void cancel_operations_of(const std::string& job); // The job of the nearest running script in `ancestry`, else the scope of the plugin whose call it is, // or "" for a client's own call. Any thread. std::string script_owner(const std::vector& ancestry) const; @@ -157,7 +180,7 @@ public: // GUI_Run after the event loop ends; wx ignores OnExit()'s return value. static int script_exit_code(); - // Runs a script for the script runner dialog: an unjournaled mutate job, as run_script runs one, + // Runs a replay for the Action Replay window: an unjournaled mutate job, as run_script runs one, // whose steps report through `events`. A thread the service owns follows the job to its end, past a // running or blocked_by_dialog reply, and posts `finished`; stop() joins it. `only_step` runs one // step (no result.json). `discard_authorized`: the user chose not to save before a run that @@ -165,11 +188,13 @@ public: // the service is not started or is stopping. UI thread. std::shared_ptr start_script_run(Script script, ScriptContext sctx, std::optional only_step, bool discard_authorized, ScriptRun::Events events); - // Runs a Python script for the script runner dialog: run_python as an unjournaled job of a person's run, - // whose result `events.finished` gets as for a JSON script (no steps are reported). `file` names the - // script in its tracebacks; empty for an unsaved one. nullptr when the service is not started or is - // stopping. UI thread. - std::shared_ptr start_python_run(std::string code, const boost::filesystem::path& file, ScriptRun::Events events); + // Hosts the Run Script panel's `session` as an unjournaled person's run_python job (run_python_session_job()) on a + // thread the service owns, which stop() joins and stop_script_runs() stops. `file` is the session's file; empty + // for an unsaved script. `events.finished` is posted only for a job refused before its handler ran or a handler + // that refused (Python scripts off), as {"error": message}; the session's end is PythonSession::ended(), which a + // refused job sets too. nullptr when the service is not started or is stopping. UI thread. + std::shared_ptr start_python_session(std::shared_ptr session, const boost::filesystem::path& file, + ScriptRun::Events events); // True when a run a person started (the script runner dialog, --mcp-script) is in `lineage`: a // run_python there runs as the person's script, not an agent's. Any thread. bool person_run(const std::set& lineage) const; @@ -233,6 +258,7 @@ private: mutable std::mutex m_rules_mutex; std::map> m_script_rule_layers; // running script job -> layers + std::set m_paused_scopes; // jobs whose layers are paused int m_session_rule_layer = 0; bool m_endpoint_open = false; diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 1079ddf13e..908a5b593d 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -23,6 +23,7 @@ namespace Slic3r { class AppConfig; +class PythonSession; struct Calib_Params; class ConfigOptionDef; class DynamicPrintConfig; @@ -42,6 +43,7 @@ class Plater; namespace Mcp { class McpService; +class ToolRegistry; struct Script; struct ScriptContext; @@ -162,6 +164,17 @@ nlohmann::json rank_python_api(const nlohmann::json& reference, const std::strin // Takes the GIL, as python_api_reference() does. bool python_has_numpy(); +// The Run Script panel's session as the calling job, a person's run_python job: refused while Python scripts are off. +// The job is idle for `wait {for: "idle"}`, and owns what the session's tool calls leave behind (auto-answer rules, a +// recording, a held press) until the session ends, with its rules paused between works and its presses released as each +// work ends. The calls hang under a lineage node of the job, which a stop cancels, inline calls included, and which the +// next work replaces. Hosts `session` (host_python_session()) under `filename` until it ends; a job cancel ends it. +ToolResult run_python_session_job(McpService& service, ToolContext& ctx, PythonSession& session, const std::string& filename); + +// What an editor suggests for each tool: [{name, title (translated), args: {name: {type?, enum?}}}]. The argument +// descriptions are written for agents, in English, and stay out. +nlohmann::json editor_tool_catalog(const ToolRegistry& registry); + // ---- settings scopes (McpToolsConfig.cpp) ---------------------------------------------------- // The keys the object scope (or, with `is_part`, the volume scope) takes: those of `offered` diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index 3cb51de432..618764e757 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -28,6 +28,25 @@ namespace Slic3r { namespace GUI { namespace Mcp { using nlohmann::json; +json editor_tool_catalog(const ToolRegistry& registry) +{ + json tools = json::array(); + for (const ToolDef& def : registry.tools()) { + json args = json::object(); + const auto properties = def.input_schema.find("properties"); + if (properties != def.input_schema.end()) + for (const auto& [name, schema] : properties->items()) { + json arg = json::object(); + for (const char* key : {"type", "enum"}) + if (schema.contains(key)) + arg[key] = schema[key]; + args[name] = std::move(arg); + } + tools.push_back({{"name", def.name}, {"title", _u8L(def.title.c_str())}, {"args", std::move(args)}}); + } + return tools; +} + namespace { // How many of each other catalog's matches api_describe shows beside the tools; its own search lists diff --git a/src/slic3r/GUI/Mcp/McpToolsPython.cpp b/src/slic3r/GUI/Mcp/McpToolsPython.cpp index 1874222fd7..90234343c8 100644 --- a/src/slic3r/GUI/Mcp/McpToolsPython.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsPython.cpp @@ -1,6 +1,8 @@ // run_python and python_api: Python scripts against orca.host, the plugin API, and the orca package's // reference. +#include "JobRegistry.hpp" +#include "McpCore.hpp" #include "McpService.hpp" #include "McpTools.hpp" #include "McpTypes.hpp" @@ -11,6 +13,7 @@ #include "slic3r/plugin/PluginAuditManager.hpp" #include "slic3r/plugin/PythonInterpreter.hpp" #include "slic3r/plugin/PythonScriptRunner.hpp" +#include "slic3r/plugin/PythonSession.hpp" #include "slic3r/plugin/host/PluginHostTools.hpp" #include @@ -19,6 +22,7 @@ #include #include +#include #include #include #include @@ -50,6 +54,48 @@ private: ToolContext& m_ctx; }; +// The Run Script panel's session's orca.host.tools calls: child calls under a lineage node of the session's job, so a +// stop cancels every call in flight, inline ones (wait) included, without stopping the session, and the next work's +// calls run under a fresh node. +class SessionBridge final : public ToolBridge +{ +public: + SessionBridge(McpService& service, const std::string& session_job) + : m_service(service), m_node(service.jobs(), "run_python", session_job) + {} + json call(const std::string& tool, const json& args) override + { + ToolResult r = m_service.core().call_child_named(tool, args, m_node.id()); + if (r.is_error) + throw ToolCallError(r.message, r.data); + return r.data; + } + // A stop or time-out, from the session's watcher: the node's calls are cancelled, and its operations, as the + // cancel tool cancels them. + void stop_calls() + { + const std::string node = m_node.id(); + m_stopped = true; + m_service.request_stop(node); + // Found again on the UI thread: the service may be gone by the time the closure runs. + m_service.post_ui([node] { + if (McpService* service = wxGetApp().mcp_service()) + service->cancel_operations_of(node); + }); + } + // As a work starts: after a stop its calls get a node no stop was asked for. + void renew_after_stop() + { + if (m_stopped.exchange(false)) + m_node.renew(); + } + +private: + McpService& m_service; + LineageNode m_node; + std::atomic m_stopped{false}; +}; + // python_api_reference()'s walk over the orca package. constexpr const char* kReferenceSource = R"PY( import inspect, re, types @@ -200,6 +246,44 @@ bool python_has_numpy() } } +ToolResult run_python_session_job(McpService& service, ToolContext& ctx, PythonSession& session, const std::string& filename) +{ + const bool allowed = ctx.observe_ui([] { return json(python_scripts_allowed(*wxGetApp().app_config)); }).get(); + if (!allowed) + throw ToolFailure("Python scripts are off. A person can allow them in Preferences > AI features > Python scripts."); + + const std::string job = ctx.job_id(); + // The session waits for the person between works: `wait {for: "idle"}` counts only the calls it makes. + service.jobs().set_idle(job); + // What its calls leave behind is the session's, as a run's is; its rules act only while a work runs. + service.begin_script_scope(job); + service.set_script_scope_paused(job, true); + struct ScopeEnd + { + McpService& service; + std::string job; + ~ScopeEnd() { service.end_script_scope(job); } + } scope_end{service, job}; + + SessionBridge bridge(service, job); + ScopedToolBridge bound(bridge); + PythonSessionRequest request; + request.identity = kScriptIdentityPerson; + request.filename = filename; + request.cancelled = [&ctx] { return ctx.cancelled(); }; + request.stop_calls = [&bridge] { bridge.stop_calls(); }; + request.work_started = [&service, &bridge, job] { + bridge.renew_after_stop(); + service.set_script_scope_paused(job, false); + }; + request.work_ended = [&service, job] { + service.set_script_scope_paused(job, true); + service.release_script_presses(job); + }; + host_python_session(request, session); + return ToolResult::ok({{"status", "ended"}}); +} + void register_python_tools(McpService& service) { ToolRegistry& reg = service.registry(); diff --git a/src/slic3r/GUI/Mcp/McpToolsUi.cpp b/src/slic3r/GUI/Mcp/McpToolsUi.cpp index 8c9f55e267..8e27dd5b8a 100644 --- a/src/slic3r/GUI/Mcp/McpToolsUi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsUi.cpp @@ -189,7 +189,7 @@ std::vector visible_webviews() } // A dialog is its parent's child too; it is visited once, as a top-level window. for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && !skipped_by_walks(child)) visit(child); }; if (wxGetApp().mainframe != nullptr) @@ -1680,9 +1680,10 @@ void register_ui_tools(McpService& service) for (const json& r : args["rules"]) rules.push_back(make_rule(r["match"].get(), r["button"].get())); const std::vector registered = rules; - const std::string scope = service.set_auto_answer(std::move(rules), service.jobs().ancestry(ctx.job_id())); - json out{{"scope", scope}, {"rules", service.modals().rules_json()}}; - json answered = ctx.run_ui([&]() -> json { + const AutoAnswerSet set = service.set_auto_answer(std::move(rules), service.jobs().ancestry(ctx.job_id())); + json out{{"scope", set.scope}, {"rules", service.modals().rules_json()}}; + // Paused rules leave the dialog that is open now to the person, as they leave the ones that open later. + json answered = set.paused ? json() : ctx.run_ui([&]() -> json { wxDialog* top = service.modals().top(); // A message box is pressed as dialog_respond presses it; a picker can't be. const bool native = top != nullptr && is_native_dialog(top); @@ -1692,10 +1693,13 @@ void register_ui_tools(McpService& service) const json info = describe_dialog(top, &text); for (const AutoAnswerRule& rule : registered) if (rule_matches(rule, info["title"].get(), info["message"].get(), text)) { + // The rule may have been paused (a Run Script work ended) or replaced since it was registered. + if (!service.modals().rule_in_force(set.layer, rule.pattern, rule.button)) + return json(); // A web dialog is answered on its page, as ModalTracker::Enter() does. if (info.value("web", false) && native_dialog_button(top, rule.button) == wxID_NONE) { const int standard = standard_dialog_button(rule.button); - start_web_answer(service.modals(), top, 0, rule.pattern, rule.button, + start_web_answer(service.modals(), top, set.layer, rule.pattern, rule.button, standard == wxID_CANCEL || standard == wxID_CLOSE ? standard : int(wxID_NONE)); return {{"dialog", info["title"]}, {"button", rule.button}, {"web", "answering on its page"}}; } @@ -1709,7 +1713,7 @@ void register_ui_tools(McpService& service) // As before any other press, the presses ui_mouse downs left on pages end first. service.modals().before_press(); if (press_dialog_button(top, id) != DialogPress::Failed) { - service.modals().count_use(0, rule.pattern, rule.button); + service.modals().count_use(set.layer, rule.pattern, rule.button); return {{"dialog", info["title"]}, {"button", rule.button}}; } } diff --git a/src/slic3r/GUI/Mcp/ModalTracker.cpp b/src/slic3r/GUI/Mcp/ModalTracker.cpp index 1e9a082386..1bba6c04cb 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.cpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.cpp @@ -911,11 +911,13 @@ bool ModalTracker::is_open(std::uint64_t serial) const ModalTracker::~ModalTracker() { Unregister(); } -int ModalTracker::push_rules(std::vector rules) +int ModalTracker::push_rules(std::vector rules, bool paused) { std::lock_guard lock(m_mutex); const int layer = m_next_layer++; m_layers.emplace_back(layer, std::move(rules)); + if (paused) + m_paused_layers.insert(layer); return layer; } @@ -923,6 +925,16 @@ void ModalTracker::pop_rules(int layer) { std::lock_guard lock(m_mutex); m_layers.erase(std::remove_if(m_layers.begin(), m_layers.end(), [layer](const auto& l) { return l.first == layer; }), m_layers.end()); + m_paused_layers.erase(layer); +} + +void ModalTracker::set_paused(int layer, bool paused) +{ + std::lock_guard lock(m_mutex); + if (!paused) + m_paused_layers.erase(layer); + else if (std::any_of(m_layers.begin(), m_layers.end(), [layer](const auto& l) { return l.first == layer; })) + m_paused_layers.insert(layer); } json ModalTracker::rules_json() const @@ -930,8 +942,12 @@ json ModalTracker::rules_json() const std::lock_guard lock(m_mutex); json out = json::array(); for (const auto& [layer, rules] : m_layers) - for (const AutoAnswerRule& r : rules) - out.push_back({{"layer", layer}, {"match", r.pattern}, {"button", r.button}, {"uses", r.uses}}); + for (const AutoAnswerRule& r : rules) { + json rule{{"layer", layer}, {"match", r.pattern}, {"button", r.button}, {"uses", r.uses}}; + if (m_paused_layers.count(layer) != 0) + rule["paused"] = true; + out.push_back(std::move(rule)); + } return out; } @@ -939,7 +955,7 @@ bool ModalTracker::rule_in_force(int layer, const std::string& pattern, const st { std::lock_guard lock(m_mutex); for (const auto& [id, rules] : m_layers) - if (layer == 0 || id == layer) + if ((layer == 0 || id == layer) && m_paused_layers.count(id) == 0) for (const AutoAnswerRule& r : rules) if (r.pattern == pattern && r.button == button) return true; @@ -1037,7 +1053,9 @@ int ModalTracker::Enter(wxDialog* dialog) std::optional> web_rule, wx_rule; const int answer = [&] { std::lock_guard lock(m_mutex); - for (auto layer = m_layers.rbegin(); layer != m_layers.rend(); ++layer) + for (auto layer = m_layers.rbegin(); layer != m_layers.rend(); ++layer) { + if (m_paused_layers.count(layer->first) != 0) + continue; for (AutoAnswerRule& rule : layer->second) if (rule_matches(rule, title, message, text)) { if (web && native_dialog_button(dialog, rule.button) == wxID_NONE) { @@ -1058,6 +1076,7 @@ int ModalTracker::Enter(wxDialog* dialog) return id; } } + } return int(wxID_NONE); }(); // A native dialog has no handlers to run: ShowModal() returns the id without showing it. @@ -1076,9 +1095,10 @@ int ModalTracker::Enter(wxDialog* dialog) // dialog_respond. The tracker lives as long as the app. if (wx_rule) dialog->CallAfter([this, dialog, answer, title, rule = *wx_rule] { - if (top() != dialog) - return; const auto& [layer, pattern, button] = rule; + // The rule may have been paused (a Run Script work ended) or dropped since the press was queued. + if (top() != dialog || !rule_in_force(layer, pattern, button)) + return; before_press(); if (const DialogPress press = press_dialog_button(dialog, answer); press == DialogPress::Disabled || press == DialogPress::Hidden) { BOOST_LOG_TRIVIAL(info) << "MCP: auto-answer rule \"" << pattern << "\" for dialog \"" << title << "\": its " diff --git a/src/slic3r/GUI/Mcp/ModalTracker.hpp b/src/slic3r/GUI/Mcp/ModalTracker.hpp index efabbf0f7f..b3f4e63fd6 100644 --- a/src/slic3r/GUI/Mcp/ModalTracker.hpp +++ b/src/slic3r/GUI/Mcp/ModalTracker.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -57,12 +58,16 @@ public: bool is_open(std::uint64_t serial) const; // Rule sets are layered so a script can add its own and drop exactly those when it ends. - // Returns the layer id to pass to pop_rules(). Any thread. - int push_rules(std::vector rules); + // Returns the layer id to pass to pop_rules(). A layer pushed `paused` is never in force until resumed (set_paused()). + // Any thread. + int push_rules(std::vector rules, bool paused = false); void pop_rules(int layer); + // A paused layer answers no dialog, and rule_in_force() is false for it, until it is resumed: a Run Script session's + // rules act only while its work runs. Any thread. + void set_paused(int layer, bool paused); nlohmann::json rules_json() const; - // For a web dialog's answer, which ends later (start_web_answer()): whether layer `layer` still - // has the rule, and counting its use. Any thread. + // For an answer that runs or ends later (a queued press, a web dialog's start_web_answer()): whether + // layer `layer` (0: any) still has the rule and is not paused. Any thread. bool rule_in_force(int layer, const std::string& pattern, const std::string& button) const; void count_use(int layer, const std::string& pattern, const std::string& button); @@ -97,6 +102,7 @@ private: mutable std::mutex m_mutex; nlohmann::json m_snapshot = nlohmann::json::array(); std::vector>> m_layers; + std::set m_paused_layers; int m_next_layer = 1; }; diff --git a/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp b/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp index bec861e984..0668b400f6 100644 --- a/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp +++ b/src/slic3r/GUI/Mcp/PythonScriptsDialog.cpp @@ -8,6 +8,7 @@ #include "slic3r/GUI/GUI_Utils.hpp" #include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/MainFrame.hpp" +#include "slic3r/GUI/RunScriptPanel.hpp" #include "slic3r/GUI/Widgets/CheckBox.hpp" #include "slic3r/GUI/Widgets/DialogButtons.hpp" #include "slic3r/GUI/Widgets/Label.hpp" @@ -40,7 +41,7 @@ public: auto* sizer = new wxBoxSizer(wxVERTICAL); m_about = new Label(this, Label::Body_13, - _L("When this is on, you can run Python scripts (.py files) in the Run Script dialog and with " + _L("When this is on, you can run Python scripts (.py files) in the Run Script panel and with " "--mcp-script, and AI agents connected to the MCP server can send Python code to run inside " "OrcaSlicer.")); m_about->Wrap(FromDIP(kTextWidth)); @@ -104,6 +105,8 @@ bool show_python_scripts_dialog(wxWindow* parent) if (allow == python_scripts_allowed(config)) return false; config.set_bool(kPythonScriptsKey, allow); + if (RunScriptPanel* panel = wxGetApp().run_script_panel_if_built()) + panel->python_setting_changed(); return true; } diff --git a/src/slic3r/GUI/Mcp/UiInspector.cpp b/src/slic3r/GUI/Mcp/UiInspector.cpp index 13410fddc9..cc40ef3063 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.cpp +++ b/src/slic3r/GUI/Mcp/UiInspector.cpp @@ -1246,10 +1246,18 @@ wxWindow* owning_window(wxWindow* w) return top; } +bool skipped_by_walks(const wxWindow* w) { return w->GetName() == kHiddenFromAutomation; } + bool hidden_from_automation(const wxWindow* w) { - const wxWindow* top = owning_window(const_cast(w)); - return top != nullptr && top->GetName() == kHiddenFromAutomation; + for (const wxWindow* at = w; at != nullptr; at = at->GetParent()) { + if (at->GetName() == kHiddenFromAutomation) + return true; + // A popup belongs to the window that opened it; any other top-level window ends the chain. + if (at->IsTopLevel() && dynamic_cast(at) == nullptr) + return false; + } + return false; } std::string within_of(wxWindow* w) @@ -1263,7 +1271,7 @@ std::vector popups_of(wxWindow* top) std::vector out; std::function visit = [&](wxWindow* w) { for (wxWindow* child : w->GetChildren()) { - if (dynamic_cast(child) != nullptr || !child->IsShown()) + if (dynamic_cast(child) != nullptr || !child->IsShown() || skipped_by_walks(child)) continue; if (dynamic_cast(child) != nullptr) out.push_back(child); @@ -1886,7 +1894,7 @@ std::vector> find_rows(const std::vectorGetChildren()) - if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr && !skipped_by_walks(child)) visit(child); }; for (wxWindow* root : roots) { @@ -2451,7 +2459,7 @@ void UiInspector::walk(wxWindow* w, int depth, std::vector& nodes, std:: return; // Popups are listed after the window they belong to (snapshot()). for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr && !skipped_by_walks(child)) walk(child, child_depth, nodes, omitted, o); } @@ -2529,7 +2537,7 @@ std::vector UiInspector::snapshot_pages(const SnapshotOptions& o, st return; } for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && dynamic_cast(child) == nullptr && !skipped_by_walks(child)) visit(child); }; if (o.include_web) @@ -2549,7 +2557,7 @@ std::vector UiInspector::web_views(const std::string& within) return; } for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && !skipped_by_walks(child)) visit(child); }; for (wxTopLevelWindow* tlw : top_level_windows(m_service)) @@ -2773,7 +2781,7 @@ std::vector UiInspector::match_windows(const json& locator) return; // not the inner text control too } for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && !skipped_by_walks(child)) visit(child); }; for (wxTopLevelWindow* tlw : top_level_windows(m_service)) @@ -2846,7 +2854,7 @@ std::vector> UiInspector::match_tabs(const json& if (into_u8(book->GetPageText(i)) == text) out.emplace_back(book, int(i)); for (wxWindow* child : w->GetChildren()) - if (dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && !skipped_by_walks(child)) visit(child); }; for (wxTopLevelWindow* tlw : top_level_windows(m_service)) diff --git a/src/slic3r/GUI/Mcp/UiInspector.hpp b/src/slic3r/GUI/Mcp/UiInspector.hpp index 863ba85357..efe00b7d62 100644 --- a/src/slic3r/GUI/Mcp/UiInspector.hpp +++ b/src/slic3r/GUI/Mcp/UiInspector.hpp @@ -274,8 +274,12 @@ private: // button's menu), the one the popup opened from, which on every port is the popup's parent. Guards and // `within` judge popup widgets by it. wxWindow* owning_window(wxWindow* w); -// `w` is, or is inside, a top-level window named kHiddenFromAutomation. +// `w`, one of its parents up to its top-level window, or that window (through a popup, the window the popup belongs +// to) is named kHiddenFromAutomation: a dialog of the person's own, or a pane inside the main window such as the Run +// Script panel. bool hidden_from_automation(const wxWindow* w); +// A child walk leaves out a window named kHiddenFromAutomation and everything inside it. +bool skipped_by_walks(const wxWindow* w); // "No modal dialog is open", naming the shown windows that don't block (the Plugins dialog) and how // to reach them, since an agent sees them as dialogs too. UI thread only. std::string no_modal_dialog(McpService& service); diff --git a/src/slic3r/GUI/Mcp/WebPages.cpp b/src/slic3r/GUI/Mcp/WebPages.cpp index facfdef676..3329eb61b4 100644 --- a/src/slic3r/GUI/Mcp/WebPages.cpp +++ b/src/slic3r/GUI/Mcp/WebPages.cpp @@ -2,6 +2,7 @@ #include "McpTypes.hpp" #include "ModalTracker.hpp" +#include "UiInspector.hpp" #include "UiRefs.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/KeyChord.hpp" @@ -504,7 +505,7 @@ wxWebView* web_view_in(wxWindow* window, bool shown) if (auto* web = dynamic_cast(window)) return web; for (wxWindow* child : window->GetChildren()) - if (dynamic_cast(child) == nullptr) + if (dynamic_cast(child) == nullptr && !skipped_by_walks(child)) if (wxWebView* web = web_view_in(child, shown)) return web; return nullptr; diff --git a/src/slic3r/GUI/NativeCommands.cpp b/src/slic3r/GUI/NativeCommands.cpp index f125f1236c..34a5770d88 100644 --- a/src/slic3r/GUI/NativeCommands.cpp +++ b/src/slic3r/GUI/NativeCommands.cpp @@ -18,6 +18,7 @@ #include "Jobs/Job.hpp" #include "Jobs/Worker.hpp" #include "MainFrame.hpp" +#include "RunScriptPanel.hpp" #include "ObjectDataViewModel.hpp" #include "NetworkTestDialog.hpp" #include "Plater.hpp" @@ -496,8 +497,10 @@ void describe_commands(std::vector& commands) {"new_project", "Start a new, empty project (asks first if the current one has unsaved changes)."}, {"undo", "Undo the last change to the project."}, {"redo", "Redo the last undone change."}, - {"open_script_runner", "Open the Run Script dialog, where a person opens or pastes an orca_script, reads its steps and runs " - "them. Agents run scripts with the run_script tool instead."}, + {"open_script_runner", "Open the Action Replay window, where a person opens a replay file (an orca_script), reads its steps " + "and replays them. Agents run replays with the run_script tool instead."}, + {"toggle_run_script", "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents " + "run Python with the run_python tool instead."}, {"take_screenshot", "Save a PNG of the main window in the folder Start Recording saves in (the person's Downloads unless " "they chose another) and show the person a notification naming it; the reply has its path. Agents use " "the screenshot tool, which returns the image."}, @@ -762,9 +765,14 @@ std::vector build_command_catalog() plater->redo(); return AppActionRunResult{AppActionRunResult::Level::Success}; }); - add_with_icon("open_script_runner", L("Run Script"), L("Commands"), "media_play", [](const std::string&) { + add_with_icon("toggle_run_script", L("Run Script"), L("Commands"), "media_play", [](const std::string&) { + if (wxGetApp().mainframe != nullptr) + wxGetApp().run_script_panel().toggle(); + return AppActionRunResult{AppActionRunResult::Level::Success}; + }); + add_with_icon("open_script_runner", L("Action Replay"), L("Commands"), "loop", [](const std::string&) { if (MainFrame* mf = wxGetApp().mainframe) - mf->show_script_runner(); + mf->show_action_replay(); return AppActionRunResult{AppActionRunResult::Level::Success}; }); add_with_icon("open_preferences", L("Preferences"), L("Commands"), "cog", [](const std::string& param) { diff --git a/src/slic3r/GUI/Plater.cpp b/src/slic3r/GUI/Plater.cpp index 63048f20fd..9982212372 100644 --- a/src/slic3r/GUI/Plater.cpp +++ b/src/slic3r/GUI/Plater.cpp @@ -7222,10 +7222,11 @@ struct Plater::priv // GUI elements AuiMgr m_aui_mgr; // Live dock panes. `on_close` runs when the user closes one from its close button; `shown` is - // what the owner asked for. + // what the owner asked for; `hide_on_close` keeps the pane's window when it is closed. struct DockPane { std::function on_close; + bool hide_on_close{false}; bool shown{true}; }; std::map m_dock_panes; @@ -7447,7 +7448,7 @@ struct Plater::priv void reset_window_layout(); Sidebar::DockingState get_sidebar_docking_state(); void add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock, - const wxSize& size, std::function on_close); + const wxSize& size, std::function on_close, bool hide_on_close); void remove_dock_pane(wxWindow* window); void show_dock_pane(wxWindow* window, bool show); bool dock_pane_visible(const DockPane& dock_pane, const wxAuiPaneInfo& pane) const; @@ -8034,7 +8035,18 @@ Plater::priv::priv(Plater *q, MainFrame *main_frame) q->Bind(wxEVT_AUI_PANE_CLOSE, [this](wxAuiManagerEvent& evt) { const wxAuiPaneInfo* pane = evt.GetPane(); auto it = pane != nullptr ? m_dock_panes.find(pane->window) : m_dock_panes.end(); - if (it != m_dock_panes.end()) { + if (it != m_dock_panes.end() && it->second.hide_on_close) { + // Hidden as its owner hides it, after the manager is done with the close; the window stays. + evt.Veto(); + this->q->CallAfter([this, window = pane->window] { + const auto kept = m_dock_panes.find(window); + if (kept == m_dock_panes.end()) + return; + show_dock_pane(window, false); + if (kept->second.on_close) + kept->second.on_close(); + }); + } else if (it != m_dock_panes.end()) { const std::function on_close = std::move(it->second.on_close); m_dock_panes.erase(it); if (on_close) @@ -8736,7 +8748,7 @@ bool Plater::priv::dock_pane_visible(const DockPane& dock_pane, const wxAuiPaneI } void Plater::priv::add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock, - const wxSize& size, std::function on_close) + const wxSize& size, std::function on_close, bool hide_on_close) { const wxString base_name = wxString::FromUTF8(name); wxString unique_name = base_name; @@ -8746,7 +8758,7 @@ void Plater::priv::add_dock_pane(wxWindow* window, const std::string& name, cons // A restored layout below already holds pixels. const wxSize pixels = q->FromDIP(size); wxAuiPaneInfo info; - info.Name(unique_name).Caption(caption).BestSize(pixels).FloatingSize(pixels).DestroyOnClose(true); + info.Name(unique_name).Caption(caption).BestSize(pixels).FloatingSize(pixels).DestroyOnClose(!hide_on_close); if (dock == "left") info.Left(); else if (dock == "bottom") @@ -8760,7 +8772,7 @@ void Plater::priv::add_dock_pane(wxWindow* window, const std::string& name, cons const std::string saved = aui_pane_layout_entry(wxGetApp().app_config->get("window_layout"), unique_name.utf8_string()); if (!saved.empty()) { m_aui_mgr.LoadPaneInfo(wxString::FromUTF8(saved), info); - info.Caption(caption).DestroyOnClose(true).Show(); + info.Caption(caption).DestroyOnClose(!hide_on_close).Show(); } // Floating is disabled on Wayland. @@ -8770,7 +8782,7 @@ void Plater::priv::add_dock_pane(wxWindow* window, const std::string& name, cons info.Right(); } - const DockPane& dock_pane = m_dock_panes[window] = DockPane{std::move(on_close)}; + const DockPane& dock_pane = m_dock_panes[window] = DockPane{std::move(on_close), hide_on_close}; info.Show(dock_pane_visible(dock_pane, info)); m_aui_mgr.AddPane(window, info); @@ -11218,12 +11230,18 @@ void Plater::priv::reset(bool apply_presets_change, bool reload_presets) sidebar.Show(); } auto layout = m_aui_mgr.SavePerspective(); - // The UV editor pane is only built when first used; keep its saved place from an earlier session. - if (!uv_editor.built()) { - const std::string kept = aui_pane_layout_entry(wxGetApp().app_config->get("window_layout"), "uv_editor"); + // The UV editor pane and the Run Script panel are only built when first used; keep their saved places from an + // earlier session. + const std::string saved = wxGetApp().app_config->get("window_layout"); + const auto keep = [&](const char* name, bool built) { + if (built) + return; + const std::string kept = aui_pane_layout_entry(saved, name); if (!kept.empty()) layout += wxString::FromUTF8(kept) + "|"; - } + }; + keep("uv_editor", uv_editor.built()); + keep("run_script", m_aui_mgr.GetPane("run_script").IsOk()); wxGetApp().app_config->set("window_layout", layout.utf8_string()); } } @@ -19620,9 +19638,9 @@ void Plater::reset_window_layout() } void Plater::add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock, - const wxSize& size, std::function on_close) + const wxSize& size, std::function on_close, bool hide_on_close) { - p->add_dock_pane(window, name, caption, dock, size, std::move(on_close)); + p->add_dock_pane(window, name, caption, dock, size, std::move(on_close), hide_on_close); } void Plater::remove_dock_pane(wxWindow* window) { p->remove_dock_pane(window); } void Plater::remove_dock_panes() diff --git a/src/slic3r/GUI/Plater.hpp b/src/slic3r/GUI/Plater.hpp index e230d948bc..4cb1145553 100644 --- a/src/slic3r/GUI/Plater.hpp +++ b/src/slic3r/GUI/Plater.hpp @@ -536,9 +536,10 @@ public: // Dock panes sit alongside the sidebar; `window` must be a child of the Plater. `dock` is // "left", "right", "bottom" or "float", and `size` is in DIPs. A pane closed from its own close - // button is destroyed after on_close runs; remove_dock_pane() destroys it without calling on_close. + // button is destroyed after on_close runs, or, with `hide_on_close`, hidden as show_dock_pane(window, + // false) hides it, keeping the window; remove_dock_pane() destroys it without calling on_close. void add_dock_pane(wxWindow* window, const std::string& name, const wxString& caption, const std::string& dock, - const wxSize& size, std::function on_close); + const wxSize& size, std::function on_close, bool hide_on_close = false); void remove_dock_pane(wxWindow* window); void show_dock_pane(wxWindow* window, bool show); // Removes every dock pane without calling on_close, for MainFrame::shutdown() (app exit and a diff --git a/src/slic3r/GUI/RunScriptPanel.cpp b/src/slic3r/GUI/RunScriptPanel.cpp new file mode 100644 index 0000000000..c5d4bcb969 --- /dev/null +++ b/src/slic3r/GUI/RunScriptPanel.cpp @@ -0,0 +1,1056 @@ +#include "RunScriptPanel.hpp" + +#include "GLCanvas3D.hpp" +#include "GUI.hpp" +#include "GUI_App.hpp" +#include "I18N.hpp" +#include "KeyChord.hpp" +#include "MainFrame.hpp" +#include "MsgDialog.hpp" +#include "Plater.hpp" +#include "Shortcuts.hpp" +#include "format.hpp" +#include "Mcp/McpPaths.hpp" +#include "Mcp/McpScriptRun.hpp" +#include "Mcp/McpService.hpp" +#include "Mcp/McpTools.hpp" +#include "Mcp/McpTypes.hpp" +#include "Mcp/PythonScriptsDialog.hpp" +#include "Widgets/WebView.hpp" +#include "Widgets/WebViewHostDialog.hpp" +#include "libslic3r/AppConfig.hpp" +#include "libslic3r/Utils.hpp" +#include "slic3r/plugin/PythonInterpreter.hpp" +#include "slic3r/plugin/PythonScriptRunner.hpp" +#include "slic3r/plugin/PythonSession.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { namespace GUI { + +using nlohmann::json; +namespace fs = boost::filesystem; + +namespace { + +constexpr int kMaxRecent = 10; +constexpr std::size_t kOutputPerTick = 256 * 1024; +// A toggle the page asks for this soon after one the main frame dispatched is the same key press, delivered twice. +constexpr auto kToggleEcho = std::chrono::milliseconds(150); + +Mcp::McpService* service() +{ + Mcp::McpService* s = wxGetApp().mcp_service(); + return s != nullptr && s->started() && !s->stopping() ? s : nullptr; +} + +#ifdef __APPLE__ +const char* const kEnter = "Return"; +#else +const char* const kEnter = "Enter"; +#endif + +std::string run_cell_key() { return shortkey_shift_prefix() + kEnter; } +std::string run_all_key() { return shortkey_ctrl_prefix() + kEnter; } + +// What New writes: one cell, from the first line, so Run cell runs it wherever the caret is, even in a new session: what +// the panel is, how cells and their keys work, the tools import, and a call whose value Run cell shows. +std::string starter_script() +{ + // TRN The title of the one cell a new script starts with, which lists the objects of the project. + return "# %% " + _u8L("List the objects") + "\n# " + + // TRN A comment line of a new script in the Run Script panel. orca.host is the name of OrcaSlicer's Python API. + _u8L("Run Script runs Python with OrcaSlicer's tools and the orca.host API.") + "\n# " + + // TRN A comment line of a new script. %1% is the cell marker "# %%", written as is; %2% and %3% are keys, such as + // Shift+Enter and Ctrl+Enter. + format(_u8L("A line that starts with %1% starts a cell. %2% runs the cell at the cursor, %3% all of them."), "# %%", + run_cell_key(), run_all_key()) + + "\nfrom orca.host import tools\ntools.call(\"list_objects\")\n"; +} + +// The page's text: its own and the code editor's. +json page_strings() +{ + const std::string ctrl = shortkey_ctrl_prefix(); +#ifdef __APPLE__ + const std::string control = u8"⌃+"; +#else + const std::string control = ctrl; +#endif + return { + {"key_run_cell", run_cell_key()}, + {"key_run_all", run_all_key()}, + {"key_save", ctrl + "S"}, + {"key_save_as", ctrl + shortkey_shift_prefix() + "S"}, + {"key_suggest", control + "Space"}, + // TRN A button of the Run Script panel that starts a new script. + {"new", _u8L_CONTEXT("New", "Script")}, + {"new_tip", _u8L("Start a new script")}, + {"open", _u8L("Open…")}, + {"open_tip", _u8L("Open a Python script")}, + {"recent_scripts", _u8L("Recent scripts")}, + {"no_recent", _u8L("No recent scripts")}, + {"close_script", _u8L("Close script")}, + {"save", _u8L("Save")}, + {"save_as", _u8L("Save as…")}, + // TRN %s is a key, such as Ctrl+S. + {"save_tip", _u8L("Save the script (%s)")}, + {"run_all", _u8L("Run all")}, + // TRN %s is a key, such as Ctrl+Enter. + {"run_all_tip", _u8L("Restart the session and run every cell (%s)")}, + {"run_cell", _u8L("Run cell")}, + // TRN %s is a key, such as Shift+Enter. + {"run_cell_tip", _u8L("Run the cell at the cursor (%s)")}, + {"stop", _u8L("Stop")}, + {"stop_tip", _u8L("Interrupt the code that runs now and the threads the session started")}, + {"restart", _u8L("Restart session")}, + {"restart_tip", _u8L("End the session: its variables, imports and threads go")}, + {"edited", _u8L("(edited)")}, + {"untitled_script", _u8L("Untitled script")}, + // TRN The first item of the Run Script panel's session line, before the number of cells run and of variables. + {"session", _u8L("Session")}, + {"no_session", _u8L("No session yet")}, + {"running", _u8L("Running")}, + {"threads_running", _u8L("Threads are running")}, + {"session_ending", _u8L("Ending the session…")}, + // TRN The first %s is the number of the cell that runs, the second how many cells the file has. + {"running_cell", _u8L("Running cell %s of %s")}, + {"running_file", _u8L("Running the file")}, + {"hands_off", _u8L("Don't use OrcaSlicer until the script finishes.")}, + // TRN The heading of the console's block for a cell; %s is its number. + {"cell_n", _u8L("Cell %s")}, + {"no_output", _u8L("(no output)")}, + // TRN A link in the heading of Run all's block in the Run Script console: opens every cell's row to show its output. + {"expand_all", _u8L("Expand all")}, + // TRN A link in the heading of Run all's block in the Run Script console: folds every cell's row to its heading. + {"collapse_all", _u8L("Collapse all")}, + // TRN The + below the last line of the Run Script editor, which adds a "# %%" cell at the end of the script. + {"add_cell", _u8L("Add a cell")}, + {"add_cell_tip", _u8L("Add a cell at the end of the script")}, + // TRN A duration; %s is a number of seconds such as 0.8. + {"seconds", _u8L("%s s")}, + {"console_placeholder", _u8L("Python, run in the session")}, + {"clear", _u8L("Clear")}, + {"clear_tip", _u8L("Clear the console: the session and its variables stay")}, + // TRN A menu of the Run Script panel: how the editor shows the script's cells, the parts that start with "# %%". + {"cells", _u8L("Cells")}, + {"cells_tip", _u8L("How the editor shows the script's cells")}, + // TRN The heading of the Run Script panel's Cells menu, above its styles: Margin bars only, Dividers, Header bands... + {"show_cells_with", _u8L("Show cells with")}, + // TRN A style of the Run Script panel's Cells menu: only the coloured bar beside each cell's line numbers. + {"cells_margin", _u8L("Margin bars only")}, + // TRN A style of the Run Script panel's Cells menu: a line across the editor above each cell. + {"cells_dividers", _u8L("Dividers")}, + // TRN A style of the Run Script panel's Cells menu: each cell's first line, "# %% title", drawn as a shaded band. + {"cells_bands", _u8L("Header bands")}, + // TRN A style of the Run Script panel's Cells menu: every other cell has a shaded background. + {"cells_shaded", _u8L("Shaded cells")}, + {"cells_highlight", _u8L("Highlight the cell at the cursor")}, + // TRN For a screen reader: the divider between the Run Script panel's editor and its console, whose value is the + // editor's share of the panel's width. + {"split_label", _u8L("Width of the editor")}, + {"split_tip", _u8L("Drag to share the width between the editor and the console. Double-click to reset it.")}, + // TRN The arrows on the divider between the Run Script panel's editor and console, and the strip a hidden side leaves at + // the panel's edge. + {"hide_editor", _u8L("Hide the editor")}, + {"hide_console", _u8L("Hide the console")}, + {"show_editor", _u8L("Show the editor")}, + {"show_console", _u8L("Show the console")}, + // TRN The strip a hidden console leaves at the Run Script panel's edge, while a script runs or after one ran. + {"show_console_running", _u8L("Show the console: a script is running")}, + {"show_console_new", _u8L("Show the console: it has new output")}, + {"show_console_failed", _u8L("Show the console: the last run failed")}, + // TRN The label of the strip a hidden console leaves at the Run Script panel's edge. + {"console", _u8L("Console")}, + {"new_script", _u8L("New script")}, + {"open_script", _u8L("Open a script…")}, + {"empty_editor", _u8L("Open a script, or start a new one.")}, + {"start_script", _u8L("Start a script")}, + // TRN %s is the cell marker "# %%", written as is. orca.host is the name of OrcaSlicer's Python API. + {"start_script_text", _u8L("A Python script runs inside OrcaSlicer and can call every tool an AI agent can, plus the whole " + "orca.host API. Split it into cells with %s and try one cell at a time.")}, + // TRN A line in the console of the Run Script panel, where Run all started a new session. + {"session_restarted", _u8L("Session restarted for Run all")}, + {"python_off_text", _u8L("You can edit and save this script, but it can't run until Python scripts are on.")}, + {"python_off", _u8L("Python scripts are off.")}, + {"python_access", _u8L("A script runs with OrcaSlicer's full access to your computer.")}, + {"turn_on_python", _u8L("Turn on Python scripts…")}, + {"starting", _u8L("OrcaSlicer is still starting…")}, + {"code_editor", WebViewHostDialog::code_editor_strings()}, + }; +} + +bool is_python_file(const fs::path& path) { return boost::iequals(path.extension().string(), ".py"); } + +wxString python_wildcard() { return format_wxstr("%1% (*.py)|*.py", _L("Python scripts")); } + +std::vector recent_paths() +{ + std::vector paths; + try { + const json list = json::parse(wxGetApp().app_config->get("run_script", "recent")); + for (const json& item : list) + if (item.is_string()) + paths.push_back(item.get()); + } catch (const std::exception&) { + } + return paths; +} + +void set_recent_paths(const std::vector& paths) { wxGetApp().app_config->set("run_script", "recent", json(paths).dump()); } + +// How the editor shows cells, as the Cells menu last set it: the page reads a missing or unknown style as its default, and +// the highlight is on unless it was turned off. +json cell_view() +{ + const AppConfig& config = *wxGetApp().app_config; + return {{"style", config.get("run_script", "cell_style")}, {"highlight", config.get("run_script", "highlight_cell") != "0"}}; +} + +// The editor's share of the width and the side hidden, as the divider last left them; the page reads a missing or unknown +// value as its default. +json pane_layout() +{ + const AppConfig& config = *wxGetApp().app_config; + return {{"split", config.get("run_script", "split")}, {"hidden", config.get("run_script", "hidden_side")}}; +} + +} // namespace + +// The panel's dock pane: a web view on the page, hidden from the automation tools with everything inside it. +class RunScriptPane : public wxPanel +{ +public: + RunScriptPane(wxWindow* parent, RunScriptPanel& owner); + ~RunScriptPane() override; + RunScriptPane(const RunScriptPane&) = delete; + RunScriptPane& operator=(const RunScriptPane&) = delete; + + wxWebView* web() const { return m_web; } + // HandleStudio(payload) on the page, after the current event and only while the pane lives. + void send(const json& payload); + +private: + void on_navigating(wxWebViewEvent& event); + + RunScriptPanel& m_owner; + wxWebView* m_web = nullptr; + wxFileName m_page; + std::shared_ptr> m_alive = std::make_shared>(true); +}; + +RunScriptPane::RunScriptPane(wxWindow* parent, RunScriptPanel& owner) + : wxPanel(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, Mcp::kHiddenFromAutomation), m_owner(owner) +{ + const fs::path page = fs::path(resources_dir()) / "web" / "dialog" / "RunScript" / "index.html"; + m_page = wxFileName(from_path(page)); + // Created empty and loaded once the user scripts are in, so the first load has them, as a WebViewHostDialog's page does. + m_web = WebView::CreateWebView(this, wxEmptyString); + auto* sizer = new wxBoxSizer(wxVERTICAL); + if (m_web != nullptr) + sizer->Add(m_web, 1, wxEXPAND); + SetSizer(sizer); + if (m_web == nullptr) + return; + // WebView2's accelerator keys would reload the page (Ctrl+R, F5) and zoom it. + m_web->EnableBrowserAcceleratorKeys(false); + m_web->AddUserScript(wxString::FromUTF8(WebViewHostDialog::theme_user_script())); + m_web->AddUserScript(wxString::FromUTF8(WebViewHostDialog::localized_strings_script(page_strings()))); + m_web->Bind(wxEVT_WEBVIEW_SCRIPT_MESSAGE_RECEIVED, [this](wxWebViewEvent& event) { + json payload; + try { + payload = json::parse(event.GetString().utf8_string()); + } catch (const std::exception&) { + return; + } + // Out of the web view's message callback: window work on its stack (file dialogs, prompts) is a crash class on GTK + // and macOS. + wxGetApp().CallAfter([owner = &m_owner, alive = m_alive, payload = std::move(payload)] { + if (alive->load()) + owner->handle(payload); + }); + }); + m_web->Bind(wxEVT_WEBVIEW_NAVIGATING, &RunScriptPane::on_navigating, this); + // A theme toggle re-themes the page in place. + m_web->Bind(EVT_WEBVIEW_RECREATED, [this](wxCommandEvent&) { + WebView::RunScript(m_web, wxString::FromUTF8(WebViewHostDialog::theme_apply_script())); + }); + wxString url = file_url_from_path(page); + if (const wxString lang = wxGetApp().current_language_code_safe(); !lang.empty()) + url += "?lang=" + lang; + WebView::LoadUrl(m_web, url); +} + +RunScriptPane::~RunScriptPane() +{ + m_alive->store(false); + m_owner.pane_destroyed(this); +} + +void RunScriptPane::send(const json& payload) +{ + const wxString script = "HandleStudio(" + wxString::FromUTF8(payload.dump(-1, ' ', false, json::error_handler_t::ignore)) + ")"; + wxGetApp().CallAfter([this, script, alive = m_alive] { + if (alive->load() && m_web != nullptr) + WebView::RunScript(m_web, script); + }); +} + +// The page goes nowhere but its own loads. A file dropped on it is a navigation to that file, opened after this event. +void RunScriptPane::on_navigating(wxWebViewEvent& event) +{ + if (WebViewHostDialog::own_page_navigation(event.GetURL(), m_page)) { + event.Skip(); + return; + } + event.Veto(); + fs::path path = WebViewHostDialog::dropped_file(event.GetURL()); + if (path.empty()) + return; + wxGetApp().CallAfter([owner = &m_owner, alive = m_alive, path = std::move(path)] { + if (alive->load()) + owner->dropped(path); + }); +} + +RunScriptPanel::RunScriptPanel() : m_alive(std::make_shared>(true)) +{ + m_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { tick(); }); + m_ready_timer.Bind(wxEVT_TIMER, [this](wxTimerEvent&) { + Mcp::McpService* s = service(); + if (s == nullptr || s->ready()) + m_ready_timer.Stop(); + send_service_state(); + }); + // The pane comes back after a rebuild once the old main window is gone: a WebView2 created while the window it + // replaces still exists shows a blank page. recreate_GUI() Destroy()s that window, which wx deletes in its idle pass + // after the app's idle event, so the pane is built from a call queued in that event. + wxGetApp().Bind(wxEVT_IDLE, [this, alive = m_alive](wxIdleEvent& event) { + event.Skip(); + if (!alive->load() || !std::exchange(m_rebuild_pending, false)) + return; + wxGetApp().CallAfter([this, alive] { + if (alive->load() && m_wanted && m_pane == nullptr) + show(); + }); + }); +} + +RunScriptPanel::~RunScriptPanel() +{ + m_alive->store(false); + m_timer.Stop(); + m_ready_timer.Stop(); + // The service, which hosts the session on a thread of its own, joins that thread as it stops. + if (m_session) { + m_session->end(); + m_session->stop(); + } + if (m_api_thread.joinable()) + m_api_thread.join(); +} + +// ---- the pane -------------------------------------------------------------------------------------------------- + +void RunScriptPanel::toggle() +{ + m_host_toggle_at = std::chrono::steady_clock::now(); + flip(); +} + +void RunScriptPanel::flip() +{ + if (on_screen()) { + m_wanted = false; + if (Plater* plater = wxGetApp().plater(); plater != nullptr && m_pane != nullptr) + plater->show_dock_pane(m_pane, false); + } else + show(); +} + +void RunScriptPanel::show() +{ + MainFrame* frame = wxGetApp().mainframe; + Plater* plater = wxGetApp().plater(); + if (frame == nullptr || plater == nullptr) + return; + m_wanted = true; + if (!frame->is_prepare_or_preview_tab()) + frame->select_tab(wxString(TAB_ID_PREPARE)); + if (m_pane == nullptr) { + m_pane = new RunScriptPane(plater, *this); + plater->add_dock_pane( + m_pane, "run_script", _L("Run Script"), "bottom", wxSize(900, 320), + [this, alive = m_alive] { + if (alive->load()) + m_wanted = false; + }, + true); + } else + plater->show_dock_pane(m_pane, true); + if (m_pane->web() != nullptr) + m_pane->web()->SetFocus(); +} + +bool RunScriptPanel::on_screen() const { return m_pane != nullptr && m_pane->IsShownOnScreen(); } + +void RunScriptPanel::pane_destroyed(RunScriptPane* pane) +{ + if (m_pane == pane) { + m_pane = nullptr; + m_editor_keys.clear(); + } +} + +bool RunScriptPanel::owns_focus(const wxWindow* focus) const +{ + if (m_pane == nullptr) + return false; + for (const wxWindow* w = focus; w != nullptr; w = w->GetParent()) + if (w == m_pane) + return true; +#ifdef _WIN32 + // WebView2 keeps the focus in windows of its own, which wx doesn't know. + if (const HWND native = ::GetFocus(); native != nullptr && ::IsChild(static_cast(m_pane->GetHWND()), native)) + return true; +#endif + return false; +} + +void RunScriptPanel::forward_action(const std::string& action) { send({{"command", "key"}, {"action", action}}); } + +wxWebView* RunScriptPanel::web_view() const { return m_pane != nullptr ? m_pane->web() : nullptr; } + +void RunScriptPanel::send(const json& payload) +{ + if (m_pane != nullptr) + m_pane->send(payload); +} + +void RunScriptPanel::main_window_closing() +{ + if (m_session) { + m_session->end(); + m_session->stop(); + m_detached = true; + m_backlog.clear(); + } + m_waiting.reset(); + m_running = false; + m_ready_timer.Stop(); + m_pane = nullptr; + m_editor_keys.clear(); +} + +void RunScriptPanel::main_window_rebuilt() +{ + m_rebuild_pending = m_wanted; + if (m_rebuild_pending) + wxWakeUpIdle(); +} + +void RunScriptPanel::python_setting_changed() +{ + const bool on = Mcp::python_scripts_allowed(*wxGetApp().app_config); + send({{"command", "python"}, {"on", on}}); + if (!on) + end_session(); +} + +void RunScriptPanel::shortcuts_changed() { send({{"command", "shortcuts"}, {"toggle_key", toggle_key()}}); } + +json RunScriptPanel::toggle_key() const +{ + const ShortcutRegistry& shortcuts = wxGetApp().shortcuts(); + return {{"chord", shortcuts.binding(Shortcut::ToggleRunScript).to_string()}, {"display", shortcuts.display(Shortcut::ToggleRunScript)}}; +} + +// ---- the page's messages ----------------------------------------------------------------------------------------- + +void RunScriptPanel::handle(const json& payload) +{ + const std::string command = payload.value("command", ""); + try { + if (command == "init") { + // The panel needs the service's tools and jobs, never its network endpoint. + if (wxGetApp().mcp_service() == nullptr) + wxGetApp().start_mcp_service(false); + send(state()); + send_service_state(); + read_api(); + } else if (command == "editor_keys") { + m_editor_keys.clear(); + for (const json& chord : payload.value("chords", json::array())) + if (chord.is_string()) + m_editor_keys.insert(chord.get()); + } else if (command == "edit") { + m_text = payload.value("text", ""); + m_edited = payload.value("edited", false); + } else if (command == "new") { + if (!m_running && confirm_unsaved()) + new_script(); + } else if (command == "open") { + if (m_running || !confirm_unsaved()) + return; + wxFileDialog dialog(wxGetApp().mainframe, _L("Open a Python script"), wxEmptyString, wxEmptyString, python_wildcard(), + wxFD_OPEN | wxFD_FILE_MUST_EXIST, wxDefaultPosition, wxDefaultSize, Mcp::kHiddenFromAutomation); + if (dialog.ShowModal() == wxID_OK) + load(into_path(dialog.GetPath())); + } else if (command == "open_recent") { + if (!m_running && confirm_unsaved()) + load(Mcp::path_from_utf8(payload.value("path", ""))); + } else if (command == "close_script") { + if (!m_running && confirm_unsaved()) + close_script(); + } else if (command == "save") + save(payload.value("pick", false)); + else if (command == "run") + run(payload); + else if (command == "stop") { + // A Run all still waiting for the old session to end is dropped before it starts, and reported stopped. + if (m_waiting) { + m_waiting.reset(); + PythonSessionEvent stopped; + stopped.kind = PythonSessionEvent::Kind::Finished; + stopped.status = "cancelled"; + stopped.executed = false; + finish_run(stopped); + } + if (m_session) + m_session->stop(); + } else if (command == "restart") + end_session(); + else if (command == "toggle") { + if (std::chrono::steady_clock::now() - m_host_toggle_at >= kToggleEcho) + flip(); + } else if (command == "counts") { + const int cells = payload.value("cells", 0), variables = payload.value("variables", 0); + send({{"command", "counts"}, + // TRN The session line of the Run Script panel: how many cells ran in the session. + {"cells_text", format(_L_PLURAL("%1% cell run", "%1% cells run", cells), cells)}, + // TRN The session line of the Run Script panel: how many variables the session holds. + {"variables_text", format(_L_PLURAL("%1% variable", "%1% variables", variables), variables)}}); + } else if (command == "cell_view") { + wxGetApp().app_config->set("run_script", "cell_style", payload.value("style", "")); + wxGetApp().app_config->set("run_script", "highlight_cell", payload.value("highlight", true) ? "1" : "0"); + } else if (command == "pane_layout") { + wxGetApp().app_config->set("run_script", "split", json(payload.value("split", 0.6)).dump()); + wxGetApp().app_config->set("run_script", "hidden_side", payload.value("hidden", "")); + } else if (command == "turn_on_python") { + // The setting's own window tells the panel about a change (python_setting_changed()). + Mcp::show_python_scripts_dialog(wxGetApp().mainframe); + } + } catch (const std::exception& e) { + send({{"command", "error"}, {"message", e.what()}}); + } +} + +json RunScriptPanel::state() const +{ + Mcp::McpService* s = service(); + json script = script_message(); + script.erase("command"); + return {{"command", "state"}, + {"script", std::move(script)}, + {"python_on", Mcp::python_scripts_allowed(*wxGetApp().app_config)}, + {"ready", s != nullptr && s->ready()}, + {"recent", recent_message()["items"]}, + {"session", session_state()}, + {"toggle_key", toggle_key()}, + {"cell_view", cell_view()}, + {"pane_layout", pane_layout()}}; +} + +json RunScriptPanel::script_message() const +{ + if (m_none) + return {{"command", "script"}, {"none", true}}; + return {{"command", "script"}, + {"none", false}, + {"file_name", m_file.empty() ? std::string() : Mcp::path_to_utf8(m_file.filename())}, + {"folder", m_file.empty() ? std::string() : Mcp::path_to_utf8(m_file.parent_path())}, + {"text", m_text}, + {"edited", m_edited}}; +} + +json RunScriptPanel::recent_message() const +{ + std::vector kept; + json items = json::array(); + for (const std::string& path : recent_paths()) { + boost::system::error_code ec; + const fs::path file = Mcp::path_from_utf8(path); + if (!fs::is_regular_file(file, ec)) + continue; + kept.push_back(path); + items.push_back({{"path", path}, {"name", Mcp::path_to_utf8(file.filename())}, {"folder", Mcp::path_to_utf8(file.parent_path())}}); + } + if (kept.size() != recent_paths().size()) + set_recent_paths(kept); + return {{"command", "recent"}, {"items", std::move(items)}}; +} + +void RunScriptPanel::remember_recent(const fs::path& path) +{ + const std::string utf8 = Mcp::path_to_utf8(path); + std::vector paths = recent_paths(); + paths.erase(std::remove(paths.begin(), paths.end(), utf8), paths.end()); + paths.insert(paths.begin(), utf8); + if (paths.size() > std::size_t(kMaxRecent)) + paths.resize(kMaxRecent); + set_recent_paths(paths); +} + +std::string RunScriptPanel::session_state() const +{ + if (!m_session) + return "none"; + if (m_detached || m_session_ending) + return "ending"; + if (m_running || m_session->working()) + return "working"; + return m_session->has_threads() ? "threads" : "idle"; +} + +void RunScriptPanel::send_session_state() +{ + const std::string now = session_state(); + if (now == m_sent_session_state) + return; + m_sent_session_state = now; + send({{"command", "session"}, {"state", now}}); +} + +void RunScriptPanel::send_service_state() +{ + Mcp::McpService* s = service(); + const bool ready = s != nullptr && s->ready(); + if (!ready && s != nullptr && !m_ready_timer.IsRunning()) + m_ready_timer.Start(500); + send({{"command", "service"}, {"ready", ready}}); + if (ready) + send({{"command", "catalog"}, {"tools", Mcp::editor_tool_catalog(s->registry())}}); +} + +// The orca.host API's entries, read once per app run on a thread of the panel's, which it joins. +void RunScriptPanel::read_api() +{ + if (m_api_asked) { + if (!m_api.is_null()) + send({{"command", "api"}, {"entries", m_api}}); + return; + } + m_api_asked = true; + m_api_thread = std::thread([this, alive = m_alive] { + json entries = json::array(); + try { + if (PythonInterpreter::instance().is_initialized()) + if (PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease()) + for (const json& e : Mcp::python_api_reference()) + entries.push_back({{"name", e["name"]}, + {"kind", e["kind"]}, + {"signature", e["signature"]}, + {"summary", Mcp::first_sentence(e["doc"].get())}}); + } catch (const std::exception&) { + // No API suggestions: the editor still suggests the tools. + } + wxGetApp().CallAfter([this, alive, entries = std::move(entries)] { + if (!alive->load()) + return; + m_api = entries; + send({{"command", "api"}, {"entries", m_api}}); + }); + }); +} + +// ---- the script --------------------------------------------------------------------------------------------------- + +// Asks whether to save an edited script before it is closed or replaced. False to keep it: the person cancelled, or chose +// to save and nothing was saved. +bool RunScriptPanel::confirm_unsaved() +{ + if (m_none || !m_edited) + return true; + const wxString question = m_file.empty() ? _L("Save this script?\nIf you don't, your changes are lost.") : + // TRN %1% is a script's file name. + format_wxstr(_L("Save the changes to %1%?\nIf you don't, your changes are lost."), + from_path(m_file.filename())); + MessageDialog dialog(wxGetApp().mainframe, question, _L("Run Script"), wxYES_NO | wxCANCEL | wxICON_QUESTION); + // The person's own question: no auto-answer rule answers it. + dialog.SetName(Mcp::kHiddenFromAutomation); + dialog.SetButtonLabel(wxID_YES, _L("Save")); + dialog.SetButtonLabel(wxID_NO, _L("Don't save")); + const int answer = dialog.ShowModal(); + return answer == wxID_YES ? save(false) : answer == wxID_NO; +} + +// Writes the script to its file, or to one the person picks when it has none or `pick` asks for another, in the encoding +// it was read in. False when nothing was written. +bool RunScriptPanel::save(bool pick) +{ + if (m_none) + return false; + fs::path path = m_file; + if (pick || path.empty()) { + wxFileDialog dialog(wxGetApp().mainframe, _L("Save the script"), path.empty() ? wxString() : from_path(path.parent_path()), + path.empty() ? wxString("script.py") : from_path(path.filename()), python_wildcard(), + wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition, wxDefaultSize, Mcp::kHiddenFromAutomation); + if (dialog.ShowModal() != wxID_OK) + return false; + path = into_path(dialog.GetPath()); + // GTK's file dialog doesn't add the filter's extension, so it never asked about the file adding it names. + if (!is_python_file(path)) { + path += ".py"; + boost::system::error_code ec; + if (fs::exists(path, ec)) { + MessageDialog confirm(wxGetApp().mainframe, + wxString::Format(_L("The file %s already exists.\nDo you want to replace it?"), from_path(path)), + _L("Confirm Save As"), wxYES_NO | wxICON_WARNING); + confirm.SetName(Mcp::kHiddenFromAutomation); + if (confirm.ShowModal() != wxID_YES) + return false; + } + } + } + const std::string target = Mcp::path_to_utf8(path); + std::string contents, error; + if (!encode_python_source(m_text, m_encoding, contents, error)) { + // TRN %1% is a file name, %2% the text encoding it is in (such as cp1252), %3% why the text doesn't fit it. + send({{"command", "error"}, {"message", format(_u8L("Can't save %1% in its encoding, %2%: %3%"), target, m_encoding, error)}}); + return false; + } + // Written beside the file, then renamed over it, so a save that fails leaves the file as it was. + const std::string temp = target + ".saving"; + boost::nowide::ofstream out(temp.c_str(), std::ios::binary | std::ios::trunc); + out << contents; + out.close(); + const bool written = bool(out); + if (!written || rename_file(temp, target)) { + boost::system::error_code ec; + // Kept when a failed replacement removed the file first (some network mounts): it is the only copy. + if (!written || fs::exists(path, ec)) + boost::nowide::remove(temp.c_str()); + send({{"command", "error"}, {"message", format(_u8L("Can't save %1%."), target)}}); + return false; + } + // A new file is the script's from the next session; the session keeps the file it started with. + m_file = path; + m_edited = false; + remember_recent(path); + send({{"command", "saved"}, {"file_name", Mcp::path_to_utf8(path.filename())}, {"folder", Mcp::path_to_utf8(path.parent_path())}, + {"text", m_text}}); + send(recent_message()); + return true; +} + +void RunScriptPanel::load(const fs::path& path) +{ + boost::nowide::ifstream in(Mcp::path_to_utf8(path).c_str(), std::ios::binary); + std::ostringstream bytes; + if (in) + bytes << in.rdbuf(); + std::string text, encoding, error; + if (!in || !decode_python_source(bytes.str(), text, encoding, error)) { + // TRN %1% is a script's file name. + send({{"command", "error"}, + {"message", in ? format(_u8L("%1% can't be read as Python source: %2%"), Mcp::path_to_utf8(path.filename()), error) : + format(_u8L("Can't read %1%."), Mcp::path_to_utf8(path))}}); + send(recent_message()); + return; + } + end_session(); + m_text = std::move(text); + m_file = path; + m_encoding = encoding; + m_edited = false; + m_none = false; + remember_recent(path); + send(script_message()); + send(recent_message()); +} + +void RunScriptPanel::new_script() +{ + end_session(); + m_text = starter_script(); + m_file = fs::path(); + m_encoding = "utf-8"; + m_edited = false; + m_none = false; + send(script_message()); +} + +void RunScriptPanel::close_script() +{ + end_session(); + m_text.clear(); + m_file = fs::path(); + m_encoding = "utf-8"; + m_edited = false; + m_none = true; + send(script_message()); +} + +void RunScriptPanel::open_file(const fs::path& path) +{ + show(); + if (!m_running && confirm_unsaved()) + load(path); +} + +bool RunScriptPanel::confirm_close() { return confirm_unsaved(); } + +void RunScriptPanel::dropped(const fs::path& path) +{ + // As Open, which is unavailable while a run goes. + if (m_running || m_waiting || !is_python_file(path)) + return; + if (confirm_unsaved()) + load(path); +} + +// ---- running ------------------------------------------------------------------------------------------------------ + +void RunScriptPanel::refuse(const std::string& message) { send({{"command", "run_refused"}, {"message", message}}); } + +void RunScriptPanel::run(const json& payload) +{ + if (m_running || m_waiting) + return; + if (!Mcp::python_scripts_allowed(*wxGetApp().app_config)) { + refuse(_u8L("Python scripts are off. You can turn them on in Preferences > AI features > Python scripts.")); + return; + } + Mcp::McpService* s = service(); + if (s == nullptr || !s->ready()) { + refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); + return; + } + const std::string kind = payload.value("kind", "cell"); + PythonWork work; + work.source = payload.value("text", m_text); + if (kind == "file") { + work.kind = PythonWork::Kind::File; + work.code = work.source; + work.cell_starts = payload.value("cell_starts", std::vector{1}); + if (work.cell_starts.empty()) + work.cell_starts = {1}; + } else { + work.kind = kind == "console" ? PythonWork::Kind::Console : PythonWork::Kind::Cell; + work.code = payload.value("code", ""); + work.first_line = std::max(1, payload.value("first_line", 1)); + } + json started{{"command", "run_started"}, {"kind", kind}, {"first_line", work.first_line}}; + + // The script's tool calls act on the main window, and keys it sends without a target go where the focus is. + if (MainFrame* frame = wxGetApp().mainframe) { + frame->Raise(); + if (Plater* plater = wxGetApp().plater()) + if (GLCanvas3D* canvas = plater->get_current_canvas3D()) { + canvas->force_set_focus(); + m_run_focus = canvas->get_wxglcanvas(); + } + } + // Run all runs the file as `python file.py` does, in a session of its own. + if (kind == "file" && m_session) { + m_waiting = std::move(work); + m_running = true; + m_run_started = std::chrono::steady_clock::now(); + send(started); + end_session(); + return; + } + if (!m_session && !start_session()) + return; + submit(std::move(work), std::move(started)); +} + +bool RunScriptPanel::start_session() +{ + Mcp::McpService* s = service(); + if (s == nullptr) { + refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); + return false; + } + auto session = std::make_shared(); + Mcp::ScriptRun::Events events; + // Only a job refused before the session was hosted (or one whose handler refused) reports here. + events.finished = [this, alive = m_alive, session](const json& result, const json&) { + if (!alive->load() || session != m_session || !m_running) + return; + m_running = false; + send({{"command", "run_finished"}, {"status", "refused"}, {"message", result.value("error", std::string())}}); + }; + m_session_run = s->start_python_session(session, m_file, std::move(events)); + if (!m_session_run) { + refuse(_u8L("Scripts can't run while OrcaSlicer is starting or closing.")); + return false; + } + m_session = std::move(session); + m_session_file = m_file.empty() ? std::string("") : Mcp::path_to_utf8(m_file); + m_session_ending = false; + m_timer.Start(100); + send_session_state(); + return true; +} + +void RunScriptPanel::end_session() +{ + if (!m_session) + return; + m_session_ending = true; + m_session->end(); + m_session->stop(); + send_session_state(); +} + +void RunScriptPanel::submit(PythonWork work, const json& started) +{ + if (!m_session->submit(std::move(work))) { + m_running = false; + refuse(_u8L("The script could not run.")); + return; + } + if (!started.is_null()) { + m_running = true; + m_run_started = std::chrono::steady_clock::now(); + send(started); + } + send_session_state(); +} + +// Every 100 ms while a session exists: its output (coalesced, at most kOutputPerTick a tick, in order with the cells, the +// results and the end of each work; a result is capped by the runner), its state, and its end. +void RunScriptPanel::tick() +{ + if (!m_session) { + m_timer.Stop(); + return; + } + // Read before the events are taken: once the host has returned, every event it sends is queued, so a session seen + // ended here leaves none behind this take. + const bool ended = m_session->ended(); + for (PythonSessionEvent& event : m_session->take_events()) + m_backlog.push_back(std::move(event)); + // A session the main window let go of reports to no page. + if (m_detached) + m_backlog.clear(); + std::string output; + const auto flush = [&] { + if (!output.empty()) + send({{"command", "output"}, {"text", std::move(output)}}); + output.clear(); + }; + while (!m_backlog.empty()) { + PythonSessionEvent& event = m_backlog.front(); + if (event.kind == PythonSessionEvent::Kind::Output) { + const std::size_t room = kOutputPerTick - output.size(); + if (event.text.size() > room) { + // Cut at a character's start, so each piece is UTF-8 on its own. + std::size_t cut = room; + while (cut > 0 && (static_cast(event.text[cut]) & 0xC0) == 0x80) + --cut; + output += event.text.substr(0, cut); + event.text.erase(0, cut); + break; + } + output += event.text; + m_backlog.pop_front(); + continue; + } + flush(); + if (event.kind == PythonSessionEvent::Kind::Cell) + send({{"command", "cell"}, {"index", event.cell}}); + else if (event.kind == PythonSessionEvent::Kind::Result) + send({{"command", "result"}, {"text", event.text}}); + else + finish_run(event); + m_backlog.pop_front(); + } + flush(); + if (ended && m_backlog.empty()) { + m_session.reset(); + m_session_run.reset(); + m_detached = false; + m_session_ending = false; + if (m_waiting) { + std::optional work = std::move(m_waiting); + m_waiting.reset(); + if (start_session()) + submit(std::move(*work), json()); + else { + m_running = false; + send({{"command", "run_finished"}, {"status", "refused"}, {"message", _u8L("Scripts can't run while OrcaSlicer is starting or closing.")}}); + } + } else if (m_running) { + // Ended without reporting its work: its job was refused, or the service stopped. + m_running = false; + send({{"command", "run_finished"}, {"status", "refused"}, {"message", _u8L("Scripts can't run while OrcaSlicer is starting or closing.")}}); + } + } + send_session_state(); +} + +void RunScriptPanel::finish_run(const PythonSessionEvent& done) +{ + m_running = false; + const std::string status = done.status; + std::string status_text; + if (status == "cancelled" || status == "timed_out") + status_text = _u8L("Stopped."); + else if (status == "raised") + status_text = _u8L("The script raised an exception."); + else if (status == "unavailable") + status_text = _u8L("Python is not available in this OrcaSlicer."); + send({{"command", "run_finished"}, + {"status", status}, + {"status_text", status_text}, + {"message", done.message}, + {"traceback", done.traceback}, + {"error_line", done.error_line}, + {"executed", done.executed}, + {"cells_reported", done.cells_reported}, + {"script_file", m_session_file}, + {"duration_ms", std::chrono::duration_cast(std::chrono::steady_clock::now() - m_run_started).count()}, + {"variables", done.variables}}); + // The run lent the focus to the canvas; it comes back while it is still there. + if (wxWebView* web = web_view(); web != nullptr && m_run_focus && wxWindow::FindFocus() == m_run_focus.get()) + web->SetFocus(); +} + +}} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/RunScriptPanel.hpp b/src/slic3r/GUI/RunScriptPanel.hpp new file mode 100644 index 0000000000..f019540dbf --- /dev/null +++ b/src/slic3r/GUI/RunScriptPanel.hpp @@ -0,0 +1,147 @@ +#pragma once + +#include "CodeEditorWindow.hpp" +#include "slic3r/plugin/PythonSession.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class wxWebView; + +namespace Slic3r { namespace GUI { + +namespace Mcp { +class ScriptRun; +} +class RunScriptPane; + +// The Run Script panel: a dock pane under the 3D view (it can float) whose page (resources/web/dialog/RunScript) edits a +// Python script in `# %%` cells and runs them, one at a time or the whole file, in a live session (PythonSession) hosted +// by the MCP service as a person's run_python job. One per app, owned by GUI_App: the script's text, file and unsaved +// state, the session and the recent scripts live here, so they survive the pane, which a main-window rebuild (a language +// change) destroys and the panel builds again. The pane and everything in it are hidden from the automation tools. +// UI thread. +class RunScriptPanel final : public CodeEditorWindow +{ +public: + RunScriptPanel(); + ~RunScriptPanel() override; + RunScriptPanel(const RunScriptPanel&) = delete; + RunScriptPanel& operator=(const RunScriptPanel&) = delete; + + // Hides the panel when it is on screen, else shows it, as File › Run Script, its shortcut and Speed Dial do. + void toggle(); + // Builds the pane on first use and shows it, selecting Prepare when the current tab is neither Prepare nor Preview. + void show(); + // The pane's window is shown on screen. + bool on_screen() const; + // Shows the panel and opens `path`, asking about unsaved changes first. + void open_file(const boost::filesystem::path& path); + // Asks about unsaved changes as the app quits; false to stay. + bool confirm_close(); + + bool owns_focus(const wxWindow* focus) const override; + void forward_action(const std::string& action) override; + wxWebView* web_view() const override; + const std::set& editor_keys() const override { return m_editor_keys; } + + // MainFrame::shutdown(), before the dock panes go: the session is stopped and ended, and from then on only its end is + // watched; the pane goes. + void main_window_closing(); + // The end of GUI_App::recreate_GUI(): the pane comes back, with an empty console, if it was wanted, once the old main + // window has been deleted. + void main_window_rebuilt(); + // The Python scripts setting changed: the page is told, and turning it off ends the session. + void python_setting_changed(); + // The toggle's key changed (MainFrame::update_shortcut_labels()). + void shortcuts_changed(); + +private: + friend class RunScriptPane; + + void pane_destroyed(RunScriptPane* pane); + // Hides the panel when it is on screen, else shows it. + void flip(); + void handle(const nlohmann::json& payload); + void dropped(const boost::filesystem::path& path); + // A message for the page, sent once it has a pane; checked for liveness at its last hop. + void send(const nlohmann::json& payload); + + nlohmann::json state() const; + nlohmann::json script_message() const; + nlohmann::json recent_message() const; + nlohmann::json toggle_key() const; + std::string session_state() const; + void send_session_state(); + + bool confirm_unsaved(); + bool save(bool pick); + void load(const boost::filesystem::path& path); + void new_script(); + void close_script(); + void remember_recent(const boost::filesystem::path& path); + + void run(const nlohmann::json& payload); + void refuse(const std::string& message); + // Starts a session on the script's file as it is now; false (and refused) when the service can't host one. + bool start_session(); + // Ends the session and stops what it runs, its teardown included; it is dropped once it has ended. + void end_session(); + // Submits `work` and tells the page with `started`, unless that is null: the page was told when the work had to wait. + void submit(PythonWork work, const nlohmann::json& started); + void tick(); + void finish_run(const PythonSessionEvent& done); + void send_service_state(); + void read_api(); + + std::shared_ptr> m_alive; + RunScriptPane* m_pane = nullptr; + bool m_wanted = false; + // The main window was rebuilt and the pane is wanted back: built at the next idle. + bool m_rebuild_pending = false; + + // The script. + std::string m_text; + boost::filesystem::path m_file; + std::string m_encoding = "utf-8"; + bool m_edited = false; + bool m_none = true; // no script open + + // The session, and the run going in it. + std::shared_ptr m_session; + std::shared_ptr m_session_run; + std::string m_session_file; // the name the session's tracebacks use + bool m_detached = false; + bool m_session_ending = false; + std::optional m_waiting; // a Run all waiting for the old session to end + std::deque m_backlog; + bool m_running = false; + std::chrono::steady_clock::time_point m_run_started; + wxWeakRef m_run_focus; // the canvas the run gave the focus to + std::string m_sent_session_state; + wxTimer m_timer; + wxTimer m_ready_timer; + + std::set m_editor_keys; + std::chrono::steady_clock::time_point m_host_toggle_at{}; + + // The orca.host API's entries for the editor's suggestions, read once per app run. + nlohmann::json m_api; + bool m_api_asked = false; + std::thread m_api_thread; +}; + +}} // namespace Slic3r::GUI diff --git a/src/slic3r/GUI/Shortcuts.cpp b/src/slic3r/GUI/Shortcuts.cpp index 5ef04523d7..a14a30e017 100644 --- a/src/slic3r/GUI/Shortcuts.cpp +++ b/src/slic3r/GUI/Shortcuts.cpp @@ -178,6 +178,8 @@ constexpr std::array shortcut_table = {{ SHORTCUT(TabPrevious, "tab_previous", L("Switch to the previous tab"), GLOBAL, TAB_PREVIOUS_CHORD), SHORTCUT(ReloadDevicePage, "reload_device_page", L("Reload the device page"), CANVAS, { WXK_F5 }), SHORTCUT(KeyboardShortcuts, "keyboard_shortcuts", L("Show keyboard shortcuts list"), CANVAS, { '?' }), + // Ctrl+Alt would be AltGr on the Windows layouts that type with it. + SHORTCUT(ToggleRunScript, "toggle_run_script", L("Show or hide the Run Script panel"), GLOBAL, { 'R', CTRL_SHIFT }), SHORTCUT(Quit, "quit", L("Quit"), GLOBAL, { 'Q', CTRL }), // Speed Dial diff --git a/src/slic3r/GUI/Shortcuts.hpp b/src/slic3r/GUI/Shortcuts.hpp index 76b7f04fee..40130716af 100644 --- a/src/slic3r/GUI/Shortcuts.hpp +++ b/src/slic3r/GUI/Shortcuts.hpp @@ -52,7 +52,8 @@ enum class Shortcut : uint8_t { #ifdef SLIC3R_CAD GoToDesign, #endif - GoToPrepare, GoToPreview, GoToDevice, GoToMultiDevice, GoToProject, GoToCalibration, TabNext, TabPrevious, ReloadDevicePage, KeyboardShortcuts, Quit, + GoToPrepare, GoToPreview, GoToDevice, GoToMultiDevice, GoToProject, GoToCalibration, TabNext, TabPrevious, ReloadDevicePage, KeyboardShortcuts, + ToggleRunScript, Quit, // Speed Dial SpeedDial, Count diff --git a/src/slic3r/GUI/Widgets/WebViewHostDialog.cpp b/src/slic3r/GUI/Widgets/WebViewHostDialog.cpp index 5890aa3f88..eec4045130 100644 --- a/src/slic3r/GUI/Widgets/WebViewHostDialog.cpp +++ b/src/slic3r/GUI/Widgets/WebViewHostDialog.cpp @@ -3,6 +3,7 @@ #include "WebView.hpp" #include "slic3r/GUI/GUI.hpp" #include "slic3r/GUI/GUI_App.hpp" +#include "slic3r/GUI/I18N.hpp" #include "slic3r/GUI/Widgets/StateColor.hpp" #include "libslic3r/Utils.hpp" #include @@ -14,6 +15,8 @@ #include #include #include +#include +#include #include #include "slic3r/GUI/GUI_Utils.hpp" #include @@ -153,6 +156,68 @@ std::string WebViewHostDialog::document_start_injector(const std::string& markup return s; } +bool WebViewHostDialog::own_page_navigation(const wxString& url, const wxFileName& page) +{ + if (url == "about:blank") + return true; + return url.Lower().StartsWith("file:") && wxFileSystem::URLToFileName(url.BeforeFirst('?').BeforeFirst('#')).SameAs(page); +} + +boost::filesystem::path WebViewHostDialog::dropped_file(const wxString& url) +{ + if (!url.Lower().StartsWith("file:")) + return {}; + return into_path(wxFileSystem::URLToFileName(url.BeforeFirst('?').BeforeFirst('#')).GetFullPath()); +} + +nlohmann::json WebViewHostDialog::code_editor_strings() +{ + // The annotation, error-marker and gutter-tooltip messages are left out: these editors never show them. + return { + {"autocomplete.loading", _u8L("Loading…")}, + {"autocomplete.popup.aria-label", _u8L("Suggestions")}, + {"autocomplete.popup.aria-roledescription", _u8L("Suggestions")}, + // TRN Read by a screen reader for one entry of the code editor's list of suggestions. + {"autocomplete.popup.item.aria-roledescription", _u8L("Suggestion")}, + // TRN Read by a screen reader for the line numbers beside the code editor. + {"editor.gutter.aria-label", _u8L("Line numbers. Press Enter to use the fold buttons with the arrow keys, and Escape to leave them.")}, + {"editor.gutter.aria-roledescription", _u8L("Line numbers")}, + // TRN Read by a screen reader for the code editor's text. + {"editor.scroller.aria-label", _u8L("Code. Press Enter to start editing, and Escape to leave the editor.")}, + {"editor.scroller.aria-roledescription", _u8L("Code editor")}, + // TRN Shown when a person types in the code editor while a script runs. + {"editor.tooltip.disable-editing", _u8L("You can edit once the run ends.")}, + // TRN The two %s are line numbers. + {"gutter.code-folding.closed.aria-label", _u8L("Unfold lines %s to %s")}, + // TRN A button beside the code editor's line numbers that shows lines it hid. + {"gutter.code-folding.closed.title", _u8L_CONTEXT("Unfold", "Code editor")}, + // TRN %s is a line number. + {"gutter.code-folding.open.aria-label", _u8L("Fold the lines from line %s")}, + // TRN A button beside the code editor's line numbers that hides the lines of a block. + {"gutter.code-folding.open.title", _u8L_CONTEXT("Fold", "Code editor")}, + // TRN The two %s are line numbers. + {"gutter.code-folding.range.aria-label", _u8L("Fold or unfold lines %s to %s")}, + {"inline-fold.closed.title", _u8L_CONTEXT("Unfold", "Code editor")}, + {"search-box.find-all.text", _u8L("Find all")}, + {"search-box.find.placeholder", _u8L("Search for")}, + {"search-box.replace-all.text", _u8L("Replace all")}, + // TRN A button of the code editor's search box that replaces the next match. + {"search-box.replace-next.text", _u8L_CONTEXT("Replace", "Code editor")}, + {"search-box.replace.placeholder", _u8L("Replace with")}, + // TRN The code editor's search box: the first %s is the match the cursor is on, the second how many there are. + {"search-box.search-counter", _u8L("%s of %s")}, + {"search-box.toggle-case.title", _u8L("Match case")}, + {"search-box.toggle-in-selection.title", _u8L("Search in the selection")}, + {"search-box.toggle-regexp.title", _u8L("Use a regular expression")}, + // TRN Shows or hides the replace field of the code editor's search box. + {"search-box.toggle-replace.title", _u8L("Show or hide Replace")}, + {"search-box.toggle-whole-word.title", _u8L("Match whole words")}, + // TRN Read by a screen reader as the cursor moves in the code editor; %s is a line number. + {"text-input.aria-label", _u8L("Cursor on line %s")}, + {"text-input.aria-roledescription", _u8L("Code editor")}, + }; +} + std::string WebViewHostDialog::localized_strings_script(const nlohmann::json& strings) { return "window.ORCA_UI_STRINGS = " + strings.dump(-1, ' ', false, nlohmann::json::error_handler_t::ignore) + ";"; diff --git a/src/slic3r/GUI/Widgets/WebViewHostDialog.hpp b/src/slic3r/GUI/Widgets/WebViewHostDialog.hpp index 27a909b1a5..d0ef3f55ea 100644 --- a/src/slic3r/GUI/Widgets/WebViewHostDialog.hpp +++ b/src/slic3r/GUI/Widgets/WebViewHostDialog.hpp @@ -1,6 +1,7 @@ #ifndef slic3r_GUI_Widgets_WebViewHostDialog_hpp_ #define slic3r_GUI_Widgets_WebViewHostDialog_hpp_ +#include #include #include @@ -17,6 +18,7 @@ #include class wxCommandEvent; +class wxFileName; class wxWebView; class wxWebViewEvent; class wxWindow; @@ -72,6 +74,16 @@ public: // static markup shows its English until the page's init calls TranslatePage(). A host builds them // when it creates its web view; a language switch rebuilds the GUI and with it the host. static std::string localized_strings_script(const nlohmann::json& strings); + // The translated text of the code editor (resources/web/dialog/js/code_editor.js, Ace): its search box, suggestion + // list, read-only note, folding and ARIA labels, keyed by Ace's message keys, with %s for each of a message's + // placeholders. A page with an editor puts it under "code_editor" in its strings. + static nlohmann::json code_editor_strings(); + // Whether a web view showing the bundled page `page` may navigate to `url`: the page's own loads (its file, with any + // query) and about:blank. Such a page never goes anywhere else, so its host vetoes every other navigation, which + // would hand the page's message handler to a page that isn't the app's: a link or a file dropped on it. + static bool own_page_navigation(const wxString& url, const wxFileName& page); + // The file a file: URL names: a web view navigates to a file dropped on it. Empty for any other URL. + static boost::filesystem::path dropped_file(const wxString& url); protected: wxWebView* browser() const { return m_browser; } diff --git a/src/slic3r/plugin/PythonRunScope.cpp b/src/slic3r/plugin/PythonRunScope.cpp index eaa9a4ed2b..08b23c833c 100644 --- a/src/slic3r/plugin/PythonRunScope.cpp +++ b/src/slic3r/plugin/PythonRunScope.cpp @@ -148,9 +148,8 @@ void PythonRunScope::task_finished(unsigned long ident) m_task_targets.erase(it); } -bool PythonRunScope::close_admission_if_quiet() +bool PythonRunScope::quiet_locked() const { - std::lock_guard lock(m_mutex); if (m_admission_closed) return true; if (m_waited_pending > 0 || m_callbacks_active > 0 || m_tasks_outstanding > 0) @@ -158,10 +157,43 @@ bool PythonRunScope::close_admission_if_quiet() for (const auto& [ident, waited] : m_live_threads) if (waited) return false; + return true; +} + +bool PythonRunScope::quiet() const +{ + std::lock_guard lock(m_mutex); + return quiet_locked(); +} + +bool PythonRunScope::close_admission_if_quiet() +{ + std::lock_guard lock(m_mutex); + if (!quiet_locked()) + return false; m_admission_closed = true; return true; } +bool PythonRunScope::has_live_work() const +{ + std::lock_guard lock(m_mutex); + return m_waited_pending > 0 || m_callbacks_active > 0 || m_tasks_outstanding > 0 || !m_live_threads.empty(); +} + +void PythonRunScope::mark_ending() +{ + if (m_ending.exchange(true)) + return; + m_ending_generation.store(m_stop_generation.load()); +} + +bool PythonRunScope::queued_task_refused(std::uint64_t submitted) const +{ + const std::uint64_t now = m_stop_generation.load(); + return now != submitted || (m_ending.load() && now != m_ending_generation.load()); +} + void PythonRunScope::close_admission() { std::lock_guard lock(m_mutex); diff --git a/src/slic3r/plugin/PythonRunScope.hpp b/src/slic3r/plugin/PythonRunScope.hpp index 668d723d4f..59c6e41dea 100644 --- a/src/slic3r/plugin/PythonRunScope.hpp +++ b/src/slic3r/plugin/PythonRunScope.hpp @@ -74,25 +74,39 @@ public: void task_running(unsigned long ident); void task_finished(unsigned long ident); - // Closes admission when nothing the run waits for is left: no waited thread pending or alive, no callback - // running, no task outstanding. Returns whether admission is closed. + // Nothing the run waits for is left: no waited thread pending or alive, no callback running, no task outstanding. + // True once admission has closed. + bool quiet() const; + // Closes admission when quiet(). Returns whether admission is closed. bool close_admission_if_quiet(); void close_admission(); bool admission_closed() const; + // Any thread the run started is alive, daemon or not, or a task of it is outstanding, or a callback of it runs. + bool has_live_work() const; + // Calls `fn` for every interrupt target of the run (its live threads and the workers running its tasks), under // the mutex, so a target can't end, and its ident be reused, while `fn` aims at it. void for_each_interrupt_target(const std::function& fn) const; - // Set at the run's first stop or time-out: its tasks that a pool has not started yet don't run. - bool stopped() const { return m_stopped.load(); } - void mark_stopped() { m_stopped.store(true); } + // Counts the run's stops and time-outs. A task a pool has not started yet doesn't run when a stop came after it + // was submitted (queued_task_refused()); a session's later work submits tasks that run. + std::uint64_t stop_generation() const { return m_stop_generation.load(); } + bool stopped() const { return stop_generation() != 0; } + void mark_stopped() { ++m_stop_generation; } + // The run is ending: no more work comes. From then on a stop refuses every queued task, as a stopped run's. + void mark_ending(); + bool ending() const { return m_ending.load(); } + // Whether a queued task submitted at stop generation `submitted` must not run. + bool queued_task_refused(std::uint64_t submitted) const; // Set when the run's UI is torn down: nothing more opens, and its callbacks do nothing. bool ui_closed() const { return m_ui_closed.load(); } void mark_ui_closed() { m_ui_closed.store(true); } private: + bool quiet_locked() const; + const std::uint64_t m_id; const std::string m_identity; const boost::filesystem::path m_file; @@ -110,7 +124,9 @@ private: int m_tasks_outstanding = 0; std::multiset m_task_targets; - std::atomic m_stopped{false}; + std::atomic m_stop_generation{0}; + std::atomic m_ending{false}; + std::atomic m_ending_generation{0}; std::atomic m_ui_closed{false}; }; diff --git a/src/slic3r/plugin/PythonScriptRunner.cpp b/src/slic3r/plugin/PythonScriptRunner.cpp index e321cf21da..9e5dee5a0e 100644 --- a/src/slic3r/plugin/PythonScriptRunner.cpp +++ b/src/slic3r/plugin/PythonScriptRunner.cpp @@ -5,6 +5,7 @@ #include "PluginLoader.hpp" #include "PythonInterpreter.hpp" #include "PythonRunScope.hpp" +#include "PythonSession.hpp" #include "host/PluginHostTools.hpp" #include "host/PluginHostUi.hpp" @@ -14,6 +15,7 @@ #include #include +#include #include #include #include @@ -23,6 +25,7 @@ #include +#include #include #include #include @@ -30,11 +33,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -59,13 +64,20 @@ import atexit, concurrent.futures.thread, importlib.machinery, os, re, sys, thre class RunInterrupted(BaseException): """Raised in a script's code when its run is cancelled or out of time.""" +_TRUNCATED = "\n[output truncated at 256 KiB]\n" + +# A run's output: kept until the run ends, or, for a session, handed to `sink` (as UTF-8 bytes) as it is written. +# Either way a stretch of output is capped at LIMIT characters and then cut with the note; a session renews the +# allowance as each work starts and ends. A session's `results` takes its results as JSON, within the same allowance. class _Capture: - __slots__ = ("parts", "size", "truncated") + __slots__ = ("parts", "size", "truncated", "sink", "results") LIMIT = 256 * 1024 - def __init__(self): + def __init__(self, sink, results): self.parts = [] self.size = 0 self.truncated = False + self.sink = sink + self.results = results _captures = {} @@ -78,16 +90,21 @@ class _RunStream: if self._original is not None: return self._original.write(s) return len(s) - if not capture.truncated: - room = _Capture.LIMIT - capture.size - if len(s) > room: - capture.parts.append(s[:room]) - capture.size = _Capture.LIMIT - capture.truncated = True - else: - capture.parts.append(s) - capture.size += len(s) - return len(s) + written = len(s) + if capture.truncated: + return written + room = _Capture.LIMIT - capture.size + if written > room: + s = s[:room] + capture.size = _Capture.LIMIT + capture.truncated = True + else: + capture.size += written + if capture.sink is None: + capture.parts.append(s) + else: + capture.sink((s + _TRUNCATED if capture.truncated else s).encode("utf-8", "replace")) + return written def flush(self): if self._original is not None: try: @@ -99,8 +116,25 @@ class _RunStream: def __getattr__(self, name): return getattr(self._original, name) -def begin(run_id): - _captures[run_id] = _Capture() +def begin(run_id, sink=None, results=None): + _captures[run_id] = _Capture(sink, results) + +def result(run_id, text): + """Host bookkeeping: hands a result's JSON to the run's `results`. False when the run has none or the JSON doesn't + fit what is left of the allowance, and the caller prints the result instead.""" + capture = _captures.get(run_id) + if capture is None or capture.results is None or capture.truncated or len(text) > _Capture.LIMIT - capture.size: + return False + capture.size += len(text) + capture.results(text.encode("utf-8", "replace")) + return True + +def renew(run_id): + """Host bookkeeping: a session's next stretch of output gets the whole allowance.""" + capture = _captures.get(run_id) + if capture is not None: + capture.size = 0 + capture.truncated = False def end(run_id): capture = _captures.pop(run_id, None) @@ -108,7 +142,7 @@ def end(run_id): return "" text = "".join(capture.parts) if capture.truncated: - text += "\n[output truncated at 256 KiB]\n" + text += _TRUNCATED return text sys.stdout = _RunStream(sys.stdout) @@ -458,6 +492,124 @@ def leave(run_id): return held )CAPTURE"; +// A session's own helpers in the capture module, run after kCaptureSource in the same module. +constexpr const char* kSessionSource = R"SESSION( +import ast, bisect, io, json, linecache, math, sys, traceback + +# A session's traceback, which quotes the editor's text (`source`) for the frames in the session's file and linecache +# for the others, in the exception and in every exception chained to it or grouped in it. linecache itself is left +# alone: every run, plugin and later traceback shares it, and theirs must quote the file on disk. +def format_quoted(exc_type, exc, tb, filename, source): + lines = io.StringIO(source, newline=None).readlines() + def quoted(stack): + frames = [] + for frame in stack: + line = "" + if frame.lineno: + if frame.filename == filename: + line = lines[frame.lineno - 1] if 0 < frame.lineno <= len(lines) else "" + else: + line = linecache.getline(frame.filename, frame.lineno) + if line and not line.endswith("\n"): + line += "\n" + frames.append(traceback.FrameSummary(frame.filename, frame.lineno, frame.name, lookup_line=False, line=line, + end_lineno=frame.end_lineno, colno=frame.colno, end_colno=frame.end_colno)) + return traceback.StackSummary.from_list(frames) + top = traceback.TracebackException(exc_type, exc, tb, lookup_lines=False) + seen = set() + todo = [top] + while todo: + item = todo.pop() + if id(item) in seen: + continue + seen.add(id(item)) + item.stack = quoted(item.stack) + todo.extend(nested for nested in (item.__cause__, item.__context__) if nested is not None) + todo.extend(item.exceptions or ()) + return "".join(top.format()) + +def error_line(exc, tb, filename): + """The innermost line of `tb` in `filename`, or a SyntaxError's own line there; 0 for none.""" + if isinstance(exc, SyntaxError) and exc.filename == filename and isinstance(exc.lineno, int): + return exc.lineno + line = 0 + while tb is not None: + if tb.tb_frame.f_code.co_filename == filename and tb.tb_lineno: + line = tb.tb_lineno + tb = tb.tb_next + return line + +# A File work's cells, reported as their lines start running: LINE events on its module code only, through +# sys.monitoring's tool id 4 while the work runs. False when another owner holds the id. +_CELLS_TOOL = 4 + +def claim_cells(code, starts, emit): + monitoring = sys.monitoring + try: + monitoring.use_tool_id(_CELLS_TOOL, "OrcaSlicer Run Script") + except ValueError: + return False + current = [-1] + def line(where, number, _code=code, _starts=starts, _emit=emit, _current=current, _find=bisect.bisect_right): + if where is _code: + cell = max(_find(_starts, number) - 1, 0) + if cell != _current[0]: + _current[0] = cell + _emit(cell) + monitoring.register_callback(_CELLS_TOOL, monitoring.events.LINE, line) + monitoring.set_local_events(_CELLS_TOOL, code, monitoring.events.LINE) + return True + +def release_cells(code): + """Host bookkeeping: the events and the callback go before the id, since freeing it leaves both in place.""" + monitoring = sys.monitoring + monitoring.set_local_events(_CELLS_TOOL, code, 0) + monitoring.register_callback(_CELLS_TOOL, monitoring.events.LINE, None) + monitoring.free_tool_id(_CELLS_TOOL) + +# A File work's module with each cell's result shown, as a Cell work shows its own: the last top-level statement that +# starts in a cell, when it is a bare expression, becomes a call with its value to `show`, the name the host binds to +# show_result() in the work's namespace, so neither __import__ nor sys.modules stands between a cell and its value. +# Every statement keeps its lines, so cells, tracebacks and error lines are the file's. The module's docstring stays its +# docstring. +def mark_cell_results(tree, starts, show): + body = tree.body + last = {} + for at, statement in enumerate(body): + last[max(bisect.bisect_right(starts, statement.lineno) - 1, 0)] = at + for at in last.values(): + statement = body[at] + if not isinstance(statement, ast.Expr): + continue + if at == 0 and isinstance(statement.value, ast.Constant) and isinstance(statement.value.value, str): + continue + statement.value = ast.copy_location(ast.Call(ast.Name(show, ast.Load()), [statement.value], []), statement.value) + ast.fix_missing_locations(tree) + +# A result as compact JSON when it is a dict or a list that JSON holds as is: str keys, finite floats, strings UTF-8 +# holds (no lone surrogate, which the trip to the page would replace), and no tuple, subclass or other value JSON would +# turn into something else. None otherwise, and for anything too deep or that can't be written; never raises an +# Exception. +def result_json(value): + def plain(item, depth): + kind = type(item) + if kind is dict: + return depth < 100 and all(type(key) is str and plain(member, depth + 1) for key, member in item.items()) + if kind is list: + return depth < 100 and all(plain(member, depth + 1) for member in item) + if kind is float: + return math.isfinite(item) + return item is None or kind is str or kind is int or kind is bool + try: + if type(value) in (dict, list) and plain(value, 0): + text = json.dumps(value, ensure_ascii=False) + text.encode("utf-8") + return text + except Exception: + pass + return None +)SESSION"; + // The capture module's functions and interrupt, installed on first use and held from then on, so a script // that rebinds the module's names or replaces it in sys.modules changes nothing the runner calls. The // references are kept for the process: dropping them after the interpreter finalizes would crash. GIL held. @@ -474,21 +626,75 @@ struct Capture PyObject* take_exits = nullptr; PyObject* call_exits = nullptr; PyObject* dependencies = nullptr; + PyObject* renew = nullptr; + PyObject* format_quoted = nullptr; + PyObject* error_line = nullptr; + PyObject* claim_cells = nullptr; + PyObject* release_cells = nullptr; + PyObject* mark_cell_results = nullptr; + PyObject* result_json = nullptr; + PyObject* result = nullptr; + PyObject* show_result = nullptr; }; -// A work item's tag (item._orca_run, a capsule that owns it): the run it belongs to and its task's accounting there, -// in plain C++, so nothing between taking the count and recording it, or between testing the claim and setting it, can -// raise or run Python code. +// The name a File work's namespace binds show_result() to for the calls mark_cell_results() puts in its cells. A +// leading underscore keeps it out of the session's variable count. +constexpr const char* kShowResultName = "_orca_show_result"; + +// The work a session's hosting thread runs now, for the show_result() calls mark_cell_results() puts in a File work. +// The function is one for every run and can outlive the work in a script's hands, so it finds the work here rather than +// holding it. +struct ResultTarget +{ + py::dict* ns = nullptr; + std::uint64_t run_id = 0; + const Capture* capture = nullptr; +}; +thread_local const ResultTarget* t_result_target = nullptr; + +// The thread's ResultTarget while a work's code runs. +class ScopedResultTarget +{ +public: + explicit ScopedResultTarget(const ResultTarget& target) : m_previous(t_result_target) { t_result_target = ⌖ } + ~ScopedResultTarget() { t_result_target = m_previous; } + ScopedResultTarget(const ScopedResultTarget&) = delete; + ScopedResultTarget& operator=(const ScopedResultTarget&) = delete; + +private: + const ResultTarget* m_previous; +}; + +// A work's or a cell's result, as the REPL shows one: `_` names it, and the session gets it as a Result event when +// result_json() writes it and it fits the output's allowance, else it is printed as its repr. Nothing for None. It is +// C++, so a repr that raises leaves no frame of the host's in the traceback. GIL held. +void show_result(const py::object& value, const ResultTarget& target) +{ + if (value.is_none()) + return; + (*target.ns)["_"] = value; + const py::object text = py::handle(target.capture->result_json)(value); + if (!text.is_none() && py::handle(target.capture->result)(target.run_id, text).cast()) + return; + const py::module_ builtins = py::module_::import("builtins"); + builtins.attr("print")(builtins.attr("repr")(value)); +} + +// A work item's tag (item._orca_run, a capsule that owns it): the run it belongs to, the run's stop generation when the +// task was submitted, and its task's accounting there, in plain C++, so nothing between taking the count and recording +// it, or between testing the claim and setting it, can raise or run Python code. struct ItemTag { std::shared_ptr run; - bool counted = false; - bool claimed = false; + std::uint64_t generation = 0; + bool counted = false; + bool claimed = false; }; py::capsule item_tag(std::shared_ptr run) { - return py::capsule(new ItemTag{std::move(run)}, [](void* tag) { delete static_cast(tag); }); + const std::uint64_t generation = run->stop_generation(); + return py::capsule(new ItemTag{std::move(run), generation}, [](void* tag) { delete static_cast(tag); }); } ItemTag& tag_of(const py::handle& capsule) { return *static_cast(py::reinterpret_borrow(capsule).get_pointer()); } @@ -536,11 +742,14 @@ py::object run_work_item(const py::object& original, const py::handle& interrupt const unsigned long ident = PyThread_get_thread_ident(); run->task_running(ident); try { - if (run->stopped() || run->admission_closed()) { - // A stopped or ended run's queued task doesn't run. - py::object future = item.attr("future"); + const bool ended = run->admission_closed(); + if (ended || run->queued_task_refused(tag.generation)) { + // A queued task doesn't run once its run has ended, or once a stop came after it was submitted; a + // session that goes on after the stop runs the tasks its later work submits. + const char* why = ended || run->ending() ? "The script's run has ended" : "The task was stopped before it ran"; + py::object future = item.attr("future"); if (future.attr("set_running_or_notify_cancel")().cast()) - future.attr("set_exception")(py::module_::import("builtins").attr("RuntimeError")("The script's run has ended")); + future.attr("set_exception")(py::module_::import("builtins").attr("RuntimeError")(why)); } else original(item); } catch (py::error_already_set& err) { @@ -591,7 +800,13 @@ const Capture& capture_functions() module.attr("_count") = py::cpp_function([](const py::handle& capsule) { return count_item(tag_of(capsule)); }); module.attr("_claim") = py::cpp_function([](const py::handle& capsule) { return claim_item(tag_of(capsule)); }); module.attr("_task_done") = py::cpp_function([](const py::handle& capsule) { tag_of(capsule).run->task_done(); }); + // Off the hosting thread of the File work that runs it, it shows nothing. + module.attr("show_result") = py::cpp_function([](const py::object& value) { + if (t_result_target != nullptr) + show_result(value, *t_result_target); + }); py::exec(kCaptureSource, module.attr("__dict__")); + py::exec(kSessionSource, module.attr("__dict__")); py::module_::import("sys").attr("modules")[kCaptureModule] = module; const auto hold = [&module](const char* name) { return py::object(module.attr(name)).release().ptr(); }; capture.end = hold("end"); @@ -604,6 +819,15 @@ const Capture& capture_functions() capture.take_exits = hold("take_exits"); capture.call_exits = hold("call_exits"); capture.dependencies = hold("script_dependencies"); + capture.renew = hold("renew"); + capture.format_quoted = hold("format_quoted"); + capture.error_line = hold("error_line"); + capture.claim_cells = hold("claim_cells"); + capture.release_cells = hold("release_cells"); + capture.mark_cell_results = hold("mark_cell_results"); + capture.result_json = hold("result_json"); + capture.result = hold("result"); + capture.show_result = hold("show_result"); { py::object item_class = py::module_::import("concurrent.futures.thread").attr("_WorkItem"); py::object original = item_class.attr("run"); @@ -693,21 +917,46 @@ json strict_json(const py::handle& value, int depth = 0) throw std::invalid_argument("result holds a " + std::string(Py_TYPE(value.ptr())->tp_name) + ", which is not JSON"); } -// Interrupts the run when it is cancelled or out of time, until stopped. What it interrupts depends on the run's -// phase: in Body (the code runs) and Exit (atexit functions, the namespace's finalizers, the folder's teardown) the -// run's thread and its interrupt targets; in Threads (the run's thread waits in C++ for the work it started) the -// targets only; in Drain (host bookkeeping) nothing, though it still records a stop or time-out. The phase is set, -// and read before an interrupt, under the GIL, so no interrupt lands after the phase that allowed it. +// How long a stop reaches a session's threads and tasks while it is idle, and how long a run or session's end waits for +// the work it started once a stop came. +constexpr std::chrono::seconds kStopWindow{5}; + +// Interrupts what a run or session runs when it is stopped, cancelled or out of time. What it interrupts depends on the +// phase: in Body (a work's code runs) and Exit (atexit functions, the namespace's finalizers, the folder's teardown) the +// hosting thread and the interrupt targets; in Threads (the hosting thread waits in C++ for the work it started) and +// Idle (a session waits for work) the targets only; in Drain (host bookkeeping) nothing, though it still records a stop. +// The phase is set, and read before an interrupt, under the GIL, so no interrupt lands after the phase that allowed it. +// +// A session's stop() reaches what runs from then until the next work starts, and while the session is idle only for +// kStopWindow; a cancel or a time-out reaches everything until the end, and ends the session. +// +// Lock order: the GIL before this object's mutex, and this mutex before the scope's. class Watcher { public: - enum class Reason { None, Cancelled, TimedOut }; - enum class Phase { Body, Threads, Exit, Drain }; + enum class Reason { None, Stopped, Cancelled, TimedOut }; + enum class Phase { Body, Threads, Exit, Drain, Idle }; - Watcher(const PythonRunRequest& request, unsigned long thread_ident, PyObject* interrupt, std::shared_ptr scope) - : m_request(request), m_ident(thread_ident), m_interrupt(interrupt), m_scope(std::move(scope)), m_thread([this] { run(); }) + struct Config + { + std::function cancelled; + std::chrono::milliseconds budget{0}; + std::function stop_calls; + bool stop_closes_ui = false; + }; + + Watcher(Config config, PythonSession& session, unsigned long thread_ident, PyObject* interrupt, std::shared_ptr scope) + : m_config(std::move(config)) + , m_session(session) + , m_ident(thread_ident) + , m_interrupt(interrupt) + , m_scope(std::move(scope)) + , m_start(std::chrono::steady_clock::now()) + , m_thread([this] { run(); }) {} ~Watcher() { stop(); } + Watcher(const Watcher&) = delete; + Watcher& operator=(const Watcher&) = delete; // Ends the watcher. Call without the GIL: an interrupt it is raising needs it. void stop() @@ -720,76 +969,159 @@ public: if (m_thread.joinable()) m_thread.join(); } - Reason reason() const { return m_reason.load(); } + // Takes in the stops asked for so far, as the watcher's own loop does, so a work's tasks are counted after them, and + // waits until no stop is still being applied (its tool calls cancelled, its modal windows ended), this call's own or + // one the loop took, so the next work's calls never meet a stop meant for the work before. Call without the GIL. + void settle() + { + std::unique_lock lock(m_mutex); + take_stops(lock); + m_cv.wait(lock, [this] { return m_applying == 0; }); + } + // With the GIL held, as a work starts: only the stops asked for after the first `floor` reach it. + void begin_work(std::uint64_t floor) + { + std::lock_guard lock(m_mutex); + m_floor = floor; + } + // With the GIL held, as the teardown starts: a stop older than kStopWindow no longer reaches it. + void begin_teardown() + { + std::lock_guard lock(m_mutex); + if (m_stops_seen > m_floor && std::chrono::steady_clock::now() - m_last_stop >= kStopWindow) + m_floor = m_stops_seen; + } + // What reaches what runs now: the end (a cancel or a time-out) when one came, else Stopped when a stop came since the + // work started. + Reason reason() const + { + std::lock_guard lock(m_mutex); + return reason_locked(); + } // With the GIL held. void set_phase(Phase phase) { m_phase = phase; } - // Time since the run's first stop or time-out, or nullopt before it. + // Time since the stop, cancel or time-out that reaches what runs now, or nullopt when none does. std::optional since_stop() const { - const long long at = m_stopped_at.load(); - if (at < 0) + std::lock_guard lock(m_mutex); + const Reason why = reason_locked(); + if (why == Reason::None) return std::nullopt; - return std::chrono::steady_clock::now().time_since_epoch() - std::chrono::steady_clock::duration(at); + return std::chrono::steady_clock::now() - (why == Reason::Stopped ? m_last_stop : m_end_at); } private: + Reason reason_locked() const + { + if (m_end != Reason::None) + return m_end; + return m_stops_seen > m_floor ? Reason::Stopped : Reason::None; + } + + // Records new stop requests, a cancel and a time-out, and does what each asks: the run's queued tasks are refused, + // its tool calls cancelled, and its modal windows ended (every window of a run that closes its UI at a stop). A + // cancel or a time-out also ends the session; the first of them sticks. `lock` is released while that is done. + void take_stops(std::unique_lock& lock) + { + const auto now = std::chrono::steady_clock::now(); + bool stopped = false; + if (const std::uint64_t asked = m_session.stop_requests(); asked > m_stops_seen) { + m_stops_seen = asked; + m_last_stop = now; + stopped = true; + } + Reason end = Reason::None; + if (m_end == Reason::None) { + if (m_config.cancelled && m_config.cancelled()) + end = Reason::Cancelled; + else if (m_config.budget.count() > 0 && now - m_start >= m_config.budget) + end = Reason::TimedOut; + } + if (end != Reason::None) { + m_end = end; + m_end_at = now; + } + if (!stopped && end == Reason::None) + return; + m_last_interrupt = {}; + m_scope->mark_stopped(); + ++m_applying; + lock.unlock(); + if (m_config.stop_calls) + m_config.stop_calls(); + if (m_scope->owns_ui()) { + // A stopped run opens nothing more, and what it has open closes now, which ends a modal loop it waits in. A + // stopped session keeps its modeless windows and only leaves the modal loops. + if (m_config.stop_closes_ui) { + m_scope->mark_ui_closed(); + PluginHostUi::close_windows_for_plugin(m_scope->ui_owner()); + } else + PluginHostUi::end_run_modals(m_scope->ui_owner()); + } + if (end != Reason::None) + m_session.end(); + lock.lock(); + --m_applying; + m_cv.notify_all(); + } + void run() { - const auto start = std::chrono::steady_clock::now(); - auto last = std::chrono::steady_clock::time_point{}; std::unique_lock lock(m_mutex); while (!m_cv.wait_for(lock, std::chrono::milliseconds(50), [this] { return m_stop; })) { - Reason why = Reason::None; - if (m_request.cancelled && m_request.cancelled()) - why = Reason::Cancelled; - else if (m_request.budget.count() > 0 && std::chrono::steady_clock::now() - start >= m_request.budget) - why = Reason::TimedOut; - if (why == Reason::None) - continue; - // The first reason sticks: a run cancelled after its budget ran out still timed out. - Reason expected = Reason::None; - if (m_reason.compare_exchange_strong(expected, why)) { - m_stopped_at = std::chrono::steady_clock::now().time_since_epoch().count(); - m_scope->mark_stopped(); - lock.unlock(); - if (m_request.stop_calls) - m_request.stop_calls(); - // A stopped script opens nothing more, and what it has open closes now, which ends a modal loop it - // waits in. - if (m_scope->owns_ui()) { - m_scope->mark_ui_closed(); - PluginHostUi::close_windows_for_plugin(m_scope->ui_owner()); - } - lock.lock(); - } + m_session.set_has_threads(m_scope->has_live_work()); + take_stops(lock); const auto now = std::chrono::steady_clock::now(); - if (now - last < std::chrono::seconds(1)) + if (reason_locked() == Reason::None || now - m_last_interrupt < std::chrono::seconds(1)) continue; - last = now; lock.unlock(); // The run holds an interpreter lease until this watcher is stopped, so the interpreter is up. const PyGILState_STATE gil = PyGILState_Ensure(); const Phase phase = m_phase.load(); - if (phase == Phase::Body || phase == Phase::Exit) + bool reaches; + { + std::lock_guard again(m_mutex); + reaches = m_end != Reason::None || + (m_stops_seen > m_floor && (phase != Phase::Idle || now - m_last_stop < kStopWindow)); + } + bool sent = false; + if (reaches && (phase == Phase::Body || phase == Phase::Exit)) { PyThreadState_SetAsyncExc(m_ident, m_interrupt); - if (phase != Phase::Drain) - m_scope->for_each_interrupt_target([this](unsigned long ident) { PyThreadState_SetAsyncExc(ident, m_interrupt); }); + sent = true; + } + if (reaches && phase != Phase::Drain) + m_scope->for_each_interrupt_target([this, &sent](unsigned long ident) { + PyThreadState_SetAsyncExc(ident, m_interrupt); + sent = true; + }); PyGILState_Release(gil); lock.lock(); + // Nothing sent (host bookkeeping, no target yet): tried again at the next poll. + if (sent) + m_last_interrupt = now; } } - const PythonRunRequest& m_request; - const unsigned long m_ident; - PyObject* m_interrupt; - std::shared_ptr m_scope; - std::mutex m_mutex; - std::condition_variable m_cv; - bool m_stop = false; - std::atomic m_reason{Reason::None}; - std::atomic m_phase{Phase::Body}; // set and read under the GIL - std::atomic m_stopped_at{-1}; - std::thread m_thread; + const Config m_config; + PythonSession& m_session; + const unsigned long m_ident; + PyObject* m_interrupt; + std::shared_ptr m_scope; + const std::chrono::steady_clock::time_point m_start; + mutable std::mutex m_mutex; + std::condition_variable m_cv; + bool m_stop = false; + // How many stops are having their tool calls and modal windows dealt with, outside the lock (take_stops()): the loop + // and settle() can each be applying one. + int m_applying = 0; + std::uint64_t m_stops_seen = 0; + std::uint64_t m_floor = 0; + std::chrono::steady_clock::time_point m_last_stop{}; + Reason m_end = Reason::None; + std::chrono::steady_clock::time_point m_end_at{}; + std::chrono::steady_clock::time_point m_last_interrupt{}; + std::atomic m_phase{Phase::Body}; // set and read under the GIL + std::thread m_thread; }; std::string format_traceback(py::error_already_set& err) @@ -815,51 +1147,154 @@ std::string exception_line(py::error_already_set& err) } } +py::object trace_of(py::error_already_set& err) { return err.trace() ? py::object(err.trace()) : py::object(py::none()); } + +// A session's traceback, quoting `source` for its file's frames; today's format when that can't be made. +std::string quoted_traceback(const Capture& capture, py::error_already_set& err, const std::string& filename, const std::string& source) +{ + try { + return py::handle(capture.format_quoted)(err.type(), err.value(), trace_of(err), filename, source).cast(); + } catch (const std::exception&) { + return format_traceback(err); + } +} + +int error_line_of(const Capture& capture, py::error_already_set& err, const std::string& filename) +{ + try { + return py::handle(capture.error_line)(err.value(), trace_of(err), filename).cast(); + } catch (const std::exception&) { + return 0; + } +} + +// The names a person calls the session's variables: not starting with '_', not `args`, not modules. Reads the dict +// without running Python code. GIL held. +int count_variables(const py::dict& ns) +{ + int count = 0; + PyObject* key = nullptr; + PyObject* value = nullptr; + Py_ssize_t pos = 0; + while (PyDict_Next(ns.ptr(), &pos, &key, &value)) { + if (!PyUnicode_Check(key)) + continue; + Py_ssize_t size = 0; + const char* name = PyUnicode_AsUTF8AndSize(key, &size); + if (name == nullptr) { + PyErr_Clear(); + continue; + } + const std::string_view text(name, static_cast(size)); + if (text.empty() || text.front() == '_' || text == "args" || PyModule_Check(value)) + continue; + ++count; + } + return count; +} + +PythonSessionEvent finished_event(std::string status, std::string message = {}) +{ + PythonSessionEvent event; + event.kind = PythonSessionEvent::Kind::Finished; + event.status = std::move(status); + event.message = std::move(message); + return event; +} + +// The status of a work an interrupt ended, from what reached it. With `ran_on`, a work that finished while a stop +// reached what it ran on into (its threads, or the session's teardown, whose finalizer swallowed the interrupt, as +// Python ignores what __del__ raises) did not finish in time either. +void resolve_interrupted(PythonSessionEvent& done, Watcher::Reason reason, bool ran_on, std::chrono::milliseconds budget) +{ + if (ran_on && done.status == "finished" && reason != Watcher::Reason::None) + done.status = "interrupted"; + if (done.status != "interrupted") + return; + if (reason == Watcher::Reason::None) { + // The code raised the interrupt itself. + done.status = "raised"; + done.message = "RunInterrupted"; + return; + } + done.result = nullptr; + if (reason == Watcher::Reason::TimedOut) { + done.status = "timed_out"; + done.message = "The script ran longer than its " + std::to_string(budget.count() / 1000) + " s budget"; + } else { + done.status = "cancelled"; + done.message = reason == Watcher::Reason::Cancelled ? "The script was cancelled" : "The script was stopped"; + } +} + +PythonSessionEvent output_event(std::string text) +{ + PythonSessionEvent event; + event.kind = PythonSessionEvent::Kind::Output; + event.text = std::move(text); + return event; +} + } // namespace -PythonRunOutcome run_python_code(const PythonRunRequest& request) +void host_python_session(const PythonSessionRequest& request, PythonSession& session) { - PythonRunOutcome outcome; - std::string result_note; + struct Returned + { + PythonSession& session; + ~Returned() { session.host_returned(); } + } returned{session}; + + // Nothing is set up before the first work: a session ended or cancelled before it leaves nothing behind. + std::uint64_t floor = 0; + std::optional work; + while (!(work = session.take_work(std::chrono::milliseconds(50), floor))) + if (session.end_requested() || (request.cancelled && request.cancelled())) + return; + // The first work ends without running, and the session with it. + const auto refuse = [&session](const char* status, std::string message) { + PythonSessionEvent done = finished_event(status, std::move(message)); + done.executed = false; + session.push_event(std::move(done)); + }; if (!PythonInterpreter::instance().is_initialized()) { - outcome.status = "unavailable"; - outcome.message = "Python is not available in this OrcaSlicer"; - return outcome; + refuse("unavailable", "Python is not available in this OrcaSlicer"); + return; } PythonRuntimeLease lease = PythonInterpreter::instance().acquire_runtime_lease(); if (!lease) { - outcome.status = "unavailable"; - outcome.message = "Python is shutting down"; - return outcome; + refuse("unavailable", "Python is shutting down"); + return; } const boost::filesystem::path file = run_file(request.filename); auto scope = std::make_shared(g_next_run_id++, request.identity, file, current_tool_bridge()); ScopedPythonRun bound(scope, PythonRunThread::Main); const std::uint64_t run_id = scope->id(); + if (session.end_requested()) + scope->mark_ending(); py::gil_scoped_acquire gil; - const unsigned long ident = PyThread_get_thread_ident(); - const Capture* capture = nullptr; + const unsigned long ident = PyThread_get_thread_ident(); + const Capture* capture = nullptr; try { capture = &capture_functions(); } catch (py::error_already_set& err) { - outcome.status = "unavailable"; - outcome.message = std::string("Cannot prepare the Python run: ") + err.what(); - return outcome; + refuse("unavailable", std::string("Cannot prepare the Python run: ") + err.what()); + return; } py::handle interrupt(capture->interrupt); - // A file run's PEP 723 dependencies are installed before its code, as a plugin's are; a block that can't be read - // or an install that fails stops the run there. The install runs without the GIL, bounded by uv's own limit. + // A file session's PEP 723 dependencies are installed before its first work, as a plugin's are; a block that can't + // be read or an install that fails ends the session there. The install runs without the GIL, bounded by uv's own + // limit. if (!file.empty()) { std::vector packages; try { - packages = py::handle(capture->dependencies)(request.code).cast>(); + packages = py::handle(capture->dependencies)(work->source).cast>(); } catch (py::error_already_set& err) { - outcome.status = "raised"; - outcome.message = "Cannot read the script's PEP 723 block: " + exception_line(err); - return outcome; + refuse("raised", "Cannot read the script's PEP 723 block: " + exception_line(err)); + return; } if (!packages.empty()) { std::string error; @@ -869,32 +1304,32 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) installed = install_dependencies(packages, error); } if (!installed) { - outcome.status = "raised"; - outcome.message = "Cannot install the script's dependencies: " + error; - return outcome; + refuse("raised", "Cannot install the script's dependencies: " + error); + return; } } } - // Everything below that can run the script's Python (its body, a result's or exception's own methods, - // finalizers of what its namespace and traceback hold) runs inside the script's audit scope and under the - // watcher, so none of it escapes the identity, the budget or a cancel. - Watcher::Reason reason = Watcher::Reason::None; + // Everything below that can run the script's Python (its works, a result's or exception's own methods, finalizers of + // what its namespace and tracebacks hold) runs inside the script's audit scope and under the watcher, so none of it + // escapes the identity, the budget, a stop or a cancel. + std::string notes; // what follows the captured output when it is not streamed + std::optional deferred; // a work's Finished event when the session's end was asked before it + Watcher::Reason deferred_reason = Watcher::Reason::None; + Watcher::Reason reason = Watcher::Reason::None; { ScopedPluginAuditContext audit(request.identity); - Watcher watcher(request, ident, interrupt.ptr(), scope); - std::optional failure; + Watcher watcher(Watcher::Config{request.cancelled, request.budget, request.stop_calls, request.stop_closes_ui}, session, ident, + interrupt.ptr(), scope); py::dict ns; - bool executed = false; - bool entered = false; - // The body is the run's main program, which `python file.py` runs on a non-daemon thread, so the threads it - // starts are waited for unless they say otherwise. The app runs it on a thread Python didn't start, which - // Python sees as a daemon dummy thread, so the body runs with that flag cleared. Thread.daemon refuses a - // started thread, hence _daemonic. - py::object main_thread; - bool was_daemon = false; - // Host bookkeeping that an interrupt must not cut in half (a folder's use count, what its teardown takes) runs - // in the Drain phase, with an interrupt already sent dropped. The caller sets the phase that follows. + bool entered = false; + py::object main_thread; + py::object builtins = py::module_::import("builtins"); + // A deferred work's exception, which keeps its frames until the teardown drops it, as a run's does. + std::optional held_failure; + // Host bookkeeping that an interrupt must not cut in half (a folder's use count, what its teardown takes, the + // monitoring id) runs in the Drain phase, with an interrupt already sent dropped. The caller sets the phase that + // follows. const auto uninterrupted = [&](const auto& step) { watcher.set_phase(Watcher::Phase::Drain); PyThreadState_SetAsyncExc(ident, nullptr); @@ -923,15 +1358,24 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) } } }; + + // The session's own __main__ and output; a file session also gets __file__, sys.argv and imports from its + // folder. A teardown an earlier run from this folder left pending runs before the first work. + bool ready = false; try { py::object taken; uninterrupted([&] { main_thread = py::module_::import("threading").attr("current_thread")(); - was_daemon = main_thread.attr("daemon").cast(); - if (was_daemon) - main_thread.attr("_daemonic") = false; - py::handle(capture->begin)(run_id); - // The run's own __main__: a file run also gets __file__, sys.argv and imports from its folder. + if (request.stream_output) { + PythonSession* target = &session; + py::handle(capture->begin)(run_id, py::cpp_function([target](const std::string& text) { target->push_event(output_event(text)); }), + py::cpp_function([target](const std::string& text) { + PythonSessionEvent event = output_event(text); + event.kind = PythonSessionEvent::Kind::Result; + target->push_event(std::move(event)); + })); + } else + py::handle(capture->begin)(run_id); const py::tuple entry = py::handle(capture->enter)(run_id, file.empty() ? py::object(py::none()) : py::str(request.filename)) .cast(); ns = entry[0].cast(); @@ -939,83 +1383,240 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) entered = true; }); watcher.set_phase(Watcher::Phase::Body); - // A teardown an earlier run from this folder left pending runs before this run's code. if (taken && !taken.is_none()) to_end([&] { py::handle(capture->teardown)(taken); }); - taken = py::object(); - py::module_ builtins = py::module_::import("builtins"); - ns["__builtins__"] = builtins; + taken = py::object(); + ns["__builtins__"] = builtins; ns["args"] = json_to_py(request.args); - // Text: a BOM a file's text kept is dropped, as Python drops it from a file. - const bool bom = request.code.compare(0, 3, "\xEF\xBB\xBF") == 0; - py::object code = builtins.attr("compile")(py::str(bom ? request.code.substr(3) : request.code), request.filename, "exec"); - builtins.attr("exec")(code, ns); - executed = true; + ready = true; } catch (py::error_already_set& err) { - failure.emplace(std::move(err)); + deferred = finished_event("raised", exception_line(err)); + deferred->traceback = format_traceback(err); + deferred->executed = false; } catch (const std::exception& e) { - // Never past the watcher while it may wait for the GIL this thread holds. - outcome.status = "raised"; - outcome.message = e.what(); + deferred = finished_event("raised", e.what()); + deferred->executed = false; } - if (was_daemon && PyObject_SetAttrString(main_thread.ptr(), "_daemonic", Py_True) != 0) - PyErr_Clear(); - try { - if (failure && failure->matches(PyExc_SystemExit)) { - py::object exit_code = failure->value().attr("code"); - if (exit_code.is_none() || (py::isinstance(exit_code) && exit_code.cast() == 0)) { - failure.reset(); - executed = true; - } + // One work, up to its Finished event, whose status may still be "interrupted" for resolve_interrupted(). + const auto run_one = [&](const PythonWork& w) { + PythonSessionEvent done = finished_event(""); + const bool is_file = w.kind == PythonWork::Kind::File; + watcher.set_phase(Watcher::Phase::Drain); + { + py::gil_scoped_release release; + watcher.settle(); + if (request.work_started) + request.work_started(); } - if (failure && !failure->matches(interrupt)) { - outcome.status = "raised"; - outcome.message = exception_line(*failure); - outcome.traceback = format_traceback(*failure); - } else if (!failure && executed && ns.contains("result")) { - try { - outcome.result = strict_json(ns["result"]); - outcome.status = "finished"; - } catch (const std::invalid_argument& e) { - if (file.empty()) { - outcome.status = "raised"; - outcome.message = e.what(); - } else { - // A standalone script may well have a variable named result: it is no result, not a failure. - outcome.status = "finished"; - result_note = std::string("\n[result is not JSON, so it was not returned: ") + e.what() + "]\n"; + std::optional failure; + bool started = false; + bool completed = false; + bool was_daemon = false; + bool claimed = false; + auto cells_sent = std::make_shared>(false); + py::object code; + try { + // A work is the session's main program, which `python file.py` runs on a non-daemon thread, so the + // threads it starts are waited for unless they say otherwise. The app hosts it on a thread Python didn't + // start, which Python sees as a daemon dummy thread, so the work runs with that flag cleared. + // Thread.daemon refuses a started thread, hence _daemonic. + uninterrupted([&] { + watcher.begin_work(floor); + if (session.end_requested()) + scope->mark_ending(); + if (request.stream_output) + py::handle(capture->renew)(run_id); + was_daemon = main_thread.attr("daemon").cast(); + if (was_daemon) + main_thread.attr("_daemonic") = false; + }); + watcher.set_phase(Watcher::Phase::Body); + py::object expr; + if (is_file) { + // Text: a BOM a file's text kept is dropped, as Python drops it from a file. + const bool bom = w.code.compare(0, 3, "\xEF\xBB\xBF") == 0; + const py::str text = py::str(bom ? w.code.substr(3) : w.code); + if (request.cell_results) { + const py::object tree = builtins.attr("compile")(text, request.filename, "exec", + py::module_::import("ast").attr("PyCF_ONLY_AST"), true); + py::handle(capture->mark_cell_results)(tree, py::cast(w.cell_starts), kShowResultName); + code = builtins.attr("compile")(tree, request.filename, "exec", 0, true); + // Bound again for each work, so one that deleted it doesn't take it from the next. + ns[kShowResultName] = py::handle(capture->show_result); + } else + code = builtins.attr("compile")(text, request.filename, "exec"); + } else { + // A Cell compiles at its own lines of the file; a trailing bare expression is split off and + // evaluated, as the REPL shows one. Only builtins compile it, so a SyntaxError's traceback holds no + // frame of the host's. + const std::string filename = w.kind == PythonWork::Kind::Console ? std::string("") : request.filename; + const std::string text = w.kind == PythonWork::Kind::Cell ? std::string(std::max(w.first_line - 1, 0), '\n') + w.code + : w.code; + const py::module_ ast = py::module_::import("ast"); + const py::object tree = builtins.attr("compile")(py::str(text), filename, "exec", ast.attr("PyCF_ONLY_AST"), true); + py::list body = tree.attr("body"); + if (py::len(body) > 0 && py::isinstance(body[py::len(body) - 1], ast.attr("Expr"))) + expr = builtins.attr("compile")(ast.attr("Expression")(body.attr("pop")().attr("value")), filename, "eval", 0, true); + code = builtins.attr("compile")(tree, filename, "exec", 0, true); + } + started = true; + if (is_file && request.report_cells) { + uninterrupted([&] { + PythonSession* target = &session; + claimed = py::handle(capture->claim_cells)(code, py::cast(w.cell_starts), py::cpp_function([target, cells_sent](int cell) { + PythonSessionEvent event; + event.kind = PythonSessionEvent::Kind::Cell; + event.cell = cell; + cells_sent->store(true); + target->push_event(std::move(event)); + })).cast(); + }); + watcher.set_phase(Watcher::Phase::Body); + } + const ResultTarget result_target{&ns, run_id, capture}; + const ScopedResultTarget showing(result_target); + builtins.attr("exec")(code, ns); + if (expr) + show_result(builtins.attr("eval")(expr, ns), result_target); + completed = true; + } catch (py::error_already_set& err) { + failure.emplace(std::move(err)); + } catch (const std::exception& e) { + // Never past the watcher while it may wait for the GIL this thread holds. + done.status = "raised"; + done.message = e.what(); + } + if (claimed) { + quietly([&] { uninterrupted([&] { py::handle(capture->release_cells)(code); }); }); + watcher.set_phase(Watcher::Phase::Body); + } + if (was_daemon && PyObject_SetAttrString(main_thread.ptr(), "_daemonic", Py_True) != 0) + PyErr_Clear(); + + try { + if (failure && failure->matches(PyExc_SystemExit)) { + py::object exit_code = failure->value().attr("code"); + if (exit_code.is_none() || (py::isinstance(exit_code) && exit_code.cast() == 0)) { + failure.reset(); + completed = true; } } - } else if (!failure && executed) - outcome.status = "finished"; - } catch (py::error_already_set& err) { - // The result's own code raised, or the run was interrupted while it ran. - if (!err.matches(interrupt)) { - outcome.status = "raised"; - outcome.message = exception_line(err); - } else - failure.emplace(std::move(err)); - } - if (outcome.status.empty()) - outcome.status = "interrupted"; // decided below from the watcher's reason + if (failure && !failure->matches(interrupt)) { + done.status = "raised"; + done.message = exception_line(*failure); + done.traceback = request.quote_source ? quoted_traceback(*capture, *failure, request.filename, w.source) : format_traceback(*failure); + done.error_line = error_line_of(*capture, *failure, request.filename); + } else if (!failure && completed && is_file && ns.contains("result")) { + try { + done.result = strict_json(ns["result"]); + done.status = "finished"; + } catch (const std::invalid_argument& e) { + if (file.empty()) { + done.status = "raised"; + done.message = e.what(); + } else { + // A standalone script may well have a variable named result: it is no result, not a failure. + done.status = "finished"; + std::string note = std::string("\n[result is not JSON, so it was not returned: ") + e.what() + "]\n"; + if (request.stream_output) + session.push_event(output_event(std::move(note))); + else + notes += note; + } + } + } else if (!failure && completed) + done.status = "finished"; + } catch (py::error_already_set& err) { + // The result's own code raised, or the work was interrupted while it ran. + if (!err.matches(interrupt)) { + done.status = "raised"; + done.message = exception_line(err); + } else + failure.emplace(std::move(err)); + } + if (done.status.empty()) + done.status = "interrupted"; // decided by resolve_interrupted() from what reached it + held_failure.reset(); + if (failure && session.end_requested()) + held_failure.emplace(std::move(*failure)); + failure.reset(); - // Like `python file.py`, the run ends once the work it started is done: its non-daemon threads, its window + // A File work in a session that goes on reports once the waited work it started is done, as `python file.py` + // ends; a stop interrupts that work and gives it kStopWindow. When the session ends, its teardown waits. + if (is_file && !session.end_requested()) { + watcher.set_phase(Watcher::Phase::Threads); + py::gil_scoped_release release; + while (!scope->quiet() && !session.end_requested()) { + if (const auto since = watcher.since_stop(); since && *since >= kStopWindow) + break; + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + } + // An interrupt sent as the work returned would land in the next Python this thread runs. What the session's + // threads print from here until the next work is a stretch of output of its own. + uninterrupted([&] { + if (request.stream_output) + py::handle(capture->renew)(run_id); + }); + { + py::gil_scoped_release release; + if (request.work_ended) + request.work_ended(); + } + // Before the Finished event, so a stop() right after it reaches the threads the work left. + session.set_has_threads(scope->has_live_work()); + done.executed = started; + done.cells_reported = cells_sent->load(); + done.variables = count_variables(ns); + return done; + }; + + // Between works the hosting thread waits for the next one without the GIL; the session's threads run on. + const auto next_work = [&]() -> std::optional { + uninterrupted([] {}); + watcher.set_phase(Watcher::Phase::Idle); + py::gil_scoped_release release; + for (;;) { + if (session.end_requested()) + return std::nullopt; + if (std::optional next = session.take_work(std::chrono::milliseconds(50), floor)) + return next; + } + }; + + while (ready && work) { + PythonSessionEvent done = run_one(*work); + if (session.end_requested()) { + // Its Finished event comes after the teardown and reflects it. + deferred_reason = watcher.reason(); + deferred = std::move(done); + break; + } + resolve_interrupted(done, watcher.reason(), work->kind == PythonWork::Kind::File, request.budget); + session.work_done(); + session.push_event(std::move(done)); + work = next_work(); + } + + // Like `python file.py`, the session ends once the work it started is done: its non-daemon threads, its window // callbacks and the pool tasks it submitted. It waits here, without the GIL, on what it counted, never through // Thread.join(), whose interrupted wait marks a live thread stopped. A stop interrupts that work and gives it - // 5 s; then the run stops waiting and closes its admission anyway. + // kStopWindow; then the session stops waiting and closes its admission anyway. + scope->mark_ending(); + uninterrupted([&] { watcher.begin_teardown(); }); watcher.set_phase(Watcher::Phase::Threads); { py::gil_scoped_release release; while (!scope->close_admission_if_quiet()) { - if (const auto since = watcher.since_stop(); since && *since >= std::chrono::seconds(5)) { + if (const auto since = watcher.since_stop(); since && *since >= kStopWindow) { scope->close_admission(); break; } std::this_thread::sleep_for(std::chrono::milliseconds(50)); } } - // An interrupt the body was sent as it returned would land in the next Python this thread runs. + // An interrupt sent as the wait ended would land in the next Python this thread runs. PyThreadState_SetAsyncExc(ident, nullptr); PyErr_Clear(); @@ -1039,7 +1640,7 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) PluginHostUi::close_run_windows(scope->ui_owner()); } ns.clear(); - failure.reset(); + held_failure.reset(); if (entered) { py::object taken; quietly([&] { uninterrupted([&] { taken = py::handle(capture->release)(run_id); }); }); @@ -1059,7 +1660,9 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) PyThreadState_SetAsyncExc(ident, nullptr); PyErr_Clear(); try { - outcome.output = py::handle(capture->end)(run_id).cast(); + std::string text = py::handle(capture->end)(run_id).cast() + notes; + if (!text.empty()) + session.push_event(output_event(std::move(text))); } catch (const std::exception&) { } { @@ -1074,22 +1677,48 @@ PythonRunOutcome run_python_code(const PythonRunRequest& request) PyThreadState_SetAsyncExc(ident, nullptr); PyErr_Clear(); } - outcome.output += result_note; + if (deferred) { + resolve_interrupted(*deferred, reason != Watcher::Reason::None ? reason : deferred_reason, true, request.budget); + session.push_event(std::move(*deferred)); + } +} - // A finalizer that ran on past the budget or a cancel while the namespace was cleared swallowed the - // interrupt, as Python ignores what __del__ raises: the run still did not finish in time. - if (outcome.status == "finished" && reason != Watcher::Reason::None) - outcome.status = "interrupted"; - if (outcome.status == "interrupted" && reason == Watcher::Reason::None) { - // The code raised the interrupt itself. - outcome.status = "raised"; - outcome.message = "RunInterrupted"; - } else if (outcome.status == "interrupted") { - outcome.result = nullptr; - outcome.status = reason == Watcher::Reason::TimedOut ? "timed_out" : "cancelled"; - outcome.message = reason == Watcher::Reason::TimedOut - ? "The script ran longer than its " + std::to_string(request.budget.count() / 1000) + " s budget" - : "The script was cancelled"; +PythonRunOutcome run_python_code(const PythonRunRequest& request) +{ + // A session with one File work and its end asked up front, so its Finished event comes after the teardown. + PythonSession session; + PythonWork work; + work.kind = PythonWork::Kind::File; + work.code = request.code; + work.source = request.code; + work.cell_starts = {1}; + session.submit(std::move(work)); + session.end(); + + PythonSessionRequest hosted; + hosted.identity = request.identity; + hosted.filename = request.filename; + hosted.args = request.args; + hosted.budget = request.budget; + hosted.cancelled = request.cancelled; + hosted.stop_calls = request.stop_calls; + hosted.stop_closes_ui = true; + hosted.stream_output = false; + hosted.quote_source = false; + hosted.report_cells = false; + hosted.cell_results = false; + host_python_session(hosted, session); + + PythonRunOutcome outcome; + for (PythonSessionEvent& event : session.take_events()) { + if (event.kind == PythonSessionEvent::Kind::Output) + outcome.output += event.text; + else if (event.kind == PythonSessionEvent::Kind::Finished) { + outcome.status = std::move(event.status); + outcome.result = std::move(event.result); + outcome.traceback = std::move(event.traceback); + outcome.message = std::move(event.message); + } } return outcome; } diff --git a/src/slic3r/plugin/PythonScriptRunner.hpp b/src/slic3r/plugin/PythonScriptRunner.hpp index 1353b0171d..5adf3ae092 100644 --- a/src/slic3r/plugin/PythonScriptRunner.hpp +++ b/src/slic3r/plugin/PythonScriptRunner.hpp @@ -15,6 +15,7 @@ class handle; namespace Slic3r { class PythonRunScope; +class PythonSession; // A Python script a person or an agent starts (run_python, a .py in the Run Script dialog or // --mcp-script), or a plugin's run_python: code run on the plugin interpreter without being packaged @@ -67,6 +68,47 @@ struct PythonRunOutcome // code 0 or None finishes it. PythonRunOutcome run_python_code(const PythonRunRequest& request); +// How a session is hosted: who it runs as, its file, and what its output, tracebacks and stops do. +struct PythonSessionRequest +{ + // As PythonRunRequest::identity. + std::string identity; + // As PythonRunRequest::filename, fixed for the session: an existing file makes it a file session, whose works + // run with `__file__`, `sys.argv` and its folder's imports, and whose first work installs its PEP 723 dependencies. + std::string filename = ""; + // Bound to the module-level name `args`. + nlohmann::json args = nlohmann::json::object(); + // The session is stopped and ended as timed_out once it has run this long, measured from its start; 0 is none. + std::chrono::milliseconds budget{0}; + // Polled from another thread; true stops and ends the session as cancelled. + std::function cancelled; + // Called from another thread at each stop or time-out, to cancel the tool calls in flight. + std::function stop_calls; + // A stop closes every window of the run, as a run's stop does, instead of only its message boxes and modal + // windows, which a session's stop ends so the code waiting in them can be interrupted. + bool stop_closes_ui = false; + // Output events as the code prints, each work and each stretch between works capped at 256 KiB with a note; + // false: one Output event at the session's end, capped at 256 KiB as a run's output is. + bool stream_output = true; + // Tracebacks quote the work's `source` for frames in the session's file, never the file on disk or linecache. + bool quote_source = true; + // File works send a Cell event as each cell's lines start running. + bool report_cells = true; + // A File work shows the result of each cell whose last statement is a bare expression, as a Cell work shows its + // own: `_` names it, and it comes as a Result event, or printed as its repr. + bool cell_results = true; + // Run on the hosting thread without the GIL, before and after each work. + std::function work_started, work_ended; +}; + +// Hosts `session` on the calling thread until it ends: one interpreter lease, audit scope, __main__, folder, output +// capture and watcher for all its works, and the teardown a run has (threads, pools, atexit, the run's windows, the +// folder's helpers) once at its end. A Cell or Console work echoes the value of a trailing bare expression and binds it +// to `_`; a File work runs as run_python_code() runs its code, and when the session goes on afterwards it reports once +// the waited threads it started have ended. Stop interrupts what runs now and the session's threads and tasks, and +// for five seconds after it, while the session is idle, its threads and tasks; the session goes on. +void host_python_session(const PythonSessionRequest& request, PythonSession& session); + // Installs a file run's PEP 723 dependencies; false with `error` when that fails. plugin_loader::install_packages // unless a test sets another; nullptr restores it. using PythonDependencyInstaller = std::function& packages, std::string& error)>; diff --git a/src/slic3r/plugin/PythonSession.cpp b/src/slic3r/plugin/PythonSession.cpp new file mode 100644 index 0000000000..7948cba0b6 --- /dev/null +++ b/src/slic3r/plugin/PythonSession.cpp @@ -0,0 +1,108 @@ +#include "PythonSession.hpp" + +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +bool PythonSession::submit(PythonWork work) +{ + { + std::lock_guard lock(m_mutex); + if (m_queued || m_running || m_end || m_returned) + return false; + m_queued = std::move(work); + m_queued_stops = m_stop_requests.load(); + } + m_cv.notify_all(); + return true; +} + +void PythonSession::stop() +{ + { + std::lock_guard lock(m_mutex); + if (m_returned || (!m_queued && !m_running && !m_end && !m_has_threads.load())) + return; + ++m_stop_requests; + } + m_cv.notify_all(); +} + +void PythonSession::end() +{ + { + std::lock_guard lock(m_mutex); + m_end = true; + } + m_cv.notify_all(); +} + +bool PythonSession::working() const +{ + std::lock_guard lock(m_mutex); + return m_queued.has_value() || m_running; +} + +bool PythonSession::ended() const +{ + std::lock_guard lock(m_mutex); + return m_returned; +} + +std::vector PythonSession::take_events() +{ + std::lock_guard lock(m_mutex); + std::vector events; + events.swap(m_events); + return events; +} + +std::optional PythonSession::take_work(std::chrono::milliseconds timeout, std::uint64_t& stops_before) +{ + std::unique_lock lock(m_mutex); + m_cv.wait_for(lock, timeout, [this] { return m_queued.has_value() || m_end; }); + if (!m_queued) + return std::nullopt; + stops_before = m_queued_stops; + std::optional work = std::move(m_queued); + m_queued.reset(); + m_running = true; + return work; +} + +bool PythonSession::end_requested() const +{ + std::lock_guard lock(m_mutex); + return m_end; +} + +void PythonSession::work_done() +{ + std::lock_guard lock(m_mutex); + m_running = false; +} + +void PythonSession::push_event(PythonSessionEvent event) +{ + std::lock_guard lock(m_mutex); + m_events.push_back(std::move(event)); +} + +void PythonSession::host_returned() +{ + { + std::lock_guard lock(m_mutex); + m_returned = true; + m_running = false; + m_queued.reset(); + } + m_has_threads.store(false); + m_cv.notify_all(); +} + +} // namespace Slic3r diff --git a/src/slic3r/plugin/PythonSession.hpp b/src/slic3r/plugin/PythonSession.hpp new file mode 100644 index 0000000000..aec2609083 --- /dev/null +++ b/src/slic3r/plugin/PythonSession.hpp @@ -0,0 +1,104 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Slic3r { + +// A piece of work a session runs in its namespace. +struct PythonWork +{ + enum class Kind { File, Cell, Console }; + Kind kind = Kind::Cell; + // The whole script (File), the cell's lines (Cell), or what was typed at the console (Console). + std::string code; + // The file line a Cell's code starts on, so its line numbers are the file's. + int first_line = 1; + // The whole editor text, which the work's traceback quotes for frames in the session's file. + std::string source; + // A File work's cell first lines, ascending, starting at 1: its Cell events index them. + std::vector cell_starts; +}; + +struct PythonSessionEvent +{ + enum class Kind { Output, Cell, Result, Finished }; + Kind kind = Kind::Output; + // Output: what was printed, as it was printed. Result: a work's or a cell's result that JSON holds as is, as + // compact JSON with json.dumps's separators; any other result is printed, so it comes as Output. + std::string text; + // Cell: the index in the running File work's cell_starts of the cell whose lines now run. + int cell = -1; + // Finished: finished, raised, cancelled, timed_out or unavailable. + std::string status; + std::string message; + std::string traceback; + // The innermost traceback line in the session's file (a SyntaxError's line), 0 for none. + int error_line = 0; + // False when the code never started: it didn't compile, or its dependencies didn't install. + bool executed = true; + // Whether a File work sent Cell events. + bool cells_reported = false; + // The names in the session's __main__ that don't start with '_', aren't `args` and aren't modules. + int variables = 0; + // The JSON `result` a File work left, for run_python_code(); null otherwise. + nlohmann::json result; +}; + +// One Python session: a __main__, folder, identity, output capture and watcher that outlive a single piece of work, +// hosted on one thread by host_python_session() (PythonScriptRunner.hpp). The person's side submits work and reads +// events from any thread; the class holds no Python and no wx. +class PythonSession +{ +public: + // Queues `work`. False while work is queued or running, after end(), or once the host returned. + bool submit(PythonWork work); + // Interrupts what runs now: the work, the session's threads and tasks, and once end() was asked its teardown. + // Nothing when it is idle with none and not ending. + void stop(); + // No more work: the session ends after the work running now. A stop() after it reaches the teardown, as a stopped + // run's does, so whatever the teardown runs (atexit functions, finalizers) can be interrupted. + void end(); + // Work is queued or running. + bool working() const; + // Threads, pool tasks or window callbacks the session started are still live. + bool has_threads() const { return m_has_threads.load(); } + // The host has returned: every event the session sends is queued. + bool ended() const; + std::vector take_events(); + + // Used only by host_python_session(). + // Waits up to `timeout` for queued work and takes it (it stays working() until work_done()), or nullopt. + // `stops_before` is set to stop_requests() as the work was submitted: only later stops reach it. + std::optional take_work(std::chrono::milliseconds timeout, std::uint64_t& stops_before); + // The stop() calls that asked for something so far. + std::uint64_t stop_requests() const { return m_stop_requests.load(); } + bool end_requested() const; + void work_done(); + void push_event(PythonSessionEvent event); + void set_has_threads(bool live) { m_has_threads.store(live); } + // The host returns: nothing more is taken, and ended() turns true. + void host_returned(); + +private: + mutable std::mutex m_mutex; + std::condition_variable m_cv; + std::optional m_queued; + std::uint64_t m_queued_stops = 0; + bool m_running = false; + bool m_end = false; + bool m_returned = false; + std::vector m_events; + std::atomic m_stop_requests{0}; + std::atomic m_has_threads{false}; +}; + +} // namespace Slic3r diff --git a/src/slic3r/plugin/host/PluginHostUi.cpp b/src/slic3r/plugin/host/PluginHostUi.cpp index 606b2cff89..32ccf9b89f 100644 --- a/src/slic3r/plugin/host/PluginHostUi.cpp +++ b/src/slic3r/plugin/host/PluginHostUi.cpp @@ -261,6 +261,17 @@ public: } return out; } + // The plugin's windows, left registered. + std::vector> windows_for_plugin(const std::string& plugin_key) + { + std::lock_guard lk(m_mtx); + std::vector> out; + for (const auto& [id, owner] : m_owners) + if (owner == plugin_key) + if (auto it = m_resources.find(id); it != m_resources.end()) + out.emplace_back(id, it->second); + return out; + } void bind_callback(const CallablePtr& callback, const std::string& plugin_key) { if (!callback) @@ -921,6 +932,26 @@ void PluginHostUi::close_windows_for_plugin(const std::string& plugin_key) GUI::wxGetApp().CallAfter(teardown); } +void PluginHostUi::end_run_modals(const std::string& owner) +{ + if (wxTheApp == nullptr) + return; + auto end_modals = [owner]() { + for (const auto& [id, window] : UiRegistry::instance().windows_for_plugin(owner)) { + if (auto* message = dynamic_cast(window)) + message->EndModal(wxID_CANCEL); // its modal call unregisters it + else if (auto* dialog = dynamic_cast(window); dialog != nullptr && dialog->IsModal()) { + UiRegistry::instance().remove(id); + GUI::WebDialog::destroy_silently(dialog); + } + } + }; + if (wxIsMainThread()) + end_modals(); + else if (!app_closing()) + GUI::wxGetApp().CallAfter(end_modals); +} + void PluginHostUi::close_run_windows(const std::string& owner) { if (wxTheApp == nullptr) diff --git a/src/slic3r/plugin/host/PluginHostUi.hpp b/src/slic3r/plugin/host/PluginHostUi.hpp index bcf4e6e90e..1184df0e5f 100644 --- a/src/slic3r/plugin/host/PluginHostUi.hpp +++ b/src/slic3r/plugin/host/PluginHostUi.hpp @@ -28,6 +28,10 @@ public: // this after plugin teardown and also for bulk unload during application shutdown. static void close_windows_for_plugin(const std::string& plugin_key); + // From any thread: on the UI thread, ends `owner`'s message boxes and modal windows, which a stopped session's code + // may wait in, and leaves its modeless windows, dock panels and callbacks open. + static void end_run_modals(const std::string& owner); + // From a script run's thread, with the GIL held: tears down what the run owns (`owner`, its ui_owner()) on the UI // thread and returns once that is done, so none of its callbacks runs after. Does nothing while the app closes. static void close_run_windows(const std::string& owner); diff --git a/tests/slic3rutils/test_action_source.cpp b/tests/slic3rutils/test_action_source.cpp index 8edab3ec89..f0af879fa1 100644 --- a/tests/slic3rutils/test_action_source.cpp +++ b/tests/slic3rutils/test_action_source.cpp @@ -287,6 +287,21 @@ TEST_CASE("Native command catalog has the screenshot and recording commands", "[ } } +// The Run Script panel's command sits beside Action Replay's, which keeps its id so existing replays and agent sessions +// that open it still do. +TEST_CASE("Native command catalog has the Run Script panel and Action Replay commands", "[ActionSource][SpeedDial]") +{ + const Slic3r::GUI::NativeCommand* replay = Slic3r::GUI::NativeCommands::find("open_script_runner"); + REQUIRE(replay != nullptr); + CHECK(std::string(replay->title) == "Action Replay"); + const Slic3r::GUI::NativeCommand* panel = Slic3r::GUI::NativeCommands::find("toggle_run_script"); + REQUIRE(panel != nullptr); + CHECK(panel->group == replay->group); + CHECK(panel->input.empty()); + CHECK(panel->param.type == Slic3r::GUI::CommandParamType::None); + CHECK_FALSE(panel->description.empty()); +} + // Every "Add Primitive" item and shipped handy model has a palette command, grouped as in the Add // menu. Groups are compared to a peer's own group to stay independent of translation. TEST_CASE("Native command catalog covers the Add menus", "[ActionSource][SpeedDial]") diff --git a/tests/slic3rutils/test_file_url.cpp b/tests/slic3rutils/test_file_url.cpp index f22b21612a..d414451b3a 100644 --- a/tests/slic3rutils/test_file_url.cpp +++ b/tests/slic3rutils/test_file_url.cpp @@ -3,10 +3,13 @@ #include #include "slic3r/GUI/GUI.hpp" +#include "slic3r/GUI/Widgets/WebViewHostDialog.hpp" +#include #include #include +#include #include #include @@ -75,3 +78,20 @@ TEST_CASE("A query appended to a Windows file URL stays separate from its path", CHECK(!uri.HasFragment()); } #endif + +TEST_CASE("A page's own loads are told from a dropped file and from other pages", "[FileUrl]") +{ + const boost::filesystem::path dir = boost::filesystem::temp_directory_path() / "orca page"; + const boost::filesystem::path page = dir / "index.html"; + const boost::filesystem::path dropped = dir / "replay.json"; + const wxFileName page_name(from_path(page)); + + CHECK(WebViewHostDialog::own_page_navigation(file_url_from_path(page) + "?lang=de", page_name)); + CHECK(WebViewHostDialog::own_page_navigation("about:blank", page_name)); + CHECK_FALSE(WebViewHostDialog::own_page_navigation("https://example.com/", page_name)); + CHECK_FALSE(WebViewHostDialog::own_page_navigation(file_url_from_path(dropped), page_name)); + + const boost::filesystem::path file = WebViewHostDialog::dropped_file(file_url_from_path(dropped)); + CHECK(wxFileName(from_path(file)).SameAs(wxFileName(from_path(dropped)))); + CHECK(WebViewHostDialog::dropped_file("https://example.com/replay.json").empty()); +} diff --git a/tests/slic3rutils/test_mcp_core.cpp b/tests/slic3rutils/test_mcp_core.cpp index 1500de6cdd..e61a3f1d73 100644 --- a/tests/slic3rutils/test_mcp_core.cpp +++ b/tests/slic3rutils/test_mcp_core.cpp @@ -1374,3 +1374,73 @@ TEST_CASE("a plugin's running call is cancelled the moment the plugin unloads", CHECK_FALSE(r.is_error); CHECK(r.data.value("cancelled", false)); } + +TEST_CASE("a call under a lineage node sees a stop asked for the node, inline calls included, and a renewed node's calls run", "[Mcp]") +{ + Harness h; + // Polls for cancellation for up to `for_ms`, as wait does. + const auto poll = [](const json& args, ToolContext& ctx) { + const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(args.value("for_ms", 5000)); + while (!ctx.cancelled() && std::chrono::steady_clock::now() < end) + std::this_thread::sleep_for(10ms); + return ToolResult::ok({{"cancelled", ctx.cancelled()}}); + }; + ToolDef inline_poll = tool("inline_poll", GuardClass::Inspect, poll); + inline_poll.inline_call = true; + h.registry.add(inline_poll); + h.registry.add(tool("job_poll", GuardClass::Mutate, poll)); + h.timing.soft_budget = 10000ms; + h.start(); + + const std::string session = h.jobs.create("run_python", ""); + h.jobs.set_idle(session); + LineageNode node(h.jobs, "run_python", session); + const auto call = [&](const char* tool, int for_ms) { + return std::async(std::launch::async, [&h, &node, tool, for_ms] { + return h.core->call_child_named(tool, {{"for_ms", for_ms}}, node.id()); + }); + }; + auto inline_call = call("inline_poll", 5000); + auto job_call = call("job_poll", 5000); + std::this_thread::sleep_for(300ms); + const auto asked = std::chrono::steady_clock::now(); + h.jobs.request_stop(node.id()); + const ToolResult stopped_inline = inline_call.get(); + const ToolResult stopped_job = job_call.get(); + CHECK(std::chrono::steady_clock::now() - asked < 1s); + CHECK(stopped_inline.data.value("cancelled", false)); + CHECK(stopped_job.data.value("cancelled", false)); + + node.renew(); + auto ran_inline = call("inline_poll", 300); + auto ran_job = call("job_poll", 300); + CHECK(ran_inline.get().data["cancelled"] == false); + CHECK(ran_job.get().data["cancelled"] == false); + CHECK_FALSE(h.jobs.stop_requested(session)); + h.jobs.finish(session, ToolResult::ok()); +} + +TEST_CASE("lineage nodes leave no running job behind", "[Mcp]") +{ + JobRegistry jobs; + const std::string session = jobs.create("run_python", ""); + const auto running_nodes = [&] { + int count = 0; + for (const json& job : jobs.list()) + if (job["tool"] == "run_python" && job.value("parent", std::string()) == session && job["state"] == "running") + ++count; + return count; + }; + { + LineageNode node(jobs, "run_python", session); + CHECK(running_nodes() == 1); + } + for (int round = 0; round < 10; ++round) { + LineageNode node(jobs, "run_python", session); + for (int renewal = 0; renewal < 3; ++renewal) + node.renew(); + CHECK(running_nodes() == 1); + } + CHECK(running_nodes() == 0); + jobs.finish(session, ToolResult::ok()); +} diff --git a/tests/slic3rutils/test_mcp_results.cpp b/tests/slic3rutils/test_mcp_results.cpp index 8306b9d4dd..18b2b2451d 100644 --- a/tests/slic3rutils/test_mcp_results.cpp +++ b/tests/slic3rutils/test_mcp_results.cpp @@ -306,6 +306,106 @@ TEST_CASE("an auto-answer rule presses a wx dialog's button, and answers a nativ } } +TEST_CASE("a paused rule layer answers nothing until resumed", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + ModalTracker tracker; + const int layer = tracker.push_rules({make_rule("unsaved", "Transfer")}); + tracker.set_paused(layer, true); + + wxDialog dialog(nullptr, wxID_ANY, "Unsaved changes"); + int transfers = 0; + auto* transfer = new wxButton(&dialog, wxID_ANY, "Transfer"); + transfer->Bind(wxEVT_BUTTON, [&transfers](wxCommandEvent&) { ++transfers; }); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + wxTheApp->ProcessPendingEvents(); + CHECK(transfers == 0); + CHECK(tracker.top() == &dialog); // it stays open for the person + wxModalDialogHook::CallExit(&dialog); + CHECK(tracker.rules_json()[0]["uses"] == 0); + CHECK(tracker.rules_json()[0].value("paused", false)); + CHECK_FALSE(tracker.rule_in_force(layer, "unsaved", "Transfer")); + + tracker.set_paused(layer, false); + CHECK(tracker.rule_in_force(layer, "unsaved", "Transfer")); + CHECK_FALSE(tracker.rules_json()[0].value("paused", false)); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + wxTheApp->ProcessPendingEvents(); + CHECK(transfers == 1); + wxModalDialogHook::CallExit(&dialog); + CHECK(tracker.rules_json()[0]["uses"] == 1); + } +} + +TEST_CASE("an answer queued for a dialog is dropped when its rule is paused before it runs", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + ModalTracker tracker; + const int layer = tracker.push_rules({make_rule("unsaved", "Transfer")}); + + wxDialog dialog(nullptr, wxID_ANY, "Unsaved changes"); + int transfers = 0; + auto* transfer = new wxButton(&dialog, wxID_ANY, "Transfer"); + transfer->Bind(wxEVT_BUTTON, [&transfers](wxCommandEvent&) { ++transfers; }); + // The press is queued for the dialog's modal loop; a Run Script work ends and pauses its rules before it runs. + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + tracker.set_paused(layer, true); + wxTheApp->ProcessPendingEvents(); + CHECK(transfers == 0); + CHECK(tracker.top() == &dialog); + wxModalDialogHook::CallExit(&dialog); + CHECK(tracker.rules_json()[0]["uses"] == 0); + } +} + +TEST_CASE("a rule layer pushed paused answers nothing from the start", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + // A Run Script session's thread registers a rule between works: the layer is paused as it is created, so it is + // never in force before the session's next work resumes it. + ModalTracker tracker; + const int layer = tracker.push_rules({make_rule("unsaved", "Transfer")}, true); + CHECK(tracker.rules_json()[0].value("paused", false)); + CHECK_FALSE(tracker.rule_in_force(layer, "unsaved", "Transfer")); + + wxDialog dialog(nullptr, wxID_ANY, "Unsaved changes"); + int transfers = 0; + auto* transfer = new wxButton(&dialog, wxID_ANY, "Transfer"); + transfer->Bind(wxEVT_BUTTON, [&transfers](wxCommandEvent&) { ++transfers; }); + CHECK(wxModalDialogHook::CallEnter(&dialog) == wxID_NONE); + wxTheApp->ProcessPendingEvents(); + CHECK(transfers == 0); + wxModalDialogHook::CallExit(&dialog); + + tracker.set_paused(layer, false); + CHECK(tracker.rule_in_force(layer, "unsaved", "Transfer")); + } +} + TEST_CASE("a dialog hidden from automation is neither tracked nor auto-answered", "[Mcp]") { #if defined(__linux__) diff --git a/tests/slic3rutils/test_mcp_ui.cpp b/tests/slic3rutils/test_mcp_ui.cpp index 8269792c4c..b7411aa8ef 100644 --- a/tests/slic3rutils/test_mcp_ui.cpp +++ b/tests/slic3rutils/test_mcp_ui.cpp @@ -28,6 +28,7 @@ #include "slic3r/GUI/Mcp/CanvasTarget.hpp" #include "slic3r/GUI/Mcp/McpService.hpp" #include "slic3r/GUI/Mcp/McpServicePtr.hpp" +#include "slic3r/GUI/Mcp/McpTypes.hpp" #include "slic3r/GUI/Mcp/UiInspector.hpp" #include "slic3r/GUI/Mcp/UiRefs.hpp" @@ -36,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -568,3 +570,26 @@ TEST_CASE("a key goes to the hooks of the target and its parents before the targ CHECK(seen == std::vector{"panel hook", "key down"}); } } + +TEST_CASE("a window inside a pane hidden from automation is hidden, and the pane's siblings are not", "[Mcp]") +{ +#if defined(__linux__) + if (!std::getenv("DISPLAY") && !std::getenv("WAYLAND_DISPLAY")) + SKIP("This test needs a display (for example, xvfb-run)."); +#endif + if (wxTheApp == nullptr) + wxApp::SetInstance(new wxApp); + wxInitializer init; + REQUIRE(init.IsOk()); + { + // A pane docked in the main window, as the Run Script panel is, beside the window's other panels. + wxFrame frame(nullptr, wxID_ANY, "main"); + auto* pane = new wxPanel(&frame, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL, kHiddenFromAutomation); + auto* child = new wxWindow(pane, wxID_ANY); + auto* sibling = new wxPanel(&frame); + CHECK(hidden_from_automation(child)); + CHECK(hidden_from_automation(pane)); + CHECK_FALSE(hidden_from_automation(sibling)); + CHECK_FALSE(hidden_from_automation(&frame)); + } +} diff --git a/tests/slic3rutils/test_python_script_runner.cpp b/tests/slic3rutils/test_python_script_runner.cpp index 493c8a0b8b..6689b50ead 100644 --- a/tests/slic3rutils/test_python_script_runner.cpp +++ b/tests/slic3rutils/test_python_script_runner.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -43,6 +44,7 @@ using namespace Slic3r; using Catch::Matchers::ContainsSubstring; +using Catch::Matchers::EndsWith; using nlohmann::json; namespace py = pybind11; @@ -2223,3 +2225,715 @@ TEST_CASE("without Python, a .py file is read only as strict UTF-8", "[PythonScr std::string saved; CHECK_FALSE(encode_python_source("x = 1\n", "iso-8859-1", saved, error)); } + +namespace { + +// A session hosted on a thread of its own, as the app hosts one on a job thread Python didn't start. The test's thread +// submits work, reads the events and asserts; the host thread only hosts. +struct HostedSession +{ + PythonSession session; + std::thread host; + std::atomic returned{false}; + + static PythonSessionRequest person_session(std::string filename = "") + { + PythonSessionRequest request; + request.identity = kScriptIdentityPerson; + request.filename = std::move(filename); + return request; + } + + explicit HostedSession(PythonSessionRequest request = person_session()) + { + host = std::thread([this, request = std::move(request)] { + host_python_session(request, session); + returned = true; + }); + } + ~HostedSession() + { + session.stop(); + session.end(); + if (host.joinable()) + host.join(); + } + HostedSession(const HostedSession&) = delete; + HostedSession& operator=(const HostedSession&) = delete; +}; + +// The events of one piece of work, up to and including its Finished event. +struct WorkEvents +{ + std::vector events; + std::optional finished; + + std::string output() const + { + std::string text; + for (const PythonSessionEvent& event : events) + if (event.kind == PythonSessionEvent::Kind::Output) + text += event.text; + return text; + } + // The Result events' JSON, in order. + std::vector results() const + { + std::vector texts; + for (const PythonSessionEvent& event : events) + if (event.kind == PythonSessionEvent::Kind::Result) + texts.push_back(event.text); + return texts; + } + // "cell N", "out " (consecutive outputs merged), "result " and "finished ", in order. + std::vector sequence() const + { + std::vector out; + for (const PythonSessionEvent& event : events) { + if (event.kind == PythonSessionEvent::Kind::Output) { + if (!out.empty() && out.back().rfind("out ", 0) == 0) + out.back() += event.text; + else + out.push_back("out " + event.text); + } else if (event.kind == PythonSessionEvent::Kind::Cell) + out.push_back("cell " + std::to_string(event.cell)); + else if (event.kind == PythonSessionEvent::Kind::Result) + out.push_back("result " + event.text); + else + out.push_back("finished " + event.status); + } + return out; + } +}; + +// Polls the session's events until a Finished event or `seconds`. +WorkEvents await_work(PythonSession& session, double seconds = 10) +{ + WorkEvents result; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration(seconds); + while (!result.finished && std::chrono::steady_clock::now() < deadline) { + for (PythonSessionEvent& event : session.take_events()) { + if (!result.finished && event.kind == PythonSessionEvent::Kind::Finished) + result.finished = event; + result.events.push_back(std::move(event)); + } + if (!result.finished) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return result; +} + +// What the session prints within `seconds`. +std::string output_within(PythonSession& session, double seconds) +{ + std::string text; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration(seconds); + while (std::chrono::steady_clock::now() < deadline) { + for (const PythonSessionEvent& event : session.take_events()) + if (event.kind == PythonSessionEvent::Kind::Output) + text += event.text; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return text; +} + +bool eventually(const std::function& condition, double seconds) +{ + const auto deadline = std::chrono::steady_clock::now() + std::chrono::duration(seconds); + while (!condition()) { + if (std::chrono::steady_clock::now() >= deadline) + return false; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + return true; +} + +PythonWork cell(std::string code, int first_line = 1, std::string source = {}) +{ + PythonWork work; + work.kind = PythonWork::Kind::Cell; + work.first_line = first_line; + work.source = source.empty() ? code : std::move(source); + work.code = std::move(code); + return work; +} + +PythonWork console(std::string code) +{ + PythonWork work; + work.kind = PythonWork::Kind::Console; + work.code = std::move(code); + return work; +} + +PythonWork file_work(std::string code, std::vector cell_starts = {1}) +{ + PythonWork work; + work.kind = PythonWork::Kind::File; + work.source = code; + work.code = std::move(code); + work.cell_starts = std::move(cell_starts); + return work; +} + +WorkEvents run_work(PythonSession& session, PythonWork work) +{ + REQUIRE(session.submit(std::move(work))); + WorkEvents result = await_work(session); + REQUIRE(result.finished); + return result; +} + +constexpr const char* kTruncatedNote = "\n[output truncated at 256 KiB]\n"; + +} // namespace + +TEST_CASE("a session keeps what each cell defined for the next one", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + CHECK(run_work(hosted.session, cell("x = 2")).finished->status == "finished"); + CHECK(run_work(hosted.session, cell("y = x * 3")).finished->status == "finished"); + const WorkEvents shown = run_work(hosted.session, console("y")); + CHECK(shown.output() == "6\n"); + CHECK(shown.finished->status == "finished"); + CHECK(shown.finished->variables == 2); +} + +TEST_CASE("a cell ending in an expression shows its value, and so does a file run's cell, but not an agent's run", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + CHECK(run_work(hosted.session, cell("1 + 1")).output() == "2\n"); + CHECK(run_work(hosted.session, cell("None")).output().empty()); + const WorkEvents file = run_work(hosted.session, file_work("1 + 1")); + CHECK(file.finished->status == "finished"); + CHECK(file.output() == "2\n"); + + const PythonRunOutcome agent = run_file("", "1 + 1\n[1, 2]\n"); + CHECK(agent.status == "finished"); + CHECK(agent.output.empty()); +} + +TEST_CASE("a file run shows the result of each cell whose last statement is an expression", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + const std::string code = "x = 1\nx + 1\n" // cell 0, lines 1-2 + "# %% two\nprint('b')\n{'a': [1, 2.5, True, None]}\n" // cell 1, lines 3-5 + "# %% three\nobjects = [1]\n" // cell 2, lines 6-7 + "# %% four\n'done'\nNone\n"; // cell 3, lines 8-10 + const WorkEvents file = run_work(hosted.session, file_work(code, {1, 3, 6, 8})); + CHECK(file.sequence() == std::vector{"cell 0", "out 2\n", "cell 1", "out b\n", "result {\"a\": [1, 2.5, true, null]}", + "cell 2", "cell 3", "finished finished"}); + // `_` is the last result shown, as after a cell. + CHECK(run_work(hosted.session, console("_ == {'a': [1, 2.5, True, None]}")).output() == "True\n"); +} + +TEST_CASE("a result comes as JSON only when JSON holds it as is", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + const WorkEvents json_result = run_work(hosted.session, cell("{'name': 'Benchy \\u00e9', 'sizes': [[1, 2], {}]}")); + CHECK(json_result.results() == std::vector{"{\"name\": \"Benchy \xC3\xA9\", \"sizes\": [[1, 2], {}]}"}); + CHECK(json_result.output().empty()); + // A str key JSON would write for an int, a tuple it would write as a list, a float it can't write, a string UTF-8 + // can't hold (a lone surrogate, as a key or a value), and anything that is not a dict or a list show as their repr. + for (const char* code : {"{1: 'a'}", "[(1, 2)]", "[float('nan')]", "{'path': '\\udcff'}", "{'\\udcff': 1}", "'text'", "3"}) { + const WorkEvents shown = run_work(hosted.session, cell(code)); + CHECK(shown.results().empty()); + CHECK(shown.output() == py_json(std::string("repr(") + code + ")").get() + "\n"); + } + // JSON past the output's allowance is printed instead, and cut as long output is. + const WorkEvents long_result = run_work(hosted.session, cell("list(range(100000))")); + CHECK(long_result.results().empty()); + CHECK_THAT(long_result.output(), EndsWith(kTruncatedNote)); +} + +TEST_CASE("a file run shows its cells' results whatever the script does to __import__ and sys.modules", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + const std::string code = "import sys\ncapture = sys.modules.pop('_orca_run_capture')\n__import__ = None\n1 + 1\n"; + const WorkEvents file = run_work(hosted.session, file_work(code)); + // The capture module goes back before anything checks, whatever the run did. + run_work(hosted.session, console("sys.modules['_orca_run_capture'] = capture")); + CHECK(file.finished->status == "finished"); + CHECK(file.output() == "2\n"); +} + +TEST_CASE("a file run keeps its docstring and its tracebacks as the file's", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + // The docstring is the last statement of its cell. + const WorkEvents documented = run_work(hosted.session, file_work("'''The plate report.'''\n# %% two\nx = 1\n", {1, 2})); + CHECK(documented.output().empty()); + CHECK(run_work(hosted.session, console("__doc__")).output() == "'The plate report.'\n"); + + const WorkEvents raised = run_work(hosted.session, file_work("x = 1\n# %% two\n1 / x\n1 / 0\n", {1, 3})); + CHECK(raised.finished->status == "raised"); + CHECK(raised.finished->error_line == 4); + CHECK_THAT(raised.finished->traceback, ContainsSubstring("1 / 0")); + CHECK_THAT(raised.finished->traceback, !ContainsSubstring("show_result")); + CHECK_THAT(raised.finished->traceback, !ContainsSubstring("_orca_run_capture")); +} + +TEST_CASE("a session's traceback quotes the editor's text and leaves other runs' tracebacks alone", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + std::string disk; + for (int line = 1; line <= 10; ++line) + disk += "print('disk line " + std::to_string(line) + "')\n"; + const std::string path = macro.write("script.py", disk); + // What another run of the same file raises at line 5: its traceback quotes the file on disk. + const auto disk_run_quotes_disk = [&] { + const PythonRunOutcome other = run_file(path, "x = 1\n\n\n\nraise ValueError('y')\n"); + CHECK(other.status == "raised"); + CHECK_THAT(other.traceback, ContainsSubstring("disk line 5")); + CHECK_THAT(other.traceback, !ContainsSubstring("raise ValueError('x')")); + }; + + auto hosted = std::make_unique(HostedSession::person_session(path)); + const std::string source = "# editor 1\n# 2\n# %% cell\na = 1\nraise ValueError('x')\n"; + const WorkEvents raised = run_work(hosted->session, cell("a = 1\nraise ValueError('x')", 4, source)); + CHECK(raised.finished->status == "raised"); + CHECK(raised.finished->error_line == 5); + CHECK(raised.finished->executed); + CHECK_THAT(raised.finished->traceback, ContainsSubstring("line 5")); + CHECK_THAT(raised.finished->traceback, ContainsSubstring("raise ValueError('x')")); + CHECK_THAT(raised.finished->traceback, !ContainsSubstring("disk line")); + + const WorkEvents syntax = run_work(hosted->session, cell("def f(:", 9, source)); + CHECK(syntax.finished->status == "raised"); + CHECK(syntax.finished->error_line == 9); + CHECK_FALSE(syntax.finished->executed); + + const std::string chained_source = "def g():\n raise KeyError('inner')\ntry:\n g()\n" + "except KeyError as e:\n raise ValueError('outer') from e\n"; + const WorkEvents chained = run_work(hosted->session, cell(chained_source, 1, chained_source)); + CHECK(chained.finished->status == "raised"); + CHECK(chained.finished->error_line == 6); + CHECK_THAT(chained.finished->traceback, ContainsSubstring("raise KeyError('inner')")); + CHECK_THAT(chained.finished->traceback, ContainsSubstring("raise ValueError('outer') from e")); + CHECK_THAT(chained.finished->traceback, !ContainsSubstring("disk line")); + + disk_run_quotes_disk(); + hosted.reset(); + disk_run_quotes_disk(); +} + +TEST_CASE("a file run reports each cell as it starts and stops where it fails", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + const WorkEvents file = run_work(hosted.session, file_work("print('a')\n# %% two\nprint('b')\n# %% three\nraise RuntimeError('c')\n", {1, 3, 5})); + CHECK(file.sequence() == std::vector{"cell 0", "out a\n", "cell 1", "out b\n", "cell 2", "finished raised"}); + CHECK(file.finished->error_line == 5); + CHECK(file.finished->cells_reported); + CHECK(py_json("sys.monitoring.get_tool(4)").is_null()); +} + +TEST_CASE("a file run sends no cell events while another owner holds the monitoring id", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + py_run("import sys\nsys.monitoring.use_tool_id(4, 'test')\n"); + HostedSession hosted; + const WorkEvents file = run_work(hosted.session, file_work("print('a')\n# %% two\nprint('b')\n# %% three\nraise RuntimeError('c')\n", {1, 3, 5})); + CHECK(file.sequence() == std::vector{"out a\nb\n", "finished raised"}); + CHECK(file.finished->error_line == 5); + CHECK_FALSE(file.finished->cells_reported); + CHECK(py_json("sys.monitoring.get_tool(4)") == "test"); + py_run("import sys\nsys.monitoring.free_tool_id(4)\n"); +} + +TEST_CASE("a file run leaves the session able to start threads and tasks", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + CHECK(run_work(hosted.session, file_work("import threading\nt = threading.Thread(target=print, args=('x',))\nt.start()\nt.join()\n")) + .finished->status == "finished"); + const WorkEvents later = run_work(hosted.session, cell("import threading\nfrom concurrent.futures import ThreadPoolExecutor\n" + "t = threading.Thread(target=print, args=('t',))\nt.start()\nt.join()\n" + "ThreadPoolExecutor(1).submit(lambda: 7).result()\n")); + CHECK(later.finished->status == "finished"); + CHECK_THAT(later.output(), ContainsSubstring("7")); + CHECK_THAT(later.output(), ContainsSubstring("t")); +} + +TEST_CASE("output arrives while the work is still running", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_stream", {"go"}); + HostedSession hosted; + REQUIRE(hosted.session.submit(cell("import _stream\nprint('a')\nok = _stream.go.wait(10)\n"))); + std::string early; + CHECK(eventually( + [&] { + for (const PythonSessionEvent& event : hosted.session.take_events()) + if (event.kind == PythonSessionEvent::Kind::Output) + early += event.text; + return early == "a\n"; + }, + 5)); + CHECK(hosted.session.working()); + shared.set("go"); + const WorkEvents rest = await_work(hosted.session); + REQUIRE(rest.finished); + CHECK(rest.finished->status == "finished"); +} + +TEST_CASE("Stop interrupts the running cell and keeps the session", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + REQUIRE(run_work(hosted.session, cell("x = 1")).finished->status == "finished"); + REQUIRE(hosted.session.submit(cell("while True:\n pass\n"))); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + CHECK(hosted.session.working()); + hosted.session.stop(); + const WorkEvents stopped = await_work(hosted.session); + REQUIRE(stopped.finished); + CHECK(stopped.finished->status == "cancelled"); + CHECK(run_work(hosted.session, cell("x + 1")).output() == "2\n"); +} + +TEST_CASE("Stop reaches a thread an earlier cell left running, and later cells start threads and tasks again", + "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + REQUIRE(run_work(hosted.session, cell("import threading, time\nfrom concurrent.futures import ThreadPoolExecutor\n" + "def spin():\n while True:\n time.sleep(0.01)\n" + "threading.Thread(target=spin).start()\nex = ThreadPoolExecutor(1)\n")) + .finished->status == "finished"); + CHECK(eventually([&] { return hosted.session.has_threads(); }, 2)); + hosted.session.stop(); + CHECK(eventually([&] { return !hosted.session.has_threads(); }, 5)); + // What the stopped thread printed as it ended comes before the next cell. + output_within(hosted.session, 0.2); + CHECK(run_work(hosted.session, cell("ex.submit(lambda: 7).result()")).output() == "7\n"); +} + +TEST_CASE("a task queued when a cell is stopped never runs, and the next cell's tasks do", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_queued", {"ran"}); + HostedSession hosted; + REQUIRE(hosted.session.submit(cell("import time, _queued\nfrom concurrent.futures import ThreadPoolExecutor\n" + "ex = ThreadPoolExecutor(1)\n" + "def spin():\n while True:\n time.sleep(0.01)\n" + "ex.submit(spin)\nsecond = ex.submit(_queued.ran.set)\n" + "while True:\n time.sleep(0.01)\n"))); + std::this_thread::sleep_for(std::chrono::milliseconds(500)); + hosted.session.stop(); + const WorkEvents stopped = await_work(hosted.session); + REQUIRE(stopped.finished); + CHECK(stopped.finished->status == "cancelled"); + CHECK(run_work(hosted.session, cell("ex.submit(lambda: 3).result()")).output() == "3\n"); + std::this_thread::sleep_for(std::chrono::seconds(1)); + CHECK(py_json("__import__('_queued').ran.is_set()") == false); + CHECK_THAT(run_work(hosted.session, console("str(second.exception(5))")).output(), ContainsSubstring("The task was stopped before it ran")); +} + +TEST_CASE("ending a session whose thread ignores Stop returns within its five seconds", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_stubborn", {"quit"}); + { + HostedSession hosted; + // The thread waits in C, where no interrupt lands, until the test lets it go; the atexit function loops until + // an interrupt ends it. + REQUIRE(run_work(hosted.session, cell("import atexit, threading, _stubborn\n" + "threading.Thread(target=_stubborn.quit.wait, args=(30,)).start()\n" + "def forever():\n while True:\n pass\n" + "atexit.register(forever)\n")) + .finished->status == "finished"); + hosted.session.stop(); + const auto start = std::chrono::steady_clock::now(); + hosted.session.end(); + CHECK(eventually([&] { return hosted.returned.load(); }, 8)); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(8)); + CHECK(hosted.session.ended()); + shared.set("quit"); + } +} + +TEST_CASE("stopping an idle session as it ends interrupts an atexit function that never returns", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_spin", {"release"}); + { + HostedSession hosted; + // No thread is left: the session is idle with nothing live when it ends, and only its teardown runs the loop. + REQUIRE(run_work(hosted.session, cell("import atexit, _spin\n" + "def spin():\n while not _spin.release.is_set():\n pass\n" + "atexit.register(spin)\n")) + .finished->status == "finished"); + REQUIRE_FALSE(hosted.session.has_threads()); + const auto start = std::chrono::steady_clock::now(); + hosted.session.end(); + hosted.session.stop(); + CHECK(eventually([&] { return hosted.returned.load(); }, 8)); + CHECK(std::chrono::steady_clock::now() - start < std::chrono::seconds(8)); + // Lets a teardown the stop never reached finish, so the session's thread can be joined. + shared.set("release"); + } +} + +TEST_CASE("a work starts only once the stop before it has finished cancelling the session's tool calls", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The watcher cancels a stop's tool calls outside its lock; this stop holds that step open until the test lets it go. + std::atomic cancelling{false}, release{false}, cancelled{false}, second_saw_cancelled{false}; + std::atomic works{0}; + PythonSessionRequest request = HostedSession::person_session(); + request.stop_calls = [&] { + cancelling = true; + for (int i = 0; i < 1000 && !release; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + cancelled = true; + }; + request.work_started = [&] { + if (++works == 2) + second_saw_cancelled = cancelled.load(); + }; + HostedSession hosted(request); + REQUIRE(hosted.session.submit(cell("import time\ntime.sleep(0.5)\n"))); + REQUIRE(eventually([&] { return works.load() == 1; }, 5)); + hosted.session.stop(); + REQUIRE(eventually([&] { return cancelling.load(); }, 5)); + REQUIRE(await_work(hosted.session).finished); // the sleep ends by itself; the stop's interrupt waits behind the cancel + + REQUIRE(hosted.session.submit(cell("1"))); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + release = true; + REQUIRE(await_work(hosted.session).finished); + CHECK(second_saw_cancelled); +} + +TEST_CASE("a work starts only once every stop being applied has finished, its own and the watcher's", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + // The watcher applies the first stop and is held there; a second stop, asked while the session is idle with a thread + // left, is taken by the next work's own start, overlapping the first. + SharedModule shared("_overlap", {"go"}); + std::atomic release{false}, first_done{false}, second_saw_first_done{false}; + std::atomic calls{0}, works{0}; + PythonSessionRequest request = HostedSession::person_session(); + request.stop_calls = [&] { + if (++calls != 1) + return; + for (int i = 0; i < 1000 && !release; ++i) + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + first_done = true; + }; + request.work_started = [&] { + if (++works == 2) + second_saw_first_done = first_done.load(); + }; + { + HostedSession hosted(request); + REQUIRE(hosted.session.submit(cell("import threading, time, _overlap\n" + "threading.Thread(target=_overlap.go.wait, args=(30,)).start()\n" + "time.sleep(0.5)\n"))); + REQUIRE(eventually([&] { return works.load() == 1; }, 5)); + hosted.session.stop(); + REQUIRE(eventually([&] { return calls.load() == 1; }, 5)); + REQUIRE(await_work(hosted.session).finished); + REQUIRE(hosted.session.has_threads()); + hosted.session.stop(); // the watcher is held in the first stop: the second work's start takes this one + REQUIRE(hosted.session.submit(cell("1"))); + std::this_thread::sleep_for(std::chrono::milliseconds(300)); + release = true; + REQUIRE(await_work(hosted.session).finished); + CHECK(calls.load() == 2); + CHECK(second_saw_first_done); + shared.set("go"); + } +} + +TEST_CASE("ending a session runs its atexit functions once, inside the session", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_bye", {"done"}); + HostedSession hosted; + REQUIRE(run_work(hosted.session, cell("import atexit, _bye\n_bye.count = 0\n" + "def bye():\n _bye.count += 1\n _bye.done.set()\n print('bye')\n" + "atexit.register(bye)\n")) + .finished->status == "finished"); + hosted.session.end(); + REQUIRE(eventually([&] { return hosted.session.ended(); }, 10)); + CHECK(shared.wait("done", 1)); + CHECK(shared.get("count") == 1); + CHECK_THAT(output_within(hosted.session, 0.1), ContainsSubstring("bye")); +} + +TEST_CASE("work hooks bracket each piece of work", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_hooks", {"go"}); + std::atomic started{0}, ended{0}; + PythonSessionRequest request = HostedSession::person_session(); + request.work_started = [&] { ++started; }; + request.work_ended = [&] { ++ended; }; + HostedSession hosted(request); + REQUIRE(hosted.session.submit(cell("import _hooks\nok = _hooks.go.wait(10)\n"))); + CHECK(eventually([&] { return started.load() == 1; }, 5)); + CHECK(ended.load() == 0); + shared.set("go"); + REQUIRE(await_work(hosted.session).finished); + run_work(hosted.session, cell("1")); + CHECK(started.load() == 2); + CHECK(ended.load() == 2); +} + +TEST_CASE("submit refuses work while work runs and after end", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_busy", {"go"}); + HostedSession hosted; + REQUIRE(hosted.session.submit(cell("import _busy\nok = _busy.go.wait(10)\n"))); + CHECK_FALSE(hosted.session.submit(cell("1"))); + shared.set("go"); + REQUIRE(await_work(hosted.session).finished); + hosted.session.end(); + CHECK_FALSE(hosted.session.submit(cell("1"))); + REQUIRE(eventually([&] { return hosted.session.ended(); }, 10)); + CHECK_FALSE(hosted.session.submit(cell("1"))); +} + +TEST_CASE("a file session imports from its folder in cells and evicts its helpers when it ends", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + MacroDir macro; + macro.write("session_helper.py", "v = 41\n"); + HostedSession hosted(HostedSession::person_session(macro.write("main.py", ""))); + CHECK(run_work(hosted.session, cell("import session_helper\nsession_helper.v")).output() == "41\n"); + hosted.session.end(); + REQUIRE(eventually([&] { return hosted.session.ended(); }, 10)); + CHECK(py_json("'session_helper' in sys.modules") == false); +} + +TEST_CASE("SystemExit(0) in a cell finishes it and keeps the session", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + HostedSession hosted; + CHECK(run_work(hosted.session, cell("raise SystemExit(0)")).finished->status == "finished"); + CHECK(run_work(hosted.session, cell("1")).output() == "1\n"); +} + +TEST_CASE("a session's output past 256 KiB is cut with a note, in a work and between works, and the next work streams again", + "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + const std::size_t limit = 256 * 1024 + std::string(kTruncatedNote).size(); + SharedModule shared("_chatter", {"go", "done"}); + HostedSession hosted; + const std::string in_work = run_work(hosted.session, cell("print('x' * (300 * 1024))")).output(); + CHECK(in_work.size() <= limit); + CHECK_THAT(in_work, ContainsSubstring("[output truncated at 256 KiB]")); + + REQUIRE(run_work(hosted.session, cell("import threading, _chatter\n" + "def chatter():\n _chatter.go.wait(10)\n print('y' * (300 * 1024))\n _chatter.done.set()\n" + "threading.Thread(target=chatter).start()\n")) + .finished->status == "finished"); + shared.set("go"); + REQUIRE(shared.wait("done", 10)); + const std::string between = output_within(hosted.session, 0.5); + CHECK(between.size() <= limit); + CHECK_THAT(between, ContainsSubstring("[output truncated at 256 KiB]")); + + CHECK(run_work(hosted.session, cell("print('ok')")).output() == "ok\n"); +} + +TEST_CASE("what a session's threads print after a work that used up its output still arrives", "[PythonScript][Python][PythonSession]") +{ + RunnerHarness harness; + if (!harness.initialized) + SKIP("Bundled Python interpreter unavailable: " + PythonInterpreter::instance().last_error()); + + SharedModule shared("_after", {"go", "done"}); + HostedSession hosted; + REQUIRE(run_work(hosted.session, cell("import threading, _after\n" + "def later():\n _after.go.wait(10)\n print('after the work')\n _after.done.set()\n" + "threading.Thread(target=later).start()\n" + "print('x' * (300 * 1024))\n")) + .finished->status == "finished"); + shared.set("go"); + REQUIRE(shared.wait("done", 10)); + CHECK_THAT(output_within(hosted.session, 0.5), ContainsSubstring("after the work")); +} diff --git a/tests/slic3rutils/test_shortcuts.cpp b/tests/slic3rutils/test_shortcuts.cpp index e73445bc5a..dccf29e6da 100644 --- a/tests/slic3rutils/test_shortcuts.cpp +++ b/tests/slic3rutils/test_shortcuts.cpp @@ -237,6 +237,15 @@ TEST_CASE("Every shortcut is listed under the section of its table row", "[Short CHECK(std::string(section_name(ShortcutSection::SlicingAndPrinting)) == "Slicing and printing"); } +TEST_CASE("Run Script toggles from anywhere with Ctrl+Shift+R", "[Shortcuts]") +{ + const ShortcutInfo& info = shortcut_info(Shortcut::ToggleRunScript); + CHECK(std::string(info.key) == "toggle_run_script"); + CHECK(info.contexts == context_bit(ShortcutContext::Global)); + CHECK(info.default_chord == KeyChord{'R', wxMOD_CONTROL | wxMOD_SHIFT}); + CHECK(shortcut_section(Shortcut::ToggleRunScript) == ShortcutSection::Application); +} + TEST_CASE("Default bindings never collide inside a context", "[Shortcuts]") { ShortcutRegistry registry; diff --git a/tools/mcp/README.md b/tools/mcp/README.md index edc191e09b..a0afd24864 100644 --- a/tools/mcp/README.md +++ b/tools/mcp/README.md @@ -94,7 +94,7 @@ plugin in the Plugins dialog withdraws its operation and ends its rule); and wit where a `--mcp-script` runs the plugin's script and its rule is still the plugin's. Run it as `python tools/mcp/test_plugin_tools.py`. The permission's own prompt opens while the app starts, before MCP can answer it, so the first launch sets `ORCA_MCP_TOOLS_FIXTURE_ASK=0` and the plugin doesn't ask; the prompt is covered by the unit tests. The -script runner's `.py` files are not driven from here: the dialog is hidden from automation and opens its +Run Script panel's `.py` files are not driven from here: the panel is hidden from automation and opens its files through a file picker, so how it reads and saves them is covered by the unit tests of `decode_python_source()` and `encode_python_source()`. @@ -321,10 +321,12 @@ tools/mcp/orca_mcp.py launch --datadir /tmp/orca-mcp-test tools/mcp/test_web_ui.py ``` -`test_script_runner_hidden.py` opens the Run Script dialog and checks that the GUI tools don't see +`test_script_runner_hidden.py` opens Action Replay and checks that the GUI tools don't see it: `ui_snapshot` lists no window for it, `webview_eval` without a target behaves as before it -opened, and a key sent without a target never reaches it; `run_script` still runs the smoke test and -a nested inline script. +opened, and a key sent without a target never reaches it. It then shows the Run Script panel on +Prepare and checks the same for it, with no more web views in `ui_snapshot` than before, a key sent +without a target reaching the 3D view, a window screenshot, and an agent's `run_python` finishing +while it is shown; `run_script` still runs the smoke test and a nested inline script. `tests/slice_stats.json` slices one cube, then two cubes in two colours, and checks the slice reply's statistics: layers, max Z, filament changes, and each filament slot's model, flush and diff --git a/tools/mcp/test_script_runner_hidden.py b/tools/mcp/test_script_runner_hidden.py index bf440c4ea3..4811215c2d 100755 --- a/tools/mcp/test_script_runner_hidden.py +++ b/tools/mcp/test_script_runner_hidden.py @@ -1,16 +1,21 @@ #!/usr/bin/env python3 -"""Checks that the Run Script dialog stays out of reach of the GUI tools, so a script can't act on it. +"""Checks that the Action Replay window and the Run Script panel stay out of reach of the GUI tools, so a +replay or a script can't act on them. tools/mcp/orca_mcp.py launch tools/mcp/test_script_runner_hidden.py -With the dialog open: ui_snapshot lists no window for it, a window screenshot still works, -webview_eval without a target behaves as it did before the dialog opened (it must not find a second -web view), and ui_key without a target goes to the 3D view. run_script still runs the smoke test, and -a script nesting an inline run_script passes. Exits 0 when every check passes. +With Action Replay open: ui_snapshot lists no window for it, a window screenshot still works, +webview_eval without a target behaves as it did before the window opened (it must not find a second +web view), and ui_key without a target never reaches its web view. With the Run Script panel shown on +Prepare: ui_snapshot lists no more web views than before, webview_eval without a target behaves as +before, ui_key without a target reaches the 3D view, a window screenshot works and an agent's run_python +finishes. run_script still runs the smoke test, and a script nesting an inline run_script passes. Exits +0 when every check passes. """ import os +import re import sys import tempfile import time @@ -34,6 +39,10 @@ def main(): except orca_mcp.McpError as e: return "error: " + str(e) + def webview_nodes(): + _snap, texts = client.call_with_text("ui_snapshot") + return len(re.findall(r"\bwebview\b", texts[0] if texts else "")) + client.call("new_project", discard_changes=True) client.call("set_view", tab="home") before = eval_outcome() @@ -43,8 +52,8 @@ def main(): snap, texts = client.call_with_text("ui_snapshot") tree = texts[0] if texts else "" - # The File menu's "Run Script..." item is listed; the dialog's window must not be. - check("ui_snapshot lists no Run Script window", 'window "Run Script"' not in tree) + # The File menu's "Action Replay..." item is listed; the window must not be. + check("ui_snapshot lists no Action Replay window", 'window "Action Replay"' not in tree) check("ui_snapshot still lists the main window", "(MainFrame)" in tree) check("a window screenshot works", client.call("screenshot", target="window").get("path")) check("webview_eval without a target behaves as before", eval_outcome() == before, f"{before} / {eval_outcome()}") @@ -52,7 +61,22 @@ def main(): client.call("set_view", tab="prepare") client.call("run_action", id="orca_command:open_script_runner:orca") # raised again, so it has the focus key = client.call("ui_key", keys="Escape") - check("a key without a target never goes to the runner's web view", "webview" not in str(key.get("to", "")).lower(), key) + check("a key without a target never goes to Action Replay's web view", "webview" not in str(key.get("to", "")).lower(), key) + + # The Run Script panel, docked under the 3D view of Prepare. + client.call("set_view", tab="prepare") + nodes_before = webview_nodes() + prepare_eval = eval_outcome() + client.call("run_action", id="orca_command:toggle_run_script:orca") + time.sleep(1.0) # let its web view load + check("ui_snapshot lists no node of the Run Script panel", webview_nodes() == nodes_before, f"{nodes_before} / {webview_nodes()}") + check("webview_eval without a target behaves as before the panel", eval_outcome() == prepare_eval, f"{prepare_eval} / {eval_outcome()}") + key = client.call("ui_key", keys="Escape") + check("a key without a target reaches the 3D view", "canvas" in str(key.get("to", "")).lower(), key) + check("a window screenshot works with the panel shown", client.call("screenshot", target="window").get("path")) + python = client.await_job(client.call("run_python", code="print('agent run')")) + check("an agent's run_python finishes while the panel is shown", python.get("status") == "finished", python) + client.call("run_action", id="orca_command:toggle_run_script:orca") # hidden again out = tempfile.mkdtemp(prefix="orca-runner-") smoke = client.await_job(client.call("run_script", path=os.path.join(HERE, "smoke_test.json"), out_dir=out))