mirror of
https://github.com/OrcaSlicer/OrcaSlicer.git
synced 2026-11-27 15:49:52 -05:00
Regroup the slicer's MCP commands and let each run from its arguments
Outside the Design tab an agent had 175 commands, 50 of them in the tool list. There are now 118, named by what they act on (`object_`, `plate_`, `preset_`, `filament_`, `plugin_` and so on), and 115 are listed. Each takes its target and values in the call, acts on the selection when it names no target and says what it acted on; an old name is refused. Printers and system filaments install and uninstall, preferences read and write, plugins enable, reload, uninstall and refresh, and objects reorder, with no dialog to drive. The Speed Dial keeps its 129 tiles under the same ids. Eight defects in the rows these commands share with the menus are fixed. For a person: an object row that cannot run says why instead of "Select an object first.", rows that failed no longer claim success, Duplicate Plate can be undone, and Refresh Plugins picked while a refresh runs now runs after it instead of beside it.
This commit is contained in:
1 parent
74c98e197c
commit
d64e10f4dd
287 files changed
+40484
-16770
No files matched your search
@@ -10,13 +10,13 @@ Replay and recordings show, and what the journal records and replays.
|
||||
|
||||
This document is the command set: how the commands are named and grouped, what each does and takes, how a
|
||||
call opens a tool for a person instead of running, and how the commands relate to the right-click menu's
|
||||
rows. How the server serves them (the catalog, `search_tools`, the gate, the journal) is in
|
||||
rows. How the server serves them (the catalog, `tool_search`, the gate, the journal) is in
|
||||
[mcp-server.md](mcp-server.md), and the tab itself in [design-tab.md](design-tab.md).
|
||||
|
||||
One table defines them all: `scripts/CAD/tool_atlas.json`. `scripts/CAD/gen_offer_table.py` writes
|
||||
`src/slic3r/GUI/CAD/DesignOffer.hpp` from it, and the commands' code is `src/slic3r/GUI/Mcp/McpToolsCad.cpp`.
|
||||
What every command takes and replies is in its entry's tool block, which the agent reads through
|
||||
`search_tools {tool}`; `tests/data/command_catalog.json` holds every command's schema, tiles and examples as
|
||||
`tool_search {tool}`; `tests/data/command_catalog.json` holds every command's schema, tiles and examples as
|
||||
an agent sees them.
|
||||
|
||||
## Naming
|
||||
@@ -35,7 +35,7 @@ variable, body and feature.
|
||||
- `construct_`: reference planes, axes and coordinate systems.
|
||||
- `feature_`: one entry of the history: describe, edit, suppress, move, rename, delete.
|
||||
- `body_`: one body as an object: name and colour it, delete it, place it, describe and measure it.
|
||||
`body_transform` is here too, since `transform` is the Prepare tab's command.
|
||||
`body_transform` is here too, since `object_transform` is the Prepare tab's command.
|
||||
2. **One command per operation, and one argument for its variants.** `type` says which kind of thing the
|
||||
command makes, or which way it makes it: a shape, a pattern's layout, a hole's kind, how a plane is
|
||||
defined. A shape drawn more than one way names the way (`rectangle_3_point`).
|
||||
@@ -52,7 +52,7 @@ whole bodies.
|
||||
|
||||
## The command set
|
||||
|
||||
The commands are listed under the headings `search_tools`' description names them under, in its order:
|
||||
The commands are listed under the headings `tool_search`' description names them under, in its order:
|
||||
Document, Sketch, Solid, Surface, Construct, Inspect, Bodies, History and Menu rows. Main arguments only;
|
||||
every argument, its default and its range are in the command's schema.
|
||||
|
||||
@@ -217,7 +217,7 @@ These take no arguments and do what their row of the right-click menu does.
|
||||
|
||||
### Outside the Design table
|
||||
|
||||
`undo` and `redo` with `{history: "design"}` step the Design history. `set_view` with `tab: "design"` takes
|
||||
`undo` and `redo` with `{history: "design"}` step the Design history. `view_set` with `tab: "design"` takes
|
||||
the Design view's options: `camera: "sketch_normal"`, which looks straight at the open sketch and is refused
|
||||
with none open; `section` `{on, z, keep}`, a horizontal cut at world `z` (left out, the model's middle) that
|
||||
keeps the lower or the upper half; and `origin_planes`, `world_axes`, `origin` and `bed`, which show or hide
|
||||
@@ -322,7 +322,7 @@ and a pattern's layout as `type` in the commands' words. A feature's type name (
|
||||
|
||||
### How a failure shows
|
||||
|
||||
A command that fails is an error (`code` `-32000`) and leaves the design as it was, so `export_replay` leaves
|
||||
A command that fails is an error (`code` `-32000`) and leaves the design as it was, so `replay_export` leaves
|
||||
it out. That holds for argument errors and for a rebuild the engine rejects alike. Twenty-one commands
|
||||
instead report a rejected rebuild in their reply, `ok` false or `error` not empty, after the same rollback,
|
||||
so such a call is journaled and replays the same rejection: `body_transform`, `boolean`, `construct_axis`,
|
||||
@@ -451,12 +451,12 @@ address, and changing one is a breaking change.
|
||||
own row's tile is under the command's key (`orca_command:sketch_trim:orca`); a folded row keeps its tile
|
||||
under its own id (`orca_command:sk_array:orca`) with its row's title and icon.
|
||||
- A pick of a folded row's tile runs its command with the row's arguments, with the MCP server on or off.
|
||||
Its action shows an agent no arguments, and `run_action` takes none for it, or exactly the row's; that is
|
||||
Its action shows an agent no arguments, and `action_run` takes none for it, or exactly the row's; that is
|
||||
what the journal records, so a replay runs it again.
|
||||
- A call of a command with a row's arguments is titled as that row's tile wherever a person is shown the
|
||||
call: a job notice, a recording's caption, an Action Replay step (`replay_what_text()`).
|
||||
- A folded tile that is not shown is named, when a call asks for it, with the call that runs it from any
|
||||
tab: `call_tool {"tool": "sketch_pattern", "args": {"type": "linear"}}`.
|
||||
tab: `tool_call {"tool": "sketch_pattern", "args": {"type": "linear"}}`.
|
||||
- The MCP skill's reference (`tools/mcp/gen_skill_reference.py`) gives a command a row of its own only when
|
||||
it has an action of its own, and one row per folded tile with its arguments.
|
||||
|
||||
|
||||
+10
-10
@@ -385,7 +385,7 @@ fold into eight commands, the 24 shape rows into `sketch_draw` among them. An en
|
||||
may name the arguments that choose its own row (`args`), as Boolean's Join row is `boolean {operation: "join"}`,
|
||||
so that each of a command's variants opens the same way. Two rows have neither an action nor a block, Pattern
|
||||
on Curve and Align to, and are shown greyed: they are no command. Every command has a `section`, its heading in
|
||||
the names index the MCP server's `search_tools` gives, and `feature_row` marks the four rows whose action works
|
||||
the names index the MCP server's `tool_search` gives, and `feature_row` marks the four rows whose action works
|
||||
on the Feature tree's selected row (Edit, Rename, Delete and Constrain sketch). `modal` marks the three
|
||||
entries whose action opens a dialog that waits for an answer: a modal one for SVG (a file picker) and Color,
|
||||
which holds the call that opened it until it is answered, and the Design tab's own modeless dialog for Text,
|
||||
@@ -398,9 +398,9 @@ for a checked-in header, not documentation.
|
||||
## Automation surface
|
||||
|
||||
The document is automated through the app's MCP server, on every platform, with the Design tab's commands, one
|
||||
per command entry of its table, in the command catalog's group `Design`: `search_tools {group: "Design"}`
|
||||
lists them, `search_tools {tool}` gives one's arguments, how its failure shows and runnable examples, and
|
||||
`call_tool {tool, args}` runs one. They are named in the industry's terminology, as popular CAD programs such
|
||||
per command entry of its table, in the command catalog's group `Design`: `tool_search {group: "Design"}`
|
||||
lists them, `tool_search {tool}` gives one's arguments, how its failure shows and runnable examples, and
|
||||
`tool_call {tool, args}` runs one. They are named in the industry's terminology, as popular CAD programs such
|
||||
as Fusion 360, Onshape and SolidWorks use it, with a prefix for where each works (`sketch_`, `surface_`,
|
||||
`construct_`, `feature_`, `body_`, and none for the model), and one argument for a variant: `type` for which
|
||||
kind of thing it makes, `operation` for what the result does to the bodies already there. A person picks the
|
||||
@@ -421,7 +421,7 @@ does and takes and which menu rows call it, is in [design-commands.md](design-co
|
||||
An agent's call needs the MCP server on (`--mcp`, or Preferences), and every command, a person's tile included,
|
||||
needs the CAD feature on (Preferences > Features, or `--cad` for one run). The catalog holds them only when the
|
||||
feature is on at startup, as the main window makes the Design page only then, so turning it on takes a restart;
|
||||
with it off they are unknown commands, whose error says how a person turns it on, as `get_app_state`'s
|
||||
with it off they are unknown commands, whose error says how a person turns it on, as `app_state`'s
|
||||
`cad_note` does. Turned off while OrcaSlicer runs, the tab stays until the restart, but the Speed Dial has no
|
||||
tile of it. A call is refused (`-32002`) while the Design tab is busy: none runs while a rebuild owns the
|
||||
document, `change` and `sketch` commands do not run under an open feature card, the Text dialog, Constrain mode
|
||||
@@ -477,7 +477,7 @@ moves and turns a body as the Move / Rotate card does, lays a face on the bed as
|
||||
it back where the model has it. Like the gizmo it is outside the history and not saved, and a placement
|
||||
follows its body when the bodies are renumbered, by the transient id of the feature that made it.
|
||||
`describe_design` reports each body's placement. The section view and the view's switches are set by value
|
||||
through `set_view {tab: "design"}` (`section {on, z, keep}`, `origin_planes`, `world_axes`, `origin`, `bed`),
|
||||
through `view_set {tab: "design"}` (`section {on, z, keep}`, `origin_planes`, `world_axes`, `origin`, `bed`),
|
||||
which the toolbar and the rows only toggle, and its `camera: "sketch_normal"` is the `N` key, refused with no
|
||||
sketch open.
|
||||
|
||||
@@ -521,10 +521,10 @@ angle to the helix axis. Thread, sweep and loft automation rebuilds through `rec
|
||||
as the cards do, so the window stays live during a long build.
|
||||
|
||||
The viewport is a canvas target like Prepare's for the app's MCP server (`DesignCanvas::gl_canvas()`):
|
||||
`set_view {tab: "design"}` shows the tab and points its camera, `screenshot` captures the view
|
||||
`view_set {tab: "design"}` shows the tab and points its camera, `window_screenshot` captures the view
|
||||
(sketch overlay and status line included) and composites it into window captures, `mouse_gesture`
|
||||
clicks and drags it at pixels, so a left click picks and a right click opens the offer, and
|
||||
`list_widgets` lists its in-canvas value fields. Keys sent with `press_keys` reach the panel's
|
||||
`widget_list` lists its in-canvas value fields. Keys sent with `keyboard_press` reach the panel's
|
||||
`wxEVT_CHAR_HOOK` as a real key press does, travelling up from the focused widget, so Escape,
|
||||
Enter and the tool shortcuts behave as they do for a person.
|
||||
|
||||
@@ -564,7 +564,7 @@ catalog holds: one per command entry and none for a folded or a greyed row, a si
|
||||
block and a block for every silent form, the folded rows' tiles, which call opens a tool and which runs, their
|
||||
schemas and summaries, and examples that call only real commands with arguments their schemas take;
|
||||
`scripts/CAD/test_gen_offer_table.py` checks the generator's refusals. On a live application launched with `tools/mcp/orca_mcp.py launch --cad`, the replays
|
||||
`tools/mcp/tests/cad_*.json` drive the commands through `call_tool`, the live tests `tools/mcp/test_cad_replay.py`,
|
||||
`tools/mcp/tests/cad_*.json` drive the commands through `tool_call`, the live tests `tools/mcp/test_cad_replay.py`,
|
||||
`test_cad_slow_build.py` and `test_cad_failed_job.py` cover journaling and replay, the app staying
|
||||
live through a long rebuild, and a call whose job fails after its reply,
|
||||
`tools/mcp/test_cad_examples.py` runs every command's examples, each on a fresh design, and
|
||||
@@ -573,7 +573,7 @@ answer. The GUI
|
||||
tests `tools/mcp/test_cad_sketching.py`, `test_cad_context_menu.py` and `test_cad_click_edit.py`
|
||||
drive the tab as a person does, through the server's UI tools: they draw on the canvas with
|
||||
clicks and typed values, run the offer's verbs from a right click and type into the value fields with
|
||||
no click into them, and grade what the reading commands and `list_widgets` report back. They
|
||||
no click into them, and grade what the reading commands and `widget_list` report back. They
|
||||
need an English UI and no CI job runs them; `tools/mcp/README.md` says how to run them.
|
||||
|
||||
Three checks in `scripts/CAD/` drive a running app through its MCP server as an agent does and
|
||||
|
||||
+1234
-831
File diff suppressed because it is too large.
Load diff
@@ -120,7 +120,7 @@ nested events of the same operation are not asked again.
|
||||
|
||||
### Python scripts
|
||||
|
||||
A Python script run from the Run Script panel, with `--run` or by an agent's `run_script`
|
||||
A Python script run from the Run Script panel, with `--run` or by an agent's `script_run`
|
||||
is not a plugin, but its events are judged here under an identity of its own, `(script)` or `(mcp)`
|
||||
(see "Python scripts" in [mcp-server.md](mcp-server.md)). A script has no sidecar, so it holds
|
||||
no grant and is never asked: steps 1 to 3 apply to it, and any other event is denied with a
|
||||
|
||||
@@ -42,7 +42,7 @@ presets are never serialized — they have their own storage and their own lifec
|
||||
| `resources/profiles/` | `<vendor>.opc` alone — the profile and its preset JSONs both pruned | What the app ships with and what installing copies from; read directly for vendors not installed |
|
||||
| `<data_dir>/system/` | `<vendor>.opc` alone, or `<vendor>.json` + `<vendor>/` after an update | What the user has installed |
|
||||
| `<data_dir>/system/` (dev build) | `<vendor>.json` + `<vendor>/` + `<vendor>.opc` written at runtime | A developer tree caches as it parses |
|
||||
| `<data_dir>/cache/wizard_profile_data.json` | The wizard's derived vendor catalog plus the stamps it was built from | Written and read by the setup wizard only; never shipped (see "The wizard's profile-data cache") |
|
||||
| `<data_dir>/cache/wizard_profile_data.json` | The wizard's derived vendor catalog plus the stamps it was built from | Written and read by the setup wizard and the commands that list and install printer models (`Ops::printer_profile_data()`); never shipped (see "The wizard's profile-data cache") |
|
||||
|
||||
Two forms of the same vendor therefore exist, and the system's central rule is that
|
||||
**a vendor's cache is the whole of it**. Where a cache ships or is installed, no profile
|
||||
@@ -273,7 +273,9 @@ function of the vendor set: each vendor's name and version, in load order. A pro
|
||||
change requires a version bump, so name and version determine a vendor's content
|
||||
wherever its copy sits; which directory served it is deliberately **not** stamped,
|
||||
and installing or removing a copy at an unchanged version leaves the cache valid. So
|
||||
the wizard caches the *derived JSON*, not another form of the inputs:
|
||||
the wizard caches the *derived JSON*, not another form of the inputs
|
||||
(`Ops::printer_profile_data()`, `GUI/Operations/InstallOps.cpp`, which `printer_list_models`,
|
||||
`printer_install` and `printer_uninstall` read the catalog through too):
|
||||
`<data_dir>/cache/wizard_profile_data.json` holds the stamp list and the catalog. On
|
||||
open, the wizard computes the current stamps (one version peek per vendor) and, when
|
||||
they match, serves the catalog from the file — no bundle built, no preset installed.
|
||||
|
||||
@@ -221,7 +221,7 @@ preserves those side effects and then verifies the resulting edited target.
|
||||
|
||||
Filament `preset_name` is an additional integration on top of `Tab::select_preset()`:
|
||||
once the filament tab edits the preset, a different name for a slot is assigned to the
|
||||
slot by `GUI::Ops::assign_filament_preset()`, the operation the MCP `select_preset` tool
|
||||
slot by `GUI::Ops::assign_filament_preset()`, the operation the MCP `preset_select` command
|
||||
calls too (docs/HLSD/mcp-server.md, "The operations layer"). It does what picking the
|
||||
preset in the slot's sidebar selector does (`Sidebar::select_filament_preset()`): the
|
||||
slot's colour settings follow the preset, the slot-to-preset mapping, the dynamic
|
||||
@@ -233,12 +233,12 @@ slot is not targetable.
|
||||
|
||||
Process and printer dropdown choices are constrained by visibility and compatibility,
|
||||
and compatibility may depend on the active context. Target resolution
|
||||
(`GUI::Ops::resolve_preset()`, the rule the `select_preset` tool resolves by, which
|
||||
(`GUI::Ops::resolve_preset()`, the rule the `preset_select` command resolves by, which
|
||||
words its refusals) checks the tab
|
||||
dropdown's actual items before the selection flow, so a target the user cannot pick
|
||||
fails without raising that flow's unsaved-edit prompt; a name two entries carry is
|
||||
rejected as ambiguous. A hidden preset that suits the printer is shown in the
|
||||
selectors first, as for the tool, and a process or printer selection that leaves
|
||||
selectors first, as for the command, and a process or printer selection that leaves
|
||||
another preset edited is refused by `GUI::Ops::select_preset()`. A filament
|
||||
`preset_name` resolves against the requested slot's own sidebar selector rather than
|
||||
the tab's, so that slot's compatibility filter is the one that applies. A name the
|
||||
|
||||
@@ -159,7 +159,10 @@ src/slic3r/GUI/Mcp/McpToolsApi.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsApp.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsCad.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsConfig.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsInstall.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsLayers.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsPlugins.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsPreferences.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsProject.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsPython.cpp
|
||||
src/slic3r/GUI/Mcp/McpToolsRecord.cpp
|
||||
@@ -188,7 +191,11 @@ src/slic3r/GUI/NotificationManager.cpp
|
||||
src/slic3r/GUI/ObjectDataViewModel.cpp
|
||||
src/slic3r/GUI/OpenGLManager.cpp
|
||||
src/slic3r/GUI/Operations/ExportOps.cpp
|
||||
src/slic3r/GUI/Operations/InstallOps.cpp
|
||||
src/slic3r/GUI/Operations/ObjectOps.cpp
|
||||
src/slic3r/GUI/Operations/PlateOps.cpp
|
||||
src/slic3r/GUI/Operations/PluginOps.cpp
|
||||
src/slic3r/GUI/Operations/PreferenceOps.cpp
|
||||
src/slic3r/GUI/Operations/PresetOps.cpp
|
||||
src/slic3r/GUI/Operations/ProjectOps.cpp
|
||||
src/slic3r/GUI/OptionsGroup.cpp
|
||||
|
||||
@@ -82,9 +82,9 @@ function draftReplay() {
|
||||
' "orca_replay_version": ' + JSON.stringify(REPLAY_VERSION) + ",",
|
||||
' "name": ' + JSON.stringify(T("untitled_replay", "Untitled replay")) + ",",
|
||||
' "steps": [',
|
||||
' {"tool": "wait", "args": {"for": "ready"}},',
|
||||
' {"tool": "slice", "expect": {"/status": {"eq": "done"}}},',
|
||||
' {"tool": "screenshot",',
|
||||
' {"tool": "app_wait", "args": {"for": "ready"}},',
|
||||
' {"tool": "plate_slice", "expect": {"/status": {"eq": "done"}}},',
|
||||
' {"tool": "window_screenshot",',
|
||||
' "args": {"target": "canvas", "save_path": "${out_dir}/preview.png", "overwrite": true}}',
|
||||
" ]",
|
||||
"}",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
// The replay format version the draft and the version key's suggestion write: the host's REPLAY_VERSION
|
||||
// (src/slic3r/GUI/Mcp/McpReplay.hpp), which says which versions it reads.
|
||||
const REPLAY_VERSION = "0.1.0";
|
||||
const REPLAY_VERSION = "0.2.0";
|
||||
|
||||
// The keys of a replay 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),
|
||||
|
||||
@@ -5,8 +5,8 @@ const editor = require("./replay_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: { plates: { type: "integer" } } },
|
||||
{ name: "set_view", title: "Set the view", args: { camera: { type: "string", enum: ["top", "front"] }, zoom: { type: ["number", "null"] } } },
|
||||
{ name: "plate_slice", title: "Slice", args: { plates: { type: "integer" } } },
|
||||
{ name: "view_set", title: "Set the view", args: { camera: { type: "string", enum: ["top", "front"] }, zoom: { type: ["number", "null"] } } },
|
||||
]);
|
||||
|
||||
// What suggestionsAt() finds with the caret at the end of `text`.
|
||||
@@ -22,25 +22,25 @@ test("a replay's root keys are suggested in a key's string", () => {
|
||||
});
|
||||
|
||||
test("a step's keys are suggested inside steps[], leaving out the ones it has", () => {
|
||||
const found = at('{"steps": [{"tool": "slice", "');
|
||||
const found = at('{"steps": [{"tool": "plate_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 text = '{"steps": [{"tool": "pl';
|
||||
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: plates" },
|
||||
{ label: "set_view", detail: "Set the view", info: "args: camera, zoom" },
|
||||
{ label: "plate_slice", detail: "Slice", info: "args: plates" },
|
||||
{ label: "view_set", detail: "Set the view", info: "args: camera, 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": {"');
|
||||
const found = at('{"steps": [{"tool": "view_set", "args": {"');
|
||||
assert.equal(found.kind, "key");
|
||||
assert.deepEqual(found.items, [
|
||||
{ label: "camera", detail: "string", info: "top | front" },
|
||||
@@ -49,13 +49,13 @@ test("a tool's arguments are suggested in its args with their types and allowed
|
||||
});
|
||||
|
||||
test("an argument's allowed values are suggested as its value", () => {
|
||||
const found = at('{"steps": [{"tool": "set_view", "args": {"camera": "');
|
||||
const found = at('{"steps": [{"tool": "view_set", "args": {"camera": "');
|
||||
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": {"camera": "${';
|
||||
const text = '{"vars": {"part": 1}, "steps": [{"tool": "plate_slice", "save_as": "s1"}, {"tool": "view_set", "args": {"camera": "${';
|
||||
const found = at(text);
|
||||
assert.equal(found.kind, "var");
|
||||
assert.equal(found.from, text.length);
|
||||
@@ -81,7 +81,7 @@ test("an accepted key gets its colon and an empty value with the caret inside",
|
||||
assert.deepEqual(editor.acceptEdit(text, found, name), { from: 2, to: 2, insert: 'name": ""', back: 1, reopen: true });
|
||||
// The format version is written whole, with the caret after it.
|
||||
const version = found.items.find((item) => item.label === "orca_replay_version");
|
||||
assert.deepEqual(editor.acceptEdit(text, found, version), { from: 2, to: 2, insert: 'orca_replay_version": "0.1.0"', back: 0, reopen: false });
|
||||
assert.deepEqual(editor.acceptEdit(text, found, version), { from: 2, to: 2, insert: 'orca_replay_version": "0.2.0"', back: 0, reopen: false });
|
||||
});
|
||||
|
||||
test("a key accepted before an existing colon replaces only the key", () => {
|
||||
@@ -92,12 +92,12 @@ test("a key accepted before an existing colon replaces only the key", () => {
|
||||
});
|
||||
|
||||
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 text = '{"steps": [{"tool": "pl"}]}';
|
||||
const caret = text.indexOf('pl"') + 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 });
|
||||
assert.deepEqual(editor.acceptEdit(text, found, { label: "plate_slice" }), { from: caret - 2, to: caret + 1, insert: 'plate_slice"', back: 0, reopen: false });
|
||||
});
|
||||
|
||||
test("an accepted placeholder closes its brace, over one already typed", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// The MCP server's agent inside a web page: lists the page as list_widgets shows it and acts on its
|
||||
// elements for click, set_widget_value, press_keys, mouse_gesture and answer_dialog. OrcaSlicer injects it on
|
||||
// The MCP server's agent inside a web page: lists the page as widget_list shows it and acts on its
|
||||
// elements for widget_click, widget_set_value, keyboard_press, mouse_gesture and dialog_answer. OrcaSlicer injects it on
|
||||
// demand into any of its web views (src/slic3r/GUI/Mcp/WebPages.cpp), so no page or host includes
|
||||
// it. It runs as the body of `function (V, SRC)`, V the version OrcaSlicer stamps it with and SRC
|
||||
// this source, which it hands to the plugin configuration frames it relays to, and installs
|
||||
@@ -175,7 +175,7 @@ function jqueryHandles(el) {
|
||||
|
||||
function isFrame(el) { return el.localName === 'iframe' || el.localName === 'frame'; }
|
||||
|
||||
// The kind list_widgets lists an element as, in the vocabulary of wx widgets, or '' when it is only a
|
||||
// The kind widget_list lists an element as, in the vocabulary of wx widgets, or '' when it is only a
|
||||
// container. `pointerAbove` says whether its parent already shows the pointer cursor or is a listed
|
||||
// button or link, so a clickable element counts once, not with every child inside it.
|
||||
function kindOf(el, st, pointerAbove) {
|
||||
@@ -483,7 +483,7 @@ function topRect(el) {
|
||||
|
||||
// ---- the walk ------------------------------------------------------------------------------
|
||||
|
||||
// Visits the page as list_widgets lists it: visit(el, info, depth) for each listed element and
|
||||
// Visits the page as widget_list lists it: visit(el, info, depth) for each listed element and
|
||||
// text(text, depth, block) for each run of text outside one. Hidden subtrees are left out; open
|
||||
// shadow roots are walked through their slots and same-origin frames entered.
|
||||
function walkPage(visit, text) {
|
||||
@@ -1050,7 +1050,7 @@ function aimAt(el, dx, dy, hitTest) {
|
||||
// What a press lands on must be the element; a move or release may be anywhere (a drag's).
|
||||
if (hitTest && ((dx !== undefined && (dx < 0 || dx > r.width)) || (dy !== undefined && (dy < 0 || dy > r.height))))
|
||||
fail('point', 'The point x, y is outside the element: they count from its top left, within the width and height ' +
|
||||
'list_widgets lists for it');
|
||||
'widget_list lists for it');
|
||||
var at = {x: dx === undefined ? r.left + r.width / 2 : r.left + dx, y: dy === undefined ? r.top + r.height / 2 : r.top + dy};
|
||||
if (hitTest) {
|
||||
var root = el.getRootNode ? el.getRootNode() : el.ownerDocument;
|
||||
@@ -1766,7 +1766,7 @@ var CHANGES_MAX = 20;
|
||||
var WATCHES_MAX = 16;
|
||||
var watches = {}; // outlines taken before actions, by the tools' id for the action: {at, lines}
|
||||
|
||||
// The page as list_widgets lists it, a line per element (kind, label, value, state and notes) and per
|
||||
// The page as widget_list lists it, a line per element (kind, label, value, state and notes) and per
|
||||
// run of text, and the configuration frames, whose agents outline their own pages.
|
||||
function outline() {
|
||||
var lines = [];
|
||||
@@ -1885,10 +1885,10 @@ function changes(req) {
|
||||
|
||||
function element(req) {
|
||||
if (req.doc !== docToken)
|
||||
fail('stale', 'The page changed (it navigated or reloaded); call list_widgets again');
|
||||
fail('stale', 'The page changed (it navigated or reloaded); call widget_list again');
|
||||
var el = byKey.get(req.k);
|
||||
if (!el || !el.isConnected)
|
||||
fail('stale', 'The element is gone from the page; call list_widgets again');
|
||||
fail('stale', 'The element is gone from the page; call widget_list again');
|
||||
return el;
|
||||
}
|
||||
|
||||
@@ -1917,7 +1917,7 @@ function forward(req) {
|
||||
var parts = String(req.k).split('/');
|
||||
var frame = byKey.get(Number(parts[0]));
|
||||
if (!frame || !frame.isConnected || !relayFrame(frame))
|
||||
fail('stale', 'The element\'s frame is gone; call list_widgets again');
|
||||
fail('stale', 'The element\'s frame is gone; call widget_list again');
|
||||
var inner = {};
|
||||
for (var p in req)
|
||||
inner[p] = req[p];
|
||||
@@ -1948,7 +1948,7 @@ function release(req) {
|
||||
function act(req) {
|
||||
if (typeof req.k === 'string' && req.k.indexOf('/') > 0) {
|
||||
if (req.doc !== docToken)
|
||||
fail('stale', 'The page changed (it navigated or reloaded); call list_widgets again');
|
||||
fail('stale', 'The page changed (it navigated or reloaded); call widget_list again');
|
||||
watch(req);
|
||||
return forward(req);
|
||||
}
|
||||
@@ -1956,7 +1956,7 @@ function act(req) {
|
||||
var el = req.k ? element(req) : null;
|
||||
if (req.action === 'key') {
|
||||
if (el && hiddenFromView(el))
|
||||
fail('hidden', 'The element is not shown; call list_widgets again');
|
||||
fail('hidden', 'The element is not shown; call widget_list again');
|
||||
// A disabled control (its fieldset's included) takes no focus, so keys would go elsewhere.
|
||||
if (el) {
|
||||
var keyed = infoOf(el);
|
||||
@@ -1993,7 +1993,7 @@ function act(req) {
|
||||
if (!el)
|
||||
fail('target', 'No element');
|
||||
if (hiddenFromView(el))
|
||||
fail('hidden', 'The element is not shown; call list_widgets again');
|
||||
fail('hidden', 'The element is not shown; call widget_list again');
|
||||
var info = infoOf(el);
|
||||
if (disabledOf(info.control || el, info.st))
|
||||
fail('disabled', 'The ' + info.kind + ' "' + clip(info.label, 40) + '" is disabled');
|
||||
@@ -2037,7 +2037,7 @@ function press(req) {
|
||||
|
||||
function evalScript(req) {
|
||||
if (typeof req.k === 'string')
|
||||
fail('relayed', 'The element is in a plugin configuration frame, which run_javascript does not reach; use click, set_widget_value and press_keys');
|
||||
fail('relayed', 'The element is in a plugin configuration frame, which webview_run_javascript does not reach; use widget_click, widget_set_value and keyboard_press');
|
||||
var el = req.k ? element(req) : undefined;
|
||||
// A page whose Content-Security-Policy forbids eval refuses to build the runner, before any of the
|
||||
// script runs; the agent itself, installed as inline code, still works there.
|
||||
@@ -2045,7 +2045,7 @@ function evalScript(req) {
|
||||
try {
|
||||
run = new Function('el', 'return eval(arguments[1]);');
|
||||
} catch (e) {
|
||||
fail('csp', 'This page\'s Content-Security-Policy forbids eval, which run_javascript runs scripts with; click, set_widget_value and press_keys ' +
|
||||
fail('csp', 'This page\'s Content-Security-Policy forbids eval, which webview_run_javascript runs scripts with; widget_click, widget_set_value and keyboard_press ' +
|
||||
'still work on it');
|
||||
}
|
||||
var res = run(el, String(req.script));
|
||||
|
||||
@@ -33,7 +33,7 @@ ENUM = {
|
||||
# a tool block's access -> CadAccess enumerator
|
||||
ACCESS = {"read": "Read", "change": "Change", "sketch": "Sketch", "ui": "Ui"}
|
||||
|
||||
# The headings of search_tools' index of the Design commands (Mcp::design_command_index()), in its order: every
|
||||
# The headings of tool_search's index of the Design commands (Mcp::design_command_index()), in its order: every
|
||||
# command's `section` is one of them. Menu rows holds the commands that take no arguments and only do what their row
|
||||
# does.
|
||||
SECTIONS = ("Document", "Sketch", "Solid", "Surface", "Construct", "Inspect", "Bodies", "History", "Menu rows")
|
||||
@@ -122,7 +122,7 @@ def faults(A):
|
||||
command's own row takes, which a call with none also gives. A command's rows are in one mode.
|
||||
|
||||
Every command, an entry with an action or a block that is no folded row, has a `section`, its heading in
|
||||
search_tools' index (SECTIONS); a folded or greyed row, which is no command, has none.
|
||||
tool_search's index (SECTIONS); a folded or greyed row, which is no command, has none.
|
||||
|
||||
`feature_row` marks a row whose action acts on the selected row of the Feature list, which a call of its
|
||||
command takes as its target when nothing is picked in the view (Mcp::open_refusal()): only a command with a row
|
||||
@@ -154,7 +154,7 @@ def faults(A):
|
||||
if not command and "section" in v:
|
||||
errs.append(f"{vid}: a folded or greyed row is no command and has no section")
|
||||
elif command and "section" not in v:
|
||||
errs.append(f"{vid}: a command needs a section, its heading in search_tools' index: one of {list(SECTIONS)}")
|
||||
errs.append(f"{vid}: a command needs a section, its heading in tool_search's index: one of {list(SECTIONS)}")
|
||||
elif command and v["section"] not in SECTIONS:
|
||||
errs.append(f'{vid}: section {v["section"]!r} is not one of {list(SECTIONS)}')
|
||||
if v.get("feature_row") and (not v.get("action") or "fold" in v):
|
||||
@@ -248,7 +248,7 @@ def main():
|
||||
"// not apply are shown disabled in place with their reason rather than removed. Row order was",
|
||||
"// ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory.",
|
||||
"// An entry with an action or a tool block, and no fold_into, is a command of the catalog's group Design",
|
||||
"// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in search_tools' index. A",
|
||||
"// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in tool_search's index. A",
|
||||
"// call whose arguments are exactly those that choose one of its rows opens that row's tool for a person",
|
||||
"// (Mcp::opened_row()): none choose the entry's own row where it has an action, else the rows folded into it",
|
||||
"// with {}; a folded row's args, or the entry's own, choose that row. Any other call runs its tool block's",
|
||||
@@ -336,7 +336,7 @@ def main():
|
||||
" // The arguments that choose this row, as JSON text: a folded row's, or those that choose the own row of",
|
||||
" // an entry with an action and a tool block as a call with none does; nullptr for none.",
|
||||
" const char* args;",
|
||||
" // The heading its command is listed under in search_tools' index (kDesignSections,",
|
||||
" // The heading its command is listed under in tool_search's index (kDesignSections,",
|
||||
" // Mcp::design_command_index()); nullptr for an entry that is no command.",
|
||||
" const char* section;",
|
||||
" // Its action acts on the selected row of the Feature list, which a call of its command, not a person's",
|
||||
@@ -344,7 +344,7 @@ def main():
|
||||
" bool feature_row;",
|
||||
"};",
|
||||
"",
|
||||
"// The headings of search_tools' index of the Design commands, in its order. Menu rows holds the commands",
|
||||
"// The headings of tool_search's index of the Design commands, in its order. Menu rows holds the commands",
|
||||
"// that take no arguments and only do what their row does.",
|
||||
"static const char* const kDesignSections[] = {",
|
||||
]
|
||||
|
||||
@@ -4356,10 +4356,10 @@
|
||||
"access": "change",
|
||||
"ok_false": false,
|
||||
"summary": "Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions and show Prepare.",
|
||||
"details": "It is one Prepare undo step. A lone body is sent even when hidden. A body named in the Bodies list or with body_set names its object or part. Reply: objects (list_objects index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.",
|
||||
"details": "It is one Prepare undo step. A lone body is sent even when hidden. A body named in the Bodies list or with body_set names its object or part. Reply: objects (object_list index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.",
|
||||
"params": [
|
||||
{"name": "mode", "type": "string", "default": "", "enum": ["assembly", "bodies"], "description": "assembly: one object with a part per body; bodies: an object per body. Default: the Commit button's mode, which this leaves as it is."},
|
||||
{"name": "replace", "type": "array", "default": [], "description": "list_objects indices to delete in the same undo step, such as an earlier commit. Their settings, modifiers and paint go with them."}
|
||||
{"name": "replace", "type": "array", "default": [], "description": "object_list indices to delete in the same undo step, such as an earlier commit. Their settings, modifiers and paint go with them."}
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
|
||||
@@ -35,15 +35,19 @@ NOT_CALLERS = {"src/slic3r/GUI/Mcp/McpToolsCad.cpp"}
|
||||
# Owner methods an operation calls, by the operation that stands for them.
|
||||
BANNED = {
|
||||
"start_gcode_export": ["export_gcode_to"],
|
||||
"import_models": ["load_files"],
|
||||
"import_models": ["load_files", "import_zip_archive", "preview_zip_archive"],
|
||||
"open_project": ["load_project"],
|
||||
"new_project": ["new_project"],
|
||||
"save_project_as": ["save_project"],
|
||||
"export_sliced_3mf": ["export_gcode_3mf"],
|
||||
"export_model_3mf": ["export_core_3mf"],
|
||||
"export_stl": ["export_stl"],
|
||||
"export_toolpaths_obj": ["export_toolpaths_to_obj"],
|
||||
"select_plate": ["select_plate"],
|
||||
"set_plate_locked": ["lock_plate", "set_plate_locked"],
|
||||
"delete_plate": ["delete_plate"],
|
||||
"duplicate_plate": ["duplicate_plate"],
|
||||
"rename_plate": ["rename_plate"],
|
||||
"start_arrange": ["set_prepare_state", "arrange"],
|
||||
"start_slice": ["request_slice"],
|
||||
"show_layer_range": ["SetHigherValue", "SetLowerValue", "show_layer_range"],
|
||||
@@ -51,7 +55,44 @@ BANNED = {
|
||||
"assign_filament_preset": ["set_filament_preset", "select_filament_preset"],
|
||||
"import_presets": ["import_configs"],
|
||||
"set_instance_count": ["set_number_of_copies"],
|
||||
"delete_objects": ["delete_from_model_and_list", "delete_all_objects_from_model", "remove_selected"],
|
||||
"rename_object": ["rename_item"],
|
||||
"separate_instances": ["instances_to_separated_object", "instances_to_separated_objects", "split_instances"],
|
||||
# assemble_objects calls ObjectList::merge(), a name too common to ban (a bounding box's merge()).
|
||||
"split_object": ["split_object", "split_volume"],
|
||||
"change_part_type": ["set_volume_type"],
|
||||
"order_objects": ["order_objects"],
|
||||
"mirror_objects": ["mirror"],
|
||||
"center_objects": ["center_selection", "do_center_plate"],
|
||||
"scale_to_fit": ["scale_selection_to_fit_print_volume"],
|
||||
"drop_objects": ["drop_selection"],
|
||||
"orient_objects": ["orient"],
|
||||
"add_primitive": ["load_shape_object"],
|
||||
"set_objects_printable": ["toggle_printable_state", "update_printable_state", "set_printable"],
|
||||
"set_objects_auto_drop": ["set_auto_drop", "toggle_auto_drop"],
|
||||
"fix_objects": ["fix_through_cgal", "fix_all_through_cgal"],
|
||||
# clone_objects calls Selection::clone(), a name too common to ban (ConfigOption::clone()).
|
||||
"clone_objects": ["clone_selection"],
|
||||
"reload_parts": ["reload_parts_from_disk", "reload_from_disk", "reload_all_from_disk"],
|
||||
"replace_part": ["replace_part_with_file", "replace_with_stl"],
|
||||
"send_gcode_to_host": ["send_gcode_legacy"],
|
||||
"sync_presets": ["restart_sync_user_preset", "start_sync_user_preset"],
|
||||
"add_filament_slot": ["add_filament"],
|
||||
"delete_filament_slot": ["delete_filament", "change_filament"],
|
||||
"add_mixed_filament": ["ensure_mixed_filament", "add_mixed_filament"],
|
||||
# uninstall_printers, and the Printer Selection dialog's Confirm, apply the set through it too (apply_install_set).
|
||||
"install_printers": ["apply_vendor_config"],
|
||||
# uninstall_filaments writes the filaments section through it too.
|
||||
"install_filaments": ["set_section"],
|
||||
# The Preferences dialog's controls run these effects through apply_preference(), as set_preferences does.
|
||||
"set_preferences": ["set_visible_page_count", "set_max_recent_count", "update_filaments_area_height"],
|
||||
# The Plugins window's switches, Delete and Unsubscribe, and Reload and Reinstall run these through the operations.
|
||||
"set_plugin_enabled": ["load_plugin", "unload_plugin", "set_capability_enabled"],
|
||||
"uninstall_plugin": ["delete_plugin", "delete_and_unsubscribe_cloud_plugin"],
|
||||
"reload_plugin": ["download_and_install_cloud_plugin"],
|
||||
# The sync dialog's Synchronize now runs the sync through the operation, and a drop in the object list a drag.
|
||||
"sync_filaments_from_ams": ["sync_ams_list", "apply_ams_sync"],
|
||||
"reorder_objects": ["move_object"],
|
||||
"the undo snapshot of an operation": ["take_snapshot"],
|
||||
}
|
||||
|
||||
|
||||
@@ -6,49 +6,53 @@
|
||||
# Generate candidates with: python3 scripts/check_operation_calls.py --print
|
||||
|
||||
[src/slic3r/GUI/NativeCommands.cpp]
|
||||
# The asking path of a command: with no param, and for load_project with or without one, the command
|
||||
# calls the owner's method, which asks the person what an operation would be told.
|
||||
# The asking path of a command, its menu row's tile (Rows): the row's function calls the owner's method, which asks
|
||||
# the person what an operation would be told (project_open {}, project_save {save_as: true}, project_import {archive:
|
||||
# true}, project_export with a tile's arguments, filament_sync_ams {}).
|
||||
plater->load_project();
|
||||
plater->load_project(from_path(*path));
|
||||
return project_save_result(plater->save_project(true));
|
||||
return NativeCommands::project_save_result(plater->save_project(true));
|
||||
plater->import_zip_archive();
|
||||
plater->export_stl();
|
||||
plater->export_core_3mf();
|
||||
plater->export_gcode_3mf(all);
|
||||
plater->set_number_of_copies();
|
||||
# Another function that uses the same owner method: every object as its own STL, and the Draco exports.
|
||||
plater->export_gcode_3mf(all_plates);
|
||||
plater->export_toolpaths_to_obj();
|
||||
const std::optional<Ops::Refusal> refusal = plater->sidebar().sync_ams_list();
|
||||
# Another function that uses the same owner method: every object as its own STL, and the Draco exports, each asking
|
||||
# for its file or folder.
|
||||
plater->export_stl(false, false, true);
|
||||
plater->export_stl(false, false, true, FT_STL, from_path(*dir));
|
||||
plater->export_stl(false, false, false, FT_DRC);
|
||||
plater->export_stl(false, false, true, FT_DRC);
|
||||
# Another function that uses the same owner method: orient, which leaves a plate-only state behind as arrange does.
|
||||
plater->set_prepare_state(Job::PREPARE_STATE_DEFAULT);
|
||||
|
||||
[src/slic3r/GUI/Mcp/McpToolsConfig.cpp]
|
||||
# The undo step of a tool whose function has one automation entry point (set_settings' object, plate
|
||||
# and project scopes).
|
||||
# The undo step of a tool whose function has one automation entry point (settings_set's object and part
|
||||
# targets, plate_set_settings and project_set_settings).
|
||||
plater.take_snapshot("Move object");
|
||||
plater.take_snapshot("Plate Settings");
|
||||
plater.take_snapshot("Change object settings");
|
||||
# A tool selecting the plate it was given before its own work, as the plate's settings icon does.
|
||||
plater.select_plate(index);
|
||||
# Another function that uses the same owner method: set_settings makes the filament tab edit a slot's
|
||||
# preset, and delete_preset selects the preset, deletes it and selects back.
|
||||
# Another function that uses the same owner method: settings_set makes the filament tab edit a slot's
|
||||
# preset, and preset_delete selects the preset, deletes it and selects back.
|
||||
if (!tab->select_preset(name))
|
||||
if (!tab->select_preset(name))
|
||||
tab->select_preset(selected);
|
||||
|
||||
[src/slic3r/GUI/Mcp/McpToolsLayers.cpp]
|
||||
# The undo step of a tool whose function has one automation entry point (set_height_ranges).
|
||||
# The undo step of a tool whose function has one automation entry point (object_set_height_ranges).
|
||||
plater.take_snapshot("Edit height ranges");
|
||||
|
||||
[src/slic3r/GUI/Mcp/McpToolsProject.cpp]
|
||||
# The asking path of a command, its person's form: new_project and save_project called with no arguments
|
||||
# The asking path of a command, its person's form: project_new and project_save called with no arguments
|
||||
# call the owner's method, which asks the person what an operation would be told.
|
||||
plater->new_project();
|
||||
return NativeCommands::project_save_result(plater->save_project(false));
|
||||
|
||||
[src/slic3r/GUI/Mcp/McpToolsScene.cpp]
|
||||
# The undo step of a tool whose function has one automation entry point (transform).
|
||||
# The asking path of a command, its person's form: object_rename {} and object_set_instances {} call the owner's
|
||||
# method on the target they resolved from the selection, which asks the person what an operation would be told.
|
||||
list->rename_item();
|
||||
plater.set_number_of_copies();
|
||||
# The undo step of a tool whose function has one automation entry point (object_transform).
|
||||
plater.take_snapshot("Transform object");
|
||||
plater.take_snapshot("Transform part", UndoRedo::SnapshotType::GizmoAction);
|
||||
|
||||
|
||||
@@ -679,6 +679,9 @@ public:
|
||||
// based on the user configuration.
|
||||
// If the "vendor" section is missing, enable all models and variants of the particular vendor.
|
||||
void load_installed_printers(const AppConfig &config);
|
||||
// Set the is_visible flag for filaments from the user configuration's filaments section,
|
||||
// first adding there the default filaments of each installed printer that no installed filament fits.
|
||||
void load_installed_filaments(AppConfig &config);
|
||||
|
||||
const std::string& get_preset_name_by_alias(const Preset::Type& preset_type, const std::string& alias) const;
|
||||
|
||||
@@ -937,9 +940,8 @@ private:
|
||||
// Update renamed_from and alias maps of system profiles.
|
||||
void update_system_maps();
|
||||
|
||||
// Set the is_visible flag for filaments and sla materials,
|
||||
// apply defaults based on enabled printers when no filaments/materials are installed.
|
||||
void load_installed_filaments(AppConfig &config);
|
||||
// Set the is_visible flag for sla materials,
|
||||
// apply defaults based on enabled printers when no materials are installed.
|
||||
void load_installed_sla_materials(AppConfig &config);
|
||||
|
||||
// Load print, filament & printer presets from a config. If it is an external config, then the name is extracted from the external path.
|
||||
|
||||
@@ -145,14 +145,23 @@ set(SLIC3R_GUI_SOURCES
|
||||
GUI/ActionRegistry.hpp
|
||||
GUI/ActionReplayDialog.cpp
|
||||
GUI/ActionReplayDialog.hpp
|
||||
GUI/NativeCommandRows.hpp
|
||||
GUI/NativeCommands.cpp
|
||||
GUI/NativeCommands.hpp
|
||||
GUI/Operations/ExportOps.cpp
|
||||
GUI/Operations/ExportOps.hpp
|
||||
GUI/Operations/InstallOps.cpp
|
||||
GUI/Operations/InstallOps.hpp
|
||||
GUI/Operations/ObjectOps.cpp
|
||||
GUI/Operations/ObjectOps.hpp
|
||||
GUI/Operations/Outcome.cpp
|
||||
GUI/Operations/Outcome.hpp
|
||||
GUI/Operations/PlateOps.cpp
|
||||
GUI/Operations/PlateOps.hpp
|
||||
GUI/Operations/PluginOps.cpp
|
||||
GUI/Operations/PluginOps.hpp
|
||||
GUI/Operations/PreferenceOps.cpp
|
||||
GUI/Operations/PreferenceOps.hpp
|
||||
GUI/Operations/PresetOps.cpp
|
||||
GUI/Operations/PresetOps.hpp
|
||||
GUI/Operations/ProjectOps.cpp
|
||||
@@ -176,6 +185,8 @@ set(SLIC3R_GUI_SOURCES
|
||||
GUI/Mcp/McpPersonRun.hpp
|
||||
GUI/Mcp/McpRecorder.cpp
|
||||
GUI/Mcp/McpRecorder.hpp
|
||||
GUI/Mcp/McpTargets.cpp
|
||||
GUI/Mcp/McpTargets.hpp
|
||||
GUI/Mcp/McpTools.hpp
|
||||
GUI/Mcp/McpPluginCaller.cpp
|
||||
GUI/Mcp/McpPluginCaller.hpp
|
||||
@@ -184,7 +195,10 @@ set(SLIC3R_GUI_SOURCES
|
||||
GUI/Mcp/McpToolsApp.cpp
|
||||
GUI/Mcp/McpToolsCommon.cpp
|
||||
GUI/Mcp/McpToolsConfig.cpp
|
||||
GUI/Mcp/McpToolsInstall.cpp
|
||||
GUI/Mcp/McpToolsLayers.cpp
|
||||
GUI/Mcp/McpToolsPlugins.cpp
|
||||
GUI/Mcp/McpToolsPreferences.cpp
|
||||
GUI/Mcp/McpToolsProject.cpp
|
||||
GUI/Mcp/McpToolsPython.cpp
|
||||
GUI/Mcp/McpToolsRecord.cpp
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
// The built-in action source's key and name, and the prefix of a command's tile id. No wx here: this header is part
|
||||
// of the library libslic3r_automation, which is built without wx.
|
||||
namespace Slic3r { namespace GUI {
|
||||
@@ -12,4 +14,17 @@ inline constexpr const char* kOrcaSourceName = "OrcaSlicer";
|
||||
// The prefix of a catalog command's tile id, "orca_command:<key>:orca" (NativeCommands::make_action()).
|
||||
inline constexpr const char* kCommandPrefix = "orca_command";
|
||||
|
||||
// The key inside a command's tile id, "orca_command:<key>:orca"; `id` itself when it has no colon, the name inside the
|
||||
// id, which action_run takes in its place; empty for any other action's id.
|
||||
inline std::string command_tile_key(const std::string& id)
|
||||
{
|
||||
if (id.find(':') == std::string::npos)
|
||||
return id;
|
||||
const std::string prefix = std::string(kCommandPrefix) + ':', suffix = std::string(":") + kOrcaSourceKey;
|
||||
if (id.size() > prefix.size() + suffix.size() && id.compare(0, prefix.size(), prefix) == 0 &&
|
||||
id.compare(id.size() - suffix.size(), suffix.size(), suffix) == 0)
|
||||
return id.substr(prefix.size(), id.size() - prefix.size() - suffix.size());
|
||||
return {};
|
||||
}
|
||||
|
||||
}} // namespace Slic3r::GUI
|
||||
@@ -478,7 +478,7 @@ struct PlateAction : AppAction
|
||||
}
|
||||
|
||||
AppActionRunResult run(const nlohmann::json& /*args*/) const override
|
||||
{ return NativeCommands::run("plate_goto", {{"plate", plate_index}}); }
|
||||
{ return NativeCommands::run("plate_select", {{"plate", plate_index}}); }
|
||||
};
|
||||
|
||||
// A dynamic "Open recent project <name>" action, one per recent project file, rebuilt on every
|
||||
@@ -608,12 +608,12 @@ void ActionRegistry::init()
|
||||
upsert(std::move(action));
|
||||
}
|
||||
|
||||
// Built-in palette commands (Save/Load, Preferences, Mode switch, Slice/Preview, Go to layer): the
|
||||
// catalog's commands with a tile, and no others. Register after plugins so the plugin ids win on any
|
||||
// (unlikely) id collision - ids are distinct by prefix, so this is order-independent. The catalog (and
|
||||
// Built-in palette tiles (Save/Load, Preferences, Mode switch, Slice/Preview, Go to layer): the catalog's
|
||||
// commands' own tiles and the items of their tiles, and no others. Register after plugins so the plugin ids win
|
||||
// on any (unlikely) id collision - ids are distinct by prefix, so this is order-independent. The catalog (and
|
||||
// its thin AppAction adapter) lives in NativeCommands; the registry only stores and dispatches the result.
|
||||
for (const NativeCommand* c : NativeCommands::palette_commands(NativeCommands::instance()))
|
||||
upsert(NativeCommands::make_action(*c));
|
||||
for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(NativeCommands::instance()))
|
||||
upsert(t.tile != nullptr ? NativeCommands::make_action(*t.command, *t.tile) : NativeCommands::make_action(*t.command));
|
||||
}
|
||||
|
||||
void ActionRegistry::relocalize_builtins()
|
||||
@@ -633,8 +633,8 @@ void ActionRegistry::relocalize_builtins()
|
||||
for (const std::string& id : stale)
|
||||
remove(id);
|
||||
|
||||
for (const NativeCommand* c : NativeCommands::palette_commands(NativeCommands::instance()))
|
||||
upsert(NativeCommands::make_action(*c));
|
||||
for (const NativeCommands::PaletteTile& t : NativeCommands::palette_tiles(NativeCommands::instance()))
|
||||
upsert(t.tile != nullptr ? NativeCommands::make_action(*t.command, *t.tile) : NativeCommands::make_action(*t.command));
|
||||
}
|
||||
|
||||
void ActionRegistry::refresh_source(const std::string& plugin_key, ActionChange change)
|
||||
|
||||
@@ -120,11 +120,13 @@ struct AppAction
|
||||
std::string automation_description;
|
||||
nlohmann::json input_schema;
|
||||
bool completes_in_background = false;
|
||||
// The catalog key of a command's tile (NativeCommands), whose own function run_action runs; empty for
|
||||
// The catalog key of a command's tile (NativeCommands), whose own function action_run runs; empty for
|
||||
// every other action.
|
||||
std::string command;
|
||||
// The arguments the tile of a menu row folded into `command` runs it with, an object that may be empty
|
||||
// (NativeCommands::make_action()); null for every other action, which runs with the arguments it is given.
|
||||
// The arguments a tile of `command` runs it with, an object that may be empty: an item of its tiles' args, to which a
|
||||
// tile that collects a value (input) adds that value (tile_call_args(), CommandCatalog.hpp), or {} for the command's
|
||||
// own tile outside the Design tab. Null for every other action, a Design command's own tile among them, which runs
|
||||
// with the arguments it is given.
|
||||
nlohmann::json preset;
|
||||
|
||||
virtual ~AppAction() = default;
|
||||
@@ -240,7 +242,7 @@ public:
|
||||
const AppAction* by_id(const std::string& id) const;
|
||||
// The action `id` as the app is now: by_id() after the families whose membership follows live state
|
||||
// (plates, recent projects, the Design tab's tiles) are re-materialised, for a caller that may have
|
||||
// changed that state since the last snapshot() or describe(), such as an automated run_action after a
|
||||
// changed that state since the last snapshot() or describe(), such as an automated action_run after a
|
||||
// sketch was opened or the tab switched. Settings are not, being thousands: snapshot() and describe()
|
||||
// with include_settings materialise them. UI thread only.
|
||||
const AppAction* find_live(const std::string& id);
|
||||
|
||||
@@ -126,17 +126,17 @@ std::pair<std::string, std::string> replay_what_text(const json& what, const Com
|
||||
const std::string key = what.value("key", "");
|
||||
const auto* command = catalog.find(key);
|
||||
// Titled as its tile is, so a Design command's step reads as the Design tab names its tool; a call that is
|
||||
// a folded row's tile, as that row.
|
||||
// a folded row's tile, as that row, with the value a tile that collects one was given.
|
||||
const std::string args = what.contains("args") ? join(what["args"]) : std::string();
|
||||
if (what.contains("tile")) {
|
||||
const auto [owner, tile] = find_tile(catalog, what.value("tile", ""));
|
||||
if (tile != nullptr && owner == command) {
|
||||
const std::string title = tile->at("title").get<std::string>();
|
||||
const char* context = title_context(*owner);
|
||||
return {into_u8(context != nullptr ? I18N::translate(title, context) : I18N::translate(title)), {}};
|
||||
return {into_u8(context != nullptr ? I18N::translate(title, context) : I18N::translate(title)), args};
|
||||
}
|
||||
}
|
||||
return {command != nullptr ? into_u8(NativeCommands::tile_title(*command)) : key,
|
||||
what.contains("args") ? join(what["args"]) : std::string()};
|
||||
return {command != nullptr ? into_u8(NativeCommands::tile_title(*command)) : key, args};
|
||||
}
|
||||
if (kind == "recent_project" || kind == "preset")
|
||||
return {what.value("name", ""), {}};
|
||||
@@ -855,7 +855,7 @@ json ActionReplayDialog::step_view(const json& entry) const
|
||||
|
||||
const json result = entry.value("result", json());
|
||||
json lines = json::array();
|
||||
if (tool == "run_script" && result.is_object()) {
|
||||
if (tool == "script_run" && result.is_object()) {
|
||||
// What the script printed, then what it returned.
|
||||
std::istringstream output(result.value("output", std::string()));
|
||||
std::string line;
|
||||
@@ -891,7 +891,7 @@ json ActionReplayDialog::step_view(const json& entry) const
|
||||
json files = json::array();
|
||||
for (const std::string& path : Mcp::result_files(result))
|
||||
files.push_back({{"path", path}, {"name", Mcp::path_to_utf8(Mcp::path_from_utf8(path).filename())}});
|
||||
if (tool == "screenshot" && !files.empty())
|
||||
if (tool == "window_screenshot" && !files.empty())
|
||||
if (const std::string url = thumbnail(files[0]["path"].get<std::string>()); !url.empty())
|
||||
view["thumbnail"] = url;
|
||||
view["files"] = std::move(files);
|
||||
|
||||
@@ -33,9 +33,9 @@ struct Replay;
|
||||
struct ReplayContext;
|
||||
} // namespace Mcp
|
||||
|
||||
// A replay step's main line in the Action Replay window and, for a command given arguments, its second line, from
|
||||
// describe_step()'s `what`, in the UI's language. A command, found in `catalog`, is titled as its own tile is, and a
|
||||
// call that is one of its tiles (`what`'s `tile`) as that tile.
|
||||
// A replay step's main line in the Action Replay window and, for a command given arguments or a tile given the value
|
||||
// it collects, its second line, from describe_step()'s `what`, in the UI's language. A command, found in `catalog`, is
|
||||
// titled as its own tile is, and a call that is one of its tiles (`what`'s `tile`) as that tile.
|
||||
std::pair<std::string, std::string> replay_what_text(const nlohmann::json& what, const CommandCatalog& catalog);
|
||||
|
||||
// The Action Replay window: a person opens or writes a replay file (the JSON list of tool calls an
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
#include <wx/event.h>
|
||||
#include <wx/gdicmn.h>
|
||||
|
||||
#include <cstddef>
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
|
||||
namespace {
|
||||
@@ -66,6 +68,21 @@ void AuiMgr::track_docked_size(wxWindow* window)
|
||||
});
|
||||
}
|
||||
|
||||
void AuiMgr::set_docked_width(wxWindow* window, int width)
|
||||
{
|
||||
wxAuiPaneInfo& pane = GetPane(window);
|
||||
if (!pane.IsOk())
|
||||
return;
|
||||
pane.BestSize(width, pane.best_size.GetHeight());
|
||||
// A dock keeps its size from layout to layout; one of size 0 takes its panes' best size at the next.
|
||||
for (std::size_t i = 0; i < m_docks.size(); ++i) {
|
||||
wxAuiDockInfo& dock = m_docks[i];
|
||||
if (dock.dock_direction == pane.dock_direction && dock.dock_layer == pane.dock_layer && dock.dock_row == pane.dock_row)
|
||||
dock.size = 0;
|
||||
}
|
||||
Update();
|
||||
}
|
||||
|
||||
wxAuiPaneInfo AuiMgr::sidebar_pane_info()
|
||||
{
|
||||
return wxAuiPaneInfo()
|
||||
|
||||
@@ -16,6 +16,9 @@ public:
|
||||
// Keeps the docked size of `window`'s pane in its best_size, which re-docking and a saved layout
|
||||
// use: wxAUI does not record a dragged sash there.
|
||||
void track_docked_size(wxWindow* window);
|
||||
// Docks the left or right pane of `window` at `width` pixels, as a drag of its sash leaves it: its best_size, which
|
||||
// its dock takes at once and again when it is docked anew.
|
||||
void set_docked_width(wxWindow* window, int width);
|
||||
|
||||
// A tab's sidebar pane: docked left by default, movable to the right or floating, no close button.
|
||||
static wxAuiPaneInfo sidebar_pane_info();
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// not apply are shown disabled in place with their reason rather than removed. Row order was
|
||||
// ratified 2026-07-31; changing an index is a breaking change to every user's muscle memory.
|
||||
// An entry with an action or a tool block, and no fold_into, is a command of the catalog's group Design
|
||||
// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in search_tools' index. A
|
||||
// (Mcp::register_cad_commands(), Mcp::is_design_command()), under its section in tool_search's index. A
|
||||
// call whose arguments are exactly those that choose one of its rows opens that row's tool for a person
|
||||
// (Mcp::opened_row()): none choose the entry's own row where it has an action, else the rows folded into it
|
||||
// with {}; a folded row's args, or the entry's own, choose that row. Any other call runs its tool block's
|
||||
@@ -126,7 +126,7 @@ struct DesignTool {
|
||||
// The arguments that choose this row, as JSON text: a folded row's, or those that choose the own row of
|
||||
// an entry with an action and a tool block as a call with none does; nullptr for none.
|
||||
const char* args;
|
||||
// The heading its command is listed under in search_tools' index (kDesignSections,
|
||||
// The heading its command is listed under in tool_search's index (kDesignSections,
|
||||
// Mcp::design_command_index()); nullptr for an entry that is no command.
|
||||
const char* section;
|
||||
// Its action acts on the selected row of the Feature list, which a call of its command, not a person's
|
||||
@@ -134,7 +134,7 @@ struct DesignTool {
|
||||
bool feature_row;
|
||||
};
|
||||
|
||||
// The headings of search_tools' index of the Design commands, in its order. Menu rows holds the commands
|
||||
// The headings of tool_search's index of the Design commands, in its order. Menu rows holds the commands
|
||||
// that take no arguments and only do what their row does.
|
||||
static const char* const kDesignSections[] = {
|
||||
"Document",
|
||||
@@ -1338,18 +1338,18 @@ static const DesignTool kDesignTools[] = {
|
||||
{"commit_to_plate", L_CONTEXT("Commit to plate", "Design"), -1, nullptr, nullptr, nullptr, 0x00000000u, 0, 0, false, false, nullptr, nullptr, nullptr, false, CadAccess::Change, false,
|
||||
"{\"summary\":\"Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions an"
|
||||
"d show Prepare.\",\"details\":\"It is one Prepare undo step. A lone body is sent even when hidden. A"
|
||||
" body named in the Bodies list or with body_set names its object or part. Reply: objects (list_o"
|
||||
"bjects index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.\",\"para"
|
||||
"ms\":[{\"name\":\"mode\",\"type\":\"string\",\"default\":\"\",\"enum\":[\"assembly\",\"bodies\"],\"description\":\"ass"
|
||||
"embly: one object with a part per body; bodies: an object per body. Default: the Commit button's"
|
||||
" mode, which this leaves as it is.\"},{\"name\":\"replace\",\"type\":\"array\",\"default\":[],\"description\""
|
||||
":\"list_objects indices to delete in the same undo step, such as an earlier commit. Their setting"
|
||||
"s, modifiers and paint go with them.\"}],\"examples\":[{\"title\":\"A plate sent to Prepare as one obj"
|
||||
"ect\",\"calls\":[{\"tool\":\"extrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"commit_to"
|
||||
"_plate\",\"args\":{}}]},{\"title\":\"Two bodies sent to Prepare as an object each\",\"calls\":[{\"tool\":\"e"
|
||||
"xtrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"extrude\",\"args\":{\"distance\":10,\"o"
|
||||
"peration\":\"new_body\",\"profile\":[[20,-5],[30,-5],[30,5],[20,5]]}},{\"tool\":\"commit_to_plate\",\"args"
|
||||
"\":{\"mode\":\"bodies\"}}]}],\"ids\":false}", nullptr, nullptr, "Document", false},
|
||||
" body named in the Bodies list or with body_set names its object or part. Reply: objects (object"
|
||||
"_list index after replace, name, parts: how many), bodies_sent, bodies_hidden, replaced.\",\"param"
|
||||
"s\":[{\"name\":\"mode\",\"type\":\"string\",\"default\":\"\",\"enum\":[\"assembly\",\"bodies\"],\"description\":\"asse"
|
||||
"mbly: one object with a part per body; bodies: an object per body. Default: the Commit button's "
|
||||
"mode, which this leaves as it is.\"},{\"name\":\"replace\",\"type\":\"array\",\"default\":[],\"description\":"
|
||||
"\"object_list indices to delete in the same undo step, such as an earlier commit. Their settings,"
|
||||
" modifiers and paint go with them.\"}],\"examples\":[{\"title\":\"A plate sent to Prepare as one objec"
|
||||
"t\",\"calls\":[{\"tool\":\"extrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"commit_to_p"
|
||||
"late\",\"args\":{}}]},{\"title\":\"Two bodies sent to Prepare as an object each\",\"calls\":[{\"tool\":\"ext"
|
||||
"rude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"extrude\",\"args\":{\"distance\":10,\"ope"
|
||||
"ration\":\"new_body\",\"profile\":[[20,-5],[30,-5],[30,5],[20,5]]}},{\"tool\":\"commit_to_plate\",\"args\":"
|
||||
"{\"mode\":\"bodies\"}}]}],\"ids\":false}", nullptr, nullptr, "Document", false},
|
||||
{"new_design", L_CONTEXT("New design", "Design"), -1, nullptr, nullptr, nullptr, 0x00000000u, 0, 0, false, false, nullptr, nullptr, nullptr, false, CadAccess::Change, false,
|
||||
"{\"summary\":\"New Design: erase every feature, body and variable and the Design undo history.\",\"de"
|
||||
"tails\":\"Committed objects stay on the plate. Reply: cleared {features, bodies, variables}.\",\"par"
|
||||
|
||||
@@ -5046,7 +5046,7 @@ bool DesignPanel::mcp_select(const DesignSelection& s, std::string& why)
|
||||
if (s.plane < 0 || s.plane > 2) { why = "plane is XY, XZ or YZ"; return false; }
|
||||
// Where update_reference_planes() puts the planes up for a click (no card is open here).
|
||||
if (!m_show_origin && !m_choosing_sketch_plane) {
|
||||
why = "no click can pick a plane now: one does while the Origin row shows the planes (set_view {\"tab\": "
|
||||
why = "no click can pick a plane now: one does while the Origin row shows the planes (view_set {\"tab\": "
|
||||
"\"design\", \"origin\": true}) or while Sketch waits for its plane (sketch_create {})";
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -230,7 +230,7 @@ public:
|
||||
// Design commands may be the first thing to touch the Design tab after a project was opened.
|
||||
void hydrate_from_model();
|
||||
|
||||
// The view switches that are not the canvas's, set by value for set_view; the toolbar's and the rows'
|
||||
// The view switches that are not the canvas's, set by value for view_set; the toolbar's and the rows'
|
||||
// toggles go through these. The section view is one horizontal clip at world height `z` that keeps the
|
||||
// lower half, or the upper one with `keep_upper`; turned on with no z it cuts at the model's middle
|
||||
// height. Turned off, z and keep_upper are left as they were.
|
||||
|
||||
@@ -16,12 +16,11 @@
|
||||
#include <wx/colour.h>
|
||||
#include "slic3r/GUI/Widgets/DialogButtons.hpp"
|
||||
#include "slic3r/GUI/Widgets/Button.hpp"
|
||||
#include "slic3r/GUI/Selection.hpp"
|
||||
#include <wx/utils.h>
|
||||
#include "slic3r/GUI/Jobs/Job.hpp"
|
||||
#include "libslic3r/AppConfig.hpp"
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include "slic3r/GUI/Operations/ObjectOps.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
|
||||
class wxWindow;
|
||||
@@ -98,30 +97,18 @@ CloneDialog::CloneDialog(wxWindow *parent)
|
||||
v_sizer->Fit(this);
|
||||
Refresh();
|
||||
|
||||
Selection& sel = m_plater->canvas3D()->get_selection();
|
||||
m_plater->take_snapshot(std::string("Selection-clone"));
|
||||
m_plater->Freeze(); // Better to stop rendering canvas while processing
|
||||
sel.copy_to_clipboard();
|
||||
for (int i = 0; i < m_count; i++) { // same method with Selection::clone()
|
||||
m_progress->SetValue(static_cast<int>(static_cast<double>(i) / m_count * 100)); // pass 0 / 100
|
||||
sel.paste_from_clipboard();
|
||||
|
||||
if (m_cancel_process) {
|
||||
m_plater->undo();
|
||||
return;
|
||||
}
|
||||
|
||||
// The selection's copies, the progress bar showing each; Cancel, which ends the dialog, undoes them.
|
||||
Ops::CloneObjectsArgs clone;
|
||||
clone.targets.from_selection = true;
|
||||
clone.count = m_count;
|
||||
clone.arrange = m_arrange_cb->GetValue();
|
||||
const auto pasted = [this](int done, int count) {
|
||||
m_progress->SetValue(static_cast<int>(static_cast<double>(done - 1) / count * 100)); // pass 0 / 100
|
||||
wxYield(); // Allow event loop to process updates
|
||||
}
|
||||
|
||||
if (!m_cancel_process) {
|
||||
if (m_arrange_cb->GetValue()) {
|
||||
m_plater->set_prepare_state(Job::PREPARE_STATE_MENU);
|
||||
m_plater->arrange();
|
||||
}
|
||||
m_plater->Thaw();
|
||||
return !m_cancel_process;
|
||||
};
|
||||
if (Ops::clone_objects(clone, pasted))
|
||||
EndModal(wxID_OK);
|
||||
}
|
||||
});
|
||||
|
||||
dlg_btns->GetCANCEL()->Bind(wxEVT_BUTTON, [this](wxCommandEvent &) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include "CommandCatalog.hpp"
|
||||
|
||||
#include "ActionIds.hpp"
|
||||
#include "CommandTypes.hpp"
|
||||
#include "Mcp/McpArguments.hpp"
|
||||
|
||||
@@ -130,12 +131,33 @@ const nlohmann::json* tile_with_args(const NativeCommand& command, const nlohman
|
||||
return nullptr;
|
||||
// A call with no arguments gives none, null as {}, as Mcp::opened_row() reads it.
|
||||
const nlohmann::json given = Mcp::person_form(args) ? nlohmann::json::object() : args;
|
||||
// A tile that collects a value is called with that value besides its own arguments, never with these alone.
|
||||
for (const nlohmann::json& tile : command.tiles)
|
||||
if (tile.at("args") == given)
|
||||
if (tile.value("input", std::string()).empty() && tile.at("args") == given)
|
||||
return &tile;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
nlohmann::json tile_call_args(const nlohmann::json* tile, const nlohmann::json& args)
|
||||
{
|
||||
if (tile == nullptr)
|
||||
return args;
|
||||
nlohmann::json out = tile->at("args");
|
||||
const std::string input = tile->value("input", std::string());
|
||||
// Without the value the tile's args alone are given: action_run refuses such a call first (action_args_error()),
|
||||
// and the Speed Dial's second phase always collects the value.
|
||||
if (input.empty() || !args.is_object() || !args.contains(input))
|
||||
return out;
|
||||
nlohmann::json value = args.at(input);
|
||||
// The Speed Dial's tab picker sends the id of a page, and view_set's tab takes the word of a page that has one.
|
||||
if (input == "tab")
|
||||
for (const TabWord& w : kTabWords)
|
||||
if (value == w.page)
|
||||
value = w.word;
|
||||
out[tile->value("input_arg", input)] = std::move(value);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string call_title(const NativeCommand& command, const nlohmann::json& args)
|
||||
{
|
||||
const nlohmann::json* tile = tile_with_args(command, args);
|
||||
@@ -154,6 +176,17 @@ std::pair<const NativeCommand*, const nlohmann::json*> find_tile(const CommandCa
|
||||
return {nullptr, nullptr};
|
||||
}
|
||||
|
||||
std::pair<std::string, const NativeCommand*> shown_title(const CommandCatalog& catalog, const NativeCommand& command,
|
||||
const nlohmann::json& args)
|
||||
{
|
||||
if (command.key == "action_run" && args.is_object() && args.value("id", nlohmann::json()).is_string()) {
|
||||
const auto [owner, tile] = find_tile(catalog, command_tile_key(args.at("id").get<std::string>()));
|
||||
if (owner != nullptr)
|
||||
return {tile != nullptr ? tile->at("title").get<std::string>() : owner->title, owner};
|
||||
}
|
||||
return {call_title(command, args), &command};
|
||||
}
|
||||
|
||||
nlohmann::json command_reference(const NativeCommand& command)
|
||||
{
|
||||
nlohmann::json entry{{"key", command.key},
|
||||
@@ -170,6 +203,11 @@ nlohmann::json command_reference(const NativeCommand& command)
|
||||
{"guard", guard_name(command.guard)},
|
||||
{"completion", completion_name(command.completion)},
|
||||
{"operations", command.operations}};
|
||||
for (const auto& [name, value] : {std::pair<const char*, const std::string*>{"icon", &command.icon},
|
||||
{"input", &command.input},
|
||||
{"tile_group", &command.tile_group}})
|
||||
if (!value->empty())
|
||||
entry[name] = *value;
|
||||
if (!command.examples.is_null())
|
||||
entry["examples"] = command.examples;
|
||||
if (!command.tiles.is_null())
|
||||
|
||||
@@ -37,10 +37,15 @@ struct NativeCommand
|
||||
{
|
||||
std::string key;
|
||||
std::string title; // untranslated English msgid; make_action() translates it for display
|
||||
// A tile's section, an untranslated msgid as the title is. A typed tool without a tile is in the group of the way it
|
||||
// acts, which search_tools filters by: core runs the session, recovers from dialogs and runs Python, api acts on
|
||||
// project data by index and name with JSON in and out, and ui drives the GUI itself.
|
||||
// What tool_search filters by. Outside the Design tab, the English heading of the command's place
|
||||
// (NativeCommands::place_heading()): Objects, Plates, The app, the place its name starts with but for the two
|
||||
// screenshot commands, which are under Recordings, replays and scripts; a plugin's operation is in Plugins. A
|
||||
// Design command's is kDesignGroup, an untranslated msgid, which is also the Speed Dial section of its own tile and
|
||||
// of its tiles.
|
||||
std::string group;
|
||||
// The Speed Dial section of the command's own tile (in_palette), an untranslated msgid; empty where that tile is in
|
||||
// `group`, as a Design command's is.
|
||||
std::string tile_group;
|
||||
// "percent"/"tab": the palette's second phase, which collects the value the command needs before it
|
||||
// runs; "" to run at once.
|
||||
std::string input;
|
||||
@@ -53,33 +58,40 @@ struct NativeCommand
|
||||
nlohmann::json input_schema = {{"type", "object"}, {"properties", nlohmann::json::object()}};
|
||||
// Calls that document the command: [{title, calls: [{tool, args}], needs?}], or null.
|
||||
nlohmann::json examples;
|
||||
// The tiles of the menu rows folded into a Design command, [{key, title, icon, description, args}], or null:
|
||||
// each, under the id of its key, runs the command with `args` (NativeCommands::make_action()). Its title is an
|
||||
// untranslated msgid in title_context(), as the command's is.
|
||||
// The tiles of the menu rows folded into the command, [{key, title, group?, icon, description, args, input?,
|
||||
// input_arg?}] (NativeCommands::tile()), or null: each, under the id of its key, runs the command with `args`
|
||||
// (NativeCommands::make_action()). Its title is an untranslated msgid in title_context(), as the command's is.
|
||||
// group is its Speed Dial section, an untranslated msgid; a Design tile has none and is in the command's group.
|
||||
// input is the Speed Dial's token for the value its second phase collects ("percent", "tab"), which the tile
|
||||
// passes on under input_arg, the command's argument, or under the token where it has no input_arg.
|
||||
nlohmann::json tiles;
|
||||
bool listed = false; // shown in tools/list: a typed tool
|
||||
// shown in tools/list: every command outside the Design tab that runs from its arguments, all but three menu rows
|
||||
bool listed = false;
|
||||
bool in_palette = false; // a person can pick it: it has a tile of its own, under its key
|
||||
// The access labels sent as MCP's annotations. Clients act on them: Codex asks a person before every call
|
||||
// of a destructive command, and Claude Code runs read-only calls in parallel and retries idempotent ones.
|
||||
// read_only: it changes nothing in the app or the project; screenshot is, since its PNG replaces no file
|
||||
// without overwrite, and export_replay, which can clear the journal, is not. destructive: every call deletes
|
||||
// what a person made, with no undo: delete_preset. A command that can lose work only when an argument asks
|
||||
// for it is not: new_project, generate_calibration_test and open_files drop unsaved changes only with
|
||||
// discard_changes, and an output replaces a file only with overwrite. Nor is a command that runs what its
|
||||
// arguments name (click and the other input tools, run_action, call_tool, run_replay, run_script), though
|
||||
// read_only: it changes nothing in the app or the project; window_screenshot is, since its PNG replaces no file
|
||||
// without overwrite, and replay_export, which can clear the journal, is not. destructive: every call deletes
|
||||
// what a person made, with no undo: preset_delete and plugin_uninstall. A command that can lose work only when an
|
||||
// argument asks for it is not: project_new, calibration_generate_test and project_open drop unsaved changes only
|
||||
// with discard_changes, and an output replaces a file only with overwrite. Nor is a command that runs what its
|
||||
// arguments name (widget_click and the other input tools, action_run, tool_call, replay_run, script_run), though
|
||||
// what it runs may be. The client sees both in the arguments, and the label would ask on every call. Nor is
|
||||
// encode_recording, which deletes only a recording this session made, once its MP4 has replaced it.
|
||||
// open_world: it can reach outside OrcaSlicer (a
|
||||
// printer, the cloud account, the network, or anything the computer allows), including through what it runs.
|
||||
// recording_encode, which deletes only a recording this session made, once its MP4 has replaced it, nor a command
|
||||
// whose deletion has undo (object_delete, plate_delete). A command made from menu rows is neither read_only nor
|
||||
// destructive. open_world: it can reach outside OrcaSlicer (a printer, the cloud account, the network, or anything
|
||||
// the computer allows), including through what it runs: of the commands made from rows, printer_send, preset_sync,
|
||||
// filament_sync_ams, app_check_for_updates, app_open_web_page and plugin_refresh; and plugin_enable and plugin_reload,
|
||||
// which run a plugin's code and download a cloud plugin, and plugin_uninstall, whose Unsubscribe reaches the account.
|
||||
bool read_only = false, destructive = false, idempotent = false, open_world = false;
|
||||
GuardClass guard = GuardClass::Mutate;
|
||||
// inline_call: pure observation, which runs on the request thread and is never a job; everything that can
|
||||
// activate UI runs as a job instead, because activating UI can open a modal that blocks the call. journal:
|
||||
// recorded by the session journal for export_replay; observation commands turn it off, except wait and
|
||||
// screenshot, which a replay needs.
|
||||
// recorded by the session journal for replay_export; observation commands turn it off, except app_wait and
|
||||
// window_screenshot, which a replay needs.
|
||||
bool inline_call = false, journal = true;
|
||||
// allowed_during_operation: may run while an MCP slice/export operation holds the project (cancel_job).
|
||||
// cancellable: `cancel_job {job}` stops a running call that is not an operation (encode_recording); the
|
||||
// allowed_during_operation: may run while an MCP slice/export operation holds the project (job_cancel).
|
||||
// cancellable: `job_cancel {job}` stops a running call that is not an operation (recording_encode); the
|
||||
// function sees ToolContext::cancelled() and ends.
|
||||
bool allowed_during_operation = false, cancellable = false;
|
||||
// How long a call may run before the reply returns a job envelope and the call continues.
|
||||
@@ -100,17 +112,39 @@ inline const char* title_context(const NativeCommand& command)
|
||||
return command.group == kDesignGroup ? "Design" : nullptr;
|
||||
}
|
||||
|
||||
// The first of `command`'s tiles whose args are `args`, compared as JSON values, a null `args` as {}; nullptr when
|
||||
// none is.
|
||||
// A word view_set's tab takes for one of the main window's own pages, and the id of that page (MainFrame's TAB_ID_*).
|
||||
struct TabWord
|
||||
{
|
||||
const char* word;
|
||||
const char* page;
|
||||
};
|
||||
// The words of the main window's own pages. A word is its page's id, but for the Device tab's: device, whose page is
|
||||
// monitor. The window's other pages (the web Device page, a plugin's) have no word and are named by their ids.
|
||||
inline constexpr TabWord kTabWords[] = {{"home", "home"}, {"design", "design"},
|
||||
{"prepare", "prepare"}, {"preview", "preview"},
|
||||
{"device", "monitor"}, {"multi_device", "multi_device"},
|
||||
{"project", "project"}, {"calibration", "calibration"}};
|
||||
|
||||
// The first of `command`'s tiles that collect no value (no input) whose args are `args`, compared as JSON values, a
|
||||
// null `args` as {}; nullptr when none is.
|
||||
const nlohmann::json* tile_with_args(const NativeCommand& command, const nlohmann::json& args);
|
||||
|
||||
// The arguments a pick of `tile`, an item of a command's tiles, runs its command with, given `args` (what
|
||||
// action_run or the Speed Dial's second phase gives): the tile's args, and for a tile with an input the value `args`
|
||||
// holds under that token, put under its input_arg, or under the token where it has none; a tab's page id that a word
|
||||
// of kTabWords names is given as that word (the Device tab's monitor as device). For a command's own tile
|
||||
// (`tile` null), `args` as they are, the call's own arguments. A person's pick, action_run and the description of a
|
||||
// replay's step all run a tile with it.
|
||||
nlohmann::json tile_call_args(const nlohmann::json* tile, const nlohmann::json& args);
|
||||
|
||||
// What a call of `command` with `args` is titled where a person is shown it (a recording's caption): the title of
|
||||
// tile_with_args(), else the command's. Untranslated, in title_context(command).
|
||||
std::string call_title(const NativeCommand& command, const nlohmann::json& args);
|
||||
|
||||
// What the reference says of a command: key, title, group, description, input_schema, examples and tiles when it
|
||||
// has some, listed, in_palette, the four access labels, guard ("inspect", "recover", "mutate"), completion
|
||||
// ("none", "export") and operations. All of it is the command's English text and constants, never translated.
|
||||
// What the reference says of a command: key, title, group, description, input_schema, listed, in_palette, the four
|
||||
// access labels, guard ("inspect", "recover", "mutate"), completion ("immediate", "deferred") and operations; icon,
|
||||
// input and tile_group when they are not empty, and examples and tiles when it has some. All of it is the command's
|
||||
// English text and constants, never translated.
|
||||
nlohmann::json command_reference(const NativeCommand& command);
|
||||
|
||||
// Commands that come and go while the app runs (plugin operations). Any thread.
|
||||
@@ -171,6 +205,13 @@ private:
|
||||
// command added with add() has one.
|
||||
std::pair<const NativeCommand*, const nlohmann::json*> find_tile(const CommandCatalog& catalog, const std::string& key);
|
||||
|
||||
// What a call of `command` with `args` is titled where a person is shown it (a recording's caption), and the command
|
||||
// whose title_context() that title is translated in: for action_run of a command's tile in `catalog` (args.id, the
|
||||
// tile's id or the key inside it), the tile's title and that command, the command's own title for its own tile; for any
|
||||
// other call, call_title() and `command`. Untranslated.
|
||||
std::pair<std::string, const NativeCommand*> shown_title(const CommandCatalog& catalog, const NativeCommand& command,
|
||||
const nlohmann::json& args);
|
||||
|
||||
// The reference of `catalog`: {"commands": [command_reference(), ...]} of the commands added with add(), in
|
||||
// the order they were added. Its sources' commands are left out: they are a plugin's, not the build's.
|
||||
// tests/data/command_catalog.json is this reference of the catalog a run with the Design tab holds, and the
|
||||
|
||||
@@ -102,7 +102,7 @@ public:
|
||||
// Calls another tool as a child of this call (replay steps and a script's calls). Returns what a client would get:
|
||||
// the result, or a job envelope when the child outlives its reply budget.
|
||||
virtual ToolResult call_child(const std::string& tool, const nlohmann::json& args) = 0;
|
||||
// This call's job and its ancestors, which `wait {for:"idle"}` must not wait for.
|
||||
// This call's job and its ancestors, which `app_wait {for:"idle"}` must not wait for.
|
||||
virtual std::set<std::string> lineage() const = 0;
|
||||
// Replaces the arguments the session journal records for this call (refs become locators).
|
||||
virtual void set_journal_args(nlohmann::json args) = 0;
|
||||
|
||||
@@ -6,7 +6,10 @@
|
||||
#include <algorithm>
|
||||
#include <wx/colour.h>
|
||||
#include "libslic3r/Config.hpp"
|
||||
#include "libslic3r/PresetBundle.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
@@ -44,75 +47,84 @@ static const wxColour TextErrorColor = wxColour("#E14747");
|
||||
|
||||
wxDEFINE_EVENT(wxEVT_INVALID_MANUAL_MAP, wxCommandEvent);
|
||||
|
||||
// The edited printer's extruder_max_nozzle_count, none where it lacks the option.
|
||||
static std::vector<int> max_nozzle_counts(const PresetBundle &preset_bundle)
|
||||
{
|
||||
const auto *opt = preset_bundle.printers.get_edited_preset().config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count");
|
||||
return opt != nullptr ? opt->values : std::vector<int>();
|
||||
}
|
||||
|
||||
// Orca: whether the edited printer has an extruder that can physically carry several nozzles
|
||||
// (only such extruders track a per-volume-type nozzle inventory worth validating against).
|
||||
static bool printer_has_multi_nozzle_extruder()
|
||||
{
|
||||
auto *max_nozzle_counts_opt = wxGetApp().preset_bundle->printers.get_edited_preset().config.option<ConfigOptionIntsNullable>("extruder_max_nozzle_count");
|
||||
return has_multi_nozzle_extruder(max_nozzle_counts(*wxGetApp().preset_bundle));
|
||||
}
|
||||
|
||||
bool has_multi_nozzle_extruder(const std::vector<int> &max_nozzle_counts)
|
||||
{
|
||||
// Skip nil entries: a nullable-int nil is INT_MAX (> 1) and would otherwise falsely pass the gate.
|
||||
return max_nozzle_counts_opt &&
|
||||
std::any_of(max_nozzle_counts_opt->values.begin(), max_nozzle_counts_opt->values.end(),
|
||||
return std::any_of(max_nozzle_counts.begin(), max_nozzle_counts.end(),
|
||||
[](int v) { return v > 1 && v != ConfigOptionIntsNullable::nil_value(); });
|
||||
}
|
||||
|
||||
NozzleInventory nozzle_inventory(const PresetBundle &preset_bundle)
|
||||
{
|
||||
NozzleInventory inventory;
|
||||
inventory.max_nozzle_counts = max_nozzle_counts(preset_bundle);
|
||||
if (const auto *types = preset_bundle.project_config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type"))
|
||||
inventory.volume_types = types->values;
|
||||
if (const auto *stats = preset_bundle.printers.get_edited_preset().config.option<ConfigOptionStrings>("extruder_nozzle_stats"))
|
||||
inventory.nozzle_counts = get_extruder_nozzle_stats(stats->values);
|
||||
return inventory;
|
||||
}
|
||||
|
||||
std::optional<NozzleShortage> manual_map_nozzle_shortage(const NozzleInventory &inventory,
|
||||
const std::vector<int> &filaments,
|
||||
const std::vector<int> &filament_map,
|
||||
const std::vector<int> &filament_volume_map)
|
||||
{
|
||||
// Orca: only multi-nozzle extruders carry a meaningful nozzle inventory; validating a plain
|
||||
// dual-extruder printer against it would flag every grouping whenever the stats are stale.
|
||||
if (!has_multi_nozzle_extruder(inventory.max_nozzle_counts))
|
||||
return std::nullopt;
|
||||
const auto nozzle_count = [&inventory](int eid, NozzleVolumeType volume_type) {
|
||||
if (eid >= (int) inventory.nozzle_counts.size())
|
||||
return 0;
|
||||
const auto it = inventory.nozzle_counts[eid].find(volume_type);
|
||||
return it == inventory.nozzle_counts[eid].end() ? 0 : it->second;
|
||||
};
|
||||
// Whether a filament the plate prints goes to extruder `eid`; with `volume_type`, with that nozzle volume type.
|
||||
const auto prints_on = [&](int eid, std::optional<NozzleVolumeType> volume_type) {
|
||||
return std::any_of(filaments.begin(), filaments.end(), [&](int fid) {
|
||||
return fid >= 1 && fid - 1 < (int) filament_map.size() && (filament_map[fid - 1] - 1) == eid &&
|
||||
(!volume_type || (fid - 1 < (int) filament_volume_map.size() &&
|
||||
filament_volume_map[fid - 1] == static_cast<int>(*volume_type)));
|
||||
});
|
||||
};
|
||||
for (int eid = 0; eid < (int) inventory.volume_types.size(); ++eid) {
|
||||
if (!prints_on(eid, std::nullopt))
|
||||
continue;
|
||||
const NozzleVolumeType extruder_volume_type = NozzleVolumeType(inventory.volume_types[eid]);
|
||||
if (extruder_volume_type != nvtHybrid) {
|
||||
if (nozzle_count(eid, extruder_volume_type) == 0)
|
||||
return NozzleShortage{eid, extruder_volume_type};
|
||||
continue;
|
||||
}
|
||||
for (const NozzleVolumeType needed : {NozzleVolumeType::nvtStandard, NozzleVolumeType::nvtHighFlow})
|
||||
if (prints_on(eid, needed) && nozzle_count(eid, needed) == 0)
|
||||
return NozzleShortage{eid, needed};
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void FilamentMapManualPanel::OnTimer(wxTimerEvent &)
|
||||
{
|
||||
bool valid = true;
|
||||
int invalid_eid = -1;
|
||||
NozzleVolumeType invalid_nozzle = NozzleVolumeType::nvtStandard;
|
||||
auto preset_bundle = wxGetApp().preset_bundle;
|
||||
auto proj_config = preset_bundle->project_config;
|
||||
auto nozzle_volume_values = proj_config.option<ConfigOptionEnumsGeneric>("nozzle_volume_type")->values;
|
||||
std::vector<int> filament_map = GetFilamentMaps();
|
||||
std::vector<int> filament_volume_map = GetFilamentVolumeMaps();
|
||||
// Orca: only multi-nozzle extruders carry a meaningful nozzle inventory; validating a plain
|
||||
// dual-extruder printer against it would flag every grouping whenever the stats are stale.
|
||||
if (printer_has_multi_nozzle_extruder()) {
|
||||
for (size_t eid = 0; eid < nozzle_volume_values.size(); ++eid) {
|
||||
NozzleVolumeType extruder_volume_type = NozzleVolumeType(nozzle_volume_values[eid]);
|
||||
bool extruder_used = std::find_if(m_filament_list.begin(), m_filament_list.end(),
|
||||
[&filament_map, eid](int fid) {
|
||||
return fid - 1 < (int) filament_map.size() && (filament_map[fid - 1] - 1) == (int) eid;
|
||||
}) != m_filament_list.end();
|
||||
|
||||
if (!extruder_used) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (extruder_volume_type == nvtHybrid) {
|
||||
int standard_count = getExtruderNozzleCount(preset_bundle, eid, NozzleVolumeType::nvtStandard);
|
||||
int highflow_count = getExtruderNozzleCount(preset_bundle, eid, NozzleVolumeType::nvtHighFlow);
|
||||
|
||||
auto has_material_of_type = [this, eid, &filament_map, &filament_volume_map](NozzleVolumeType volume_type) {
|
||||
return std::find_if(m_filament_list.begin(), m_filament_list.end(),
|
||||
[eid, &filament_map, &filament_volume_map, volume_type](int fid) {
|
||||
return fid - 1 < (int) filament_map.size() && (filament_map[fid - 1] - 1) == (int) eid &&
|
||||
fid - 1 < (int) filament_volume_map.size() &&
|
||||
filament_volume_map[fid - 1] == static_cast<int>(volume_type);
|
||||
}) != m_filament_list.end();
|
||||
};
|
||||
|
||||
bool has_standard = has_material_of_type(NozzleVolumeType::nvtStandard);
|
||||
bool has_highflow = has_material_of_type(NozzleVolumeType::nvtHighFlow);
|
||||
|
||||
if ((has_standard && standard_count == 0) ||
|
||||
(has_highflow && highflow_count == 0)) {
|
||||
valid = false;
|
||||
invalid_eid = eid;
|
||||
invalid_nozzle = (has_standard && standard_count == 0) ? NozzleVolumeType::nvtStandard : NozzleVolumeType::nvtHighFlow;
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
int count = getExtruderNozzleCount(preset_bundle, eid, extruder_volume_type);
|
||||
if (count == 0) {
|
||||
valid = false;
|
||||
invalid_eid = eid;
|
||||
invalid_nozzle = extruder_volume_type;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const std::optional<NozzleShortage> shortage = manual_map_nozzle_shortage(nozzle_inventory(*wxGetApp().preset_bundle), m_filament_list,
|
||||
GetFilamentMaps(), GetFilamentVolumeMaps());
|
||||
const bool valid = !shortage;
|
||||
const int invalid_eid = shortage ? shortage->extruder : -1;
|
||||
const NozzleVolumeType invalid_nozzle = shortage ? shortage->volume_type : NozzleVolumeType::nvtStandard;
|
||||
|
||||
bool update_ui = m_invalid_id != invalid_eid;
|
||||
bool send_event = update_ui || m_force_validation;
|
||||
|
||||
@@ -8,13 +8,53 @@
|
||||
#include "Widgets/Label.hpp"
|
||||
#include <wx/event.h>
|
||||
#include <wx/panel.h>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <wx/timer.h>
|
||||
#include <wx/string.h>
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
|
||||
namespace Slic3r { namespace GUI {
|
||||
namespace Slic3r {
|
||||
class PresetBundle;
|
||||
|
||||
namespace GUI {
|
||||
|
||||
// The nozzles a printer's extruders carry, per extruder: the most nozzles it can hold (the printer's
|
||||
// extruder_max_nozzle_count), its nozzle volume type (the project's nozzle_volume_type) and how many nozzles of each
|
||||
// volume type it has (the printer's extruder_nozzle_stats, none of a type it lacks).
|
||||
struct NozzleInventory
|
||||
{
|
||||
std::vector<int> max_nozzle_counts;
|
||||
std::vector<int> volume_types;
|
||||
std::vector<std::map<NozzleVolumeType, int>> nozzle_counts;
|
||||
};
|
||||
|
||||
// The inventory of the printer being edited and the project.
|
||||
NozzleInventory nozzle_inventory(const PresetBundle& preset_bundle);
|
||||
|
||||
// Whether one of the extruders can hold several nozzles. Only such an extruder keeps an inventory worth checking: a
|
||||
// plain multi-extruder printer has none, and checking it would refuse every grouping whenever its counts are stale.
|
||||
bool has_multi_nozzle_extruder(const std::vector<int>& max_nozzle_counts);
|
||||
|
||||
// An extruder (0-based) that a manual filament grouping gives filaments and that has no nozzle of the volume type
|
||||
// they need.
|
||||
struct NozzleShortage
|
||||
{
|
||||
int extruder = -1;
|
||||
NozzleVolumeType volume_type = nvtStandard;
|
||||
};
|
||||
|
||||
// The check the filament grouping dialog's Custom page makes before its OK can be pressed: the first extruder that
|
||||
// `filament_map` (the 1-based extruder of each filament) gives one of `filaments` (the 1-based filaments the plate
|
||||
// prints) and that has no nozzle of the volume type it needs. That type is the extruder's own, or on a Hybrid extruder
|
||||
// each of the types `filament_volume_map` gives its filaments (Standard checked before High Flow). None on a printer
|
||||
// with no multi-nozzle extruder.
|
||||
std::optional<NozzleShortage> manual_map_nozzle_shortage(const NozzleInventory& inventory,
|
||||
const std::vector<int>& filaments,
|
||||
const std::vector<int>& filament_map,
|
||||
const std::vector<int>& filament_volume_map);
|
||||
|
||||
// Fired by the manual panel's validation timer: the event int is 1 when the current manual
|
||||
// grouping is printable with the installed nozzles, 0 when some zone has no matching nozzle.
|
||||
@@ -126,6 +166,7 @@ public:
|
||||
private:
|
||||
Label *m_label;
|
||||
};
|
||||
}} // namespace Slic3r::GUI
|
||||
} // namespace GUI
|
||||
} // namespace Slic3r
|
||||
|
||||
#endif
|
||||
@@ -189,6 +189,12 @@ ArchiveViewCtrl::~ArchiveViewCtrl()
|
||||
}
|
||||
}
|
||||
|
||||
bool is_archive_model(const boost::filesystem::path& path)
|
||||
{
|
||||
static const std::regex pattern_drop(".*[.](stl|obj|amf|3mf|step|stp)", std::regex::icase);
|
||||
return !boost::algorithm::starts_with(path.string(), "__MACOSX") && std::regex_match(path.extension().string(), pattern_drop);
|
||||
}
|
||||
|
||||
FileArchiveDialog::FileArchiveDialog(wxWindow* parent_window, mz_zip_archive* archive, std::vector<std::pair<boost::filesystem::path, size_t>>& selected_paths_w_size)
|
||||
: DPIDialog(parent_window, wxID_ANY, _(L("Archive preview")), wxDefaultPosition,
|
||||
wxSize(45 * wxGetApp().em_unit(), 40 * wxGetApp().em_unit()),
|
||||
@@ -235,7 +241,6 @@ FileArchiveDialog::FileArchiveDialog(wxWindow* parent_window, mz_zip_archive* ar
|
||||
return struct_size + 1;
|
||||
};
|
||||
|
||||
const std::regex pattern_drop(".*[.](stl|obj|amf|3mf|step|stp)", std::regex::icase);
|
||||
mz_uint num_entries = mz_zip_reader_get_num_files(archive);
|
||||
mz_zip_archive_file_stat stat;
|
||||
std::vector<std::pair<boost::filesystem::path, size_t>> filtered_entries; // second is unzipped size
|
||||
@@ -263,7 +268,7 @@ FileArchiveDialog::FileArchiveDialog(wxWindow* parent_window, mz_zip_archive* ar
|
||||
depth = std::max(depth, adjust_stack(path, stack));
|
||||
if (!stack.empty())
|
||||
parent = stack.back();
|
||||
if (std::regex_match(path.extension().string(), pattern_drop)) { // this leaves out non-compatible files
|
||||
if (is_archive_model(path)) { // this leaves out non-compatible files
|
||||
std::shared_ptr<ArchiveViewNode> new_node = m_avc->get_model()->AddFile(parent, boost::nowide::widen(path.filename().string()), false);
|
||||
new_node->set_fullpath(/*std::move(path)*/path); // filename string to wstring?
|
||||
new_node->set_size(entry.second);
|
||||
|
||||
@@ -111,6 +111,10 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
// Whether `path`, an entry of a ZIP archive, is a model file the archive's file list offers: a file named .stl, .obj,
|
||||
// .amf, .3mf, .step or .stp, outside the __MACOSX folder macOS adds to an archive.
|
||||
bool is_archive_model(const boost::filesystem::path& path);
|
||||
|
||||
class FileArchiveDialog : public DPIDialog
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -141,46 +141,53 @@ static void add_swatch(ImDrawList* draw_list, const ImVec2& min, const ImVec2& m
|
||||
draw_list->AddRectFilled(min, max, ImGuiWrapper::to_ImU32(color));
|
||||
}
|
||||
|
||||
static std::string get_view_type_string(libvgcode::EViewType view_type)
|
||||
// The English name of a view type, marked for translation; empty for a type the preview does not offer.
|
||||
static const char* view_type_msgid(libvgcode::EViewType view_type)
|
||||
{
|
||||
if (view_type == libvgcode::EViewType::Summary)
|
||||
return _u8L("Summary");
|
||||
return L("Summary");
|
||||
else if (view_type == libvgcode::EViewType::FeatureType)
|
||||
return _u8L("Line Type");
|
||||
return L("Line Type");
|
||||
else if (view_type == libvgcode::EViewType::Height)
|
||||
return _u8L("Layer Height");
|
||||
return L("Layer Height");
|
||||
else if (view_type == libvgcode::EViewType::Width)
|
||||
return _u8L("Line Width");
|
||||
return L("Line Width");
|
||||
else if (view_type == libvgcode::EViewType::Speed)
|
||||
return _u8L("Speed");
|
||||
return L("Speed");
|
||||
else if (view_type == libvgcode::EViewType::ActualSpeed)
|
||||
return _u8L("Actual Speed");
|
||||
return L("Actual Speed");
|
||||
else if (view_type == libvgcode::EViewType::Acceleration)
|
||||
return _u8L("Acceleration");
|
||||
return L("Acceleration");
|
||||
else if (view_type == libvgcode::EViewType::Jerk)
|
||||
return _u8L("Jerk");
|
||||
return L("Jerk");
|
||||
else if (view_type == libvgcode::EViewType::FanSpeed)
|
||||
return _u8L("Fan Speed");
|
||||
return L("Fan Speed");
|
||||
else if (view_type == libvgcode::EViewType::Temperature)
|
||||
return _u8L("Temperature");
|
||||
return L("Temperature");
|
||||
else if (view_type == libvgcode::EViewType::VolumetricFlowRate)
|
||||
return _u8L("Flow");
|
||||
return L("Flow");
|
||||
else if (view_type == libvgcode::EViewType::ActualVolumetricFlowRate)
|
||||
return _u8L("Actual Flow");
|
||||
return L("Actual Flow");
|
||||
else if (view_type == libvgcode::EViewType::Tool)
|
||||
return _u8L("Tool");
|
||||
return L("Tool");
|
||||
else if (view_type == libvgcode::EViewType::ColorPrint)
|
||||
return _u8L("Filament");
|
||||
return L("Filament");
|
||||
else if (view_type == libvgcode::EViewType::LayerTimeLinear)
|
||||
return _u8L("Layer Time");
|
||||
return L("Layer Time");
|
||||
else if (view_type == libvgcode::EViewType::LayerTimeLogarithmic)
|
||||
return _u8L("Layer Time (log)");
|
||||
return L("Layer Time (log)");
|
||||
// ORCA: Add Pressure Advance visualization support
|
||||
else if (view_type == libvgcode::EViewType::PressureAdvance)
|
||||
return _u8L("Pressure Advance");
|
||||
return L("Pressure Advance");
|
||||
return "";
|
||||
}
|
||||
|
||||
static std::string get_view_type_string(libvgcode::EViewType view_type)
|
||||
{
|
||||
const char* msgid = view_type_msgid(view_type);
|
||||
return *msgid == '\0' ? std::string() : _u8L(msgid);
|
||||
}
|
||||
|
||||
// ORCA: Stable, locale independent names used to persist a view type in the application config.
|
||||
// Keep these in sync with the entries of libvgcode::EViewType exposed in the preview combo box.
|
||||
static const std::vector<std::pair<std::string, libvgcode::EViewType>>& view_type_config_map()
|
||||
@@ -1268,11 +1275,11 @@ bool GCodeViewer::view_type_from_config_name(const std::string& name, libvgcode:
|
||||
std::vector<std::pair<std::string, std::string>> GCodeViewer::default_view_type_choices()
|
||||
{
|
||||
std::vector<std::pair<std::string, std::string>> choices = {
|
||||
{ "auto", _u8L("Automatic") },
|
||||
{ "last", _u8L("Last used") },
|
||||
{ "auto", L("Automatic") },
|
||||
{ "last", L("Last used") },
|
||||
};
|
||||
for (const auto& [name, type] : view_type_config_map())
|
||||
choices.push_back({ name, get_view_type_string(type) });
|
||||
choices.push_back({ name, view_type_msgid(type) });
|
||||
return choices;
|
||||
}
|
||||
|
||||
|
||||
@@ -553,13 +553,16 @@ public:
|
||||
bool can_switch_time_mode() const;
|
||||
// What the legend's "Show stealth mode" / "Show normal mode" button does.
|
||||
void set_time_mode(libvgcode::ETimeMode mode);
|
||||
// The legend folded to its title row, as its fold button leaves it; picking a view type unfolds it.
|
||||
bool is_legend_folded() const { return m_fold; }
|
||||
void fold_legend(bool fold) { m_fold = fold; }
|
||||
// ORCA: apply the "preview_default_view_type" preference, see the definition for the supported values
|
||||
void apply_default_view_type();
|
||||
|
||||
// ORCA: stable, locale independent name of a view type, as stored in the application config
|
||||
static std::string view_type_to_config_name(libvgcode::EViewType type);
|
||||
static bool view_type_from_config_name(const std::string& name, libvgcode::EViewType& type);
|
||||
// ORCA: (config value, translated label) pairs for the "preview_default_view_type" preference combo box
|
||||
// ORCA: (config value, English label marked for translation) pairs for the "preview_default_view_type" preference
|
||||
static std::vector<std::pair<std::string, std::string>> default_view_type_choices();
|
||||
void reset_visible(libvgcode::EViewType type) {
|
||||
if (type == libvgcode::EViewType::FeatureType) {
|
||||
|
||||
@@ -1200,6 +1200,7 @@ public:
|
||||
void share_section_view(const GLCanvas3D& owner) { m_section_view = owner.m_section_view; }
|
||||
|
||||
void toggle_world_axes_visibility(bool force_show = false);
|
||||
bool are_world_axes_shown() const { return m_show_world_axes; }
|
||||
void refresh_camera_scene_box();
|
||||
void set_color_by(const std::string& value);
|
||||
|
||||
|
||||
+13
-22
@@ -73,6 +73,8 @@
|
||||
#include <miniz.h>
|
||||
#include "slic3r/GUI/Monitor.hpp"
|
||||
#include "slic3r/GUI/OpenGLManager.hpp"
|
||||
#include "slic3r/GUI/Operations/PluginOps.hpp"
|
||||
#include "slic3r/GUI/Operations/PreferenceOps.hpp"
|
||||
#include "slic3r/GUI/DeviceCore/DevDefs.h"
|
||||
#include <optional>
|
||||
#include "slic3r/GUI/UserNotification.hpp"
|
||||
@@ -3360,7 +3362,7 @@ bool GUI_App::on_init_inner()
|
||||
// Slic3r::debugf "wxWidgets version %s, Wx version %s\n", wxVERSION_STRING, wxVERSION;
|
||||
// The command catalog, before anything that runs or lists a command: the automation runtime below and the
|
||||
// Speed Dial's action registry. Then the Python scripts setting's value in force, before the endpoint opens and
|
||||
// the command line's run starts, so that get_app_state and the first script read it. Each value in force is the
|
||||
// the command line's run starts, so that app_state and the first script read it. Each value in force is the
|
||||
// preference, or the command line's flag (--cad, --unrestricted-scripts). The CAD feature's is read here from the
|
||||
// config and the launch parameters, since is_enable_cad_feature() is in a CAD build only.
|
||||
const bool cad_in_force = app_config->get_bool("enable_cad_feature") || (init_params != nullptr && init_params->cad);
|
||||
@@ -9202,20 +9204,14 @@ void GUI_App::notify_plugin_permissions_changed(const std::string& plugin_key)
|
||||
m_plugins_dlg->refresh_permissions_if_visible();
|
||||
}
|
||||
|
||||
void GUI_App::refresh_plugins()
|
||||
Ops::RefreshTicket GUI_App::refresh_plugins()
|
||||
{
|
||||
// The metadata refresh blocks on disc discovery and a cloud round-trip, so run it on a worker
|
||||
// and report completion through the notification manager -- the speed dial needs no dialog.
|
||||
std::thread([]() {
|
||||
wxString error;
|
||||
bool unknown_error = false;
|
||||
try {
|
||||
refresh_plugin_metadata_blocking(/*fetch_cloud=*/true);
|
||||
} catch (const std::exception& ex) {
|
||||
error = from_u8(ex.what());
|
||||
} catch (...) {
|
||||
unknown_error = true; // translated in CallAfter: wx translation isn't safe off the UI thread
|
||||
}
|
||||
// The metadata refresh blocks on disc discovery and a cloud round-trip, so it runs off the UI thread, after
|
||||
// the refreshes asked for before it, and the notification manager reports its end -- the speed dial needs no
|
||||
// dialog.
|
||||
return Ops::start_plugin_refresh([](const std::string& what, bool unknown_error) {
|
||||
// An unknown failure's text is translated in CallAfter: wx translation isn't safe off the UI thread.
|
||||
const wxString error = from_u8(what);
|
||||
if (!wxTheApp)
|
||||
return;
|
||||
wxTheApp->CallAfter([error, unknown_error]() {
|
||||
@@ -9236,7 +9232,7 @@ void GUI_App::refresh_plugins()
|
||||
NotificationManager::NotificationLevel::ErrorNotificationLevel,
|
||||
into_u8(wxString::Format(_L("Failed to refresh plugins: %s"), unknown_error ? _L("Unknown error") : error)));
|
||||
});
|
||||
}).detach();
|
||||
});
|
||||
}
|
||||
|
||||
void GUI_App::update_plugins_dialog()
|
||||
@@ -9311,14 +9307,9 @@ void GUI_App::open_preferences() { open_preferences(PreferencesTab::General); }
|
||||
void GUI_App::open_preferences(PreferencesTab tab, const std::string& highlight_option)
|
||||
{
|
||||
// Render settings the canvas reads every frame; a change needs one redraw to show.
|
||||
static constexpr const char* opengl_render_setting_keys[] = {
|
||||
SETTING_OPENGL_FXAA_ENABLED, SETTING_OPENGL_FPS_CAP, SETTING_OPENGL_SHOW_FPS_OVERLAY, SETTING_OPENGL_SHOW_RENDER_TIMINGS,
|
||||
SETTING_OPENGL_SCENE_CACHE, SETTING_OPENGL_SKIP_IDENTICAL_FRAMES, SETTING_OPENGL_REALISTIC_SHADOWS,
|
||||
SETTING_OPENGL_REALISTIC_GLOSS, SETTING_OPENGL_OUTLINE_PERSISTENT, SETTING_OPENGL_OUTLINE_COLOR,
|
||||
SETTING_OPENGL_SELECTION_OUTLINE_COLOR
|
||||
};
|
||||
const std::vector<std::string>& opengl_render_setting_keys = Ops::canvas_preferences();
|
||||
std::vector<std::string> previous_opengl_render_settings;
|
||||
for (const char* key : opengl_render_setting_keys)
|
||||
for (const std::string& key : opengl_render_setting_keys)
|
||||
previous_opengl_render_settings.emplace_back(app_config->get(key));
|
||||
|
||||
bool need_recreate_gui = false;
|
||||
|
||||
@@ -107,6 +107,9 @@ class Downloader;
|
||||
struct GUI_InitParams;
|
||||
class ParamsDialog;
|
||||
class HMSQuery;
|
||||
namespace Ops {
|
||||
class RefreshTicket;
|
||||
}
|
||||
class ModelMallDialog;
|
||||
class PingCodeBindDialog;
|
||||
class PresetBundleDialog;
|
||||
@@ -775,8 +778,10 @@ public:
|
||||
// Called on the GUI thread after an audit prompt stores a grant outside the Plugins dialog.
|
||||
// Refreshes an existing dialog instance; never creates or raises it.
|
||||
void notify_plugin_permissions_changed(const std::string& plugin_key);
|
||||
// Dialog-free plugin action used by the speed dial: it never requires the Plugins dialog to be open.
|
||||
void refresh_plugins();
|
||||
// Refresh Plugins, which needs no Plugins dialog: starts a run of Ops::start_plugin_refresh(), whose end a
|
||||
// notification reports, and returns its ticket. A refresh asked for while one waits or runs is a run of its own
|
||||
// after it, with a notification of its own. GUI thread.
|
||||
Ops::RefreshTicket refresh_plugins();
|
||||
// Shows the current plugin list in the Plugins dialog when it is open, after a change made outside it
|
||||
// (the speed dial's refresh or install, a plugin loading). GUI thread; never creates or raises it.
|
||||
void update_plugins_dialog();
|
||||
|
||||
@@ -210,7 +210,11 @@ std::vector<std::string> SettingsFactory::get_options(const bool is_part)
|
||||
options.erase(find(options.begin(), options.end(), "layer_height"));
|
||||
return options;
|
||||
}
|
||||
return get_fff_options(is_part);
|
||||
}
|
||||
|
||||
std::vector<std::string> SettingsFactory::get_fff_options(const bool is_part)
|
||||
{
|
||||
PrintRegionConfig reg_config;
|
||||
auto options = reg_config.keys();
|
||||
if (!is_part) {
|
||||
|
||||
@@ -43,6 +43,9 @@ struct SettingsFactory
|
||||
static wxBitmap get_category_bitmap(const std::string& category_name, bool menu_bmp = true);
|
||||
static Bundle get_bundle(const DynamicPrintConfig* config, bool is_object_settings, bool is_layer_settings = false);
|
||||
static std::vector<std::string> get_options(bool is_part);
|
||||
// get_options() for an FFF printer, which reads no printer: the region settings for a part or modifier, and the
|
||||
// object settings too for an object.
|
||||
static std::vector<std::string> get_fff_options(bool is_part);
|
||||
// Options of this category are not offered to objects (is_object_settings) or to parts and
|
||||
// modifiers: internal options without a category, and per-feature filaments with one filament.
|
||||
static bool is_improper_category(const std::string& category, int filaments_cnt, bool is_object_settings = true);
|
||||
|
||||
+206
-145
@@ -96,7 +96,8 @@
|
||||
#include <wx/headerctrl.h>
|
||||
#include <wx/window.h>
|
||||
|
||||
#include "slic3r/Utils/FixModelByCgal.hpp"
|
||||
#include "Operations/ObjectOps.hpp"
|
||||
#include "Operations/Outcome.hpp"
|
||||
#include "libslic3r/Format/bbs_3mf.hpp"
|
||||
#include "libslic3r/Orient.hpp"
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
@@ -965,7 +966,7 @@ void ObjectList::update_name_for_items()
|
||||
wxGetApp().plater()->update();
|
||||
}
|
||||
|
||||
void ObjectList::object_config_options_changed(const ObjectVolumeID& ov_id)
|
||||
void ObjectList::object_config_options_changed(const ObjectVolumeID& ov_id, const t_layer_height_range* range)
|
||||
{
|
||||
if (ov_id.object == nullptr)
|
||||
return;
|
||||
@@ -974,6 +975,15 @@ void ObjectList::object_config_options_changed(const ObjectVolumeID& ov_id)
|
||||
ModelObject* mo = ov_id.object;
|
||||
ModelVolume* mv = ov_id.volume;
|
||||
|
||||
if (range != nullptr) {
|
||||
// A height range's row, as a change in the range's panel marks it (TabPrintLayer::notify_changed()).
|
||||
const auto config = mo->layer_config_ranges.find(*range);
|
||||
const auto obj = std::find(objects.begin(), objects.end(), mo);
|
||||
if (config != mo->layer_config_ranges.end() && obj != objects.end())
|
||||
add_settings_item(m_objects_model->GetItemByLayerRange(int(obj - objects.begin()), *range), &config->second.get());
|
||||
return;
|
||||
}
|
||||
|
||||
wxDataViewItem obj_item = m_objects_model->GetObjectItem(mo);
|
||||
if (mv != nullptr) {
|
||||
size_t vol_idx;
|
||||
@@ -2078,33 +2088,7 @@ void ObjectList::OnDrop(wxDataViewEvent &event)
|
||||
take_snapshot(_u8L("Object order changed"));
|
||||
|
||||
if(m_dragged_data.type() & itObject){
|
||||
int delta = dest_obj_id < src_obj_id ? -1 : 1;
|
||||
PartPlateList& partplate_list = wxGetApp().plater()->get_partplate_list();
|
||||
/*int cnt = 0, cur_id = src_obj_id, next_id, total = abs(src_obj_id - dest_obj_id);
|
||||
//for (cur_id = src_obj_id; cnt < total; id += delta, cnt++)
|
||||
next_id = src_obj_id + delta;
|
||||
while (cnt < total)
|
||||
{
|
||||
int cur_plate = partplate_list.find_instance(next_id, 0);
|
||||
if (cur_plate != src_plate) {
|
||||
cnt ++;
|
||||
next_id += delta;
|
||||
continue;
|
||||
}
|
||||
std::swap((*m_objects)[cur_id], (*m_objects)[next_id]);
|
||||
cur_id = next_id;
|
||||
cnt ++;
|
||||
next_id += delta;
|
||||
}*/
|
||||
|
||||
int cnt = 0;
|
||||
for (int id = src_obj_id; cnt < abs(src_obj_id - dest_obj_id); id += delta, cnt++)
|
||||
std::swap((*m_objects)[id], (*m_objects)[id + delta]);
|
||||
|
||||
select_item(m_objects_model->ReorganizeObjects(src_obj_id, dest_obj_id));
|
||||
|
||||
partplate_list.reload_all_objects(false, src_plate);
|
||||
changed_object(src_obj_id);
|
||||
move_object(src_obj_id, dest_obj_id, src_plate);
|
||||
}
|
||||
else if (m_dragged_data.type() & itVolume) {
|
||||
int from_volume_id = m_dragged_data.sub_obj_idx();
|
||||
@@ -2690,7 +2674,9 @@ void ObjectList::load_generic_subobject(const std::string& type_name, const Mode
|
||||
Plater::SingleSnapshot single(wxGetApp().plater());
|
||||
|
||||
if (type == ModelVolumeType::INVALID) {
|
||||
load_shape_object(type_name, interactive, given_size);
|
||||
// Add Primitive adds nothing while an object is selected on the 3D scene.
|
||||
if (can_add_shape_object())
|
||||
load_shape_object(type_name, interactive, given_size);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2801,10 +2787,6 @@ bool ObjectList::can_add_shape_object() const
|
||||
|
||||
void ObjectList::load_shape_object(const std::string &type_name, bool interactive, const std::vector<double>& given_size)
|
||||
{
|
||||
// Add nothing while an object is selected on the 3D scene.
|
||||
if (!can_add_shape_object())
|
||||
return;
|
||||
|
||||
const int obj_idx = m_objects->size();
|
||||
if (obj_idx < 0)
|
||||
return;
|
||||
@@ -3169,6 +3151,18 @@ void ObjectList::split()
|
||||
if (!item || obj_idx < 0)
|
||||
return;
|
||||
|
||||
ModelVolume* volume = nullptr;
|
||||
if (!(*m_objects)[obj_idx]->hides_imported_parts() && !get_volume_by_item(item, volume))
|
||||
return;
|
||||
// The object's row stands for its one part.
|
||||
const ModelVolumePtrs& volumes = (*m_objects)[obj_idx]->volumes;
|
||||
const ItemType type = m_objects_model->GetItemType(item);
|
||||
split(obj_idx, volume == nullptr || type != itVolume ? -1 : int(std::find(volumes.begin(), volumes.end(), volume) - volumes.begin()),
|
||||
type == itObject);
|
||||
}
|
||||
|
||||
void ObjectList::split(int obj_idx, int volume_idx, bool expand)
|
||||
{
|
||||
ModelObject* imported = (*m_objects)[obj_idx];
|
||||
if (imported->hides_imported_parts()) {
|
||||
// Reveal the original CAD bodies, including their names and exact transforms.
|
||||
@@ -3179,8 +3173,9 @@ void ObjectList::split()
|
||||
return;
|
||||
}
|
||||
|
||||
ModelVolume* volume;
|
||||
if (!get_volume_by_item(item, volume)) return;
|
||||
if (volume_idx < 0 && imported->volumes.size() != 1)
|
||||
return;
|
||||
ModelVolume* volume = imported->volumes[volume_idx < 0 ? 0 : std::size_t(volume_idx)];
|
||||
DynamicPrintConfig& config = printer_config();
|
||||
// BBS
|
||||
const ConfigOptionStrings* filament_colors = config.option<ConfigOptionStrings>("filament_colour", false);
|
||||
@@ -3198,11 +3193,8 @@ void ObjectList::split()
|
||||
|
||||
auto model_object = (*m_objects)[obj_idx];
|
||||
|
||||
auto parent = m_objects_model->GetObject(item);
|
||||
if (parent)
|
||||
m_objects_model->DeleteVolumeChildren(parent);
|
||||
else
|
||||
parent = item;
|
||||
wxDataViewItem parent = m_objects_model->GetItemById(obj_idx);
|
||||
m_objects_model->DeleteVolumeChildren(parent);
|
||||
|
||||
for (const ModelVolume* volume : model_object->volumes) {
|
||||
const wxDataViewItem& vol_item = m_objects_model->AddVolumeChild(parent, from_u8(volume->name),
|
||||
@@ -3218,7 +3210,7 @@ void ObjectList::split()
|
||||
|
||||
model_object->input_file.clear();
|
||||
|
||||
if (parent == item)
|
||||
if (expand)
|
||||
Expand(parent);
|
||||
|
||||
changed_object(obj_idx);
|
||||
@@ -3229,11 +3221,19 @@ void ObjectList::split()
|
||||
update_info_items(obj_idx);
|
||||
}
|
||||
|
||||
void ObjectList::merge(bool to_multipart_object)
|
||||
void ObjectList::merge(bool to_multipart_object, const wxDataViewItemArray& items)
|
||||
{
|
||||
wxBusyCursor wait;
|
||||
// merge selected objects to the multipart object
|
||||
if (to_multipart_object) {
|
||||
// The rows given are selected first: the instances are split off into objects of their own, and the merged
|
||||
// objects removed, as the selected rows.
|
||||
if (!items.IsEmpty()) {
|
||||
m_prevent_list_events = true;
|
||||
UnselectAll();
|
||||
SetSelections(items);
|
||||
m_prevent_list_events = false;
|
||||
}
|
||||
auto get_object_idxs = [this](std::vector<int>& obj_idxs, wxDataViewItemArray& sels)
|
||||
{
|
||||
// check selections and split instances to the separated objects...
|
||||
@@ -6173,14 +6173,15 @@ static void move_volume_to_end(ModelObject* obj, ModelVolume* volume)
|
||||
}
|
||||
}
|
||||
|
||||
wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype, bool show_errors)
|
||||
wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype, bool show_errors,
|
||||
const std::vector<std::pair<int, int>>& parts)
|
||||
{
|
||||
struct VolumeSelection {
|
||||
int object_idx;
|
||||
ModelVolume* volume;
|
||||
};
|
||||
|
||||
// --- Collect selected volumes from the object tree, falling back to the 3D canvas ---
|
||||
// --- Collect the parts given, else the selected volumes from the object tree, falling back to the 3D canvas ---
|
||||
std::vector<VolumeSelection> volumes;
|
||||
auto add_volume = [&volumes](int obj_idx, ModelVolume* volume) {
|
||||
// A painted modifier has no shape of its own to keep as another type.
|
||||
@@ -6191,8 +6192,12 @@ wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_
|
||||
volumes.push_back({ obj_idx, volume });
|
||||
};
|
||||
|
||||
for (const auto& [obj_idx, vol_idx] : parts)
|
||||
add_volume(obj_idx, (*m_objects)[obj_idx]->volumes[vol_idx]);
|
||||
|
||||
wxDataViewItemArray sels;
|
||||
GetSelections(sels);
|
||||
if (parts.empty())
|
||||
GetSelections(sels);
|
||||
for (auto item : sels) {
|
||||
wxDataViewItem volume_item = item;
|
||||
ItemType type = m_objects_model->GetItemType(item);
|
||||
@@ -6228,6 +6233,9 @@ wxString ObjectList::set_volume_type(ModelVolumeType new_type, bool preserve_ps_
|
||||
}
|
||||
};
|
||||
|
||||
// Parts given are what changes, painted modifiers aside, and the selection is not read.
|
||||
if (volumes.empty() && !parts.empty())
|
||||
return {};
|
||||
if (volumes.empty()) {
|
||||
collect_from_canvas(wxGetApp().plater()->canvas3D());
|
||||
if (volumes.empty()) {
|
||||
@@ -6646,13 +6654,6 @@ void ObjectList::fix_through_cgal(const std::vector<int> &obj_idxs, const std::v
|
||||
if (obj_idxs.empty() || !wxGetApp().plater()->get_view3D_canvas3D()->get_gizmos_manager().check_gizmos_closed_except(GLGizmosManager::Undefined))
|
||||
return;
|
||||
|
||||
// model_name
|
||||
std::vector<std::string> succes_models;
|
||||
// model_name failing reason
|
||||
std::vector<std::pair<std::string, std::string>> failed_models;
|
||||
size_t unchanged_models = 0;
|
||||
bool painting_removed = false;
|
||||
|
||||
std::vector<std::string> model_names;
|
||||
|
||||
if (vol_idxs.empty()) {
|
||||
@@ -6669,77 +6670,62 @@ void ObjectList::fix_through_cgal(const std::vector<int> &obj_idxs, const std::v
|
||||
}
|
||||
|
||||
auto plater = wxGetApp().plater();
|
||||
const bool keep_painting = GUI::wxGetApp().app_config->get_bool("keep_painting");
|
||||
|
||||
auto fix_and_update_progress = [&](const int obj_idx, const int vol_idx, int model_idx, ProgressDialog& progress_dlg)
|
||||
{
|
||||
ModelObject *mo = object(obj_idx);
|
||||
if (!mo)
|
||||
return false;
|
||||
// The objects whole, or the parts of the first object, as Ops::fix_objects() repairs them in turn.
|
||||
Ops::FixObjectsArgs repair;
|
||||
if (vol_idxs.empty())
|
||||
repair.targets.objects = obj_idxs;
|
||||
else
|
||||
for (int vol_idx : vol_idxs)
|
||||
repair.targets.parts.emplace_back(obj_idxs.front(), vol_idx);
|
||||
|
||||
// Open a progress dialog.
|
||||
ProgressDialog progress_dlg(_L("Repairing model object"), "", 100, find_toplevel_parent(plater),
|
||||
wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT, true);
|
||||
const auto shown = [&](std::size_t model_idx, int percent, const std::string& what) {
|
||||
const std::string& model_name = model_names[model_idx];
|
||||
wxString msg = _L("Repairing model object");
|
||||
if (model_names.size() == 1)
|
||||
msg += ": " + from_u8(model_name) + "\n";
|
||||
else if (model_names.size() > 10)
|
||||
msg += ": " + from_u8(model_name) + wxString::Format(" (%d/%d)", model_idx + 1, int(model_names.size())) + "\n";
|
||||
msg += ": " + from_u8(model_name) + wxString::Format(" (%d/%d)", int(model_idx) + 1, int(model_names.size())) + "\n";
|
||||
else {
|
||||
msg += ":\n";
|
||||
for (int i = 0; i < int(model_names.size()); ++i)
|
||||
for (std::size_t i = 0; i < model_names.size(); ++i)
|
||||
msg += (i == model_idx ? " > " : " ") + from_u8(model_names[i]) + "\n";
|
||||
msg += "\n";
|
||||
}
|
||||
|
||||
auto count_painted = [mo]() { return std::count_if(mo->volumes.begin(), mo->volumes.end(), [](const ModelVolume *mv) { return mv->is_any_painted(); }); };
|
||||
const auto painted_before = count_painted();
|
||||
std::string res;
|
||||
bool modified = false;
|
||||
if (!fix_model_with_cgal_gui(*mo, vol_idx, progress_dlg, msg, res, keep_painting, &modified))
|
||||
// One percent short of the maximum, so that the dialog does not close itself.
|
||||
if (!progress_dlg.Update(std::max(0, percent - 1), msg + from_u8(what)))
|
||||
return false;
|
||||
|
||||
if (modified) {
|
||||
painting_removed = painting_removed || count_painted() < painted_before;
|
||||
mo->ensure_on_bed();
|
||||
plater->changed_mesh(obj_idx);
|
||||
plater->get_partplate_list().notify_instance_update(obj_idx, 0);
|
||||
plater->sidebar().obj_list()->update_plate_values_for_items();
|
||||
update_item_error_icon(obj_idx, vol_idx);
|
||||
update_info_items(obj_idx);
|
||||
}
|
||||
|
||||
if (!res.empty())
|
||||
failed_models.push_back({ model_name, res });
|
||||
else if (modified)
|
||||
succes_models.push_back(model_name);
|
||||
else
|
||||
++unchanged_models;
|
||||
progress_dlg.Fit();
|
||||
return true;
|
||||
};
|
||||
|
||||
Plater::TakeSnapshot snapshot(plater, _u8L("Repairing model object"));
|
||||
|
||||
// Open a progress dialog.
|
||||
ProgressDialog progress_dlg(_L("Repairing model object"), "", 100, find_toplevel_parent(plater),
|
||||
wxPD_AUTO_HIDE | wxPD_APP_MODAL | wxPD_CAN_ABORT, true);
|
||||
int model_idx{ 0 };
|
||||
if (vol_idxs.empty()) {
|
||||
int vol_idx{ -1 };
|
||||
for (int obj_idx : obj_idxs) {
|
||||
if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg))
|
||||
break;
|
||||
model_idx++;
|
||||
}
|
||||
}
|
||||
else {
|
||||
int obj_idx{ obj_idxs.front() };
|
||||
for (int vol_idx : vol_idxs) {
|
||||
if (!fix_and_update_progress(obj_idx, vol_idx, model_idx, progress_dlg))
|
||||
break;
|
||||
model_idx++;
|
||||
}
|
||||
}
|
||||
// The gizmo check above is the operation's only refusal here.
|
||||
const Ops::Outcome<Ops::FixedModels> fixed = Ops::fix_objects(repair, shown);
|
||||
// Close the progress dialog
|
||||
progress_dlg.Update(100, "");
|
||||
if (!fixed)
|
||||
return;
|
||||
|
||||
// model_name
|
||||
std::vector<std::string> succes_models;
|
||||
// model_name failing reason
|
||||
std::vector<std::pair<std::string, std::string>> failed_models;
|
||||
size_t unchanged_models = 0;
|
||||
bool painting_removed = false;
|
||||
for (const Ops::FixedModel& model : fixed.value().models) {
|
||||
// The notification tells the models whose repair ended; the one a Cancel stopped is left out of it.
|
||||
if (model.cancelled)
|
||||
continue;
|
||||
painting_removed = painting_removed || model.painting_removed;
|
||||
if (!model.failed.empty())
|
||||
failed_models.push_back({ model.name, model.failed });
|
||||
else if (model.changed)
|
||||
succes_models.push_back(model.name);
|
||||
else
|
||||
++unchanged_models;
|
||||
}
|
||||
|
||||
if (painting_removed)
|
||||
plater->notify_painting_removed();
|
||||
@@ -7325,47 +7311,124 @@ void set_import_volume_order(ModelObject& object, bool sort_names)
|
||||
parts[i]->import_display_order = static_cast<int>(i);
|
||||
}
|
||||
|
||||
void ObjectList::order_objects(ObjectOrder order, bool all_plates)
|
||||
std::vector<ModelObject*> plate_order(const std::vector<ModelObject*>& objects, const std::function<int(size_t)>& plate_of, int plate,
|
||||
ObjectOrder order, bool descending)
|
||||
{
|
||||
std::map<int, std::vector<size_t>> slots; // each plate's list positions, in order
|
||||
for (size_t obj_idx = 0; obj_idx < objects.size(); ++obj_idx)
|
||||
if (const int on = plate_of(obj_idx); on >= 0 && (plate < 0 || on == plate))
|
||||
slots[on].push_back(obj_idx);
|
||||
std::vector<ModelObject*> out = objects;
|
||||
for (const auto& [on, positions] : slots) {
|
||||
std::vector<ModelObject*> plate_objects;
|
||||
for (size_t obj_idx : positions)
|
||||
plate_objects.push_back(objects[obj_idx]);
|
||||
sort_objects(plate_objects, order, descending);
|
||||
for (size_t i = 0; i < positions.size(); ++i)
|
||||
out[positions[i]] = plate_objects[i];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void move_object_in_list(std::vector<ModelObject*>& objects, int from, int to)
|
||||
{
|
||||
const int delta = to < from ? -1 : 1;
|
||||
for (int id = from; id != to; id += delta)
|
||||
std::swap(objects[id], objects[id + delta]);
|
||||
}
|
||||
|
||||
Ops::Outcome<std::vector<ObjectMove>> object_order_moves(const std::vector<int>& plate_of, int plate, const std::vector<int>& order)
|
||||
{
|
||||
const int count = int(plate_of.size());
|
||||
std::set<int> named;
|
||||
for (const int object : order) {
|
||||
if (count == 0)
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "no_such_object", L("The project has no objects.")};
|
||||
if (object < 0 || object >= count)
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "no_such_object",
|
||||
// TRN %1% is the object index asked for, %2% the last object's.
|
||||
L("Object %1% does not exist: the project has objects 0 to %2%."),
|
||||
{std::to_string(object), std::to_string(count - 1)}};
|
||||
if (plate_of[std::size_t(object)] != plate)
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "object_not_on_plate",
|
||||
// TRN %1% is an object's index, %2% a plate's.
|
||||
L("Object %1% is not on plate %2%."), {std::to_string(object), std::to_string(plate)}};
|
||||
if (!named.insert(object).second)
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "order_repeats_object",
|
||||
// TRN %1% is an object's index.
|
||||
L("The order names object %1% twice."), {std::to_string(object)}};
|
||||
}
|
||||
std::vector<std::string> missing;
|
||||
for (int object = 0; object < count; ++object)
|
||||
if (plate_of[std::size_t(object)] == plate && named.count(object) == 0)
|
||||
missing.push_back(std::to_string(object));
|
||||
if (!missing.empty()) {
|
||||
std::string list;
|
||||
for (const std::string& object : missing)
|
||||
list += (list.empty() ? "" : ", ") + object;
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "order_misses_object",
|
||||
// TRN %1% is a plate's index, %2% the indices of the objects left out, separated by commas.
|
||||
L("The order leaves out objects of plate %1%: %2%. Name each of its objects once."),
|
||||
{std::to_string(plate), list}, missing};
|
||||
}
|
||||
|
||||
// Each object in turn is dropped on the object that holds its place, as the list's positions stand after the drops
|
||||
// before it.
|
||||
std::vector<int> listed(plate_of.size());
|
||||
std::vector<ObjectMove> moves;
|
||||
for (int position = 0; position < count; ++position)
|
||||
listed[std::size_t(position)] = position;
|
||||
for (std::size_t k = 0; k < order.size(); ++k) {
|
||||
int seen = -1, to = -1, from = -1;
|
||||
for (int position = 0; position < count; ++position) {
|
||||
const int object = listed[std::size_t(position)];
|
||||
if (plate_of[std::size_t(object)] == plate && ++seen == int(k))
|
||||
to = position;
|
||||
if (object == order[k])
|
||||
from = position;
|
||||
}
|
||||
if (from == to)
|
||||
continue;
|
||||
moves.push_back({from, to});
|
||||
const int delta = to < from ? -1 : 1;
|
||||
for (int id = from; id != to; id += delta)
|
||||
std::swap(listed[std::size_t(id)], listed[std::size_t(id + delta)]);
|
||||
}
|
||||
return moves;
|
||||
}
|
||||
|
||||
void ObjectList::order_objects(ObjectOrder order, bool all_plates, int plate, std::optional<bool> descending)
|
||||
{
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (!plater->get_view3D_canvas3D()->get_gizmos_manager().check_gizmos_closed_except(GLGizmosManager::Undefined))
|
||||
return;
|
||||
|
||||
PartPlateList& plates = plater->get_partplate_list();
|
||||
const int curr_plate = plates.get_curr_plate_index();
|
||||
auto sorted = [&](bool descending) {
|
||||
std::vector<ModelObject*> objects = *m_objects;
|
||||
for (int plate_idx = 0; plate_idx < plates.get_plate_count(); ++plate_idx) {
|
||||
if (!all_plates && plate_idx != curr_plate)
|
||||
continue;
|
||||
// Sort within the list positions the plate already holds, so other plates keep their order.
|
||||
std::vector<size_t> slots;
|
||||
std::vector<ModelObject*> plate_objects;
|
||||
for (size_t obj_idx = 0; obj_idx < objects.size(); ++obj_idx)
|
||||
if (plates.find_instance(int(obj_idx), 0) == plate_idx) {
|
||||
slots.push_back(obj_idx);
|
||||
plate_objects.push_back(objects[obj_idx]);
|
||||
}
|
||||
sort_objects(plate_objects, order, descending);
|
||||
for (size_t i = 0; i < slots.size(); ++i)
|
||||
objects[slots[i]] = plate_objects[i];
|
||||
}
|
||||
return objects;
|
||||
};
|
||||
// Choosing the order the objects already have reverses it.
|
||||
std::vector<ModelObject*> objects = sorted(false);
|
||||
if (objects == *m_objects)
|
||||
const int sort_plate = plate >= 0 ? plate : plates.get_curr_plate_index();
|
||||
const auto plate_of = [&plates](size_t obj_idx) { return plates.find_instance(int(obj_idx), 0); };
|
||||
const auto sorted = [&](bool descending) { return plate_order(*m_objects, plate_of, all_plates ? -1 : sort_plate, order, descending); };
|
||||
std::vector<ModelObject*> objects = sorted(descending.value_or(false));
|
||||
// Choosing the order the objects already have reverses it, unless the direction is given.
|
||||
if (!descending && objects == *m_objects)
|
||||
objects = sorted(true);
|
||||
|
||||
if (objects != *m_objects) {
|
||||
take_snapshot(_u8L("Object order changed"));
|
||||
*m_objects = std::move(objects);
|
||||
plates.reload_all_objects(false, all_plates ? -1 : curr_plate);
|
||||
plates.reload_all_objects(false, all_plates ? -1 : sort_plate);
|
||||
}
|
||||
// Rebuilt even when the order holds: an object moved to another plate is listed last there.
|
||||
reload_all_plates();
|
||||
}
|
||||
|
||||
void ObjectList::move_object(int from, int to, int plate)
|
||||
{
|
||||
move_object_in_list(*m_objects, from, to);
|
||||
select_item(m_objects_model->ReorganizeObjects(from, to));
|
||||
wxGetApp().plater()->get_partplate_list().reload_all_objects(false, plate);
|
||||
changed_object(from);
|
||||
}
|
||||
|
||||
void ObjectList::on_plate_selected(int plate_index)
|
||||
{
|
||||
wxDataViewItem item = m_objects_model->GetItemByPlateId(plate_index);
|
||||
@@ -7454,6 +7517,8 @@ void ObjectList::toggle_printable_state()
|
||||
// BBS: remove snapshot name "Set Printable group", "Set Unprintable group", "Set Printable"...
|
||||
take_snapshot("");
|
||||
|
||||
// An object row sets every instance of its object, an instance row its instance alone.
|
||||
Ops::Targets rows;
|
||||
std::vector<size_t> obj_idxs;
|
||||
for (auto item : sels)
|
||||
{
|
||||
@@ -7462,22 +7527,18 @@ void ObjectList::toggle_printable_state()
|
||||
continue;
|
||||
|
||||
obj_idx = m_objects_model->GetObjectIdByItem(item);
|
||||
ModelObject* obj = object(obj_idx);
|
||||
|
||||
obj_idxs.emplace_back(static_cast<size_t>(obj_idx));
|
||||
|
||||
// set printable value for selected instance/instances in object
|
||||
if (type == itInstance) {
|
||||
inst_idx = m_objects_model->GetInstanceIdByItem(item);
|
||||
obj->instances[m_objects_model->GetInstanceIdByItem(item)]->printable = printable;
|
||||
}
|
||||
if (type == itInstance)
|
||||
rows.instances.emplace_back(obj_idx, m_objects_model->GetInstanceIdByItem(item));
|
||||
else
|
||||
for (auto inst : obj->instances)
|
||||
inst->printable = printable;
|
||||
|
||||
// update printable state in ObjectList
|
||||
m_objects_model->SetObjectPrintableState(printable ? piPrintable : piUnprintable, item);
|
||||
rows.objects.push_back(obj_idx);
|
||||
}
|
||||
Ops::set_printable(wxGetApp().plater()->model(), rows, printable);
|
||||
|
||||
// update printable state in ObjectList
|
||||
for (auto item : sels)
|
||||
if (m_objects_model->GetItemType(item) & (itObject | itInstance))
|
||||
m_objects_model->SetObjectPrintableState(printable ? piPrintable : piUnprintable, item);
|
||||
|
||||
sort(obj_idxs.begin(), obj_idxs.end());
|
||||
obj_idxs.erase(unique(obj_idxs.begin(), obj_idxs.end()), obj_idxs.end());
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -21,6 +22,7 @@
|
||||
|
||||
#include "Event.hpp"
|
||||
#include "ObjectDataViewModel.hpp"
|
||||
#include "Operations/Outcome.hpp"
|
||||
#include "SyntheticInput.hpp"
|
||||
|
||||
#include "libslic3r/PrintConfig.hpp"
|
||||
@@ -65,6 +67,29 @@ enum class ObjectOrder { Name, Filament, Height, Size };
|
||||
// Stable sort by natural name order, filament, top Z, or bounding box volume of the first instance.
|
||||
void sort_objects(std::vector<ModelObject*>& objects, ObjectOrder order, bool descending = false);
|
||||
|
||||
// The order Order By gives `objects`, the project's: the objects of plate `plate`, or of every plate with -1, sorted
|
||||
// (sort_objects()) within the list positions they hold, so that the objects of the other plates, and those on no plate,
|
||||
// keep theirs. `plate_of` is the plate an object's first instance is on, -1 for none.
|
||||
std::vector<ModelObject*> plate_order(const std::vector<ModelObject*>& objects, const std::function<int(std::size_t)>& plate_of, int plate,
|
||||
ObjectOrder order, bool descending);
|
||||
|
||||
// A drop of the object at list position `from` onto the one at `to`, as dragging an object in the object list makes it.
|
||||
struct ObjectMove
|
||||
{
|
||||
int from = 0;
|
||||
int to = 0;
|
||||
};
|
||||
|
||||
// Moves the object at `from` to `to`, those between shifting by one toward `from`, as a drop in the object list does.
|
||||
void move_object_in_list(std::vector<ModelObject*>& objects, int from, int to);
|
||||
|
||||
// The drops that put the objects of plate `plate` in `order` (their indices), each dropped in turn on the object in its
|
||||
// place, as a person drags them in the object list: the plate's objects take their list positions in that order, and
|
||||
// the objects between them, of other plates or of none, move by one with each drop, keeping their own order.
|
||||
// `plate_of` is the plate each object's first instance is on, -1 for none. No drop where they are in that order.
|
||||
// Refuses: no_such_object, object_not_on_plate, order_repeats_object, order_misses_object (with the objects left out).
|
||||
Ops::Outcome<std::vector<ObjectMove>> object_order_moves(const std::vector<int>& plate_of, int plate, const std::vector<int>& order);
|
||||
|
||||
// Set import-only presentation ranks without changing part order used by slicing.
|
||||
void set_import_volume_order(ModelObject& object, bool sort_names);
|
||||
|
||||
@@ -343,8 +368,10 @@ public:
|
||||
// dialog after adding a part.
|
||||
void load_generic_subobject(const std::string& type_name, const ModelVolumeType type, bool interactive = true,
|
||||
const std::vector<double>& size = {});
|
||||
// Adds the shape as a new object, whatever is selected.
|
||||
void load_shape_object(const std::string &type_name, bool interactive, const std::vector<double>& size = {});
|
||||
// Whether load_shape_object() adds an object now: not while an object is selected, whose Add Part menu adds shapes.
|
||||
// Whether Add Primitive (load_generic_subobject() of no part type) adds an object now: not while an object is
|
||||
// selected, whose Add Part menu adds shapes.
|
||||
bool can_add_shape_object() const;
|
||||
void load_mesh_object(const TriangleMesh &mesh, const wxString &name, bool center = true);
|
||||
// One object holding one part per mesh; the parts keep their placement relative to each other.
|
||||
@@ -360,8 +387,16 @@ public:
|
||||
bool del_from_cut_object(bool is_connector, bool is_model_part = false, bool is_negative_volume = false);
|
||||
bool del_subobject_from_object(const int obj_idx, const int idx, const int type);
|
||||
void del_info_item(const int obj_idx, InfoItemType type);
|
||||
// Split > To Parts on the selected object or part.
|
||||
void split();
|
||||
void merge(bool to_multipart_object);
|
||||
// Splits part `volume_idx` of object `obj_idx` into parts by its shells, or with -1 the object's one part, or shows
|
||||
// the bodies of an import shown as one part. The caller has checked that the part is of several shells. With
|
||||
// `expand` the object's row is opened on its parts, as a split from that row opens it.
|
||||
void split(int obj_idx, int volume_idx, bool expand);
|
||||
// With `to_multipart_object`, assembles the objects and instances of `items`, rows of the list, else the selected
|
||||
// ones, into one object of parts added last, as Assemble does: the rows are selected first, and each instance of
|
||||
// them becomes an object of its own. Without it, merges the selected object's parts into one.
|
||||
void merge(bool to_multipart_object, const wxDataViewItemArray& items = {});
|
||||
// void merge_volumes(); // BBS: merge parts to single part
|
||||
void layers_editing();
|
||||
|
||||
@@ -484,9 +519,11 @@ public:
|
||||
// generic "Change type → Precise Seam" entry where CENTER is a default fallback.
|
||||
// preserve_ps_subtype = false: no preservation — target type is applied verbatim. Used
|
||||
// by the "Precise Seam Type" subtype picker where the user explicitly wants CENTER.
|
||||
// Returns why the selected parts kept their type, empty when they changed or already had it.
|
||||
// The parts changed are `parts`, [object, part] by their index in the model, else the selected ones.
|
||||
// Returns why the parts kept their type, empty when they changed or already had it.
|
||||
// show_errors shows that reason as the menu always has; automation passes false and reports it.
|
||||
wxString set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype = true, bool show_errors = true);
|
||||
wxString set_volume_type(ModelVolumeType new_type, bool preserve_ps_subtype = true, bool show_errors = true,
|
||||
const std::vector<std::pair<int, int>>& parts = {});
|
||||
ModelVolumeType get_selected_volume_type();
|
||||
|
||||
void last_volume_is_deleted(const int obj_idx);
|
||||
@@ -549,11 +586,17 @@ public:
|
||||
void on_plate_added(PartPlate* part_plate);
|
||||
void on_plate_deleted(int plate_index);
|
||||
void reload_all_plates(bool notify_partplate = false);
|
||||
// Sorts the selected plate or every plate, which sets the print order; repeating a sort reverses it.
|
||||
void order_objects(ObjectOrder order, bool all_plates);
|
||||
// Sorts plate `plate` (-1: the selected one) or every plate, which sets the print order (plate_order()). With
|
||||
// `descending` none, choosing the order the objects already have reverses it, as the plate menu's Order By does.
|
||||
void order_objects(ObjectOrder order, bool all_plates, int plate = -1, std::optional<bool> descending = std::nullopt);
|
||||
// Drops the object at list position `from` onto the one at `to`, both on plate `plate`, as a drag in the list does
|
||||
// (move_object_in_list()), and selects it. The caller takes the undo snapshot.
|
||||
void move_object(int from, int to, int plate);
|
||||
void on_plate_selected(int plate_index);
|
||||
void notify_instance_updated(int obj_idx);
|
||||
void object_config_options_changed(const ObjectVolumeID& ov_id);
|
||||
// Marks the row of the object or part `ov_id` names, or with `range` the row of that height range of the object,
|
||||
// with the icon of its own settings, or takes the icon away when it has none.
|
||||
void object_config_options_changed(const ObjectVolumeID& ov_id, const t_layer_height_range* range = nullptr);
|
||||
void printable_state_changed(const std::vector<ModelObject*> model_objects);
|
||||
void printable_state_changed(const std::vector<ObjectVolumeID>& ov_ids);
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "slic3r/GUI/NotificationManager.hpp"
|
||||
#include "libslic3r/PresetBundle.hpp"
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
@@ -109,9 +110,15 @@ void OrientJob::prepare_selected() {
|
||||
|
||||
std::vector<bool> obj_sel(model.objects.size(), false);
|
||||
|
||||
for (auto &s : m_plater->get_selection().get_content())
|
||||
if (s.first < int(obj_sel.size()))
|
||||
obj_sel[size_t(s.first)] = !s.second.empty();
|
||||
if (m_objects) {
|
||||
for (int object : *m_objects)
|
||||
if (object >= 0 && size_t(object) < obj_sel.size())
|
||||
obj_sel[size_t(object)] = true;
|
||||
} else {
|
||||
for (auto &s : m_plater->get_selection().get_content())
|
||||
if (s.first < int(obj_sel.size()))
|
||||
obj_sel[size_t(s.first)] = !s.second.empty();
|
||||
}
|
||||
|
||||
//BBS: add only one plate mode
|
||||
prepare_selection(obj_sel, false);
|
||||
@@ -256,7 +263,7 @@ void OrientJob::process(Ctl &ctl)
|
||||
wxGetApp().plater()->show_status_message(ctl.was_canceled() ? "Orienting canceled." : ss.str());
|
||||
}
|
||||
|
||||
OrientJob::OrientJob() : m_plater{wxGetApp().plater()} {}
|
||||
OrientJob::OrientJob(std::optional<std::vector<int>> objects) : m_plater{wxGetApp().plater()}, m_objects{std::move(objects)} {}
|
||||
|
||||
void OrientJob::finalize(bool canceled, std::exception_ptr &eptr)
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include "Job.hpp"
|
||||
#include "libslic3r/Orient.hpp"
|
||||
#include <optional>
|
||||
#include <vector>
|
||||
#include <exception>
|
||||
#include "libslic3r/Model.hpp"
|
||||
@@ -22,6 +23,8 @@ class OrientJob : public Job
|
||||
|
||||
OrientMeshs m_selected, m_unselected, m_unprintable;
|
||||
Plater *m_plater;
|
||||
// The objects to orient in place of the selection, read when the job starts; none of them: every object.
|
||||
std::optional<std::vector<int>> m_objects;
|
||||
|
||||
// clear m_selected and m_unselected, reserve space for next usage
|
||||
void clear_input();
|
||||
@@ -29,7 +32,7 @@ class OrientJob : public Job
|
||||
//BBS: add only one plate mode
|
||||
void prepare_selection(std::vector<bool> obj_sel, bool only_one_plate);
|
||||
|
||||
// Prepare the selected and unselected items separately. If nothing is
|
||||
// Prepare the selected (or the given) and unselected items separately. If nothing is
|
||||
// selected, behaves as if everything would be selected.
|
||||
void prepare_selected();
|
||||
|
||||
@@ -41,7 +44,8 @@ public:
|
||||
|
||||
void process(Ctl &ctl) override;
|
||||
|
||||
OrientJob();
|
||||
// `objects`, given, are oriented as if they were the selection.
|
||||
explicit OrientJob(std::optional<std::vector<int>> objects = std::nullopt);
|
||||
|
||||
void finalize(bool canceled, std::exception_ptr &e) override;
|
||||
#if 0
|
||||
|
||||
@@ -3078,12 +3078,12 @@ wxMenu* MainFrame::generate_help_menu()
|
||||
if (wxGetApp().is_editor()) {
|
||||
helpMenu->AppendSeparator();
|
||||
append_menu_item(helpMenu, wxID_ANY, _L("Take Screenshot"), _L("Save a picture of the main window"),
|
||||
[](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("take_screenshot")); });
|
||||
[](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("window_save_screenshot")); });
|
||||
append_menu_item(helpMenu, wxID_ANY, _L("Start Recording") + dots, _L("Record a video of the main window"),
|
||||
[](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("start_recording")); }, "", nullptr,
|
||||
[](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("recording_start")); }, "", nullptr,
|
||||
[]() { return !NativeCommands::recording_active(); }, this);
|
||||
append_menu_item(helpMenu, wxID_ANY, _L("Stop Recording"), _L("Stop the recording and save it"),
|
||||
[](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("stop_recording")); }, "", nullptr,
|
||||
[](wxCommandEvent&) { NativeCommands::notify_result(NativeCommands::run("recording_stop")); }, "", nullptr,
|
||||
[]() { return NativeCommands::recording_active(); }, this);
|
||||
}
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@ class UiInspector;
|
||||
class WebPresses;
|
||||
struct AutoAnswerRule;
|
||||
|
||||
// Whose an auto_answer_dialogs call's rules are ("run", "plugin" or "session"), the tracker layer they went into (0 for
|
||||
// Whose a dialog_auto_answer call's rules are ("run", "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
|
||||
@@ -137,21 +137,21 @@ public:
|
||||
UiInvoker& ui() { return *m_invoker; }
|
||||
McpCore& core() { return *m_core; }
|
||||
ModalTracker& modals() { return *m_modals; }
|
||||
// Refs from list_widgets live here. Turns the GUI instruments on if they are off. UI thread only.
|
||||
// Refs from widget_list live here. Turns the GUI instruments on if they are off. UI thread only.
|
||||
UiInspector& inspector();
|
||||
// The presses mouse_gesture downs left on pages, the web counterpart of the inspector's held press.
|
||||
// Any thread.
|
||||
WebPresses& web_presses() { return *m_web_presses; }
|
||||
// start_recording and its kin; also told about every call, for the captions.
|
||||
// recording_start and its kin; also told about every call, for the captions.
|
||||
McpRecorder& recorder() { return *m_recorder; }
|
||||
|
||||
// Auto-answer rules from auto_answer_dialogs. Rules registered from inside a run (the nearest
|
||||
// Auto-answer rules from dialog_auto_answer. Rules registered from inside a run (the nearest
|
||||
// running replay or script in `ancestry`, the caller's job chain, nearest first) last until that run
|
||||
// ends; a client's rules replace the ones it registered before, and end when the client scope
|
||||
// closes: with the scope closed (the server turned off meanwhile), a client's rules are refused.
|
||||
// A run scope that is paused (set_run_scope_paused()) gets them paused. Any thread.
|
||||
AutoAnswerSet set_auto_answer(std::vector<AutoAnswerRule> rules, const std::vector<std::string>& ancestry);
|
||||
// run_replay and run_script bracket their runs with these. A mouse press the run left held is released
|
||||
// replay_run and script_run bracket their runs with these. A mouse press the run 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_run_scope(const std::string& job);
|
||||
@@ -162,7 +162,7 @@ public:
|
||||
// Releases the mouse presses `job`'s calls left held, on widgets and pages, as the end of its scope does. Any
|
||||
// thread.
|
||||
void release_run_presses(const std::string& job);
|
||||
// Cancels the operations whose lineage holds `job`, as cancel_job does: a background job through the worker,
|
||||
// Cancels the operations whose lineage holds `job`, as job_cancel 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 replay or script in `ancestry`, else the scope of the plugin whose call it is,
|
||||
|
||||
@@ -49,7 +49,7 @@ std::string JobRegistry::register_job(const std::string& tool, const std::string
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
const std::size_t running = std::count_if(m_jobs.begin(), m_jobs.end(), [](const auto& kv) { return !kv.second.finished; });
|
||||
if (running >= kMaxRunning)
|
||||
throw ToolFailure("Too many running jobs; wait for some to finish (see get_app_state.jobs)");
|
||||
throw ToolFailure("Too many running jobs; wait for some to finish (see app_state.jobs)");
|
||||
std::string id = "j" + std::to_string(m_next++);
|
||||
Job job;
|
||||
job.tool = tool;
|
||||
|
||||
@@ -24,7 +24,7 @@ namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
inline constexpr char kPluginUnloaded[] = "The plugin that made this call has been unloaded";
|
||||
|
||||
// Bookkeeping for mutate tool calls that run on their own threads. A call that outlives its reply
|
||||
// budget stays here until it finishes, so a later `wait {for:"job"}` can return its result; the
|
||||
// budget stays here until it finishes, so a later `app_wait {for:"job"}` can return its result; the
|
||||
// most recent finished jobs are kept for that purpose, and so is a finished job whose parent (a
|
||||
// running replay) may still wait for it, up to kKeepFinishedMax in all. Thread-safe.
|
||||
class JobRegistry
|
||||
@@ -41,7 +41,7 @@ public:
|
||||
// job is registered: a plugin found loaded then was loaded while the job was there for its unload to
|
||||
// find, so every job of the plugin is either refused or one the unload finds running.
|
||||
std::string create(const std::string& tool, const std::string& parent, const std::string& owner = {}, bool person = false);
|
||||
// True when an unfinished job in `lineage` carries the person mark: a run_script there runs as the person's.
|
||||
// True when an unfinished job in `lineage` carries the person mark: a script_run there runs as the person's.
|
||||
bool person_in(const std::set<std::string>& lineage) const;
|
||||
// Lets the unfinished job `id`, and the calls under it, drop the project's unsaved changes: the user chose
|
||||
// not to save before a run that replaces the project. Does nothing for an unknown or finished job.
|
||||
@@ -84,7 +84,7 @@ public:
|
||||
bool stop_requested(const std::string& id) const;
|
||||
// True when a running job exists that is not in `excluded` and isn't set idle.
|
||||
bool any_running_except(const std::set<std::string>& excluded) const;
|
||||
// Marks a running job as one that leaves `wait {for: "idle"}` to the calls it makes: a run_script run, which may
|
||||
// Marks a running job as one that leaves `app_wait {for: "idle"}` to the calls it makes: a script_run run, which may
|
||||
// wait for a person in its window for minutes. list() shows it as idle.
|
||||
void set_idle(const std::string& id);
|
||||
// Operation admission: a job marked as an operation holds the project until it finishes.
|
||||
@@ -92,7 +92,7 @@ public:
|
||||
std::string begin_operation(const std::string& id);
|
||||
std::vector<std::string> running_operations() const;
|
||||
|
||||
// [{id, tool, parent, state, age_ms}] for get_app_state.
|
||||
// [{id, tool, parent, state, age_ms}] for app_state.
|
||||
nlohmann::json list() const;
|
||||
// The tool of `id` while it runs; empty for an unknown or finished job.
|
||||
std::string running_tool(const std::string& id) const;
|
||||
|
||||
@@ -87,7 +87,7 @@ void start_launch_run(AutomationRuntime& runtime, const McpLaunchOptions& option
|
||||
set_run_output_dir(path_from_utf8(options.run_out));
|
||||
|
||||
FollowedCall call;
|
||||
call.command = *NativeCommands::instance().find(python ? "run_script" : "run_replay");
|
||||
call.command = *NativeCommands::instance().find(python ? "script_run" : "replay_run");
|
||||
call.person = true;
|
||||
// The file is read off the UI thread.
|
||||
call.ready = [&runtime, file, out = options.run_out, python, replay](json& args) {
|
||||
|
||||
@@ -50,6 +50,19 @@ bool type_matches(const json& value, const json& type)
|
||||
return json_type_name(value) == t;
|
||||
}
|
||||
|
||||
// Whether `value`, a call's arguments, meets `cond`, the "if" of with_silent(): it is no person's form, so what the
|
||||
// silent form requires applies. {"minProperties": 1} holds for any argument, {"not": {"enum": [...]}} for arguments
|
||||
// other than those listed; any other "if" is not with_silent()'s, and never holds.
|
||||
bool silent_form(const json& cond, const json& value)
|
||||
{
|
||||
if (cond == json{{"minProperties", 1}})
|
||||
return !value.empty();
|
||||
if (const auto no = cond.find("not"); cond.size() == 1 && no != cond.end() && no->is_object() && no->size() == 1)
|
||||
if (const auto forms = no->find("enum"); forms != no->end() && forms->is_array())
|
||||
return std::find(forms->begin(), forms->end(), value) == forms->end();
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string validate_value(const json& schema, const json& value, const std::string& path)
|
||||
{
|
||||
if (!schema.is_object())
|
||||
@@ -70,6 +83,9 @@ std::string validate_value(const json& schema, const json& value, const std::str
|
||||
return path + " must be <= " + it->dump();
|
||||
}
|
||||
if (value.is_array()) {
|
||||
if (auto it = schema.find("minItems");
|
||||
it != schema.end() && it->is_number_integer() && it->get<long long>() > 0 && value.size() < it->get<std::size_t>())
|
||||
return path + " must hold at least " + it->dump() + " item" + (it->get<long long>() == 1 ? "" : "s");
|
||||
if (auto it = schema.find("items"); it != schema.end())
|
||||
for (std::size_t i = 0; i < value.size(); ++i)
|
||||
if (std::string err = validate_value(*it, value[i], path + "[" + std::to_string(i) + "]"); !err.empty())
|
||||
@@ -102,10 +118,10 @@ std::string validate_value(const json& schema, const json& value, const std::str
|
||||
if (auto it = schema.find("required"); it != schema.end())
|
||||
if (std::string err = missing(*it); !err.empty())
|
||||
return err;
|
||||
// with_silent()'s shape, and no other use of if: what the silent form requires, once the call gives any
|
||||
// argument.
|
||||
// with_silent()'s shapes, and no other use of if: what the silent form requires, once the call is not one of
|
||||
// the person's forms.
|
||||
const auto cond = schema.find("if"), then = schema.find("then");
|
||||
if (cond != schema.end() && then != schema.end() && *cond == json{{"minProperties", 1}} && then->is_object() && !value.empty())
|
||||
if (cond != schema.end() && then != schema.end() && then->is_object() && silent_form(*cond, value))
|
||||
if (auto it = then->find("required"); it != then->end())
|
||||
if (std::string err = missing(*it); !err.empty())
|
||||
return err;
|
||||
@@ -132,6 +148,24 @@ const std::vector<std::pair<std::string, std::vector<std::string>>>& argument_al
|
||||
return aliases;
|
||||
}
|
||||
|
||||
// The arguments that pick a command's variant where it is not a type, named for what is picked (project_export's
|
||||
// format, object_add_primitive's shape). A guessed type stands for the one of them a command takes, where it takes
|
||||
// exactly one and no type of its own; with two, either could be meant.
|
||||
constexpr const char* kVariantArguments[] = {"format", "shape", "model", "test", "into", "by", "axis", "mode", "window", "page"};
|
||||
|
||||
// The one argument of kVariantArguments that `props` has, or nullptr where it has none or several.
|
||||
const char* only_variant_argument(const json& props)
|
||||
{
|
||||
const char* found = nullptr;
|
||||
for (const char* name : kVariantArguments)
|
||||
if (props.contains(name)) {
|
||||
if (found != nullptr)
|
||||
return nullptr;
|
||||
found = name;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
bool type_includes(const json& type, const char* name)
|
||||
{
|
||||
return type.is_array() ? std::find(type.begin(), type.end(), name) != type.end() : type == name;
|
||||
@@ -232,9 +266,9 @@ void normalize_arguments(const json& schema, json& args)
|
||||
if (!args.is_object() || !schema.is_object() || !schema.contains("properties"))
|
||||
return;
|
||||
const json& props = schema["properties"];
|
||||
// x and y, and width and height, as list_windows reports them, read as the position and size arrays
|
||||
// x and y, and width and height, as window_list reports them, read as the position and size arrays
|
||||
// of a tool that takes those as window geometry, arrays of integers, and neither part by its own
|
||||
// name. The mm arrays of the 3D tools (transform, add_part) hold numbers and never take a pair. Only
|
||||
// name. The mm arrays of the 3D tools (object_transform, part_add) hold numbers and never take a pair. Only
|
||||
// both parts of a pair fold, and never over an array the call gives.
|
||||
struct Pair
|
||||
{
|
||||
@@ -254,27 +288,34 @@ void normalize_arguments(const json& schema, json& args)
|
||||
args.erase(pair.first);
|
||||
args.erase(pair.second);
|
||||
}
|
||||
// Moves `alias`'s value to `name` where the schema takes name, the call leaves it out and the value fits: the
|
||||
// widget_click tool's action "click" is no button, and its error should name action.
|
||||
const auto read_as = [&props, &args](const std::string& alias, const std::string& name) {
|
||||
if (!props.contains(name) || args.contains(name))
|
||||
return false;
|
||||
json value = args[alias];
|
||||
coerce_value(props[name], value);
|
||||
if (!validate_value(props[name], value, name).empty())
|
||||
return false;
|
||||
args[name] = std::move(value);
|
||||
args.erase(alias);
|
||||
return true;
|
||||
};
|
||||
for (const auto& [alias, names] : argument_aliases()) {
|
||||
if (!args.contains(alias) || props.contains(alias))
|
||||
continue;
|
||||
// Only where the value fits: the click tool's action "click" is no button, and its error should name action.
|
||||
for (const std::string& name : names) {
|
||||
if (!props.contains(name) || args.contains(name))
|
||||
continue;
|
||||
json value = args[alias];
|
||||
coerce_value(props[name], value);
|
||||
if (validate_value(props[name], value, name).empty()) {
|
||||
args[name] = std::move(value);
|
||||
args.erase(alias);
|
||||
for (const std::string& name : names)
|
||||
if (read_as(alias, name))
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (args.contains("type") && !props.contains("type"))
|
||||
if (const char* variant = only_variant_argument(props))
|
||||
read_as("type", variant);
|
||||
for (auto it = args.begin(); it != args.end(); ++it)
|
||||
if (auto p = props.find(it.key()); p != props.end())
|
||||
coerce_value(*p, it.value());
|
||||
// A value outside its own enum that the enum of one other argument, which the call leaves out,
|
||||
// takes: set_view's canvas "front" is its camera. The schema keeps each enum to its own values,
|
||||
// takes: view_set's canvas "front" is its camera. The schema keeps each enum to its own values,
|
||||
// as listing them under both names would have agents give a value to the wrong one.
|
||||
std::vector<std::pair<std::string, std::string>> moves;
|
||||
for (const auto& [key, value] : args.items()) {
|
||||
@@ -299,6 +340,25 @@ std::string validate_arguments(const json& schema, const json& args) { return va
|
||||
|
||||
bool person_form(const json& args) { return args.is_null() || (args.is_object() && args.empty()); }
|
||||
|
||||
std::vector<json> person_forms(const NativeCommand& command)
|
||||
{
|
||||
std::vector<json> forms;
|
||||
if (command.in_palette)
|
||||
forms.push_back(json::object());
|
||||
if (command.tiles.is_array())
|
||||
for (const json& tile : command.tiles)
|
||||
if (tile.value("input", std::string()).empty())
|
||||
forms.push_back(tile.at("args"));
|
||||
return forms;
|
||||
}
|
||||
|
||||
bool person_form(const NativeCommand& command, const json& args)
|
||||
{
|
||||
const json given = person_form(args) ? json::object() : args;
|
||||
const std::vector<json> forms = person_forms(command);
|
||||
return std::find(forms.begin(), forms.end(), given) != forms.end();
|
||||
}
|
||||
|
||||
json silent_args(json args)
|
||||
{
|
||||
if (args.is_object())
|
||||
@@ -306,19 +366,29 @@ json silent_args(json args)
|
||||
return args;
|
||||
}
|
||||
|
||||
json with_silent(json schema)
|
||||
json with_silent(json schema, const std::vector<json>& person_args)
|
||||
{
|
||||
schema["properties"]["silent"] = {{"type", "boolean"},
|
||||
{"enum", {true}},
|
||||
{"description", "true runs the command without asking, with the defaults of what the call "
|
||||
"leaves out. A call with no arguments does what a person's pick does."}};
|
||||
json required = json::array();
|
||||
if (auto it = schema.find("required"); it != schema.end()) {
|
||||
json required = std::move(*it);
|
||||
required = std::move(*it);
|
||||
schema.erase(it);
|
||||
if (!required.empty()) {
|
||||
schema["if"] = {{"minProperties", 1}};
|
||||
schema["then"] = {{"required", std::move(required)}};
|
||||
}
|
||||
}
|
||||
const bool only_none = person_args.size() == 1 && person_form(person_args.front());
|
||||
const bool has_none = std::any_of(person_args.begin(), person_args.end(), [](const json& a) { return person_form(a); });
|
||||
// What silent says is the command's own: what its silent form still needs, and which calls are its person's forms.
|
||||
std::string needs;
|
||||
for (std::size_t i = 0; i < required.size(); ++i)
|
||||
needs += (i == 0 ? "" : i + 1 == required.size() ? " and " : ", ") + required[i].get<std::string>();
|
||||
std::string text = needs.empty() ? "true runs the command without asking; what the call leaves out takes its default." :
|
||||
"true runs the command without asking; it then needs " + needs +
|
||||
", and what else the call leaves out takes its default.";
|
||||
text += only_none ? " A call with no arguments does what a person's pick does." :
|
||||
has_none ? " A call with no arguments, or with exactly a tile's arguments, does what a person's pick of that tile does." :
|
||||
" A call with exactly a tile's arguments does what a person's pick of that tile does.";
|
||||
schema["properties"]["silent"] = {{"type", "boolean"}, {"enum", {true}}, {"description", std::move(text)}};
|
||||
if (!required.empty()) {
|
||||
schema["if"] = only_none ? json{{"minProperties", 1}} : json{{"not", {{"enum", person_args}}}};
|
||||
schema["then"] = {{"required", std::move(required)}};
|
||||
}
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// For a call of call_tool ({tool, args}): replaces `command` and `args` with its target's, normalized and
|
||||
// For a call of tool_call ({tool, args}): replaces `command` and `args` with its target's, normalized and
|
||||
// validated, so the call runs and is journaled as the target's own. Returns an error message, or "" (also
|
||||
// for any other command, which it leaves as it is).
|
||||
std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr<const NativeCommand>& command, nlohmann::json& args);
|
||||
@@ -20,22 +20,28 @@ std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr<const Na
|
||||
// ---- arguments and name matching (McpArguments.cpp) ------------------------------------------
|
||||
|
||||
// Validates `args` against the subset of JSON Schema the tool catalog uses (object properties with
|
||||
// type, enum, minimum/maximum, required, additionalProperties:false, array items, and the
|
||||
// "if": {"minProperties": 1}, "then": {"required": [...]} of with_silent()). Returns an empty string when
|
||||
// valid, else a message naming the offending property.
|
||||
// type, enum, minimum/maximum, required, additionalProperties:false, array items, and the "if" and "then"
|
||||
// of with_silent()). Returns an empty string when valid, else a message naming the offending property.
|
||||
std::string validate_arguments(const nlohmann::json& schema, const nlohmann::json& args);
|
||||
|
||||
// Whether `args` asks for a command's person's form: an object with no members, or null. A command that has
|
||||
// a person's form and a silent one does the person's then (it asks, as a person's pick does), and the
|
||||
// silent one when it is given any argument.
|
||||
// Whether `args` is a call with no arguments: an object with no members, or null. A Design command and a menu
|
||||
// row's function do their person's form then (they ask, as a person's pick does).
|
||||
bool person_form(const nlohmann::json& args);
|
||||
// The arguments of each of `command`'s person's forms: {} for its own tile (in_palette), and the args of each item
|
||||
// of its tiles that collects no value (no input), in their order.
|
||||
std::vector<nlohmann::json> person_forms(const NativeCommand& command);
|
||||
// Whether `args`, null as {}, are a person's form of `command`: exactly the arguments of one of person_forms(). Such
|
||||
// a call does what a person's pick of that tile does, and may ask; any other call is its silent form.
|
||||
bool person_form(const NativeCommand& command, const nlohmann::json& args);
|
||||
// `args` without `silent`, which only chooses the silent form.
|
||||
nlohmann::json silent_args(nlohmann::json args);
|
||||
// The schema of a two-form command from its silent form's `schema`: it gains the property `silent`, which
|
||||
// takes only true and asks for the silent form with its defaults, and a top-level `required` list moves to
|
||||
// "if": {"minProperties": 1}, "then": {"required": [...]}, since the call with no arguments, the person's
|
||||
// form, needs none of them.
|
||||
nlohmann::json with_silent(nlohmann::json schema);
|
||||
// takes only true and asks for the silent form with its defaults, described by what that form still requires and by
|
||||
// which calls are the person's forms (none, a tile's arguments, or both), and a top-level `required` list moves under
|
||||
// "then", with an "if" that holds for every call but the person's forms, `person_args` (never empty), so that a
|
||||
// person's form needs none of them: {"minProperties": 1} where the only one is the call with no arguments, else
|
||||
// {"not": {"enum": [<each of person_args>]}}.
|
||||
nlohmann::json with_silent(nlohmann::json schema, const std::vector<nlohmann::json>& person_args = {nlohmann::json::object()});
|
||||
|
||||
// Readies a call's arguments for `command`, as every caller of a command does: normalizes `args` in place
|
||||
// (normalize_arguments()) and returns why validate_arguments() refuses them; empty when they are valid.
|
||||
@@ -45,10 +51,11 @@ std::string argument_error(const NativeCommand& command, nlohmann::json& args);
|
||||
// argument under a name the tool does not take but that stands for one it does, which the call leaves
|
||||
// out and the value fits (ref for target, key for keys, text for value, action for id or button, object for objects,
|
||||
// plate for plates, filter for query, settings for values, path for save_path, index for feature, params or
|
||||
// values for fields), a value written in
|
||||
// values for fields, and type for the one argument that picks a command's variant where that has another name, as
|
||||
// project_export's format, when it takes exactly one such and no type), a value written in
|
||||
// another JSON form (a number, boolean, array or object as a string, a single item for an array),
|
||||
// a value outside its argument's enum that only one omitted argument's enum takes (set_view's canvas
|
||||
// "front" as camera), and the x and y, or width and height, that list_windows reports, both given, as
|
||||
// a value outside its argument's enum that only one omitted argument's enum takes (view_set's canvas
|
||||
// "front" as camera), and the x and y, or width and height, that window_list reports, both given, as
|
||||
// the position or size array of a tool that takes that array, of integers, and neither part. Anything
|
||||
// that still does not fit is left for validate_arguments to report.
|
||||
void normalize_arguments(const nlohmann::json& schema, nlohmann::json& args);
|
||||
|
||||
@@ -56,7 +56,7 @@ void deliver(const std::function<void(const ToolResult&)>& done, const ToolResul
|
||||
std::string busy_message(const std::string& op)
|
||||
{
|
||||
return "Busy: job " + op +
|
||||
" is running an operation (slice, export, arrange or another background job); wait for it or stop it with cancel_job";
|
||||
" is running an operation (slice, export, arrange or another background job); wait for it or stop it with job_cancel";
|
||||
}
|
||||
|
||||
class CallContext final : public ToolContext
|
||||
@@ -291,7 +291,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a
|
||||
ToolResult& refused)
|
||||
{
|
||||
// Operation admission: an MCP operation holds the project until it finishes; only recovery
|
||||
// input and the commands that may run during an operation (cancel_job) get through.
|
||||
// input and the commands that may run during an operation (job_cancel) get through.
|
||||
if (def.guard == GuardClass::Mutate && !def.allowed_during_operation)
|
||||
if (const auto busy = m_jobs.running_operations(); !busy.empty()) {
|
||||
refused = ToolResult::error(busy_message(busy.front()) + " before changing the project", {{"job", busy.front()}});
|
||||
@@ -332,7 +332,7 @@ std::string McpCore::start_job(const NativeCommand& def, const nlohmann::json& a
|
||||
result = await_worker(job, def.key, invoke(def, args, ctx));
|
||||
notify(m_observer, [&](CallObserver& o) { o.call_ended(call, result); });
|
||||
}
|
||||
// Before finish(): an export_replay right after the wait that sees the result must know it.
|
||||
// Before finish(): a replay_export right after the app_wait that sees the result must know it.
|
||||
if (seq != 0)
|
||||
m_journal->job_ended(seq, result);
|
||||
deliver(done, result);
|
||||
@@ -400,8 +400,8 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co
|
||||
return ToolResult::ok(std::move(out));
|
||||
};
|
||||
const std::string running_note = "The call is still running and will finish on its own; do not retry it. "
|
||||
"Use wait {for:\"job\", job:\"" + job + "\"} for its result.";
|
||||
// answer_dialog presses a native message box by the buttons ModalTracker lists for it, but not a
|
||||
"Use app_wait {for:\"job\", job:\"" + job + "\"} for its result.";
|
||||
// dialog_answer presses a native message box by the buttons ModalTracker lists for it, but not a
|
||||
// picker, nor a dialog while it holds the UI thread (macOS), so their note asks for a person.
|
||||
auto blocked = [&](nlohmann::json dialogs, bool ui_held) {
|
||||
std::string note;
|
||||
@@ -409,16 +409,16 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co
|
||||
const bool pressable = native && !ui_held && !dialogs.back().value("buttons", nlohmann::json::array()).empty();
|
||||
if (pressable) {
|
||||
note = "The call is waiting on a native message box and continues after it closes; do not retry it. Answer it "
|
||||
"with answer_dialog and one of its buttons, then wait {for:\"job\", job:\"" + job + "\"}.";
|
||||
"with dialog_answer and one of its buttons, then app_wait {for:\"job\", job:\"" + job + "\"}.";
|
||||
} else if (native) {
|
||||
note = "The call is waiting on a native dialog, which only a person can answer (answer_dialog can't); do not retry it. ";
|
||||
note = "The call is waiting on a native dialog, which only a person can answer (dialog_answer can't); do not retry it. ";
|
||||
if (ui_held)
|
||||
note += "Until it closes, tools that need the UI thread fail. ";
|
||||
note += "Once it is answered, wait {for:\"job\", job:\"" + job +
|
||||
"\"}. Register auto_answer_dialogs before a step that opens a native dialog.";
|
||||
note += "Once it is answered, app_wait {for:\"job\", job:\"" + job +
|
||||
"\"}. Register dialog_auto_answer before a step that opens a native dialog.";
|
||||
} else {
|
||||
note = "The call is waiting on a dialog and continues after it closes; do not retry it. "
|
||||
"Answer the dialog (list_widgets, answer_dialog), then wait {for:\"job\", job:\"" + job + "\"}.";
|
||||
"Answer the dialog (widget_list, dialog_answer), then app_wait {for:\"job\", job:\"" + job + "\"}.";
|
||||
}
|
||||
return envelope("blocked_by_dialog", {{"dialogs", std::move(dialogs)}, {"note", note}});
|
||||
};
|
||||
@@ -481,7 +481,7 @@ void McpCore::admit(const std::string& job) const
|
||||
return;
|
||||
}
|
||||
throw ToolFailure("Busy: a background job (arrange, orient, fill bed, or one a gizmo started, such as Text typing) is "
|
||||
"running in OrcaSlicer; wait {for:\"idle\"} before changing the project");
|
||||
"running in OrcaSlicer; app_wait {for:\"idle\"} before changing the project");
|
||||
}
|
||||
|
||||
bool McpCore::worker_busy() const { return m_worker.busy && m_worker.busy(); }
|
||||
|
||||
@@ -89,7 +89,7 @@ public:
|
||||
// As call(), with the job marked a person's.
|
||||
ToolResult call_person(const NativeCommand& command, const nlohmann::json& args);
|
||||
// A call made by a running job (a replay step or a script's call). The new job's parent is `parent_job`, so a
|
||||
// `wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out.
|
||||
// `app_wait {for:"idle"}` from that job does not wait for it, and the journal leaves it out.
|
||||
ToolResult call_child(const NativeCommand& command, const nlohmann::json& args, const std::string& parent_job,
|
||||
const std::string& plugin = {});
|
||||
// A child call by the command's key, as ToolContext::call_child() makes one, under any parent: the command is
|
||||
@@ -174,7 +174,7 @@ private:
|
||||
mutable std::mutex m_dialogs_mutex;
|
||||
std::map<std::string, std::uint64_t> m_dialogs_of;
|
||||
|
||||
// Requests that may block (a job within its reply budget, or wait) hold a slot, so the number of
|
||||
// Requests that may block (a job within its reply budget, or app_wait) hold a slot, so the number of
|
||||
// blocked request threads stays below the connection limit and recovery calls always get through.
|
||||
bool acquire_slot();
|
||||
void release_slot();
|
||||
|
||||
@@ -193,7 +193,7 @@ bool McpEndpoint::listen(int port, std::string& err)
|
||||
{"token", token}},
|
||||
m_discovery_error))
|
||||
// Serving anyway: clients configured with the URL and token still connect; the stdio
|
||||
// bridge and the harness, which need the file, see the reason in get_app_state.
|
||||
// bridge and the harness, which need the file, see the reason in app_state.
|
||||
BOOST_LOG_TRIVIAL(warning) << "MCP server: " << m_discovery_error;
|
||||
BOOST_LOG_TRIVIAL(info) << "MCP server listening on http://127.0.0.1:" << m_http->port() << "/mcp";
|
||||
return true;
|
||||
|
||||
@@ -29,21 +29,19 @@ namespace {
|
||||
// counted as replacement characters rather than thrown on: the journal only needs the size.
|
||||
std::size_t serialized_size(const json& args) { return args.dump(-1, ' ', false, json::error_handler_t::replace).size(); }
|
||||
|
||||
// The command a journaled call of `tool` with `args` runs, and the arguments it runs it with: the call's own, or,
|
||||
// for run_action of a command's tile, named by the command's key or by the tile's full id, that command and the
|
||||
// arguments inside the tile's {id, args}.
|
||||
// The name a journaled call of `tool` with `args` runs under, and the arguments it runs with: the call's own, or, for
|
||||
// action_run of a command's tile, by its full id or the key inside it, that key and the arguments inside the tile's
|
||||
// {id, args}. A command's own tile is under its command's key, so a Design command's tile is rewritten as its command
|
||||
// is; a tile of a row folded into a command is under a key of its own, and its call's arguments, none, the tile's own
|
||||
// or the value it collects, hold no path to rewrite.
|
||||
std::pair<std::string, json*> called_command(const std::string& tool, json& args)
|
||||
{
|
||||
if (tool != "run_action" || !args.is_object() || !args.value("id", json()).is_string() || !args.value("args", json()).is_object())
|
||||
if (tool != "action_run" || !args.is_object() || !args.value("id", json()).is_string() || !args.value("args", json()).is_object())
|
||||
return {tool, &args};
|
||||
const std::string id = args["id"];
|
||||
const std::string prefix = std::string(kCommandPrefix) + ':', suffix = std::string(":") + kOrcaSourceKey;
|
||||
if (id.find(':') == std::string::npos)
|
||||
return {id, &args["args"]};
|
||||
if (id.size() > prefix.size() + suffix.size() && id.compare(0, prefix.size(), prefix) == 0 &&
|
||||
id.compare(id.size() - suffix.size(), suffix.size(), suffix) == 0)
|
||||
return {id.substr(prefix.size(), id.size() - prefix.size() - suffix.size()), &args["args"]};
|
||||
return {tool, &args};
|
||||
const std::string key = command_tile_key(args["id"].get<std::string>());
|
||||
if (key.empty())
|
||||
return {tool, &args};
|
||||
return {key, &args["args"]};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -52,12 +50,12 @@ json without_expected_ids(const CommandCatalog& catalog, const std::string& comm
|
||||
{
|
||||
if (!args.is_object())
|
||||
return args;
|
||||
if (command == "call_tool") {
|
||||
if (command == "tool_call") {
|
||||
if (args.contains("args") && args["args"].is_object())
|
||||
args["args"] = without_expected_ids(catalog, args.value("tool", std::string()), std::move(args["args"]));
|
||||
return args;
|
||||
}
|
||||
if (command == "run_replay") {
|
||||
if (command == "replay_run") {
|
||||
// An inline replay given as JSON text is recorded as the object it parses to, so its steps are
|
||||
// stripped too. Text that doesn't parse stays as given: the call fails, and no replay keeps it.
|
||||
if (args.contains("replay") && args["replay"].is_string()) {
|
||||
@@ -106,7 +104,7 @@ void Journal::set_args(uint64_t seq, nlohmann::json args)
|
||||
const std::size_t bytes = serialized_size(args);
|
||||
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
// export_replay {clear:true} may have emptied the journal meanwhile.
|
||||
// replay_export {clear:true} may have emptied the journal meanwhile.
|
||||
const auto it = std::find_if(m_entries.begin(), m_entries.end(), [seq](const Entry& e) { return e.seq == seq; });
|
||||
if (it == m_entries.end())
|
||||
return;
|
||||
@@ -125,7 +123,7 @@ void Journal::end(uint64_t seq, const ToolResult& result)
|
||||
e.finished = true;
|
||||
e.failed = e.failed || result.is_error;
|
||||
e.menu_listed = !result.is_error && result.data.is_object() && result.data.contains("popup_menu");
|
||||
// The envelope names the call's own job; a `wait` that timed out names another one.
|
||||
// The envelope names the call's own job; an `app_wait` that timed out names another one.
|
||||
if (result.is_error || e.job.empty() || !result.data.is_object())
|
||||
continue;
|
||||
const auto job = result.data.find("job");
|
||||
@@ -167,7 +165,7 @@ void Journal::clear()
|
||||
void Journal::trim()
|
||||
{
|
||||
// A session kept open for days, or one that sends thousands of large calls (a CAD run's sketch_draw),
|
||||
// must not grow without bound; a replay is exported from the recent calls anyway (export_replay
|
||||
// must not grow without bound; a replay is exported from the recent calls anyway (replay_export
|
||||
// {clear:true} starts afresh). The oldest calls whose outcome is known go first; a call still
|
||||
// waiting for its reply or its job keeps its place, even when that holds the journal over a bound
|
||||
// until it finishes. One pass moves the kept calls forward and one erase drops the rest, so a large
|
||||
@@ -220,14 +218,14 @@ nlohmann::json Journal::to_replay(const std::string& name, nlohmann::json* left_
|
||||
if (e.menu_listed && repeated_with_item(it))
|
||||
continue;
|
||||
nlohmann::json step{{"tool", e.tool}, {"args", e.args}};
|
||||
if (e.tool == "wait" && e.args.value("for", "") == "job") {
|
||||
if (e.tool == "app_wait" && e.args.value("for", "") == "job") {
|
||||
auto it = job_names.find(e.args.value("job", ""));
|
||||
if (it == job_names.end())
|
||||
continue; // waits on a job the journal did not see start
|
||||
step["args"]["job"] = "${jobs." + it->second + "}";
|
||||
}
|
||||
// The command the step calls and its arguments: run_action of a command's tile calls the tile's command
|
||||
// with the arguments inside the tile's {id, args}, which the step keeps.
|
||||
// The name the step runs under and its arguments: action_run of a command's tile runs as the tile's key, with
|
||||
// the arguments inside the tile's {id, args}, which the step keeps, so that its replay runs the tile again.
|
||||
const auto [tool, called_args] = called_command(e.tool, step["args"]);
|
||||
nlohmann::json& args = *called_args;
|
||||
auto in_out_dir = [&](const char* key) {
|
||||
@@ -235,16 +233,16 @@ nlohmann::json Journal::to_replay(const std::string& name, nlohmann::json* left_
|
||||
return "${out_dir}/" + file;
|
||||
};
|
||||
auto has_path = [&](const char* key) { return args.contains(key) && args[key].is_string(); };
|
||||
if ((tool == "screenshot" || tool == "encode_recording") && has_path("save_path"))
|
||||
if ((tool == "window_screenshot" || tool == "recording_encode") && has_path("save_path"))
|
||||
args["save_path"] = in_out_dir("save_path");
|
||||
if (tool == "start_recording" && has_path("save_path")) {
|
||||
if (tool == "recording_start" && has_path("save_path")) {
|
||||
const std::string key = path_compare_key(path_from_utf8(args["save_path"].get<std::string>()));
|
||||
args["save_path"] = in_out_dir("save_path");
|
||||
recordings[key] = args["save_path"];
|
||||
}
|
||||
// An encode of a recording this replay makes reads it where the replay writes it; any other
|
||||
// source stays where it is.
|
||||
if (tool == "encode_recording" && has_path("path"))
|
||||
if (tool == "recording_encode" && has_path("path"))
|
||||
if (auto it = recordings.find(path_compare_key(path_from_utf8(args["path"].get<std::string>()))); it != recordings.end())
|
||||
args["path"] = it->second;
|
||||
if (e.unawaited()) {
|
||||
@@ -254,7 +252,7 @@ nlohmann::json Journal::to_replay(const std::string& name, nlohmann::json* left_
|
||||
step["save_as"] = job_name;
|
||||
}
|
||||
if (e.answers_dialog)
|
||||
steps.push_back({{"tool", "wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}});
|
||||
steps.push_back({{"tool", "app_wait"}, {"args", {{"for", "dialog"}, {"timeout_s", 50}}}, {"expect", {{"/satisfied", {{"eq", true}}}}}});
|
||||
steps.push_back(std::move(step));
|
||||
}
|
||||
return {{"orca_replay_version", REPLAY_VERSION}, {"name", name}, {"steps", std::move(steps)}};
|
||||
|
||||
@@ -14,14 +14,14 @@
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// `args` of a call of `command` as the journal records them: without the command's id_args (expected object
|
||||
// and part ids), as ids are allocated per process and a replay addresses by index. So are a call_tool call's
|
||||
// arguments for its target and a run_replay's inline steps. The arguments of any other command stay as
|
||||
// written: a plugin operation's own fields, and a run_script call's code and args, since a script reads the
|
||||
// and part ids), as ids are allocated per process and a replay addresses by index. So are a tool_call call's
|
||||
// arguments for its target and a replay_run's inline steps. The arguments of any other command stay as
|
||||
// written: a plugin operation's own fields, and a script_run call's code and args, since a script reads the
|
||||
// ids it uses.
|
||||
nlohmann::json without_expected_ids(const CommandCatalog& catalog, const std::string& command, nlohmann::json args);
|
||||
|
||||
// The session's client calls, in the order they were made, for export_replay. A call that returned
|
||||
// a job envelope is replayed with `await:false` and a name its later `wait` refers to, so a step
|
||||
// The session's client calls, in the order they were made, for replay_export. A call that returned
|
||||
// a job envelope is replayed with `await:false` and a name its later `app_wait` refers to, so a step
|
||||
// that opened a dialog can be followed by the steps that answered it. An input call that only listed
|
||||
// the menu it opened is kept, since it may have changed the selection, unless the next call repeats
|
||||
// it with a popup_item.
|
||||
@@ -32,21 +32,21 @@ nlohmann::json without_expected_ids(const CommandCatalog& catalog, const std::st
|
||||
// in the replay whatever becomes of it, since the steps after it answer that dialog. So does a job
|
||||
// that was running while a later call answered a dialog: the dialog may be one the job opened, after
|
||||
// its reply or before it, and the answer depends on it. Such a job replays with `await:false`, and a
|
||||
// call that answered a dialog replays after a `wait {for:"dialog"}`, since the dialog may open later
|
||||
// call that answered a dialog replays after an `app_wait {for:"dialog"}`, since the dialog may open later
|
||||
// than the job's replayed reply. Thread-safe. It records the arguments it is given, which McpCore gives it
|
||||
// through without_expected_ids().
|
||||
class Journal
|
||||
{
|
||||
public:
|
||||
// Starts an entry; returns its sequence number. Calls made by replays and scripts are not recorded.
|
||||
// `answers_dialog`: the call acts while a modal dialog is open (answer_dialog, input to it).
|
||||
// `answers_dialog`: the call acts while a modal dialog is open (dialog_answer, input to it).
|
||||
uint64_t begin(const std::string& tool, const nlohmann::json& args, bool answers_dialog = false);
|
||||
void set_args(uint64_t seq, nlohmann::json args);
|
||||
// The call's reply.
|
||||
void end(uint64_t seq, const ToolResult& result);
|
||||
// The call runs as `job`; its outcome is open until job_ended().
|
||||
void job_started(uint64_t seq, const std::string& job);
|
||||
// The job's final result, reported before a `wait` on the job can see it, so an export right
|
||||
// The job's final result, reported before an `app_wait` on the job can see it, so an export right
|
||||
// after that wait already knows the outcome.
|
||||
void job_ended(uint64_t seq, const ToolResult& result);
|
||||
void clear();
|
||||
|
||||
@@ -9,7 +9,7 @@ inline constexpr int kDefaultPort = 13619;
|
||||
|
||||
// The app config key of the unrestricted Python scripts setting: one switch, off unless true. While it is on,
|
||||
// or the command line's --unrestricted-scripts is, the scripts a person runs (the Run Script panel, --run) and
|
||||
// agents send (run_script) skip the plugin permission checks. Only the window show_python_scripts_dialog() opens
|
||||
// agents send (script_run) skip the plugin permission checks. Only the window show_python_scripts_dialog() opens
|
||||
// writes it; no tool and no command line option does.
|
||||
inline constexpr char kPythonUnrestrictedKey[] = "python_scripts_unrestricted";
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
#include <utility>
|
||||
|
||||
// The contexts a command runs with besides the MCP core's own: a person's pick, and a Speed Dial tile that
|
||||
// run_action runs. No wx here, so that unit tests can include it (the slic3rutils tile case does).
|
||||
// action_run runs. No wx here, so that unit tests can include it (the slic3rutils tile case does).
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// A person's pick from the Speed Dial or a menu, on the UI thread and outside the automation runtime's dispatch
|
||||
@@ -41,13 +41,19 @@ public:
|
||||
void begin_operation() override {}
|
||||
};
|
||||
|
||||
// What run_action runs a command's tile with: the context of run_action's own call, except that a command
|
||||
// that rewrites its journal entry does so inside run_action's, as {"id": <the tile's action id>, "args": ...},
|
||||
// so that a replay runs the tile again through run_action.
|
||||
// What action_run runs a command's tile with: the context of action_run's own call, except that a command
|
||||
// that rewrites its journal entry does so inside action_run's, as {"id": <the tile's action id>, "args": ...},
|
||||
// so that a replay runs the tile again through action_run. A tile of fixed arguments (an item of a command's tiles, a
|
||||
// Design command's folded rows among them, or a command's own tile outside the Design tab) records `tile_args` there in
|
||||
// place of the command's rewrite: what action_run takes for it (tile_journal_args()). action_run refuses any other
|
||||
// arguments for such a tile, and so would refuse the replay of a rewrite (object_arrange's adds the settings in
|
||||
// force). A Design command's own tile, which takes its command's arguments, has none, and the command's rewrite stands.
|
||||
class TileContext final : public ToolContext
|
||||
{
|
||||
public:
|
||||
TileContext(ToolContext& call, std::string action_id) : m_call(call), m_id(std::move(action_id)) {}
|
||||
TileContext(ToolContext& call, std::string action_id, nlohmann::json tile_args = nullptr)
|
||||
: m_call(call), m_id(std::move(action_id)), m_tile_args(std::move(tile_args))
|
||||
{}
|
||||
|
||||
bool person() const override { return m_call.person(); }
|
||||
AutomationRuntime& runtime() override { return m_call.runtime(); }
|
||||
@@ -60,15 +66,16 @@ public:
|
||||
std::set<std::string> lineage() const override { return m_call.lineage(); }
|
||||
void set_journal_args(nlohmann::json args) override
|
||||
{
|
||||
m_call.set_journal_args({{"id", m_id}, {"args", std::move(args)}});
|
||||
m_call.set_journal_args({{"id", m_id}, {"args", m_tile_args.is_null() ? std::move(args) : m_tile_args}});
|
||||
}
|
||||
void begin_operation() override { m_call.begin_operation(); }
|
||||
void works_in_dialog(std::uint64_t dialog) override { m_call.works_in_dialog(dialog); }
|
||||
const std::string& caller_plugin() const override { return m_call.caller_plugin(); }
|
||||
|
||||
private:
|
||||
ToolContext& m_call;
|
||||
std::string m_id;
|
||||
ToolContext& m_call;
|
||||
std::string m_id;
|
||||
nlohmann::json m_tile_args;
|
||||
};
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -53,7 +53,7 @@ void PersonRun::stop()
|
||||
if (job.empty() || m_runtime.stopping())
|
||||
return;
|
||||
m_runtime.jobs().request_stop(job);
|
||||
// The step's own operation stops too, as cancel_job stops it.
|
||||
// The step's own operation stops too, as job_cancel stops it.
|
||||
m_runtime.cancel_operations_of(job);
|
||||
}
|
||||
|
||||
@@ -86,14 +86,14 @@ void PersonRun::post_finished(nlohmann::json result, nlohmann::json jobs)
|
||||
std::shared_ptr<PersonRun> start_replay_run(AutomationRuntime& runtime, Replay replay, ReplayContext sctx,
|
||||
std::optional<std::size_t> only_step, bool discard_authorized, PersonRun::Events events)
|
||||
{
|
||||
const NativeCommand* run_replay_def = NativeCommands::instance().find("run_replay");
|
||||
const NativeCommand* run_replay_def = NativeCommands::instance().find("replay_run");
|
||||
if (run_replay_def == nullptr || runtime.stopping())
|
||||
return nullptr;
|
||||
|
||||
auto run = std::make_shared<PersonRun>(runtime, std::move(events));
|
||||
auto shared = std::make_shared<Replay>(std::move(replay));
|
||||
auto ctx_held = std::make_shared<ReplayContext>(std::move(sctx));
|
||||
// run_replay's properties, outside the session journal: a person's run is not an agent's call.
|
||||
// replay_run's properties, outside the session journal: a person's run is not an agent's call.
|
||||
NativeCommand def = *run_replay_def;
|
||||
def.journal = false;
|
||||
def.run = [&runtime, run, shared, ctx_held, only_step, discard_authorized](const json&, ToolContext& ctx) {
|
||||
|
||||
@@ -28,7 +28,7 @@ public:
|
||||
{
|
||||
std::function<void(std::size_t index)> step_started;
|
||||
std::function<void(const nlohmann::json& entry)> step_finished;
|
||||
// Exactly once: run_replay's result, or {"error": message} when the run failed as a call (refused,
|
||||
// Exactly once: replay_run's result, or {"error": message} when the run failed as a call (refused,
|
||||
// or its job ended in an error or was lost); `jobs` are the jobs the run saved, for later steps,
|
||||
// or null when it was refused before it started.
|
||||
std::function<void(const nlohmann::json& result, const nlohmann::json& jobs)> finished;
|
||||
@@ -38,7 +38,7 @@ public:
|
||||
|
||||
// UI thread. Latches the stop, so one asked before the job exists still counts, stops the job's lineage
|
||||
// once it is known (JobRegistry::request_stop), and cancels the run's operation (a slice, an export, a
|
||||
// background job) as cancel_job does. Does nothing once the runtime is stopping.
|
||||
// background job) as job_cancel does. Does nothing once the runtime is stopping.
|
||||
void stop();
|
||||
// UI thread: the events are dropped from now on; the run carries on to its end.
|
||||
void detach();
|
||||
@@ -63,7 +63,7 @@ private:
|
||||
std::atomic<bool> m_running{true};
|
||||
};
|
||||
|
||||
// Runs a replay for the Action Replay window: an unjournaled mutate job, as run_replay runs one, whose steps
|
||||
// Runs a replay for the Action Replay window: an unjournaled mutate job, as replay_run runs one, whose steps
|
||||
// report through `events`. `runtime` follows the job to its end, past a running or blocked_by_dialog reply, and
|
||||
// posts `finished`. `only_step` runs one step (no result.json). `discard_authorized`: the user chose not to save
|
||||
// before a run that replaces the project, so the replacing tools may drop unsaved changes while it runs. nullptr
|
||||
|
||||
@@ -66,18 +66,18 @@ int base64_value(char c)
|
||||
|
||||
} // namespace
|
||||
|
||||
// ---- call_tool ----------------------------------------------------------------
|
||||
// ---- tool_call ----------------------------------------------------------------
|
||||
|
||||
std::string resolve_call(const CommandCatalog& catalog, std::shared_ptr<const NativeCommand>& command, json& args)
|
||||
{
|
||||
if (!command || command->key != "call_tool")
|
||||
if (!command || command->key != "tool_call")
|
||||
return {};
|
||||
const std::string target = args.value("tool", std::string());
|
||||
std::shared_ptr<const NativeCommand> inner = catalog.lookup(target);
|
||||
if (!inner)
|
||||
return catalog.unknown_command(target, /*suggest=*/true);
|
||||
if (inner->key == "call_tool")
|
||||
return "call_tool calls another tool, not itself";
|
||||
if (inner->key == "tool_call")
|
||||
return "tool_call calls another tool, not itself";
|
||||
json inner_args = args.contains("args") && args["args"].is_object() ? args["args"] : json::object();
|
||||
if (std::string err = argument_error(*inner, inner_args); !err.empty())
|
||||
return "Invalid arguments for " + target + ": " + err;
|
||||
|
||||
@@ -286,7 +286,7 @@ bool capture_area(ModalTracker& modals, bool suspended, Recording& rec, const Ca
|
||||
if (rec.options.target == "canvas") {
|
||||
GLCanvas3D* canvas = shown_canvas();
|
||||
if (canvas == nullptr || canvas->get_wxglcanvas() == nullptr) {
|
||||
err = "No 3D view is shown; switch to one with set_view tab";
|
||||
err = "No 3D view is shown; switch to one with view_set tab";
|
||||
return false;
|
||||
}
|
||||
std::optional<Capture> cap = capture_canvas(*canvas, err, options);
|
||||
@@ -453,7 +453,7 @@ json McpRecorder::start(const RecordingOptions& options, uint64_t files_owner)
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (m_rec && !m_rec->sink->finalized())
|
||||
throw ToolFailure("A recording is already running (" + path_to_utf8(m_rec->options.path) + "); stop_recording ends it");
|
||||
throw ToolFailure("A recording is already running (" + path_to_utf8(m_rec->options.path) + "); recording_stop ends it");
|
||||
previous = m_rec;
|
||||
}
|
||||
if (previous) {
|
||||
@@ -787,7 +787,7 @@ json McpRecorder::stop_and_report(std::chrono::milliseconds timeout, json& encod
|
||||
}
|
||||
end_recording(rec, "stopped");
|
||||
if (!rec->sink->wait_finalized(timeout))
|
||||
throw ToolFailure("The recording is still being written to " + path_to_utf8(rec->options.path) + "; call stop_recording again");
|
||||
throw ToolFailure("The recording is still being written to " + path_to_utf8(rec->options.path) + "; call recording_stop again");
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
rec->reported = true;
|
||||
@@ -828,7 +828,7 @@ bool McpRecorder::wait_closed(const fs::path& path, std::chrono::milliseconds ti
|
||||
|
||||
bool McpRecorder::encode_when_closed(AutomationRuntime& runtime, json args, std::function<void(const ToolResult&)> done)
|
||||
{
|
||||
const NativeCommand* encode = NativeCommands::instance().find("encode_recording");
|
||||
const NativeCommand* encode = NativeCommands::instance().find("recording_encode");
|
||||
if (encode == nullptr || runtime.stopping())
|
||||
return false;
|
||||
FollowedCall call;
|
||||
@@ -901,10 +901,10 @@ void McpRecorder::call_started(uint64_t call, const NativeCommand& def, const js
|
||||
std::lock_guard<std::mutex> lock(m_mutex);
|
||||
if (!m_rec || m_rec->ending || !m_rec->options.captions)
|
||||
return;
|
||||
// A call with a folded row's arguments is captioned as that row's tile.
|
||||
const char* context = title_context(def);
|
||||
m_rec->board.call_started(call, call_title(def, args), safe_caption_detail(def.key, args), Clock::now(),
|
||||
context != nullptr ? context : "");
|
||||
// A tile's call is captioned with the tile's title: action_run of it, or its command called with its arguments.
|
||||
const auto [title, titled] = shown_title(NativeCommands::instance(), def, args);
|
||||
const char* context = title_context(*titled);
|
||||
m_rec->board.call_started(call, title, safe_caption_detail(def.key, args), Clock::now(), context != nullptr ? context : "");
|
||||
m_captioned[call] = {def.key, {args}};
|
||||
}
|
||||
|
||||
@@ -1020,7 +1020,7 @@ void McpRecorder::on_event(wxEvent& event)
|
||||
return;
|
||||
}
|
||||
|
||||
// A real click sent its press first; a command alone is a click made without the mouse (click).
|
||||
// A real click sent its press first; a command alone is a click made without the mouse (widget_click).
|
||||
wxWindow* pressed = in.pressed_window.get();
|
||||
if (pressed != nullptr && now - in.pressed_at < kSemanticClick && (pressed == window || window->IsDescendant(pressed)))
|
||||
return;
|
||||
|
||||
@@ -44,7 +44,7 @@ wxFont font_with_line_height(const wxFont& font, int line_height);
|
||||
// the coverage. Null for no text. UI thread.
|
||||
std::shared_ptr<const TextMask> render_text(const std::string& text, const wxFont& font, int max_width);
|
||||
|
||||
// start_recording's arguments.
|
||||
// recording_start's arguments.
|
||||
struct RecordingOptions
|
||||
{
|
||||
std::string target = "main"; // main | canvas
|
||||
@@ -56,7 +56,7 @@ struct RecordingOptions
|
||||
bool pointer = false; // the pointer highlighted, its clicks rippling
|
||||
boost::filesystem::path path;
|
||||
std::string owner; // the job of the run (a replay or a script) that started it, "" for a client, kPersonOwner
|
||||
// encode_recording's arguments, path included, for the stop_recording that reports this recording to run;
|
||||
// recording_encode's arguments, path included, for the recording_stop that reports this recording to run;
|
||||
// null for none.
|
||||
nlohmann::json encode;
|
||||
// Runs on the UI thread once the recording ends, while its file is still being closed, with the reason it
|
||||
@@ -104,20 +104,20 @@ public:
|
||||
// Any thread. Ends the recording `owner` started ("" for a client's), and with `wait`, waits up to 30 s
|
||||
// for its file to be closed. Returns the path of a file still being written after that wait.
|
||||
std::optional<std::string> end_owned_by(const std::string& owner, const std::string& reason, bool wait);
|
||||
// stop_recording: ends the running recording and waits for its file, or takes the result of the last
|
||||
// recording_stop: ends the running recording and waits for its file, or takes the result of the last
|
||||
// one that ended on its own, once. Null when there is none. `encode` gets the recording's
|
||||
// RecordingOptions::encode.
|
||||
nlohmann::json stop_and_report(std::chrono::milliseconds timeout, nlohmann::json& encode);
|
||||
// get_app_state's recording: {path, target, seconds, frames} while one runs, else null.
|
||||
// app_state's recording: {path, target, seconds, frames} while one runs, else null.
|
||||
nlohmann::json state() const;
|
||||
// A recording is being written or finalized.
|
||||
bool active() const;
|
||||
// Any thread. Waits up to `timeout` for the recording at `path` to have its file closed; true once it has,
|
||||
// or when that recording is not the latest, since another starts only after it is closed.
|
||||
bool wait_closed(const boost::filesystem::path& path, std::chrono::milliseconds timeout) const;
|
||||
// Any thread. Encodes a recording once its file is closed: encode_recording with `args` as an unjournaled job,
|
||||
// Any thread. Encodes a recording once its file is closed: recording_encode with `args` as an unjournaled job,
|
||||
// which `runtime` follows to its end before posting `done` its result on the UI thread. The job is cancelled
|
||||
// like any encode (cancel_job {job}, the runtime's stop), and `done` is not called once the runtime stops.
|
||||
// like any encode (job_cancel {job}, the runtime's stop), and `done` is not called once the runtime stops.
|
||||
// False when the runtime is not started or is stopping, or when the system cannot start a thread.
|
||||
bool encode_when_closed(AutomationRuntime& runtime, nlohmann::json args, std::function<void(const ToolResult&)> done);
|
||||
// The files recordings and encodes use; shared with the sinks' finalizers.
|
||||
|
||||
@@ -75,7 +75,7 @@ std::optional<json> resolve_placeholder(const std::string& key, const Replay& re
|
||||
}
|
||||
|
||||
// How a substitution went: in lenient mode an unresolvable placeholder is kept as written; otherwise
|
||||
// the first one fails the substitution and is recorded here, so run_replay can say why.
|
||||
// the first one fails the substitution and is recorded here, so replay_run can say why.
|
||||
struct Substitution
|
||||
{
|
||||
bool lenient = false;
|
||||
@@ -315,7 +315,7 @@ std::optional<Replay> parse_replay(const std::string& text, std::string& err)
|
||||
}
|
||||
|
||||
// A step's arguments with their placeholders filled in, except Python source, which runs as written (D7):
|
||||
// the code of a run_script call, of one a call_tool makes, and of the Python steps of an inline replay.
|
||||
// the code of a script_run call, of one a tool_call makes, and of the Python steps of an inline replay.
|
||||
json substitute_args(const std::string& tool, const json& args, const Replay& replay, const ReplayContext& ctx, Substitution& sub)
|
||||
{
|
||||
if (!args.is_object())
|
||||
@@ -323,12 +323,12 @@ json substitute_args(const std::string& tool, const json& args, const Replay& re
|
||||
json out = json::object();
|
||||
for (auto it = args.begin(); it != args.end(); ++it) {
|
||||
const std::string& key = it.key();
|
||||
if (tool == "run_script" && key == "code") {
|
||||
if (tool == "script_run" && key == "code") {
|
||||
out[key] = it.value();
|
||||
} else if (tool == "call_tool" && key == "args" && it.value().is_object()) {
|
||||
} else if (tool == "tool_call" && key == "args" && it.value().is_object()) {
|
||||
const json target = substitute_value(args.value("tool", json()), replay, ctx, sub, 0);
|
||||
out[key] = substitute_args(target.is_string() ? target.get<std::string>() : std::string(), it.value(), replay, ctx, sub);
|
||||
} else if (tool == "run_replay" && key == "replay" && it.value().is_object() && it.value().contains("steps") &&
|
||||
} else if (tool == "replay_run" && key == "replay" && it.value().is_object() && it.value().contains("steps") &&
|
||||
it.value()["steps"].is_array()) {
|
||||
json nested = json::object();
|
||||
for (auto field = it.value().begin(); field != it.value().end(); ++field) {
|
||||
@@ -472,7 +472,7 @@ json run_replay(const Replay& replay, ReplayContext& ctx, const ReplayHost& host
|
||||
if (const json dialogs = host.open_dialogs ? host.open_dialogs() : json::array();
|
||||
dialogs.is_array() && !dialogs.empty()) {
|
||||
message += " with the dialog \"" + dialogs.back().value("title", std::string()) +
|
||||
"\" open: a step can't answer a dialog it opens, so register an auto_answer_dialogs rule for it "
|
||||
"\" open: a step can't answer a dialog it opens, so register a dialog_auto_answer rule for it "
|
||||
"before the step, or give the step \"await\": false and answer the dialog in the steps after it";
|
||||
details["dialogs"] = dialogs;
|
||||
}
|
||||
@@ -488,11 +488,11 @@ json run_replay(const Replay& replay, ReplayContext& ctx, const ReplayHost& host
|
||||
bool ok = !result.is_error;
|
||||
if (ok) {
|
||||
entry["result"] = result.data;
|
||||
// run_script reports a script that raised, was cancelled or ran out of time in a successful
|
||||
// result, as run_replay reports a failed step; inside a replay that fails the step, also when an
|
||||
// call_tool made the call. A job left running (await: false) has no outcome yet.
|
||||
const std::string target = step.tool == "call_tool" ? args.value("tool", std::string()) : step.tool;
|
||||
if (target == "run_script" && !is_job_envelope(result) && result.data.value("status", "") != "finished") {
|
||||
// script_run reports a script that raised, was cancelled or ran out of time in a successful
|
||||
// result, as replay_run reports a failed step; inside a replay that fails the step, also when an
|
||||
// tool_call made the call. A job left running (await: false) has no outcome yet.
|
||||
const std::string target = step.tool == "tool_call" ? args.value("tool", std::string()) : step.tool;
|
||||
if (target == "script_run" && !is_job_envelope(result) && result.data.value("status", "") != "finished") {
|
||||
entry["error"] = result.data.value("message", "the Python script did not finish");
|
||||
reason = {{"kind", "python"}, {"status", result.data.value("status", "")}};
|
||||
ok = false;
|
||||
|
||||
@@ -42,14 +42,15 @@ struct ReplayContext
|
||||
|
||||
// The version of the replay format this build writes, the semver string a replay gives as "orca_replay_version".
|
||||
// A replay is read when it has this major version and a minor version no newer than this one; while the major
|
||||
// version is 0, every minor version may break, so only this minor version is read. The editor's draft and key
|
||||
// suggestions write the same version (REPLAY_VERSION in resources/web/dialog/ActionReplay/replay_editor.js).
|
||||
inline constexpr const char* REPLAY_VERSION = "0.1.0";
|
||||
// version is 0, every minor version may break, so only this minor version is read. A replay of another format, whose
|
||||
// steps may name commands this build does not have, is refused for its format before any step is read. The editor's
|
||||
// draft and key suggestions write the same version (REPLAY_VERSION in resources/web/dialog/ActionReplay/replay_editor.js).
|
||||
inline constexpr const char* REPLAY_VERSION = "0.2.0";
|
||||
|
||||
// Parses a replay (JSON with // and /* */ comments). nullopt with `err` set when invalid.
|
||||
std::optional<Replay> parse_replay(const std::string& text, std::string& err);
|
||||
|
||||
// The text of a run_replay inline replay, which is given as the replay object or as its JSON text.
|
||||
// The text of a replay_run inline replay, which is given as the replay object or as its JSON text.
|
||||
std::string inline_replay_text(const nlohmann::json& replay);
|
||||
|
||||
// Replaces ${replay_dir}, ${out_dir}, ${env:NAME}, ${vars.NAME} and ${jobs.NAME} in every string of
|
||||
@@ -80,7 +81,7 @@ struct ExpectFailure
|
||||
};
|
||||
std::optional<ExpectFailure> check_expect_detail(const nlohmann::json& result, const nlohmann::json& expect);
|
||||
|
||||
// What run_replay needs from its host: calling a tool as a child of the replay's job, waiting for
|
||||
// What replay_run needs from its host: calling a tool as a child of the replay's job, waiting for
|
||||
// a job's result, and dropping replay-scoped dialog auto-answer rules when the replay ends.
|
||||
// step_started and step_finished, when set, report each step as it runs: step_started (1-based
|
||||
// index) before its arguments are substituted, step_finished with the entry as it goes into the
|
||||
@@ -93,7 +94,7 @@ struct ReplayHost
|
||||
std::function<bool()> cancelled;
|
||||
std::function<void(std::size_t index)> step_started;
|
||||
std::function<void(const nlohmann::json& entry)> step_finished;
|
||||
// The open modal dialogs, topmost last, as get_app_state lists them. Optional.
|
||||
// The open modal dialogs, topmost last, as app_state lists them. Optional.
|
||||
std::function<nlohmann::json()> open_dialogs;
|
||||
};
|
||||
|
||||
|
||||
@@ -116,8 +116,6 @@ std::pair<std::string, std::string> split_action_id(const std::string& id)
|
||||
return {id.substr(0, first), id.substr(first + 1, last - first - 1)};
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const char* prefix) { return s.rfind(prefix, 0) == 0; }
|
||||
|
||||
bool one_of(const std::string& s, std::initializer_list<const char*> names)
|
||||
{
|
||||
for (const char* n : names)
|
||||
@@ -126,8 +124,34 @@ bool one_of(const std::string& s, std::initializer_list<const char*> names)
|
||||
return false;
|
||||
}
|
||||
|
||||
// The effects of command `key` called with `args`, whichever way it is called: the files it writes, the presets it
|
||||
// changes, what it sends to a printer.
|
||||
void flag_effects(Builder& b, const std::string& key, const json& args)
|
||||
{
|
||||
if (one_of(key, {"project_save", "project_export", "preset_export"}))
|
||||
b.flag(StepFlag::WritesFile);
|
||||
// The preset bundle manager imports and deletes bundles of presets.
|
||||
const bool preset_bundle = key == "window_open" && args.is_object() && args.value("window", std::string()) == "preset_bundle";
|
||||
if (one_of(key, {"preset_import", "preset_sync"}) || preset_bundle)
|
||||
b.flag(StepFlag::ChangesPresets);
|
||||
if (key == "printer_send")
|
||||
b.flag(StepFlag::SendsToPrinter);
|
||||
}
|
||||
|
||||
// Each argument of `args` as "name: value", the file of a path by its name.
|
||||
json argument_texts(const json& args)
|
||||
{
|
||||
json texts = json::array();
|
||||
for (const auto& [name, value] : args.items()) {
|
||||
const bool file = name == "path" && value.is_string();
|
||||
texts.push_back(name + ": " + (file ? file_name(value.get<std::string>()) : value.is_string() ? value.get<std::string>() : value.dump()));
|
||||
}
|
||||
return texts;
|
||||
}
|
||||
|
||||
// A call of command `key` with `args`, or of its tile `tile` (one of its tiles, which runs it with `args`): a call
|
||||
// whose arguments are a tile's is that tile, `tile` or else the first with them (tile_with_args()).
|
||||
// whose arguments are a tile's is that tile, `tile` or else the first with them (tile_with_args()). A tile that
|
||||
// collects a value is described with the call's arguments, which hold that value.
|
||||
void describe_command(Builder& b, const CommandCatalog& catalog, const std::string& key, const json& args,
|
||||
const json* tile = nullptr)
|
||||
{
|
||||
@@ -135,48 +159,40 @@ void describe_command(Builder& b, const CommandCatalog& catalog, const std::stri
|
||||
if (tile == nullptr)
|
||||
if (const NativeCommand* command = catalog.find(key))
|
||||
tile = tile_with_args(*command, args);
|
||||
if (tile != nullptr) {
|
||||
if (tile != nullptr)
|
||||
what["tile"] = tile->at("key");
|
||||
} else if (args.is_object() && !args.empty()) {
|
||||
// Each argument as "name: value", the file of a path by its name.
|
||||
json texts = json::array();
|
||||
for (const auto& [name, value] : args.items()) {
|
||||
const bool file = name == "path" && value.is_string();
|
||||
texts.push_back(name + ": " +
|
||||
(file ? file_name(value.get<std::string>()) : value.is_string() ? value.get<std::string>() : value.dump()));
|
||||
}
|
||||
what["args"] = std::move(texts);
|
||||
}
|
||||
if ((tile == nullptr || !tile->value("input", std::string()).empty()) && args.is_object() && !args.empty())
|
||||
what["args"] = argument_texts(args);
|
||||
b.d.what = std::move(what);
|
||||
|
||||
if (starts_with(key, "calib_")) {
|
||||
// What the command's tile does, as a person's pick of it: a calibration test's dialog, which then replaces the
|
||||
// project and changes the presets, and Load Project and New Project, which ask about unsaved changes.
|
||||
if (key == "calibration_generate_test") {
|
||||
b.flag(StepFlag::ReplacesProject);
|
||||
b.flag(StepFlag::ChangesPresets);
|
||||
b.replace("app_asked");
|
||||
}
|
||||
if (one_of(key, {"load_project", "new_project"})) {
|
||||
if (one_of(key, {"project_open", "project_new"})) {
|
||||
b.flag(StepFlag::ReplacesProject);
|
||||
b.replace("app_asked");
|
||||
}
|
||||
if (one_of(key, {"save_project", "save_project_as", "export_config"}) || starts_with(key, "export_"))
|
||||
b.flag(StepFlag::WritesFile);
|
||||
if (one_of(key, {"import_configs", "preset_bundle", "sync_presets"}))
|
||||
b.flag(StepFlag::ChangesPresets);
|
||||
if (key == "send_gcode")
|
||||
b.flag(StepFlag::SendsToPrinter);
|
||||
flag_effects(b, key, args);
|
||||
}
|
||||
|
||||
void describe_action(Builder& b, const CommandCatalog& catalog, const json& args)
|
||||
{
|
||||
const std::string id = args.contains("id") && args["id"].is_string() ? args["id"].get<std::string>() : std::string();
|
||||
const std::string id = args.contains("id") && args["id"].is_string() ? args["id"].get<std::string>() : std::string();
|
||||
const json given = args.contains("args") ? args["args"] : json();
|
||||
// A command's tile, by its full id or by the key inside it, as action_run takes either: a folded row's tile runs its
|
||||
// command with the row's arguments, and the value it collects when it has one, as a person's pick of it does.
|
||||
if (const auto [command, tile] = find_tile(catalog, command_tile_key(id)); command != nullptr) {
|
||||
describe_command(b, catalog, command->key, tile_call_args(tile, given), tile);
|
||||
return;
|
||||
}
|
||||
const auto [prefix, middle] = split_action_id(id);
|
||||
if (prefix == kCommandPrefix) {
|
||||
// A folded row's tile runs its command with the row's arguments, whatever run_action was given.
|
||||
const auto [command, tile] = find_tile(catalog, middle);
|
||||
if (tile != nullptr)
|
||||
describe_command(b, catalog, command->key, tile->at("args"), tile);
|
||||
else
|
||||
describe_command(b, catalog, middle, args.contains("args") ? args["args"] : json());
|
||||
// A tile `catalog` does not hold (a Design tile of a run without the Design tab), by the key in its id.
|
||||
describe_command(b, catalog, middle, given);
|
||||
} else if (prefix == "orca_recent_project") {
|
||||
b.d.what = {{"kind", "recent_project"}, {"name", file_name(middle)}};
|
||||
b.flag(StepFlag::ReplacesProject);
|
||||
@@ -192,13 +208,15 @@ void describe_action(Builder& b, const CommandCatalog& catalog, const json& args
|
||||
}
|
||||
}
|
||||
|
||||
// A command of `catalog` with no typed tool's place in the tool list called as one of its tiles: with a tile of its
|
||||
// own (load_project, export_stl), or with the arguments of a tile that runs it with them (a Design command's folded
|
||||
// row). Called so, it does what run_action of that tile does.
|
||||
// A command of `catalog` called as one of its tiles: with the arguments of a tile that runs it with them (a menu row
|
||||
// folded into it), or with none, as its tile of its own (plate_delete). A command with a tile of its own that the tool
|
||||
// list does not show (a Design command) is its tile's call whatever its arguments. Called so, it does what action_run
|
||||
// of that tile does.
|
||||
bool tile_command(const CommandCatalog& catalog, const std::string& tool, const json& args)
|
||||
{
|
||||
const NativeCommand* command = catalog.find(tool);
|
||||
return command != nullptr && !command->listed && (command->in_palette || tile_with_args(*command, args) != nullptr);
|
||||
return command != nullptr && (tile_with_args(*command, args) != nullptr ||
|
||||
(command->in_palette && (!command->listed || person_form(args))));
|
||||
}
|
||||
|
||||
std::optional<std::string> read_text(const fs::path& path)
|
||||
@@ -211,7 +229,7 @@ std::optional<std::string> read_text(const fs::path& path)
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
// A run_replay step: the nested replay, read in the context its run will have.
|
||||
// A replay_run step: the nested replay, read in the context its run will have.
|
||||
void describe_nested(Builder& b, const CommandCatalog& catalog, const json& args, const ReplayContext& outer, int depth)
|
||||
{
|
||||
std::optional<Replay> nested;
|
||||
@@ -271,13 +289,13 @@ json describe_what(const std::string& tool, const json& args)
|
||||
return {{"kind", "value"}, {"text", args[key].is_string() ? args[key].get<std::string>() : args[key].dump()}};
|
||||
return nullptr;
|
||||
};
|
||||
if (one_of(tool, {"select_preset", "save_preset", "delete_preset"}) && args.contains("name") && args["name"].is_string())
|
||||
if (one_of(tool, {"preset_select", "preset_save", "preset_delete"}) && args.contains("name") && args["name"].is_string())
|
||||
return {{"kind", "preset"}, {"name", args["name"]}};
|
||||
if (one_of(tool, {"slice", "arrange"}))
|
||||
return {{"kind", "plates"}, {"plates", args.contains("plates") ? args["plates"] : json(tool == "slice" ? "current" : "all")}};
|
||||
if (tool == "wait")
|
||||
if (one_of(tool, {"plate_slice", "object_arrange"}))
|
||||
return {{"kind", "plates"}, {"plates", args.contains("plates") ? args["plates"] : json(tool == "plate_slice" ? "current" : "all")}};
|
||||
if (tool == "app_wait")
|
||||
return text("for");
|
||||
if (tool == "answer_dialog")
|
||||
if (tool == "dialog_answer")
|
||||
return text("button");
|
||||
if (args.contains("paths") && args["paths"].is_array()) {
|
||||
json names = json::array();
|
||||
@@ -302,7 +320,7 @@ json describe_what(const std::string& tool, const json& args)
|
||||
|
||||
json describe_call(const CommandCatalog& catalog, const std::string& tool, const json& args)
|
||||
{
|
||||
if (tool == "run_action") {
|
||||
if (tool == "action_run") {
|
||||
Builder b;
|
||||
describe_action(b, catalog, args);
|
||||
return b.d.what;
|
||||
@@ -312,7 +330,7 @@ json describe_call(const CommandCatalog& catalog, const std::string& tool, const
|
||||
describe_command(b, catalog, tool, args);
|
||||
return b.d.what;
|
||||
}
|
||||
if (tool == "run_replay")
|
||||
if (tool == "replay_run")
|
||||
return args.contains("path") && args["path"].is_string() ? json{{"kind", "files"}, {"names", {file_name(args["path"].get<std::string>())}}} :
|
||||
json();
|
||||
return describe_what(tool, args);
|
||||
@@ -337,11 +355,11 @@ StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& s
|
||||
Builder b;
|
||||
b.d.checks_result = !step.expect.empty();
|
||||
|
||||
if (tool == "run_action") {
|
||||
if (tool == "action_run") {
|
||||
describe_action(b, catalog, args);
|
||||
return b.done();
|
||||
}
|
||||
if (tool == "run_replay") {
|
||||
if (tool == "replay_run") {
|
||||
describe_nested(b, catalog, args, ctx, depth);
|
||||
return b.done();
|
||||
}
|
||||
@@ -356,46 +374,46 @@ StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& s
|
||||
if (args.contains(key) && args[key].is_string() && !inside(args[key].get<std::string>(), ctx.out_dir))
|
||||
b.flag(StepFlag::WritesFile);
|
||||
};
|
||||
if (one_of(tool, {"export", "save_project"}))
|
||||
b.flag(StepFlag::WritesFile);
|
||||
if (one_of(tool, {"screenshot", "start_recording"}))
|
||||
flag_effects(b, tool, args);
|
||||
if (one_of(tool, {"window_screenshot", "recording_start"}))
|
||||
writes_outside("save_path");
|
||||
if (tool == "encode_recording") {
|
||||
if (tool == "recording_encode") {
|
||||
// Without save_path the video goes beside its source, which it deletes unless keep_raw_video_file.
|
||||
writes_outside(args.contains("save_path") ? "save_path" : "path");
|
||||
if (!(args.contains("keep_raw_video_file") && args["keep_raw_video_file"].is_boolean() && args["keep_raw_video_file"].get<bool>()))
|
||||
writes_outside("path");
|
||||
}
|
||||
if (tool == "export_replay")
|
||||
if (tool == "replay_export")
|
||||
writes_outside("path");
|
||||
if (tool == "pick_gizmo_file" && args.value("action", std::string()) == "svg_save_as")
|
||||
if (tool == "gizmo_pick_file" && args.value("action", std::string()) == "svg_save_as")
|
||||
writes_outside("path");
|
||||
// A rule's path lets a save picker write the file, or with overwrite replace it. Which picker a rule will
|
||||
// answer isn't known here, so every path counts.
|
||||
if (tool == "auto_answer_dialogs" && args.contains("rules") && args["rules"].is_array())
|
||||
if (tool == "dialog_auto_answer" && args.contains("rules") && args["rules"].is_array())
|
||||
for (const json& rule : args["rules"])
|
||||
if (rule.is_object() && rule.contains("path") && rule["path"].is_string() && !rule["path"].get<std::string>().empty() &&
|
||||
!inside(rule["path"].get<std::string>(), ctx.out_dir))
|
||||
b.flag(StepFlag::WritesFile);
|
||||
if (one_of(tool, {"save_preset", "delete_preset", "generate_calibration_test"}))
|
||||
if (one_of(tool, {"preset_save", "preset_delete", "calibration_generate_test"}))
|
||||
b.flag(StepFlag::ChangesPresets);
|
||||
if (one_of(tool, {"new_project", "generate_calibration_test"})) {
|
||||
if (one_of(tool, {"project_new", "calibration_generate_test"})) {
|
||||
b.flag(StepFlag::ReplacesProject);
|
||||
// new_project with no arguments is New Project's: the app asks about the unsaved changes.
|
||||
b.replace(tool == "new_project" && person_form(args) ? "app_asked" : "checked");
|
||||
// project_new with no arguments is New Project's: the app asks about the unsaved changes.
|
||||
b.replace(tool == "project_new" && person_form(args) ? "app_asked" : "checked");
|
||||
}
|
||||
if (tool == "open_files" && args.contains("paths") && args["paths"].is_array() && args["paths"].size() == 1 &&
|
||||
args["paths"][0].is_string()) {
|
||||
const std::string path = args["paths"][0].get<std::string>();
|
||||
// A project replaces the current one as discard_changes says; a G-code to look at, after the app asks about its
|
||||
// unsaved changes. project_open refuses any other file, which replaces nothing.
|
||||
if (tool == "project_open" && args.contains("path") && args["path"].is_string()) {
|
||||
const std::string path = args["path"].get<std::string>();
|
||||
if (has_extension(path, {".gcode", ".bgcode"})) {
|
||||
b.flag(StepFlag::ReplacesProject);
|
||||
b.replace("app_asked");
|
||||
} else if (has_extension(path, {".3mf"}) && args.value("as", std::string("auto")) != "geometry") {
|
||||
} else if (has_extension(path, {".3mf"})) {
|
||||
b.flag(StepFlag::ReplacesProject);
|
||||
b.replace("checked");
|
||||
}
|
||||
}
|
||||
b.d.answers_dialogs = one_of(tool, {"auto_answer_dialogs", "answer_dialog", "click", "press_keys"});
|
||||
b.d.answers_dialogs = one_of(tool, {"dialog_auto_answer", "dialog_answer", "widget_click", "keyboard_press"});
|
||||
return b.done();
|
||||
}
|
||||
|
||||
@@ -408,22 +426,22 @@ json describe_result(const std::string& tool, const json& result)
|
||||
return {{"kind", "file"}, {"name", file_name(result[key].get<std::string>())}};
|
||||
return nullptr;
|
||||
};
|
||||
if (tool == "open_files" && result.value("opened", std::string()) == "gcode")
|
||||
if (tool == "project_open" && result.value("opened", std::string()) == "gcode")
|
||||
return file_of("path");
|
||||
if (one_of(tool, {"open_files", "new_project", "generate_calibration_test"}) && result.contains("objects") &&
|
||||
if (one_of(tool, {"project_open", "project_import", "project_new", "calibration_generate_test"}) && result.contains("objects") &&
|
||||
result["objects"].is_number_integer())
|
||||
return {{"kind", "objects"}, {"count", result["objects"]}};
|
||||
if (tool == "slice" && result.contains("plates") && result["plates"].is_array()) {
|
||||
if (tool == "plate_slice" && result.contains("plates") && result["plates"].is_array()) {
|
||||
int ok = 0, other = 0;
|
||||
for (const json& p : result["plates"])
|
||||
(p.is_object() && p.value("outcome", std::string()) == "ok" ? ok : other)++;
|
||||
return {{"kind", "plates"}, {"ok", ok}, {"other", other}};
|
||||
}
|
||||
if (one_of(tool, {"export", "save_project", "screenshot"}))
|
||||
if (one_of(tool, {"project_export", "project_save", "window_screenshot"}))
|
||||
return file_of("path");
|
||||
if (tool == "pick_gizmo_file")
|
||||
if (tool == "gizmo_pick_file")
|
||||
return file_of("saved");
|
||||
if (tool == "run_replay" && result.contains("passed") && result["passed"].is_boolean()) {
|
||||
if (tool == "replay_run" && result.contains("passed") && result["passed"].is_boolean()) {
|
||||
json out{{"kind", "replay"}, {"passed", result["passed"]}};
|
||||
if (result.contains("failed_step"))
|
||||
out["failed_step"] = result["failed_step"];
|
||||
|
||||
@@ -41,9 +41,11 @@ struct StepDescription
|
||||
};
|
||||
|
||||
// Describes `step` of `replay`, substituting its arguments leniently over `ctx`; a file counts as
|
||||
// written inside the output folder when it is inside ctx.out_dir. A step that calls a Speed Dial command
|
||||
// by its key (one of `catalog` with no place in the tool list, with a tile of its own or called with the
|
||||
// arguments of one of its tiles) is described as run_action of that tile is. A run_replay step is described by
|
||||
// written inside the output folder when it is inside ctx.out_dir. A step that calls a command of `catalog` as one
|
||||
// of its tiles (with exactly a tile's arguments, or with none where it has a tile of its own, or, for one the tool
|
||||
// list does not show, a Design command, with any) is described as action_run of that tile is. A step's flags come
|
||||
// from the command it runs and its arguments, whether it calls the command or action_run of its tile (an export flags
|
||||
// writes_file either way). A replay_run step is described by
|
||||
// the steps of its inline replay, or of its file when `path` reads and parses, each in the nested
|
||||
// run's own context (its vars merged with the step's `vars`, its own replay and output folders);
|
||||
// past `depth` 4, or when the file doesn't read or parse, it gets every flag, "checked" and
|
||||
@@ -52,7 +54,7 @@ StepDescription describe_step(const CommandCatalog& catalog, const ReplayStep& s
|
||||
const ReplayContext& ctx, int depth = 0);
|
||||
|
||||
// What a call of `tool` with `args` acts on, as describe_step()'s `what` says it over `catalog`, Speed Dial
|
||||
// ids included, but from the arguments as they are and without reading files: a run_replay call is named
|
||||
// ids included, but from the arguments as they are and without reading files: a replay_run call is named
|
||||
// by its replay file. For recording captions.
|
||||
nlohmann::json describe_call(const CommandCatalog& catalog, const std::string& tool, const nlohmann::json& args);
|
||||
|
||||
|
||||
@@ -12,51 +12,54 @@ namespace {
|
||||
// Server instructions shown to the model; clients truncate them at 4096 characters.
|
||||
const char* kInstructions =
|
||||
"OrcaSlicer, a 3D-printing slicer, driven through its GUI.\n"
|
||||
"Workflow: get_app_state (is it ready? which presets, plates, dialogs?) -> act -> check it with the reading "
|
||||
"tools (list_objects, list_plates, get_settings, slice's reply, get_slice_stats); screenshot only to see what they "
|
||||
"do not report.\n"
|
||||
"Workflow: app_state (ready? which presets, plates, dialogs?) -> act -> check with object_list, plate_list, "
|
||||
"settings_get, plate_slice's reply or plate_slice_stats; window_screenshot only for what they do not report.\n"
|
||||
"Running the session, dialogs, replays and scripts:\n"
|
||||
"- A call that takes long or opens a dialog returns {status:\"running\"|\"blocked_by_dialog\", job}. It keeps "
|
||||
"running: never retry it. Answer dialogs with answer_dialog (see get_app_state.dialogs), then wait {for:\"job\"}. "
|
||||
"A native message box (native: true) is answered with answer_dialog by one of the buttons listed for it; a file or "
|
||||
"folder picker, or a native dialog whose buttons list is empty (any on macOS), can't be: register auto_answer_dialogs "
|
||||
"before the step that opens one.\n"
|
||||
"- While an operation (slice, export, arrange or another background job) runs, other changes are refused; use wait "
|
||||
"or cancel_job.\n"
|
||||
"- export_replay saves this session's calls as a replay that run_replay runs.\n"
|
||||
"- run_script runs Python against orca.host, the plugin API (search_python_api searches it), computing over meshes and "
|
||||
"settings and calling tools through orca.host.tools; its own file, program, thread and network use is restricted "
|
||||
"unless get_app_state.python.scripts_unrestricted.\n"
|
||||
"- Not sure what does something? search_tools {query} searches every catalog at once: the commands, with those the "
|
||||
"tool list does not show (Speed Dial commands, the Design tab's, and operations plugins offer as "
|
||||
"plugin.<plugin>.<name>; call_tool runs them), the Speed Dial's other actions, settings and the Python API, each "
|
||||
"match with how to use it.\n"
|
||||
"running: never retry it. Answer dialogs with dialog_answer (see app_state.dialogs), then app_wait {for:\"job\"}. A "
|
||||
"native message box (native: true) takes dialog_answer with one of its listed buttons; a file or folder picker, "
|
||||
"or a native dialog with no buttons listed (any on macOS), can't: register dialog_auto_answer before the step "
|
||||
"that opens one.\n"
|
||||
"- During an operation (slicing, exporting, arranging, another job) other changes are refused: app_wait or "
|
||||
"job_cancel.\n"
|
||||
"- replay_export saves this session's calls as a replay that replay_run runs.\n"
|
||||
"- script_run runs Python against orca.host, the plugin API (script_search_api searches it), to compute over "
|
||||
"meshes and settings and call tools (orca.host.tools); its file, program, thread and network use is restricted "
|
||||
"unless app_state.python.scripts_unrestricted.\n"
|
||||
"- tool_search {query} searches every catalog: the commands, those the tool list does not show too (menu rows "
|
||||
"with no arguments, the Design tab's, plugin operations as plugin.<plugin>.<name>; tool_call runs them), the "
|
||||
"Speed Dial's other actions, settings and the Python API.\n"
|
||||
"Acting on project data by index and name, JSON in and out; prefer these:\n"
|
||||
"- Typed tools: open_files, select_preset, set_settings, slice, export and the rest.\n"
|
||||
"- What a setting does, or which one controls an effect: get_settings with keys, or query with a few words, and no "
|
||||
"scope, which looks through the process, filament and printer settings; each item names its scope, the one "
|
||||
"set_settings needs (its default is the process), and its meta has its description and where (its settings page and "
|
||||
"group).\n"
|
||||
"- Objects, parts and plates are 0-based indices, as list_objects and list_plates give "
|
||||
"them; filament slots and Preview layers are 1-based.\n"
|
||||
"- Lists come in pages: {items, offset, total}, with next_offset while more remain; call again with that offset to "
|
||||
"read on. list_objects has plates and outside in place of items.\n"
|
||||
"- Paths are absolute. Outputs never overwrite a file unless overwrite is true.\n"
|
||||
"Driving the GUI itself, for what those do not reach or to see what a person sees:\n"
|
||||
"- run_action runs every Speed Dial command (search_actions finds them): prefer it to GUI clicks.\n"
|
||||
"- list_widgets lists widgets, menus, 3D toolbar items, gizmos, ImGui items and web page elements with refs; click "
|
||||
"/ set_widget_value / press_keys / mouse_gesture act on its refs, good across later listings, or on locators, which "
|
||||
"its description lists.\n"
|
||||
"- list_windows lists the open windows, modal or not, with refs: a window's ref as screenshot's target captures "
|
||||
"that window, as list_widgets's target lists it alone, and as set_window's target sizes, moves or raises it.\n"
|
||||
"- Gizmos (Cut, Text, SVG, the painting tools...): click {target: {gizmo: \"Cut\"}} opens one; its panel's "
|
||||
"fields and buttons are ImGui items for set_widget_value / click, and painting is a mouse_gesture drag starting on the "
|
||||
"object. Move the camera with set_view, never a drag: what a drag does follows the user's mouse settings. pick_gizmo_file only stands in for a file picker inside an open gizmo.\n"
|
||||
"- screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n"
|
||||
"- start_recording / stop_recording record a video (MJPEG .mkv), optionally with the tool calls as captions and the "
|
||||
"pointer highlighted; with encode, stop_recording then encodes it to MP4 with the system ffmpeg as a job to wait "
|
||||
"for, and encode_recording encodes any recording later. An encode deletes the .mkv this session recorded once the "
|
||||
"MP4 is written, unless keep_raw_video_file.";
|
||||
"- Commands are named place first, then verb (object_mirror); tool_search {group:\"Objects\"} lists a place's "
|
||||
"commands.\n"
|
||||
"- A call with exactly one Speed Dial tile's arguments (project_export {format:\"gcode\"}) may ask in a dialog or "
|
||||
"act on the selection, as a person's pick of it does. Any other call, with silent: true where a "
|
||||
"schema takes it, runs from its arguments; a dialog it still opens (preset_export's always) is in its "
|
||||
"description.\n"
|
||||
"- Which setting does what: settings_get {query} (a few words, no type) searches the settings being edited; each "
|
||||
"item names its type, which settings_set needs, and its meta its description and page.\n"
|
||||
"- Objects, parts and plates are 0-based, as object_list and plate_list number them; filament slots and Preview "
|
||||
"layers are 1-based.\n"
|
||||
"- Lists come in pages: {items, offset, total}, next_offset while more remain (call again with it); object_list "
|
||||
"has plates and outside for items.\n"
|
||||
"- Paths are absolute; an output replaces a file only with overwrite: true.\n"
|
||||
"Driving the GUI, for what those do not reach or to see what a person sees:\n"
|
||||
"- action_run runs a Speed Dial entry by id from action_search: a tile as a call with its arguments does; a plate, "
|
||||
"a recent project, a plugin's script or page as a person's pick does.\n"
|
||||
"- widget_list lists widgets, menus, 3D toolbar items, gizmos, ImGui items and web page elements with refs; "
|
||||
"widget_click / widget_set_value / keyboard_press / mouse_gesture act on its refs (good across later listings) or "
|
||||
"on the locators its description lists.\n"
|
||||
"- window_list lists the open windows with refs: a window's ref as the target of window_screenshot captures it, "
|
||||
"of widget_list lists it alone, and of window_set sizes, moves or raises it.\n"
|
||||
"- Gizmos (Cut, Text, SVG, painting...): widget_click {target: {gizmo: \"Cut\"}} opens one; its panel's fields and "
|
||||
"buttons are ImGui items for widget_set_value / widget_click, and painting is a mouse_gesture drag from the "
|
||||
"object. Move the camera with view_set, never a drag, which follows the user's mouse settings. gizmo_pick_file "
|
||||
"stands in for a file picker inside an open gizmo.\n"
|
||||
"- window_screenshot returns a downscaled image plus the full-size PNG path; target \"canvas\" is the 3D view.\n"
|
||||
"- recording_start / recording_stop record a video (MJPEG .mkv), optionally captioned with the tool calls, the "
|
||||
"pointer highlighted; with encode, recording_stop encodes it to MP4 (system ffmpeg) as a job, and "
|
||||
"recording_encode encodes any later; an encode deletes this session's .mkv once the MP4 is written, unless "
|
||||
"keep_raw_video_file.";
|
||||
|
||||
} // namespace
|
||||
|
||||
|
||||
@@ -155,7 +155,7 @@ std::optional<std::pair<int, std::string>> post(const Endpoint& e, const std::st
|
||||
if (sent != nullptr)
|
||||
*sent = false;
|
||||
// Deadlines only apply to Beast's asynchronous operations, so each step runs as one on a
|
||||
// private io_context. A tool replies within its budget (45 s) and `wait` within 50 s.
|
||||
// private io_context. A tool replies within its budget (45 s) and `app_wait` within 50 s.
|
||||
try {
|
||||
net::io_context ioc;
|
||||
boost::beast::tcp_stream stream(ioc);
|
||||
@@ -482,7 +482,7 @@ int run_stdio_bridge(int argc, char** argv, const std::function<const CommandCat
|
||||
endpoint = fresh;
|
||||
if (is_request)
|
||||
write_line(error_reply(msg["id"], -32603,
|
||||
sent ? "OrcaSlicer did not reply; the call may have run. Check with get_app_state before "
|
||||
sent ? "OrcaSlicer did not reply; the call may have run. Check with app_state before "
|
||||
"repeating it."
|
||||
: "OrcaSlicer's MCP server is not reachable.")
|
||||
.dump());
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
#include "McpTargets.hpp"
|
||||
|
||||
#include "McpTools.hpp"
|
||||
|
||||
#include "slic3r/GUI/3DScene.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/Operations/ObjectOps.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Selection.hpp"
|
||||
|
||||
#include "libslic3r/Model.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
// Every argument that names a target, in one form or the other.
|
||||
constexpr const char* kTargetArgs[] = {"object", "objects", "object_id", "object_ids", "instance", "instances", "instance_object_ids",
|
||||
"part", "parts", "part_id", "part_ids"};
|
||||
|
||||
template<class T> void add_once(std::vector<T>& list, const T& item)
|
||||
{
|
||||
if (std::find(list.begin(), list.end(), item) == list.end())
|
||||
list.push_back(item);
|
||||
}
|
||||
|
||||
// The checks of a target's indices against the model, with the texts object_select gives.
|
||||
struct IndexCheck
|
||||
{
|
||||
const Model& model;
|
||||
|
||||
const ModelObject& object(int index) const
|
||||
{
|
||||
if (index < 0 || std::size_t(index) >= model.objects.size())
|
||||
throw ToolFailure("object index " + std::to_string(index) + " is out of range");
|
||||
return *model.objects[std::size_t(index)];
|
||||
}
|
||||
|
||||
// An instance, or with !instance a part, of object `owner`; the object is checked first.
|
||||
void member(int owner, int index, bool instance) const
|
||||
{
|
||||
const ModelObject& o = object(owner);
|
||||
if (index < 0 || std::size_t(index) >= (instance ? o.instances.size() : o.volumes.size()))
|
||||
throw ToolFailure("object " + std::to_string(owner) + " has no " + (instance ? "instance " : "part ") + std::to_string(index) +
|
||||
" (object_list lists them)");
|
||||
}
|
||||
|
||||
// [object, index] of a pair argument.
|
||||
std::pair<int, int> pair(const json& entry, bool instance) const
|
||||
{
|
||||
if (!entry.is_array() || entry.size() != 2 || !entry[0].is_number_integer() || !entry[1].is_number_integer())
|
||||
throw ToolFailure(std::string("an entry of ") + (instance ? "instances" : "parts") + " is [object, " +
|
||||
(instance ? "instance" : "part") + "]");
|
||||
const std::pair<int, int> out{entry[0].get<int>(), entry[1].get<int>()};
|
||||
member(out.first, out.second, instance);
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
// The ids `ids_key` expects for the entries of `list_key`, one each, checked against `expected` (the object or part
|
||||
// each entry names) as check_expected_ids() checks one.
|
||||
template<class Expected> void check_ids(const json& args, const char* list_key, const char* ids_key, const char* id_key, std::size_t entries,
|
||||
const Expected& expected)
|
||||
{
|
||||
if (!args.contains(ids_key))
|
||||
return;
|
||||
const json& ids = args.at(ids_key);
|
||||
if (!ids.is_array() || ids.size() != entries)
|
||||
throw ToolFailure(std::string(ids_key) + " takes one id per entry of " + list_key);
|
||||
for (std::size_t k = 0; k < entries; ++k)
|
||||
expected(k, json{{id_key, ids[k]}});
|
||||
}
|
||||
|
||||
Targets named_targets(const Model& model, const json& args, unsigned kinds)
|
||||
{
|
||||
using Forms = std::pair<const char*, const char*>;
|
||||
for (const Forms& forms : {Forms{"object", "objects"}, Forms{"instance", "instances"}, Forms{"part", "parts"}})
|
||||
if (args.contains(forms.first) && args.contains(forms.second))
|
||||
throw ToolFailure(std::string("Give ") + forms.first + " or " + forms.second + ", not both");
|
||||
const IndexCheck check{model};
|
||||
Targets out;
|
||||
|
||||
// One target: the object, or an instance or a part of it.
|
||||
if (args.contains("object")) {
|
||||
const int index = args.at("object").get<int>();
|
||||
const ModelObject& object = check.object(index);
|
||||
check_expected_ids(object, nullptr, args);
|
||||
if ((kinds & kParts) && args.contains("part")) {
|
||||
const int part = args.at("part").get<int>();
|
||||
check.member(index, part, false);
|
||||
check_expected_ids(object, object.volumes[std::size_t(part)], args);
|
||||
out.parts.emplace_back(index, part);
|
||||
} else if ((kinds & kInstances) && args.contains("instance")) {
|
||||
const int instance = args.at("instance").get<int>();
|
||||
check.member(index, instance, true);
|
||||
out.instances.emplace_back(index, instance);
|
||||
} else if (kinds & kObjects) {
|
||||
if (args.contains("part_id"))
|
||||
throw ToolFailure("part_id goes with part");
|
||||
out.objects.push_back(index);
|
||||
} else {
|
||||
throw ToolFailure(std::string("object names the object of a ") + (kinds & kParts ? "part: give part too" : "instance: give instance too"));
|
||||
}
|
||||
} else {
|
||||
for (const char* key : {"instance", "part", "object_id", "part_id"})
|
||||
if (args.contains(key))
|
||||
throw ToolFailure(std::string(key) + " goes with object");
|
||||
}
|
||||
|
||||
// Several targets, each checked with its expected id before any is taken.
|
||||
const json objects = kinds & kObjects ? args.value("objects", json::array()) : json::array();
|
||||
const json instances = kinds & kInstances ? args.value("instances", json::array()) : json::array();
|
||||
const json parts = kinds & kParts ? args.value("parts", json::array()) : json::array();
|
||||
std::vector<int> object_list;
|
||||
std::vector<std::pair<int, int>> instance_list, part_list;
|
||||
for (const json& entry : objects) {
|
||||
if (!entry.is_number_integer())
|
||||
throw ToolFailure("an entry of objects is an object index");
|
||||
check.object(entry.get<int>());
|
||||
object_list.push_back(entry.get<int>());
|
||||
}
|
||||
for (const json& entry : instances)
|
||||
instance_list.push_back(check.pair(entry, true));
|
||||
for (const json& entry : parts)
|
||||
part_list.push_back(check.pair(entry, false));
|
||||
check_ids(args, "objects", "object_ids", "object_id", object_list.size(), [&](std::size_t k, const json& id) {
|
||||
check_expected_ids(*model.objects[std::size_t(object_list[k])], nullptr, id);
|
||||
});
|
||||
check_ids(args, "instances", "instance_object_ids", "object_id", instance_list.size(), [&](std::size_t k, const json& id) {
|
||||
check_expected_ids(*model.objects[std::size_t(instance_list[k].first)], nullptr, id);
|
||||
});
|
||||
check_ids(args, "parts", "part_ids", "part_id", part_list.size(), [&](std::size_t k, const json& id) {
|
||||
const ModelObject& object = *model.objects[std::size_t(part_list[k].first)];
|
||||
check_expected_ids(object, object.volumes[std::size_t(part_list[k].second)], id);
|
||||
});
|
||||
for (int index : object_list)
|
||||
add_once(out.objects, index);
|
||||
for (const auto& instance : instance_list)
|
||||
add_once(out.instances, instance);
|
||||
for (const auto& part : part_list)
|
||||
add_once(out.parts, part);
|
||||
if (out.objects.empty() && out.instances.empty() && out.parts.empty())
|
||||
throw ToolFailure("The call names no target; give one, or none to act on the selection");
|
||||
return out;
|
||||
}
|
||||
|
||||
// Whether `selection` holds parts rather than whole instances.
|
||||
bool holds_parts(const Selection& selection)
|
||||
{
|
||||
return selection.get_mode() == Selection::Volume && !selection.is_single_full_instance() && !selection.is_multiple_full_instance() &&
|
||||
!selection.is_single_full_object() && !selection.is_multiple_full_object();
|
||||
}
|
||||
|
||||
Ops::Outcome<Targets> selected_targets(const Model& model, const Selection* selection, unsigned kinds)
|
||||
{
|
||||
if (selection == nullptr || selection->is_empty())
|
||||
return Ops::nothing_selected();
|
||||
if (selection->is_wipe_tower())
|
||||
return Ops::wrong_selection();
|
||||
Targets out;
|
||||
out.from_selection = true;
|
||||
const auto in_model = [&model](int object) { return object >= 0 && std::size_t(object) < model.objects.size(); };
|
||||
const bool as_object = (kinds & kObjects) && (kinds & kObjectOfSelection);
|
||||
if (holds_parts(*selection)) {
|
||||
for (unsigned int index : selection->get_volume_idxs()) {
|
||||
const GLVolume* volume = selection->get_volume(index);
|
||||
if (volume == nullptr || volume->is_wipe_tower || volume->volume_idx() < 0 || !in_model(volume->object_idx()))
|
||||
continue;
|
||||
if (kinds & kParts)
|
||||
add_once(out.parts, std::make_pair(volume->object_idx(), volume->volume_idx()));
|
||||
else if ((kinds & kInstances) && (kinds & kInstanceOfSelectedPart))
|
||||
add_once(out.instances, std::make_pair(volume->object_idx(), volume->instance_idx()));
|
||||
else if (as_object)
|
||||
add_once(out.objects, volume->object_idx());
|
||||
else
|
||||
return Ops::wrong_selection();
|
||||
}
|
||||
} else {
|
||||
for (const auto& [object, instances] : selection->get_content()) {
|
||||
if (!in_model(object))
|
||||
continue;
|
||||
const bool whole = instances.size() == model.objects[std::size_t(object)]->instances.size();
|
||||
if ((kinds & kObjects) && (whole || (as_object && !(kinds & kInstances))))
|
||||
add_once(out.objects, object);
|
||||
else if (kinds & kInstances)
|
||||
for (int instance : instances)
|
||||
add_once(out.instances, std::make_pair(object, instance));
|
||||
else
|
||||
return Ops::wrong_selection();
|
||||
}
|
||||
}
|
||||
if (out.objects.empty() && out.instances.empty() && out.parts.empty())
|
||||
return Ops::nothing_selected();
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<Property> target_props(unsigned kinds, bool one)
|
||||
{
|
||||
std::vector<Property> out;
|
||||
if (one) {
|
||||
out.emplace_back("object", json{{"type", "integer"}, {"minimum", 0}, {"description", "Object index (object_list)."}});
|
||||
out.emplace_back("object_id", expected_id_prop("object"));
|
||||
if (kinds & kInstances)
|
||||
out.emplace_back("instance", json{{"type", "integer"}, {"minimum", 0}, {"description", "An instance of the object (object_list)."}});
|
||||
if (kinds & kParts) {
|
||||
out.emplace_back("part", json{{"type", "integer"}, {"minimum", 0}, {"description", "A part of the object (object_list)."}});
|
||||
out.emplace_back("part_id", expected_id_prop("part"));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
if (kinds & kObjects) {
|
||||
out.emplace_back("objects", array_prop({{"type", "integer"}}, "Object indices."));
|
||||
out.emplace_back("object_ids", array_prop({{"type", "integer"}}, "The ids object_list reports for objects, one per entry: refused "
|
||||
"when an index names another object now."));
|
||||
}
|
||||
if (kinds & kInstances) {
|
||||
out.emplace_back("instances", array_prop({{"type", "array"}}, "[[object, instance], ...]"));
|
||||
out.emplace_back("instance_object_ids", array_prop({{"type", "integer"}}, "The ids object_list reports for the objects of instances, "
|
||||
"one per entry: refused when a pair names another object now."));
|
||||
}
|
||||
if (kinds & kParts) {
|
||||
out.emplace_back("parts", array_prop({{"type", "array"}}, "[[object, part], ...]"));
|
||||
out.emplace_back("part_ids", array_prop({{"type", "integer"}}, "The ids object_list reports for the entries of parts, one per entry: "
|
||||
"refused when a pair names another part now."));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
json with_targets(json schema, unsigned kinds, bool one)
|
||||
{
|
||||
for (Property& property : target_props(kinds, one))
|
||||
schema["properties"][property.first] = std::move(property.second);
|
||||
return schema;
|
||||
}
|
||||
|
||||
bool names_targets(const json& args)
|
||||
{
|
||||
return args.is_object() && std::any_of(std::begin(kTargetArgs), std::end(kTargetArgs), [&args](const char* key) { return args.contains(key); });
|
||||
}
|
||||
|
||||
bool names_empty_lists(const json& args)
|
||||
{
|
||||
return names_targets(args) && std::all_of(std::begin(kTargetArgs), std::end(kTargetArgs), [&args](const char* key) {
|
||||
return !args.contains(key) || (args.at(key).is_array() && args.at(key).empty());
|
||||
});
|
||||
}
|
||||
|
||||
Ops::Outcome<Targets> resolve_targets(const Model& model, const Selection* selection, const json& args, unsigned kinds, bool one)
|
||||
{
|
||||
Targets targets;
|
||||
if (names_targets(args)) {
|
||||
targets = named_targets(model, args, kinds);
|
||||
} else {
|
||||
Ops::Outcome<Targets> selected = selected_targets(model, selection, kinds);
|
||||
if (!selected)
|
||||
return selected;
|
||||
targets = selected.value();
|
||||
}
|
||||
if (one && targets.objects.size() + targets.instances.size() + targets.parts.size() > 1)
|
||||
return Ops::one_object_only();
|
||||
return targets;
|
||||
}
|
||||
|
||||
json targets_reply(const Model& model, const Targets& targets)
|
||||
{
|
||||
const auto object_at = [&model](int index) -> const ModelObject* {
|
||||
return index >= 0 && std::size_t(index) < model.objects.size() ? model.objects[std::size_t(index)] : nullptr;
|
||||
};
|
||||
json out = json::object();
|
||||
json objects = json::array(), instances = json::array(), parts = json::array();
|
||||
for (int index : targets.objects)
|
||||
if (const ModelObject* object = object_at(index))
|
||||
objects.push_back({{"index", index}, {"object_id", object->id().id}, {"name", object->name}});
|
||||
for (const auto& [index, instance] : targets.instances)
|
||||
if (const ModelObject* object = object_at(index))
|
||||
instances.push_back({{"object", index}, {"instance", instance}, {"object_id", object->id().id}, {"name", object->name}});
|
||||
for (const auto& [index, part] : targets.parts)
|
||||
if (const ModelObject* object = object_at(index); object != nullptr && part >= 0 && std::size_t(part) < object->volumes.size())
|
||||
parts.push_back({{"object", index}, {"part", part}, {"part_id", object->volumes[std::size_t(part)]->id().id},
|
||||
{"name", object->volumes[std::size_t(part)]->name}});
|
||||
if (!targets.objects.empty())
|
||||
out["objects"] = std::move(objects);
|
||||
if (!targets.instances.empty())
|
||||
out["instances"] = std::move(instances);
|
||||
if (!targets.parts.empty())
|
||||
out["parts"] = std::move(parts);
|
||||
return out;
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,73 @@
|
||||
#pragma once
|
||||
|
||||
#include "McpTools.hpp"
|
||||
|
||||
#include "slic3r/GUI/Operations/ObjectOps.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r {
|
||||
|
||||
class Model;
|
||||
|
||||
namespace GUI {
|
||||
|
||||
class Selection;
|
||||
|
||||
// What a command acts on, read from its arguments, or from the Prepare view's selection when they name nothing: one
|
||||
// reading of the target arguments for every command that takes objects, instances or parts. The struct is the
|
||||
// operations' (Ops::Targets), since the operations take it.
|
||||
namespace Mcp {
|
||||
|
||||
using Ops::Targets;
|
||||
|
||||
// The kinds of target a command takes, or'ed, with how the selection is read for a command that asks for it.
|
||||
enum TargetKind : unsigned {
|
||||
kObjects = 1,
|
||||
kInstances = 2,
|
||||
kParts = 4,
|
||||
// An instance or a part selected stands for its object, for a command that takes objects and not them. Asked for by
|
||||
// object_set_instances, whose items read the selected object so (Plater::get_selected_object_idx()), and by the
|
||||
// commands of one object that have no row: part_add, object_set_variable_layer_height and object_set_height_ranges.
|
||||
kObjectOfSelection = 8,
|
||||
// A part selected stands for its instance, for a command that takes instances and not parts. Asked for by
|
||||
// object_separate_instances, as Set as Individual Objects reads it (ObjectList::split_instances()).
|
||||
kInstanceOfSelectedPart = 16,
|
||||
};
|
||||
|
||||
// The schema properties that name a command's targets of `kinds`, worded as object_select and object_transform word
|
||||
// them: objects, object_ids, instances ([[object, instance], ...]), instance_object_ids, parts ([[object, part], ...])
|
||||
// and part_ids; or with `one`, for a command of one target, object and object_id, then instance and part, each of
|
||||
// the object.
|
||||
std::vector<Property> target_props(unsigned kinds, bool one);
|
||||
// `schema` (object_schema()) with target_props(kinds, one) among its properties.
|
||||
nlohmann::json with_targets(nlohmann::json schema, unsigned kinds, bool one);
|
||||
|
||||
// Whether `args` name a target in any of the forms target_props() gives.
|
||||
bool names_targets(const nlohmann::json& args);
|
||||
// Whether the target arguments `args` give are all empty lists (objects: [] and the like), which object_select reads
|
||||
// as naming nothing, where resolve_targets() refuses them.
|
||||
bool names_empty_lists(const nlohmann::json& args);
|
||||
|
||||
// The targets of `kinds` that `args` name, each once, in the order named. Every index is checked to be in range and
|
||||
// every expected id to match (check_expected_ids()) before anything is returned, and a miss throws ToolFailure naming
|
||||
// it, as do both forms of one target at once (object and objects), an instance or a part without its object, and
|
||||
// arguments that name nothing (empty lists).
|
||||
// With none named: what `selection` holds, from_selection set. Every instance of an object selected is the object,
|
||||
// for a command that takes objects; an instance or a part selected stands for its object only with
|
||||
// kObjectOfSelection, and a part for its instance only with kInstanceOfSelectedPart. The selection is refused with
|
||||
// Ops::nothing_selected() when it is empty or null, and Ops::wrong_selection() when it holds a kind the command does
|
||||
// not take. With `one`, more than one target is refused with Ops::one_object_only().
|
||||
Ops::Outcome<Targets> resolve_targets(const Model& model, const Selection* selection, const nlohmann::json& args, unsigned kinds, bool one);
|
||||
|
||||
// What a reply says a command acted on: {"objects": [{index, object_id, name}], "instances": [{object, instance,
|
||||
// object_id, name}], "parts": [{object, part, part_id, name}]}, each key there when `targets` holds that kind. The
|
||||
// indices and names are as `model` has them now.
|
||||
nlohmann::json targets_reply(const Model& model, const Targets& targets);
|
||||
|
||||
} // namespace Mcp
|
||||
} // namespace GUI
|
||||
} // namespace Slic3r
|
||||
+238
-89
@@ -17,6 +17,8 @@
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <iosfwd>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
@@ -42,13 +44,17 @@ namespace CustomGCode { struct Info; }
|
||||
namespace GUI {
|
||||
|
||||
struct AppAction;
|
||||
struct AppActionRunResult;
|
||||
class IMSlider;
|
||||
class PartPlate;
|
||||
class PartPlateList;
|
||||
class Plater;
|
||||
|
||||
namespace Ops {
|
||||
struct ExportTicket;
|
||||
struct Preference;
|
||||
struct Refusal;
|
||||
enum class PresetChanges;
|
||||
} // namespace Ops
|
||||
|
||||
namespace Mcp {
|
||||
@@ -57,22 +63,43 @@ class AutomationRuntime;
|
||||
struct Replay;
|
||||
struct ReplayContext;
|
||||
|
||||
// Each tool family adds its commands to the catalog (NativeCommands::register_all_commands()), and so do the
|
||||
// Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function reaches the automation runtime
|
||||
// through its call's context (ToolContext::runtime()), so the catalog is built without one.
|
||||
void register_app_tools(CommandCatalog& catalog);
|
||||
// Each tool family adds its commands to the catalog (NativeCommands::register_all_commands(), which gives each the
|
||||
// group of its place), and so do the Design tab's (register_cad_commands(), McpToolsCad.hpp). A command's function
|
||||
// reaches the automation runtime through its call's context (ToolContext::runtime()), so the catalog is built
|
||||
// without one.
|
||||
// `cad`: the catalog holds the Design tab's commands, which undo's and redo's examples call.
|
||||
void register_app_tools(CommandCatalog& catalog, bool cad);
|
||||
void register_action_tools(CommandCatalog& catalog);
|
||||
void register_project_tools(CommandCatalog& catalog);
|
||||
void register_config_tools(CommandCatalog& catalog);
|
||||
// The printer models and system filaments a person installs (McpToolsInstall.cpp).
|
||||
void register_install_tools(CommandCatalog& catalog);
|
||||
// The Preferences dialog's preferences, read and written (McpToolsPreferences.cpp).
|
||||
void register_preference_tools(CommandCatalog& catalog);
|
||||
void register_scene_tools(CommandCatalog& catalog);
|
||||
void register_view_tools(CommandCatalog& catalog);
|
||||
void register_plugin_tools(CommandCatalog& catalog);
|
||||
// The error of a plugin command refused by `refusal` (McpToolsPlugins.cpp), the plugin's row (plugin_list's) being
|
||||
// `before` the call and `after` it, null where it is not listed. Where the call changed how the plugin stands (installed,
|
||||
// enabled or its error: a cloud plugin downloaded before the refusal, or its download's error recorded), the error says
|
||||
// how it is left and carries its row under "plugin"; else it is the refusal alone.
|
||||
ToolFailure plugin_refusal_after(const Ops::Refusal& refusal, const nlohmann::json& before, const nlohmann::json& after);
|
||||
// plugin_enable's reply once the call has ended (McpToolsPlugins.cpp), `row` being the plugin's row then, null where it is
|
||||
// not listed: {plugin, changed}, with a note while the load the call started (`load_started`) goes on (`still_loading`), or
|
||||
// where the plugin is no longer listed. A load that ended with the plugin not enabled, or no longer listed, is an error
|
||||
// (not_loaded) that says how the plugin is left and carries its row.
|
||||
nlohmann::json plugin_enable_reply(const std::string& plugin, bool changed, bool load_started, bool still_loading,
|
||||
const nlohmann::json& row);
|
||||
void register_ui_tools(CommandCatalog& catalog);
|
||||
void register_replay_tools(CommandCatalog& catalog);
|
||||
void register_record_tools(CommandCatalog& catalog);
|
||||
void register_python_tools(CommandCatalog& catalog);
|
||||
// `design_index` ends search_tools' description: what it says of the Design commands (design_command_index(),
|
||||
// `design_index` ends tool_search's description: what it says of the Design commands (design_command_index(),
|
||||
// McpToolsCad.hpp) in a catalog that holds them, and nothing in one that does not.
|
||||
void register_api_tools(CommandCatalog& catalog, const std::string& design_index);
|
||||
// Adds the source of the operations the loaded plugins offer (plugin.<plugin>.<name>), which come and go with their
|
||||
// plugins, in group Plugins: tool_call runs one by name and tool_search finds it; tools/list does not show them.
|
||||
void register_plugin_operations(CommandCatalog& catalog);
|
||||
|
||||
// How run_replay_job() runs a replay beyond what the replay says.
|
||||
struct ReplayRunOptions
|
||||
@@ -84,11 +111,11 @@ struct ReplayRunOptions
|
||||
std::function<void(const nlohmann::json&)> step_finished;
|
||||
};
|
||||
|
||||
// Runs a parsed replay as the calling job, as run_replay does: steps are child calls, dialog rules
|
||||
// Runs a parsed replay as the calling job, as replay_run does: steps are child calls, dialog rules
|
||||
// the replay registers end with it, and result.json goes to sctx.out_dir (created if missing). It
|
||||
// stops before the next step, and stops waiting on a step's job, once the call is cancelled: the
|
||||
// runtime stops, or a stop was asked for any job in the call's lineage (JobRegistry::request_stop), so
|
||||
// a nested run_replay stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file).
|
||||
// a nested replay_run stops with the run that holds it. Returns run_replay()'s result with out_dir (and result_file).
|
||||
nlohmann::json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay& replay, ReplayContext& sctx,
|
||||
const ReplayRunOptions& options);
|
||||
|
||||
@@ -103,23 +130,33 @@ nlohmann::json enum_prop(std::vector<std::string> values, const std::string& des
|
||||
nlohmann::json array_prop(nlohmann::json items, const std::string& description);
|
||||
|
||||
// The typed tools are listed commands (tools/list shows them) made with NativeCommands::long_command(), their
|
||||
// function unchanged, each in its `group`: core, api or ui (NativeCommand::group).
|
||||
// function unchanged. A command's group is its place's, which the catalog gives it (NativeCommands::place_heading()).
|
||||
// Pure observation: inline, read-only, inspect guard, not journaled.
|
||||
NativeCommand inspect_tool(std::string group, std::string name, std::string title, std::string description, nlohmann::json schema,
|
||||
CommandFn handler);
|
||||
NativeCommand inspect_tool(std::string name, std::string title, std::string description, nlohmann::json schema, CommandFn handler);
|
||||
// `command`, naming the operations (GUI/Operations) its function reaches, by function name.
|
||||
NativeCommand reaching(std::vector<std::string> operations, NativeCommand command);
|
||||
// Anything that changes the app: a job under the mutate guard, journaled.
|
||||
NativeCommand mutate_tool(std::string group, std::string name, std::string title, std::string description, nlohmann::json schema,
|
||||
CommandFn handler, bool destructive = false);
|
||||
NativeCommand mutate_tool(std::string name, std::string title, std::string description, nlohmann::json schema, CommandFn handler,
|
||||
bool destructive = false);
|
||||
// A command made from menu rows (NativeCommandRows.hpp): NativeCommands::ui_command(), listed, with `description` and
|
||||
// the rows as its `tiles`. `fn` does what the row a call's variant argument names does, as a person's pick of that row
|
||||
// does: on the targets the call names (McpTargets.hpp) where the command takes them, else on what is selected. A row
|
||||
// with no argument form is no command of the tool list: its declaration sets listed false.
|
||||
NativeCommand row_command(std::string name, std::string title, std::string description, nlohmann::json schema, nlohmann::json tiles,
|
||||
std::function<AppActionRunResult(const nlohmann::json& args)> fn);
|
||||
// What a command made from rows replies to a call, which a pick does not show: `reply`.
|
||||
AppActionRunResult row_reply(const nlohmann::json& reply);
|
||||
// What a command made from rows answers for a refusal after a dialog the person answered or read, which told them why:
|
||||
// a pick shows nothing more, and a call learns the refusal.
|
||||
AppActionRunResult quiet_refusal(const Ops::Refusal& refusal);
|
||||
|
||||
// ---- expected object IDs ---------------------------------------------------------------------
|
||||
|
||||
// The schema of an expected ID argument: the id list_objects reports for an object or part (`of`), which
|
||||
// The schema of an expected ID argument: the id object_list reports for an object or part (`of`), which
|
||||
// orca.host shows too, so a script addresses what it read.
|
||||
nlohmann::json expected_id_prop(const char* of);
|
||||
// `command` with its id_args: the expected-id arguments its schema has (object_id and part_id, as
|
||||
// expected_id_prop() describes them, and select_objects' object_ids, part_ids and instance_object_ids). Ids are
|
||||
// expected_id_prop() describes them, and object_select's object_ids, part_ids and instance_object_ids). Ids are
|
||||
// allocated per process, so the session journal leaves them out (without_expected_ids()).
|
||||
NativeCommand with_expected_ids(NativeCommand command);
|
||||
// Refuses the call when `args` names an expected object_id, or part_id, that is not the id of `object`,
|
||||
@@ -154,7 +191,7 @@ bool arg_bool(const nlohmann::json& args, const char* key, bool fallback)
|
||||
|
||||
// ---- search ----------------------------------------------------------------------------------
|
||||
|
||||
// search_tools' answer from `catalog`, every command it holds and those its sources hold now, for `args`:
|
||||
// tool_search's answer from `catalog`, every command it holds and those its sources hold now, for `args`:
|
||||
// - tool: that command's group, read_only, description and input schema, and its examples when it has some;
|
||||
// ToolFailure, naming the closest keys, for a key lookup() does not resolve.
|
||||
// - query: {total, items, use}, the `limit` (default 5) best matches by match_score(), each {name, group, summary,
|
||||
@@ -168,17 +205,23 @@ nlohmann::json search_commands(const CommandCatalog& catalog, const nlohmann::js
|
||||
// The Speed Dial actions of `listed` (ActionRegistry::describe()'s items: id, title, group, description)
|
||||
// that `words` (of query_words()) describe, best first: those matching more of the words, then those
|
||||
// matching more of them in what the action is called (the name inside its id, its title and its group),
|
||||
// then the shorter name, which is the plainer command (obj_delete before obj_delete_all). search_actions
|
||||
// and search_tools both rank with it, so one query finds the same actions through either.
|
||||
// then the shorter name, which is the plainer tile (obj_delete before obj_delete_all). action_search
|
||||
// and tool_search both rank with it, so one query finds the same actions through either.
|
||||
nlohmann::json rank_actions(const nlohmann::json& listed, const std::vector<std::string>& words);
|
||||
|
||||
// Why run_action refuses `args` for `action`, or empty when it does not: a command's tile takes its command's
|
||||
// arguments, which the command checks, a tile with a preset (a folded row's) takes none or exactly its preset, and
|
||||
// every other action (a plugin's script or page, a plate's, a setting's or a recent project's) takes none.
|
||||
// Why action_run refuses `args` for `action`, or empty when it does not: a tile that collects a value (input) takes
|
||||
// exactly that value, a command's own tile takes its command's arguments, which the command checks, an item of a
|
||||
// command's tiles (a folded row's, with a preset) takes none or exactly its preset, and every other action (a
|
||||
// plugin's script or page, a plate's, a setting's or a recent project's) takes none.
|
||||
std::string action_args_error(const AppAction& action, const nlohmann::json& args);
|
||||
// The arguments action_run's journal step keeps for a command's tile of fixed arguments (AppAction::preset), run with
|
||||
// `args`, which action_run accepted: what it takes for that tile, the tile's own arguments, or for a tile that collects
|
||||
// a value, `args` (that value alone). Null for an action without a preset, a Design command's own tile among them,
|
||||
// which takes its command's arguments and keeps the command's rewrite of them (Mcp::TileContext).
|
||||
nlohmann::json tile_journal_args(const AppAction& action, const nlohmann::json& args);
|
||||
|
||||
// What run_action answers for `id`, an action id or the name inside one, that no action of the app's state has:
|
||||
// for a Design tab tile's, when that tile is there and the call_tool that runs it from any tab (its command, with
|
||||
// What action_run answers for `id`, an action id or the name inside one, that no action of the app's state has:
|
||||
// for a Design tab tile's, when that tile is there and the tool_call that runs it from any tab (its command, with
|
||||
// the row's arguments for a folded row's tile), or, when `catalog` leaves the tile's command out
|
||||
// (CommandCatalog::leave_out()), why; for any other, where an action or a command is found.
|
||||
std::string unknown_action(const std::string& id, const CommandCatalog& catalog);
|
||||
@@ -191,7 +234,7 @@ std::string to_config_string(const nlohmann::json& value, const std::string& key
|
||||
|
||||
// ---- Python (McpToolsPython.cpp) -------------------------------------------------------------
|
||||
|
||||
// search_python_api's reference: every public module, class, function, method, property, named instance (such
|
||||
// script_search_api's reference: every public module, class, function, method, property, named instance (such
|
||||
// as orca.host.preset.process) and constant (such as orca.host.ui.PD_CAN_ABORT) of the orca package, in
|
||||
// the order the package lists them, each {name, kind, signature, doc}. signature holds the signature lines
|
||||
// pybind11 starts a docstring with (a class's are its constructors, joined with " | "), and doc the rest
|
||||
@@ -209,14 +252,14 @@ 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_script job.
|
||||
// The job is idle for `wait {for: "idle"}`, and owns what the session's tool calls leave behind (auto-answer rules, a
|
||||
// The Run Script panel's session as the calling job, a person's script_run job.
|
||||
// The job is idle for `app_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(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename);
|
||||
|
||||
// Hosts the Run Script panel's `session` as an unjournaled person's run_script job (run_python_session_job()), which
|
||||
// Hosts the Run Script panel's `session` as an unjournaled person's script_run job (run_python_session_job()), which
|
||||
// `runtime` follows on a thread of its own that its stop() joins and stop_followed() 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(),
|
||||
@@ -231,39 +274,70 @@ nlohmann::json editor_tool_catalog(const CommandCatalog& catalog);
|
||||
|
||||
// ---- recording (McpToolsRecord.cpp) ----------------------------------------------------------
|
||||
|
||||
// Starts encode_recording with `args` as an unjournaled job of its own and returns at once: the job's envelope, or
|
||||
// the error that refused it. For a recording's encode that stop_recording starts, which a replay of the recording
|
||||
// Starts recording_encode with `args` as an unjournaled job of its own and returns at once: the job's envelope, or
|
||||
// the error that refused it. For a recording's encode that recording_stop starts, which a replay of the recording
|
||||
// asks for again. Any thread.
|
||||
ToolResult start_encode(AutomationRuntime& runtime, const nlohmann::json& args);
|
||||
|
||||
// ---- settings scopes (McpToolsConfig.cpp) ----------------------------------------------------
|
||||
// ---- settings (McpToolsConfig.cpp) -----------------------------------------------------------
|
||||
|
||||
// The keys the object scope (or, with `is_part`, the volume scope) takes: those of `offered`
|
||||
// Why settings_get (or, with `writes`, settings_set) refuses `args` before reading anything, or empty when it does
|
||||
// not: a target the type has not (an object's, a part's and a height range's settings are the process's), an object,
|
||||
// part or height range given with a target that does not take it, a target part named by its object alone, a target
|
||||
// height_range without min_z and max_z, or nothing named, worded for the tool called (settings_get: no keys, query or
|
||||
// compare with the target global; settings_set: no values or reset_all), and an extruders_count set with anything
|
||||
// else or on another type than the printer. Any thread.
|
||||
std::string settings_request_error(const nlohmann::json& args, bool writes = false);
|
||||
|
||||
// The keys the target object (or, with `is_part`, the target part) takes: those of `offered`
|
||||
// (SettingsFactory::get_options()) that the object list offers with `filaments` filament slots, and
|
||||
// extruder, the object's or part's filament.
|
||||
std::vector<std::string> model_scope_options(const std::vector<std::string>& offered, bool is_part, int filaments);
|
||||
|
||||
// What `key` is for an object (`volume` null) or one of its parts, and where it comes from:
|
||||
// {"effective", "source"}, the part's override ("part"), else the object's ("object"), else the
|
||||
// process's ("process"), else the option's default ("default"; extruder 1). An extruder of 0 is no
|
||||
// override. For an object, "parts" lists [{volume, value}] for the parts and modifiers overriding
|
||||
// `key`, each applying only inside its own volume.
|
||||
nlohmann::json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object,
|
||||
const ModelVolume* volume);
|
||||
// The process settings a target of the settings tools takes, as its rows in the Process panel's Objects mode offer
|
||||
// them on an FFF printer with `filaments` filament slots: object, an object or an assembly, and part, a part or a
|
||||
// modifier (SettingsFactory::get_fff_options(), model_scope_options()); height_range, one of an object's height
|
||||
// ranges (layer_range_option_keys()). Each with extruder, the filament its row sets. Empty for another target.
|
||||
std::vector<std::string> target_options(const std::string& target, int filaments);
|
||||
// The targets whose target_options() hold `key`, in the order object, part, height_range.
|
||||
std::vector<std::string> targets_taking(const std::string& key, int filaments);
|
||||
// Why `target` does not take the process setting `key`, saying where it is set, from targets_taking(): "layer_height is
|
||||
// set on an object or a height range, not on a part", or for a key no target takes, that it is set globally only.
|
||||
// Empty when the target takes it.
|
||||
std::string untaken_setting_error(const std::string& key, const std::string& target, int filaments);
|
||||
|
||||
// Checks save_preset's `name` against `presets` as the Save preset dialog does, and returns whether the
|
||||
// settings_list's page of `items`: all of them, unless the items carry their meta (include_meta, which where implies),
|
||||
// which pages them by 100; limit and offset as given.
|
||||
nlohmann::json settings_list_page(const nlohmann::json& items, const nlohmann::json& args);
|
||||
|
||||
// What `key` is for an object (`volume` and `range` null), one of its parts, or one of its height ranges (`range`, its
|
||||
// settings), and where it comes from, in the order the slicer applies them: {"effective", "source"}, the height range's
|
||||
// own value ("height_range"), else the part's ("part"), else the object's ("object"), else the process's, the global
|
||||
// value ("global"), else the option's default ("default"; extruder 1). An extruder of 0 is no override. For an object
|
||||
// or a height range, "parts" lists [{part, value}] for the parts and modifiers overriding `key`, each applying only
|
||||
// inside its own volume (inside a height range that sets the key, its modifiers alone); for an object, one of its parts
|
||||
// or a region modifier that sets none of `key`, "height_ranges" lists [{min_z, max_z, value}] for the object's height
|
||||
// ranges overriding it, each applying only between its heights. Inside a region modifier (a mesh or a painted one) that
|
||||
// sets none of `key`, the value of the region it overlaps applies: a model part's, or that of a region modifier before it
|
||||
// in the object's list. Where one of those sets the key, which it overlaps is not worked out: "effective" is null,
|
||||
// "source" "overlapped_part", "object_effective" and "object_source" give what the object's chain resolves to, and
|
||||
// "parts" lists [{part, value}] for those that set it.
|
||||
nlohmann::json effective_setting(const std::string& key, const DynamicPrintConfig& process, const ModelObject& object,
|
||||
const ModelVolume* volume, const DynamicPrintConfig* range = nullptr);
|
||||
|
||||
// Checks preset_save's `name` against `presets` as the Save preset dialog does, and returns whether the
|
||||
// preset is kept inside the project: where an existing preset of that name is, else `inside_project`,
|
||||
// else where the edited preset is. Throws ToolFailure for a name the dialog refuses, for replacing
|
||||
// another existing preset without `overwrite`, and for an `inside_project` that contradicts where the
|
||||
// existing preset is, which the dialog does not let a person change.
|
||||
bool save_preset_inside_project(const PresetCollection& presets, const std::string& name, const nlohmann::json& args);
|
||||
|
||||
// get_settings' meta of an option: label, description (its whole tooltip: what it does, when to change
|
||||
// settings_get's meta of an option: label, description (its whole tooltip: what it does, when to change
|
||||
// it, what it affects), type, mode, category, unit, range, and for an enum its values with their labels
|
||||
// (the untranslated texts the GUI shows), in the same order.
|
||||
nlohmann::json option_meta(const ConfigOptionDef& def);
|
||||
|
||||
// get_settings' search: the keys of `within` that `query` describes, best first, at most `limit`.
|
||||
// settings_get's search: the keys of `within` that `query` describes, best first, at most `limit`.
|
||||
// A query word matches a word of a key (split at _), its label or its tooltip that starts with it, so
|
||||
// "retract" finds "retraction". Settings matching more of the query's words come first, then those
|
||||
// matching more of them in the key or label, so of two that match alike, the one the query names
|
||||
@@ -271,8 +345,8 @@ nlohmann::json option_meta(const ConfigOptionDef& def);
|
||||
// the query has longer ones.
|
||||
std::vector<std::string> rank_settings(const std::string& query, const std::vector<std::string>& within, std::size_t limit);
|
||||
|
||||
// get_settings' search without a scope, for search_tools: the process, filament and printer settings being
|
||||
// edited that `query` describes, best first, {total, items: [{key, scope, label, where}]} with at most
|
||||
// settings_get's search without a type, for tool_search: the process, filament and printer settings being
|
||||
// edited that `query` describes, best first, {total, items: [{key, type, label, where}]} with at most
|
||||
// `limit` items. UI thread.
|
||||
nlohmann::json search_settings(const std::string& query, std::size_t limit);
|
||||
|
||||
@@ -283,7 +357,7 @@ nlohmann::json search_settings(const std::string& query, std::size_t limit);
|
||||
nlohmann::json variant_entries(const std::string& key, const DynamicPrintConfig& config, const std::vector<int>& extruder_types,
|
||||
const std::vector<int>& nozzle_volume_types);
|
||||
|
||||
// The serialized value set_settings writes for `key` of the preset whose config is `config`: `value`
|
||||
// The serialized value settings_set writes for `key` of the preset whose config is `config`: `value`
|
||||
// itself, or for {"index": i, "value": v} the whole vector with entry i replaced, as editing one variant
|
||||
// in the tab leaves it. Throws ToolFailure, naming the entries, for a value with another number of
|
||||
// entries than a per-variant or per-extruder vector of several (a scalar would collapse it), and for a
|
||||
@@ -297,7 +371,7 @@ std::string preset_setting_value(const std::string& key, const nlohmann::json& v
|
||||
// are left out.
|
||||
nlohmann::json preset_diff(const Preset& left, const Preset& right, const std::vector<std::string>& keys);
|
||||
|
||||
// set_settings' "changed": {key: value} for every key whose value differs between `before` and `after`,
|
||||
// settings_set's "changed": {key: value} for every key whose value differs between `before` and `after`,
|
||||
// with null for a key `after` no longer has.
|
||||
nlohmann::json changed_settings(const DynamicPrintConfig& before, const DynamicPrintConfig& after);
|
||||
|
||||
@@ -305,6 +379,15 @@ nlohmann::json changed_settings(const DynamicPrintConfig& before, const DynamicP
|
||||
// a vector), whose value `config` no longer holds; each key once.
|
||||
nlohmann::json discarded_changes(const nlohmann::json& changes, const DynamicPrintConfig& config);
|
||||
|
||||
// What a command that changes presets (preset_select, printer_install, printer_uninstall) replies when an operation
|
||||
// refuses: the refusal's text with what an agent can do about it, and the names it carries under the key each refusal
|
||||
// has.
|
||||
ToolFailure preset_refused(const Ops::Refusal& refusal);
|
||||
|
||||
// The answer a call's preset_changes gives about the presets' unsaved changes, as the preset tools take it: transfer or
|
||||
// discard them; Ask where the call gives none.
|
||||
Ops::PresetChanges preset_changes_answer(const nlohmann::json& args);
|
||||
|
||||
// The process, filament and printer presets being edited that have unsaved changes:
|
||||
// {type: {name, changes: {key or key#index: value}}}. UI thread.
|
||||
nlohmann::json unsaved_changes();
|
||||
@@ -314,7 +397,7 @@ nlohmann::json unsaved_changes();
|
||||
// that have keys, and left out when there are none. UI thread.
|
||||
nlohmann::json unsaved_changes_outcome(const nlohmann::json& before);
|
||||
|
||||
// Checks that delete_preset may delete the preset `name` of `presets`, as the GUI offers and checks it, and
|
||||
// Checks that preset_delete may delete the preset `name` of `presets`, as the GUI offers and checks it, and
|
||||
// returns the presets deleted with it: for a custom printer (a base printer that is not a system one),
|
||||
// {"process": [names], "filament": [names]} of the user presets of `prints` and `filaments` made for it
|
||||
// alone; otherwise an empty object. Throws ToolFailure for an unknown name (with similar names), a system,
|
||||
@@ -323,17 +406,17 @@ nlohmann::json unsaved_changes_outcome(const nlohmann::json& before);
|
||||
nlohmann::json check_preset_deletable(const PresetCollection& presets, const std::string& name, bool delete_attached,
|
||||
const PresetCollection& prints, const PresetCollection& filaments);
|
||||
|
||||
// The project scope's filament_colour to write: one colour per slot of `current`, each #RRGGBB (stored in
|
||||
// project_set_settings' filament_colour to write: one colour per slot of `current`, each #RRGGBB (stored in
|
||||
// upper case, as the colour pickers store it) or the slot's current colour in any case. `mixed` flags the
|
||||
// mixed slots, whose colour comes from their components and cannot change. Throws ToolFailure otherwise.
|
||||
std::vector<std::string> check_filament_colours(std::vector<std::string> colours, const std::vector<std::string>& current,
|
||||
const std::vector<unsigned char>& mixed);
|
||||
|
||||
// The project scope's flush_multiplier to write: one per nozzle, or one value for all, each within the
|
||||
// project_set_settings' flush_multiplier to write: one per nozzle, or one value for all, each within the
|
||||
// Flushing volumes dialog's 0..3. Throws ToolFailure otherwise.
|
||||
std::vector<double> check_flush_multipliers(std::vector<double> multipliers, std::size_t nozzles);
|
||||
|
||||
// The project scope's flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from,
|
||||
// project_set_settings' flush_volumes_matrix to write: per nozzle, `slots` x `slots` volumes (row = from,
|
||||
// column = to) in config order over every slot, as project_config and the G-code header hold it, limited
|
||||
// as the Flushing volumes dialog limits them (g_max_flush_volume / the nozzle's multiplier). Throws
|
||||
// ToolFailure for another length, a negative volume, a non-zero diagonal, or a changed entry of a mixed
|
||||
@@ -341,6 +424,41 @@ std::vector<double> check_flush_multipliers(std::vector<double> multipliers, std
|
||||
std::vector<double> check_flush_matrix(std::vector<double> matrix, std::size_t slots, const std::vector<double>& multipliers,
|
||||
const std::vector<double>& current, const std::vector<unsigned char>& mixed);
|
||||
|
||||
// The keys of a plate's own settings, which plate_get_settings reads and plate_set_settings writes: what the Plate
|
||||
// Settings dialog sets on one plate, and the filament grouping its filament map icon opens (filament_map_mode,
|
||||
// filament_map). Its name and its lock are set by its icons, as plate_rename and plate_lock set them.
|
||||
const std::vector<std::string>& plate_setting_keys();
|
||||
|
||||
// plate_list's place of a plate on the bed: {origin, size}, the [x, y] of its front left corner and its [width, depth]
|
||||
// in mm, in the bed coordinates object positions are given in, read from the plate's rectangle on the bed.
|
||||
nlohmann::json plate_place(PartPlate& plate);
|
||||
|
||||
// Why plate_set_settings refuses `map` as a plate's filament_map (the 1-based extruder of each filament), or empty
|
||||
// when it does not: the map is the plate's own grouping, "Manual" as its `mode` (filament_map_mode, "" where the plate
|
||||
// follows the project's grouping), with one extruder per filament of the `filaments` and each of the printer's
|
||||
// `extruders`.
|
||||
std::string filament_map_error(const std::string& mode, const std::vector<int>& map, int filaments, int extruders);
|
||||
|
||||
// preset_list's filters over `items`, one per preset as preset_list builds them: query (part of the name or alias),
|
||||
// vendor and filament_type (in either case), source (system, user or project; a preset kept in the project is no user
|
||||
// one), and the items marked compatible: false or installed: false only with include_incompatible or
|
||||
// include_uninstalled. With `printer`, `fits` says whether an item's preset fits that printer preset: it stands for the
|
||||
// item's compatible flag, which is for the selected printer, and sets it.
|
||||
nlohmann::json filter_preset_items(nlohmann::json items, const nlohmann::json& args,
|
||||
const std::function<bool(const nlohmann::json&)>& fits);
|
||||
|
||||
// settings_set's extruders_count for the printer: what the Extruders field of the Printer settings takes, a whole
|
||||
// number from 1 to MAXIMUM_EXTRUDER_NUMBER (or a string of one), and nothing while single extruder multi-material is
|
||||
// on, which greys the field out. Throws ToolFailure otherwise.
|
||||
std::size_t extruders_count_value(const nlohmann::json& value, bool single_extruder_multi_material);
|
||||
|
||||
// The printer variant settings_set's nozzle_diameter switches to, as the sidebar's nozzle diameter does: the plain
|
||||
// diameter among `variants` (the printer model's, PresetCollection::diameters_of_selected_printer()) that every
|
||||
// extruder is given, unless it is the `current` variant. Empty when the extruders differ, no variant has the diameter
|
||||
// or the printer has it already: the value is then typed into the Printer settings.
|
||||
std::string nozzle_diameter_variant(const std::vector<double>& diameters, const std::vector<std::string>& variants,
|
||||
const std::string& current);
|
||||
|
||||
// A plate's filament order as the Plate Settings dialog's drag canvas gives it: every slot 1..`slots` once.
|
||||
// Throws ToolFailure otherwise.
|
||||
std::vector<int> filament_order(const nlohmann::json& order, int slots);
|
||||
@@ -359,17 +477,20 @@ nlohmann::json layer_sequences_json(const std::vector<std::pair<std::pair<int, i
|
||||
// at the height of its last extrusion that is not custom G-code, or for a belt print at its print Z.
|
||||
std::vector<double> gcode_layer_zs(const GCodeProcessorResult& result);
|
||||
|
||||
// list_plates' layer_gcode of a plate's codes: [{z, layer, type, filament, color, gcode}] by height, z
|
||||
// plate_list's layer_gcode of a plate's codes: [{z, layer, type, filament, color, gcode}] by height, z
|
||||
// rounded to the G-code's 0.001 mm; layer (1-based, as the slider numbers it) where `layer_zs` has a layer
|
||||
// at or above z, the slider's rule for a stored height; filament and color for a filament or colour
|
||||
// change, gcode for custom G-code.
|
||||
nlohmann::json layer_gcode_json(const CustomGCode::Info& codes, const std::vector<double>& layer_zs);
|
||||
|
||||
// get_settings on the preferences scope: [{key, value}] for the `keys` of `args` that `config`'s app section,
|
||||
// where the Preferences dialog keeps its settings, holds, paged, and unknown_keys for the others with a note
|
||||
// that a preference never changed is not stored. Values are as stored. Throws ToolFailure without keys: the
|
||||
// section also holds account and device state, so nothing is listed unasked.
|
||||
nlohmann::json preferences_settings(const AppConfig& config, const nlohmann::json& args);
|
||||
// preferences_get's reply: {total, items}, an item for each preference of `shown` (the rows the Preferences dialog shows,
|
||||
// Ops::shown_preferences()) that `args`' keys, tab and query leave (query: each of its words in the key, the label or
|
||||
// the section, in any case), with its value typed by its kind: the text `shown_texts` gives for its key, which is what
|
||||
// the dialog shows where that is not the stored value (Ops::shown_texts()), else the one in `config`'s app section; then
|
||||
// {key, value} as stored for each named key outside `shown` that the section holds, and unknown_keys, with a note, for
|
||||
// the named keys it lacks. The section also holds account and device state, so nothing outside `shown` is listed unasked.
|
||||
nlohmann::json preferences_settings(const AppConfig& config, const std::vector<Ops::Preference>& shown, const nlohmann::json& args,
|
||||
const std::map<std::string, std::string>& shown_texts = {});
|
||||
|
||||
// Points the filament tab at the preset of filament slot `slot` (1-based, in range), as opening that slot's
|
||||
// settings does, through the tab's switch, which asks about its unsaved changes. Returns the preset the tab
|
||||
@@ -379,14 +500,14 @@ std::string edit_filament_slot(int slot);
|
||||
|
||||
// ---- calibration (McpToolsProject.cpp) -------------------------------------------------------
|
||||
|
||||
// generate_calibration_test's arguments as the test's dialog takes them on `printer`: its defaults for what is left out (the
|
||||
// calibration_generate_test's arguments as the test's dialog takes them on `printer`: its defaults for what is left out (the
|
||||
// pressure advance ones by the printer's extruder type, an input shaping Y range or frequency by the X one),
|
||||
// temperatures clamped to the dialog field's 155-500 °C and rounded down to its 5 °C, and the dialog's rules
|
||||
// (check_calib_params()). Adds to `warnings` what the dialog would say without refusing. Throws ToolFailure
|
||||
// for an argument the test does not take, a value the dialog refuses, or a choice the printer does not offer.
|
||||
Calib_Params calib_params_from_args(const nlohmann::json& args, const DynamicPrintConfig& printer, std::vector<std::string>& warnings);
|
||||
|
||||
// The parameters `params` holds for generate_calibration_test's `args`, in its argument names and units: what generate_calibration_test
|
||||
// The parameters `params` holds for calibration_generate_test's `args`, in its argument names and units: what calibration_generate_test
|
||||
// reports and records in the journal, so a replay does not depend on the dialogs' defaults.
|
||||
nlohmann::json calib_params_json(const nlohmann::json& args, const Calib_Params& params, const DynamicPrintConfig& printer);
|
||||
|
||||
@@ -419,6 +540,25 @@ nlohmann::json poll_until(ToolContext& ctx,
|
||||
// thread.
|
||||
std::string undrawn_window(ToolContext& ctx);
|
||||
|
||||
// ---- app (McpToolsApp.cpp) -------------------------------------------------------------------
|
||||
|
||||
// app_log's lines of the log read from `in`: the last `lines` of those at or above `min_level` (trace, debug, info,
|
||||
// warning, error, fatal).
|
||||
std::vector<std::string> log_tail(std::istream& in, const std::string& min_level, std::size_t lines);
|
||||
|
||||
// ---- view (McpToolsView.cpp) -----------------------------------------------------------------
|
||||
|
||||
// What view_set sets outside the Design tab, as app_state's view gives it, under the names of view_set's arguments so
|
||||
// that it can be passed back: sidebar_collapsed and sidebar_width (pixels), legend_collapsed and gcode_window, the 3D
|
||||
// camera's projection (perspective or orthographic), the section view of Prepare and the Preview ({on}), and the display
|
||||
// switches labels, overhangs, outline, wireframe, gridlines, axes and navigator. UI thread.
|
||||
nlohmann::json view_state(Plater& plater);
|
||||
|
||||
// The page of the main window's notebook that view_set's `tab` names, of `pages`, the notebook's page ids: the page
|
||||
// of one of the words of kTabWords (CommandCatalog.hpp), device being the page monitor; else the page of that id,
|
||||
// when no word names that page (a plugin's page, the web Device page); else nothing.
|
||||
std::optional<std::string> view_tab_page(const std::string& tab, const std::vector<std::string>& pages);
|
||||
|
||||
// ---- windows (McpToolsUi.cpp) ----------------------------------------------------------------
|
||||
|
||||
// What a window's title bar offers and where it runs, for window_request_refusal().
|
||||
@@ -430,10 +570,10 @@ struct WindowAbilities
|
||||
bool can_minimize = false; // wxMINIMIZE_BOX in its style
|
||||
bool positions_known = true; // false on Wayland (window_positions_known())
|
||||
};
|
||||
// Why set_window can't apply `args` to such a window, or empty when it can. Checks everything
|
||||
// Why window_set can't apply `args` to such a window, or empty when it can. Checks everything
|
||||
// before anything changes.
|
||||
std::string window_request_refusal(const nlohmann::json& args, const WindowAbilities& window);
|
||||
// How set_window's wait for a window ended, for add_window_notes().
|
||||
// How window_set's wait for a window ended, for add_window_notes().
|
||||
struct WindowSettling
|
||||
{
|
||||
bool limited = false; // the size was held to the window's minimum or maximum size
|
||||
@@ -443,7 +583,7 @@ struct WindowSettling
|
||||
int seconds = 3; // how long the wait for the window lasted at most
|
||||
std::string undrawn; // undrawn_window()'s reason the 3D view isn't drawn, or empty
|
||||
};
|
||||
// Adds to set_window's `reply`, which holds the size, position and state the window reads back,
|
||||
// Adds to window_set's `reply`, which holds the size, position and state the window reads back,
|
||||
// adjusted, the fields of `args` the window differs from, and a note on why: a size limit, the window
|
||||
// manager, a compositor that refused to activate a minimized window, or a 3D view that didn't draw.
|
||||
void add_window_notes(const nlohmann::json& args, const WindowSettling& settling, nlohmann::json& reply);
|
||||
@@ -452,7 +592,7 @@ void add_window_notes(const nlohmann::json& args, const WindowSettling& settling
|
||||
// view is shown. UI thread.
|
||||
bool view_drawn_at_size();
|
||||
// {index, x, y, width, height}: the work area of display `index` (the screen less the taskbar or the
|
||||
// dock and menu bar), in the units list_windows reports. UI thread.
|
||||
// dock and menu bar), in the units window_list reports. UI thread.
|
||||
nlohmann::json display_area(unsigned index);
|
||||
|
||||
// ---- scene -----------------------------------------------------------------------------------
|
||||
@@ -464,26 +604,26 @@ GLCanvas3D& require_prepare_scene(Plater& plater);
|
||||
// it does. UI thread.
|
||||
void select_rows(ModelObject* object, ModelVolume* volume);
|
||||
|
||||
// Scale factors that turn `current` (mm per axis) into the sizes of transform's `size` argument, [x, y, z]
|
||||
// Scale factors that turn `current` (mm per axis) into the sizes of object_transform's `size` argument, [x, y, z]
|
||||
// with null for an axis that keeps its size. With one number and two nulls, every axis scales by that
|
||||
// axis's factor. Throws ToolFailure for another length, no number, or a size that is not positive.
|
||||
Vec3d size_factors(const Vec3d& current, const nlohmann::json& size);
|
||||
|
||||
// Applies arrange's spacing, rotate, align_y and multi_material to `settings` by the Arrange options
|
||||
// Applies object_arrange's spacing, rotate, align_y and multi_material to `settings` by the Arrange options
|
||||
// panel's rules: Align to Y axis stays off while rotation is on. Settings not given keep their values.
|
||||
// Returns why an asked-for value did not apply, or "".
|
||||
std::string apply_arrange_args(GLCanvas3D::ArrangeSettings& settings, const nlohmann::json& args);
|
||||
// The settings as arrange replies with them and records them for replay.
|
||||
// The settings as object_arrange replies with them and records them for replay.
|
||||
nlohmann::json arrange_settings_json(const GLCanvas3D::ArrangeSettings& settings);
|
||||
|
||||
// An object as list_objects describes it: its filament, auto_drop, overrides, instances (without the
|
||||
// An object as object_list describes it: its filament, auto_drop, overrides, mesh errors, instances (without the
|
||||
// plate, which the GUI's plate registry knows), parts, and its height ranges and variable layer height
|
||||
// profile when it has them. Bounding boxes, on the bed and of model parts only, are {min, max, size}.
|
||||
nlohmann::json object_info(const ModelObject& object, std::size_t index);
|
||||
// A part as list_objects describes it: its type, filament, placement on the bed measured on instance 0,
|
||||
// A part as object_list describes it: its type, filament, placement on the bed measured on instance 0,
|
||||
// rotation and scale in the object's frame, mesh, paint, and what a text or SVG part was made from.
|
||||
nlohmann::json volume_info(const ModelVolume& volume, std::size_t index);
|
||||
// What list_objects replies with, laid out as the Objects panel is: `plates`, each {index, name, objects}
|
||||
// What object_list replies with, laid out as the Objects panel is: `plates`, each {index, name, objects}
|
||||
// with the objects that have an instance on it, and `outside`, the objects with an instance on no plate.
|
||||
// An object row lists the instances of its plate only, so an object on two plates has a row under each.
|
||||
// `plate_of(object, instance)` is the plate an instance is on, or -1, and `plate_names` has a name per
|
||||
@@ -498,17 +638,20 @@ nlohmann::json objects_by_plate(const Model& model, const std::vector<std::strin
|
||||
// registry does not hold, as Fill bed leaves its new ones, the first plate it stands on. UI thread.
|
||||
int instance_plate(PartPlateList& plates, int object, int instance);
|
||||
|
||||
// What `canvas` has selected, in the indices select_objects takes: its objects, the instances [[object, instance]]
|
||||
// What `canvas` has selected, in the indices object_select takes: its objects, the instances [[object, instance]]
|
||||
// they are selected in and, when the selection holds parts rather than whole instances, those parts
|
||||
// [[object, part]]; wipe_tower when a prime tower is selected. UI thread.
|
||||
nlohmann::json selection_state(GLCanvas3D& canvas);
|
||||
// A part's type as list_objects and add_part name it: part, negative, modifier, support_blocker,
|
||||
// A part's type as object_list and part_add name it: part, negative, modifier, support_blocker,
|
||||
// support_enforcer, precise_seam (any subtype), else other.
|
||||
const char* volume_type_name(ModelVolumeType type);
|
||||
// The type add_part's `type` adds, as the context menu's Add items do (precise_seam: a Center seam);
|
||||
// The type part_add's `type` adds, as the context menu's Add items do (precise_seam: a Center seam);
|
||||
// ModelVolumeType::INVALID for another name.
|
||||
ModelVolumeType volume_type_from_name(const std::string& name);
|
||||
// add_part's size of a shape (cube, cylinder, sphere, cone, disc, torus): one positive number of mm
|
||||
// The precise seam a subtype name stands for, as object_list names a seam's subtype (center, left, right, enforced,
|
||||
// blocked, neutral); ModelVolumeType::INVALID for another name.
|
||||
ModelVolumeType precise_seam_subtype(const std::string& name);
|
||||
// part_add's size of a shape (cube, cylinder, sphere, cone, disc, torus): one positive number of mm
|
||||
// per field of the Primitive size dialog, in its order. Empty when size is null (the built-in size).
|
||||
// Throws ToolFailure naming the fields.
|
||||
std::vector<double> part_shape_size(const std::string& shape, const nlohmann::json& size);
|
||||
@@ -520,28 +663,34 @@ void register_layer_tools(CommandCatalog& catalog);
|
||||
// The settings a height range modifier takes: layer_height, the per-region process settings the object
|
||||
// list offers a part or a range (with `filaments` filament slots), and extruder, the range's filament.
|
||||
std::vector<std::string> layer_range_option_keys(int filaments);
|
||||
// set_height_ranges' ranges as an object's layer_config_ranges. Each starts from `defaults`, what the
|
||||
// object list gives a new range, and takes its values, parsed strictly. Throws ToolFailure for a range
|
||||
// that is not 0 <= min_z < max_z or that overlaps another (touching is fine), a key a range does not
|
||||
// take, an invalid value, an extruder above `filaments`, or a layer_height given outside
|
||||
// `layer_height_bounds(extruder)`.
|
||||
t_layer_config_ranges layer_config_ranges_from_json(const nlohmann::json& ranges, const DynamicPrintConfig& defaults, int filaments,
|
||||
const std::function<std::pair<double, double>(int extruder)>& layer_height_bounds);
|
||||
// An object's height range modifiers as list_objects and set_height_ranges report them:
|
||||
// [{min_z, max_z, values: {key: value serialized as get_settings returns it}}], lowest first.
|
||||
// A height range as messages give it: "0-5", "12.5-20".
|
||||
std::string height_range_text(const Slic3r::t_layer_height_range& range);
|
||||
// object_set_height_ranges' ranges, each {min_z, max_z}, as an object's layer_config_ranges: a range of `current`, the
|
||||
// object's, with the same heights keeps its settings, and any other starts from `defaults`, what the object list gives
|
||||
// a new range. Throws ToolFailure for a range that is not 0 <= min_z < max_z or that overlaps another (touching is
|
||||
// fine).
|
||||
t_layer_config_ranges layer_config_ranges_from_json(const nlohmann::json& ranges, const t_layer_config_ranges& current,
|
||||
const DynamicPrintConfig& defaults);
|
||||
// settings_set's check of the `values` it writes to a height range whose settings are `range`: a layer_height given is
|
||||
// within `layer_height_bounds(extruder)` for the range's filament after the call (the one given, else the range's), as the
|
||||
// range editor checks what a person types. Throws ToolFailure otherwise.
|
||||
void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range,
|
||||
const std::function<std::pair<double, double>(int extruder)>& layer_height_bounds);
|
||||
// An object's height range modifiers as object_list and object_set_height_ranges report them:
|
||||
// [{min_z, max_z, values: {key: value serialized as settings_get returns it}}], lowest first.
|
||||
nlohmann::json layer_config_ranges_json(const t_layer_config_ranges& ranges);
|
||||
// An object's layer_height_profile ([z0, h0, z1, h1, ...]) as list_objects and set_variable_layer_height
|
||||
// An object's layer_height_profile ([z0, h0, z1, h1, ...]) as object_list and object_set_variable_layer_height
|
||||
// report it: {points, min_height, max_height}, heights to 0.001 mm; null unless the object list marks the
|
||||
// object's layer height as variable (more than 4 entries).
|
||||
nlohmann::json layer_height_profile_json(const std::vector<double>& profile);
|
||||
|
||||
// The names set_custom_gcode_at_layer and list_plates give the types of layer codes: pause, custom, template,
|
||||
// The names plate_set_custom_gcode and plate_list give the types of layer codes: pause, custom, template,
|
||||
// change_filament, and color_change for an old project's colour change.
|
||||
const char* custom_gcode_type_name(CustomGCode::Type type);
|
||||
// The type set_custom_gcode_at_layer adds for a name; CustomGCode::Unknown for any other, color_change included,
|
||||
// The type plate_set_custom_gcode adds for a name; CustomGCode::Unknown for any other, color_change included,
|
||||
// since the layer slider adds none.
|
||||
CustomGCode::Type custom_gcode_type_from_name(const std::string& name);
|
||||
// set_custom_gcode_at_layer's clear, remove and add, in that order, on a layer slider that holds a plate's layers
|
||||
// plate_set_custom_gcode's clear, remove and add, in that order, on a layer slider that holds a plate's layers
|
||||
// and codes. Everything is checked against the slider's layers and codes before it changes, with the
|
||||
// rules of its menus: one code per layer, a template only when the printer has one (`has_template`), a
|
||||
// filament change only with two or more filaments, as many as the slider has (`filaments`, the slots now),
|
||||
@@ -571,13 +720,13 @@ class GCodeViewer;
|
||||
|
||||
namespace Mcp {
|
||||
|
||||
// The camera set_view leaves, as its reply's camera_state and get_app_state.camera give it: type ("ortho"
|
||||
// The camera view_set leaves, as its reply's camera_state and app_state.camera give it: type ("ortho"
|
||||
// or "perspective"), look_at, the point it looks at, and position ([x, y, z] in mm, to 0.001), zoom (viewport
|
||||
// pixels per mm at look_at's depth) and click_px_per_mm (the zoom in the logical pixels the input tools take, the zoom over
|
||||
// `canvas_scale`), both to 0.0001, and the elevation and azimuth orbit uses, in whole degrees.
|
||||
nlohmann::json camera_state(Camera& camera, double canvas_scale);
|
||||
|
||||
// What a sliced plate reports in the slice reply: print time, filament totals with the flush, cost,
|
||||
// What a sliced plate reports in plate_slice's reply: print time, filament totals with the flush, cost,
|
||||
// layer count, max Z, filament changes, and every filament slot of the project (zeros for slots the
|
||||
// plate does not use, so filaments[i] is slot i + 1) split into model, support, flush and prime
|
||||
// tower. Read from `statistics`, the plate's gcode_statistics_json() parsed, so the reply agrees with
|
||||
@@ -585,18 +734,18 @@ nlohmann::json camera_state(Camera& camera, double canvas_scale);
|
||||
// leaves out, come from `result`.
|
||||
nlohmann::json plate_summary(const nlohmann::json& statistics, const GCodeProcessorResult& result);
|
||||
|
||||
// get_slice_stats's tables, from the same parsed statistics, which sum the moves as the Preview does.
|
||||
// plate_slice_stats's tables, from the same parsed statistics, which sum the moves as the Preview does.
|
||||
// Per feature type, keyed by the English names of the G-code's ;FEATURE: tags: seconds, share of
|
||||
// the print time and grams, plus a Travel row with its distance. The shares need not add up to 100:
|
||||
// the print time also counts retractions, wipes, Z moves, tool changes and the prepare time.
|
||||
nlohmann::json preview_features(const nlohmann::json& statistics);
|
||||
// Every layer, numbered from 1 as the Preview's layer slider and set_view count them, with its Z,
|
||||
// Every layer, numbered from 1 as the Preview's layer slider and view_set count them, with its Z,
|
||||
// its height above the layer below (a layer lower than that one, the next object of a by-object
|
||||
// print, starts again from the bed), seconds and grams; with `with_features`, the seconds of each
|
||||
// feature type on it.
|
||||
nlohmann::json preview_layers(const nlohmann::json& statistics, bool with_features);
|
||||
// Grams per object instance, model and support. The G-code names an instance by its object's name
|
||||
// and its index among that object's instances, so an entry gets the list_objects index `object`
|
||||
// and its index among that object's instances, so an entry gets the object_list index `object`
|
||||
// only when exactly one of `object_names` (the model's objects, in order) has its name.
|
||||
nlohmann::json preview_objects(const nlohmann::json& statistics, const std::vector<std::string>& object_names);
|
||||
// What the Preview shows: view type, time mode, the layer slider's range (1-based) with the Z of
|
||||
@@ -605,7 +754,7 @@ nlohmann::json preview_state(GCodeViewer& viewer);
|
||||
// Whether the Preview's toolpaths are `result`'s. It loads a plate's only while it is shown, so after
|
||||
// another plate is selected it keeps the last one's. UI thread.
|
||||
bool viewer_holds(const GCodeViewer& viewer, const GCodeProcessorResult* result);
|
||||
// The names get_slice_stats and set_view give the legend's rows: a feature type by the English name of
|
||||
// The names plate_slice_stats and view_set give the legend's rows: a feature type by the English name of
|
||||
// its ;FEATURE: tag, an option by a key; null for the options that are markers, not rows.
|
||||
std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role);
|
||||
const char* legend_option_key(libvgcode::EOptionType type);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// search_actions and run_action: every Speed Dial action - built-in commands, plates, recent projects,
|
||||
// action_search and action_run: every Speed Dial action - built-in commands, plates, recent projects,
|
||||
// plugin scripts and pages, and (on request) settings - is reachable through these two tools.
|
||||
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
@@ -31,7 +31,7 @@ ActionRegistry& registry_or_fail()
|
||||
{
|
||||
ActionRegistry* reg = wxGetApp().m_action_registry.get();
|
||||
if (reg == nullptr)
|
||||
throw ToolFailure("The action catalog is not available yet; wait {for:\"ready\"} first");
|
||||
throw ToolFailure("The action catalog is not available yet; app_wait {for:\"ready\"} first");
|
||||
return *reg;
|
||||
}
|
||||
|
||||
@@ -79,18 +79,38 @@ const AppAction& find_action(ActionRegistry& actions, std::string& id)
|
||||
|
||||
std::string action_args_error(const AppAction& action, const json& args)
|
||||
{
|
||||
// A tile that collects a value takes that value alone, as the Speed Dial's second phase gives it.
|
||||
if (!action.input.empty())
|
||||
return args.is_object() && args.size() == 1 && args.contains(action.input) ?
|
||||
std::string() :
|
||||
"The action " + action.id() + " takes exactly its " + action.input + ": run it with args {\"" + action.input +
|
||||
"\": ...} (its input_schema)";
|
||||
if (person_form(args))
|
||||
return {};
|
||||
// A folded row's tile runs its command with the row's arguments, which it takes as well as none.
|
||||
if (!action.preset.is_null())
|
||||
return args == action.preset ? std::string() :
|
||||
"The action " + action.id() + " runs " + action.command + " with " + action.preset.dump() +
|
||||
": run it without args, or with exactly those";
|
||||
// A command's tile runs its command with the tile's arguments, which it takes as well as none; other arguments are
|
||||
// the command's to take.
|
||||
if (!action.preset.is_null()) {
|
||||
if (args == action.preset)
|
||||
return {};
|
||||
if (action.preset.empty())
|
||||
return "The action " + action.id() + " takes no arguments: run it without args, or call " + action.command +
|
||||
" with them";
|
||||
return "The action " + action.id() + " runs " + action.command + " with " + action.preset.dump() +
|
||||
": run it without args or with exactly those, or call " + action.command + " with other arguments";
|
||||
}
|
||||
// A Design command's own tile takes the command's arguments, which the command checks.
|
||||
if (!action.command.empty())
|
||||
return {};
|
||||
return "The action " + action.id() + " takes no arguments: run it without args";
|
||||
}
|
||||
|
||||
json tile_journal_args(const AppAction& action, const json& args)
|
||||
{
|
||||
if (action.preset.is_null())
|
||||
return nullptr;
|
||||
return action.input.empty() ? action.preset : args;
|
||||
}
|
||||
|
||||
std::string unknown_action(const std::string& id, const CommandCatalog& catalog)
|
||||
{
|
||||
// A Design tile is no action while it is not live (ActionRegistry::materialize_design_actions()); its
|
||||
@@ -110,10 +130,10 @@ std::string unknown_action(const std::string& id, const CommandCatalog& catalog)
|
||||
call += ", \"args\": {" + args + "}";
|
||||
}
|
||||
return id + " is a Design tab tile, there only while the Design tab is shown in its mode (a sketch's or the model's) "
|
||||
"with the CAD feature on; call_tool " + call + "} runs its command from any tab";
|
||||
"with the CAD feature on; tool_call " + call + "} runs its command from any tab";
|
||||
}
|
||||
// The name may be a command's that has no tile, which call_tool runs.
|
||||
return "Unknown action id " + id + "; find an action with search_actions, or a command with search_tools";
|
||||
// The name may be a command's that has no tile, which tool_call runs.
|
||||
return "Unknown action id " + id + "; find an action with action_search, or a command with tool_search";
|
||||
}
|
||||
|
||||
json rank_actions(const json& listed, const std::vector<std::string>& words)
|
||||
@@ -175,13 +195,13 @@ ToolResult await_gcode_export(ToolContext& ctx, const Ops::ExportTicket& ticket)
|
||||
void register_action_tools(CommandCatalog& catalog)
|
||||
{
|
||||
catalog.add(inspect_tool(
|
||||
"ui", "search_actions", L("Search Speed Dial actions"),
|
||||
"action_search", L("Search Speed Dial actions"),
|
||||
"Search everything the Speed Dial can run: built-in commands (slice, export, views, object operations, plates, "
|
||||
"calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for run_action, a "
|
||||
"calibration wizards, help), recent projects, plugin scripts and pages. Each entry has an id for action_run, a "
|
||||
"description, the command's key for a built-in command, and, when it takes arguments, their input_schema. A query "
|
||||
"ranks them, best match first, as "
|
||||
"search_tools does; without one they are listed by group and title. include_settings also lists settings (each "
|
||||
"jumps to that setting in the sidebar; use get_settings / set_settings to read or change values).",
|
||||
"tool_search does; without one they are listed by group and title. include_settings also lists settings (each "
|
||||
"jumps to that setting in the sidebar; use settings_get / settings_set to read or change values).",
|
||||
object_schema({{"query", prop("string", "A few words, e.g. \"delete object\": each is matched at the start of the words of "
|
||||
"an action's id, title, group and description.")},
|
||||
{"group", prop("string", "Only this group, e.g. \"Object\", \"View\", \"Slice & Export\".")},
|
||||
@@ -205,58 +225,61 @@ void register_action_tools(CommandCatalog& catalog)
|
||||
}));
|
||||
|
||||
NativeCommand run = mutate_tool(
|
||||
"ui", "run_action", L("Run a Speed Dial action"),
|
||||
"Run one action by the id search_actions returned (orca_command:view_front:orca, or the name inside it, view_front), "
|
||||
"with args, the command's arguments, when it takes some (its input_schema). A command that asks in a dialog asks "
|
||||
"when it is given no args, as a person's pick does, and runs without asking when given them: an absolute path "
|
||||
"skips a file dialog, and an output needs {\"path\": ..., \"overwrite\": true} to replace a file. Go to layer and "
|
||||
"Go to tab need their value ({\"percent\": 50}, {\"tab\": \"preview\"}). Actions that open a dialog return "
|
||||
"blocked_by_dialog; answer it with answer_dialog, or, for a native one it can't press (a file picker), register "
|
||||
"auto_answer_dialogs before the call. An export_gcode with a path completes when the file is written; an action "
|
||||
"that starts a background job (obj_arrange, obj_orient) when the job ends. An action that does nothing (no object "
|
||||
"selected) is an error. Some commands add what they did to the reply (the obj_order_by_* order, the object "
|
||||
"obj_assemble made). A command's action runs that command, as call_tool {tool: its command} does; the tile of a "
|
||||
"Design tab menu row folded into a command runs that command with the row's arguments, and takes no others. The "
|
||||
"other actions (plates, recent projects, plugin scripts and pages, settings) run only here.",
|
||||
object_schema({{"id", prop("string", "Action id from search_actions, or the name inside it.")},
|
||||
"action_run", L("Run a Speed Dial action"),
|
||||
"Run one action by the id action_search returned (orca_command:view_front:orca, or the name inside it, view_front), "
|
||||
"with args, the command's arguments, when it takes some (its input_schema). A command's tile (action_search names "
|
||||
"the command) runs the command as a call with the tile's arguments does: a tile that asks in a dialog asks, and "
|
||||
"the call returns blocked_by_dialog; answer it with dialog_answer, or, for a native one it can't press (a file "
|
||||
"picker), register dialog_auto_answer before the call. Such a tile takes no args, or exactly its own; to run a "
|
||||
"command without asking, call it with its arguments (an absolute path skips a file dialog). Go to layer and Go to "
|
||||
"tab take their value alone ({\"percent\": 50}, {\"tab\": \"preview\"}), and a Design command's own tile takes the "
|
||||
"command's arguments. An action that starts a background job (obj_arrange, obj_orient) completes when the job "
|
||||
"ends. An action that does nothing (no object selected) is an error. Some commands add what they did to the reply "
|
||||
"(the order object_order leaves, the object object_assemble made). The other actions (plates, recent projects, "
|
||||
"plugin scripts and pages, settings) run only here.",
|
||||
object_schema({{"id", prop("string", "Action id from action_search, or the name inside it.")},
|
||||
{"args", {{"type", "object"}, {"description", "The command's arguments, as its input_schema gives them."}}}},
|
||||
{"id"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
std::string id = arg_string(args, "id");
|
||||
json command_args = args.contains("args") ? args["args"] : json::object();
|
||||
std::string key; // the command of a command's tile
|
||||
AppActionRunResult result; // of any other action
|
||||
std::string key; // the command of a command's tile
|
||||
json tile_args; // what its journal step keeps for a tile of fixed arguments
|
||||
AppActionRunResult result; // of any other action
|
||||
ctx.run_ui([&]() -> json {
|
||||
ActionRegistry& actions = registry_or_fail();
|
||||
const AppAction& action = find_action(actions, id);
|
||||
if (const std::string err = action_args_error(action, command_args); !err.empty())
|
||||
throw ToolFailure(err);
|
||||
key = action.command;
|
||||
if (key.empty())
|
||||
key = action.command;
|
||||
tile_args = tile_journal_args(action, command_args);
|
||||
if (key.empty()) {
|
||||
result = actions.run(id, command_args, /*record_stats=*/false);
|
||||
else if (!action.preset.is_null())
|
||||
// A folded row's tile runs its command with the row's arguments, which the journal records.
|
||||
command_args = action.preset;
|
||||
} else {
|
||||
// What a person's pick of the tile runs its command with, which the journal records.
|
||||
const json* tile = find_tile(NativeCommands::instance(), short_id(id)).second;
|
||||
command_args = tile_call_args(tile, command_args);
|
||||
}
|
||||
return json();
|
||||
});
|
||||
if (key.empty()) {
|
||||
settle(ctx);
|
||||
return NativeCommands::from_run_result(id, result);
|
||||
}
|
||||
// A command's tile runs the command's own function, as a call of the command does, inside run_action's
|
||||
// A command's tile runs the command's own function, as a call of the command does, inside action_run's
|
||||
// journal entry.
|
||||
const NativeCommand* command = NativeCommands::find(key);
|
||||
if (command == nullptr)
|
||||
throw ToolFailure("Unknown command " + key);
|
||||
if (const std::string err = argument_error(*command, command_args); !err.empty())
|
||||
throw ToolFailure("Invalid arguments for " + key + ": " + err);
|
||||
TileContext tile(ctx, id);
|
||||
TileContext tile(ctx, id, tile_args);
|
||||
ToolResult reply = command->run(command_args, tile);
|
||||
if (!reply.is_error && reply.data.is_object())
|
||||
reply.data["ran"] = id;
|
||||
return reply;
|
||||
});
|
||||
// Its commands upload G-code to a print host (send_gcode) and sync presets with the cloud account (sync_presets).
|
||||
// Its tiles upload G-code to a print host (printer_send) and sync presets with the cloud account (preset_sync).
|
||||
run.open_world = true;
|
||||
catalog.add(run);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// search_tools and call_tool: a generic way to every command of the catalog, those tools/list never shows
|
||||
// among them: the Speed Dial's commands, the Design tab's and the operations plugins offer (plugin.<key>.<name>).
|
||||
// search_tools's search also reaches the other catalogs an agent calls into: the Speed Dial's other actions,
|
||||
// settings and the Python API.
|
||||
// tool_search and tool_call: a generic way to every command of the catalog, those tools/list does not show among
|
||||
// them: the menu rows that take no arguments, the Design tab's commands and the operations plugins offer
|
||||
// (plugin.<key>.<name>). tool_search's search also reaches the other catalogs an agent calls into: the Speed Dial's
|
||||
// other actions, settings and the Python API.
|
||||
|
||||
#include "McpArguments.hpp"
|
||||
#include "McpTools.hpp"
|
||||
@@ -56,11 +56,11 @@ json editor_tool_catalog(const CommandCatalog& catalog)
|
||||
|
||||
namespace {
|
||||
|
||||
// How many of each other catalog's matches search_tools shows beside the commands, and of the commands
|
||||
// How many of each other catalog's matches tool_search shows beside the commands, and of the commands
|
||||
// without a limit; each catalog's own search lists the rest.
|
||||
constexpr std::size_t kCatalogHits = 5;
|
||||
|
||||
// What search_tools looks through: every command of `catalog`, in the order they were added, then what its
|
||||
// What tool_search looks through: every command of `catalog`, in the order they were added, then what its
|
||||
// sources hold now; with `group`, those of that group, compared in any case. A group none of them has is
|
||||
// refused with the groups there are, in the order they first appear.
|
||||
std::vector<std::shared_ptr<const NativeCommand>> search_inventory(const CommandCatalog& catalog, const std::string& group)
|
||||
@@ -89,7 +89,7 @@ std::vector<std::shared_ptr<const NativeCommand>> search_inventory(const Command
|
||||
return out;
|
||||
}
|
||||
|
||||
// A catalog's best matches for search_tools, from `ranked`, its matches best first: {total, items, use}
|
||||
// A catalog's best matches for tool_search, from `ranked`, its matches best first: {total, items, use}
|
||||
// with the first few, or null when nothing matched.
|
||||
json catalog_hits(const json& ranked, const std::string& use)
|
||||
{
|
||||
@@ -102,7 +102,7 @@ json catalog_hits(const json& ranked, const std::string& use)
|
||||
}
|
||||
|
||||
// The Speed Dial's actions that are no command (plates, recent projects, plugin scripts and pages) and settings
|
||||
// matching `words` (of `query`), for search_tools. A command's tile is left out: the command is among the
|
||||
// matching `words` (of `query`), for tool_search. A command's tile is left out: the command is among the
|
||||
// commands already. A catalog that can't be read yet (startup, before the main window) is left out. UI thread.
|
||||
json ui_catalog_hits(const std::vector<std::string>& words, const std::string& query)
|
||||
{
|
||||
@@ -115,13 +115,13 @@ json ui_catalog_hits(const std::vector<std::string>& words, const std::string& q
|
||||
for (json& action : listed["items"])
|
||||
if (!action.contains("command"))
|
||||
others.push_back(std::move(action));
|
||||
// Ranked as search_actions ranks them, so the same query reads on there from these.
|
||||
out["actions"] = catalog_hits(rank_actions(others, words), "run_action {id, args}; search_actions {query} lists the rest");
|
||||
// Ranked as action_search ranks them, so the same query reads on there from these.
|
||||
out["actions"] = catalog_hits(rank_actions(others, words), "action_run {id, args}; action_search {query} lists the rest");
|
||||
}
|
||||
try {
|
||||
json settings = search_settings(query, kCatalogHits);
|
||||
if (settings["total"] != 0) {
|
||||
settings["use"] = "get_settings {scope, keys} reads one with its description; set_settings {scope, values} changes it";
|
||||
settings["use"] = "settings_get {type, keys} reads one with its description; settings_set {type, values} changes it";
|
||||
out["settings"] = std::move(settings);
|
||||
}
|
||||
} catch (const ToolFailure&) {
|
||||
@@ -129,7 +129,7 @@ json ui_catalog_hits(const std::vector<std::string>& words, const std::string& q
|
||||
return out;
|
||||
}
|
||||
|
||||
// The Python API entries matching `query`, for search_tools, or null when Python is not running or none
|
||||
// The Python API entries matching `query`, for tool_search, or null when Python is not running or none
|
||||
// matches.
|
||||
json python_hits(const std::string& query)
|
||||
{
|
||||
@@ -142,7 +142,7 @@ json python_hits(const std::string& query)
|
||||
try {
|
||||
ranked = rank_python_api(python_api_reference(), query);
|
||||
} catch (const ToolFailure&) {
|
||||
return nullptr; // search_python_api reports why
|
||||
return nullptr; // script_search_api reports why
|
||||
}
|
||||
if (ranked.empty())
|
||||
return nullptr;
|
||||
@@ -152,7 +152,7 @@ json python_hits(const std::string& query)
|
||||
{"summary", first_sentence(ranked[i]["doc"].get<std::string>())}});
|
||||
return {{"total", ranked.size()},
|
||||
{"items", std::move(items)},
|
||||
{"use", "run_script {code}; search_python_api {query} gives each entry's whole documentation"}};
|
||||
{"use", "script_run {code}; script_search_api {query} gives each entry's whole documentation"}};
|
||||
}
|
||||
|
||||
json describe_tool(const NativeCommand& def)
|
||||
@@ -169,14 +169,14 @@ json describe_tool(const NativeCommand& def)
|
||||
}
|
||||
|
||||
// A plugin's operation as a command: a job (plugin code may take long), under the mutate guard and journaled
|
||||
// when it changes something, under the inspect guard and unjournaled when it only reads. Not listed; in the api
|
||||
// group, as it is called by name with JSON in and out.
|
||||
// when it changes something, under the inspect guard and unjournaled when it only reads. Not listed; in the group
|
||||
// Plugins, the place of the commands that manage the plugins.
|
||||
std::shared_ptr<const NativeCommand> operation_command(const PluginOperation& op)
|
||||
{
|
||||
auto def = std::make_shared<NativeCommand>();
|
||||
def->key = op.full_name();
|
||||
def->title = op.name;
|
||||
def->group = "api";
|
||||
def->group = "Plugins";
|
||||
def->description = "Offered by a plugin. " + op.description;
|
||||
def->input_schema = op.schema;
|
||||
def->read_only = !op.changes;
|
||||
@@ -199,7 +199,7 @@ std::shared_ptr<const NativeCommand> operation_command(const PluginOperation& op
|
||||
}
|
||||
|
||||
// The operations the loaded plugins offer (plugin.<key>.<name>), which come and go with their plugins: a
|
||||
// call finds one by name, and search_tools lists them; tools/list does not.
|
||||
// call finds one by name, and tool_search lists them; tools/list does not.
|
||||
class PluginOperationSource final : public CommandSource
|
||||
{
|
||||
public:
|
||||
@@ -265,34 +265,40 @@ json search_commands(const CommandCatalog& catalog, const json& args)
|
||||
}
|
||||
return {{"total", scored.size()},
|
||||
{"items", std::move(items)},
|
||||
{"use", "call a listed command by its name; call_tool {tool, args} runs one that is not listed"}};
|
||||
{"use", "call a listed command by its name; tool_call {tool, args} runs one that is not listed"}};
|
||||
}
|
||||
|
||||
void register_plugin_operations(CommandCatalog& catalog)
|
||||
{
|
||||
// Plugin operations resolve by name, beside the catalog's commands, without being listed.
|
||||
catalog.add_source(std::make_unique<PluginOperationSource>());
|
||||
}
|
||||
|
||||
void register_api_tools(CommandCatalog& catalog, const std::string& design_index)
|
||||
{
|
||||
// Plugin operations resolve by name, beside the catalog's commands, without being listed.
|
||||
catalog.add_source(std::make_unique<PluginOperationSource>());
|
||||
|
||||
// Its description ends with `design_index`: the Design commands' names, in a catalog that holds them.
|
||||
catalog.add(inspect_tool(
|
||||
"api", "search_tools", L("Find tools, actions, settings and APIs"),
|
||||
"tool_search", L("Find tools, actions, settings and APIs"),
|
||||
"Find what does something, in one search, or look up one command. With query: the commands that match, best "
|
||||
"first, each with its group, the first sentence of its description and listed, whether the tool list shows it; "
|
||||
"one that is not listed (a Speed Dial command, a Design tab command, or an operation a plugin offers, "
|
||||
"plugin.<plugin>.<name>) comes with its input schema, and its description when that says more, which nothing "
|
||||
"else shows. Beside them, the best few matches of each other catalog, with its total and how to use it: actions "
|
||||
"(the Speed Dial's plates, recent projects and plugin scripts and pages, for run_action), settings (get_settings "
|
||||
"/ set_settings) and python (the orca API for run_script). With tool: that command's description and input schema, "
|
||||
"and its examples when it has some (the Design commands do). With neither: every command's name. group keeps the "
|
||||
"names and the command matches to one group; the other catalogs' matches stay as they are. call_tool runs any "
|
||||
"command, listed or not." + design_index,
|
||||
"one that is not listed (a menu row that takes no arguments, a Design tab command, or an operation a plugin "
|
||||
"offers, plugin.<plugin>.<name>) comes with its input schema, and its description when that says more, which "
|
||||
"nothing else shows. Beside them, the best few matches of each other catalog, with its total and how to use it: "
|
||||
"actions (the Speed Dial's plates, recent projects and plugin scripts and pages), settings, and python (the orca "
|
||||
"API a script calls). The reply says how to call each kind of match. With tool: that command's description and "
|
||||
"input schema, and its examples when it has some (the Design commands do). With neither: every command's name. "
|
||||
"group keeps the names and the command matches to one group; the other catalogs' matches stay as they are." +
|
||||
design_index,
|
||||
object_schema({{"tool", prop("string", "A command's name: its description and schema.")},
|
||||
{"query", prop("string", "A few words saying what you want to do or find, e.g. \"brim\" or \"mesh normals\".")},
|
||||
{"group", prop("string", "Only the commands of this group, in any case: core (the session, dialogs and "
|
||||
"Python), api (project data by index and name; plugin operations too), ui (the "
|
||||
"GUI itself), Design (the Design tab's, with the CAD feature on), or a Speed Dial "
|
||||
"section such as Commands, Object or View. A group no command has is refused with "
|
||||
"the groups there are.")},
|
||||
{"group", prop("string", "Only the commands of this group, in any case: the heading of a place (Tools "
|
||||
"and actions; The app; The project; Objects; Parts; Plates; Presets and "
|
||||
"settings; Filaments; Printers and prints; Plugins, with the operations plugins "
|
||||
"offer; View and windows; Recordings, replays and scripts; Driving the GUI), the "
|
||||
"place a command's name starts with, but for window_screenshot and "
|
||||
"window_save_screenshot, which are under Recordings, replays and scripts; or "
|
||||
"Design (the Design tab's, with the CAD feature on). A group no command has is "
|
||||
"refused with the groups there are.")},
|
||||
{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "At most this many commands (default 5)."}}}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
json out = search_commands(NativeCommands::instance(), args);
|
||||
@@ -316,15 +322,15 @@ void register_api_tools(CommandCatalog& catalog, const std::string& design_index
|
||||
// Dispatched before it runs (resolve_call): the call runs as the target's own, with its guard,
|
||||
// mode, budget and journal flag, and is journaled as the target's call. This handler is never reached.
|
||||
NativeCommand call = mutate_tool(
|
||||
"api", "call_tool", L("Call a tool or plugin operation"),
|
||||
"Call any command by name with its arguments: a tool, or one the tool list does not show, a Speed Dial command, a "
|
||||
"Design tab command or an operation a plugin offers (see search_tools). It runs and is recorded as that command's "
|
||||
"own call, with its guards and reply budget.",
|
||||
"tool_call", L("Call a tool or plugin operation"),
|
||||
"Call any command by name with its arguments: a tool, or one the tool list does not show, a menu row that takes no "
|
||||
"arguments, a Design tab command or an operation a plugin offers (see tool_search). It runs and is recorded as "
|
||||
"that command's own call, with its guards and reply budget.",
|
||||
object_schema({{"tool", prop("string", "The command to call.")},
|
||||
{"args", {{"type", "object"}, {"description", "Its arguments."}}}},
|
||||
{"tool"}),
|
||||
[](const json&, ToolContext&) -> ToolResult { throw ToolFailure("call_tool is dispatched to its tool before it runs"); });
|
||||
// It calls any tool, run_script included, and plugin code.
|
||||
[](const json&, ToolContext&) -> ToolResult { throw ToolFailure("tool_call is dispatched to its tool before it runs"); });
|
||||
// It calls any tool, script_run included, and plugin code.
|
||||
call.open_world = true;
|
||||
catalog.add(call);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// get_app_state, wait and get_log: what an agent reads before and after acting.
|
||||
// app_state, app_wait and app_log: what an agent reads before and after acting; undo and redo; and the app's
|
||||
// commands made from the Help menu's rows.
|
||||
|
||||
#include "JobRegistry.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
@@ -13,6 +14,8 @@
|
||||
#include "ScreenCapture.hpp"
|
||||
#include "UiInspector.hpp"
|
||||
#include "WindowControl.hpp"
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GCodeViewer.hpp"
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
@@ -21,20 +24,25 @@
|
||||
#include "slic3r/GUI/Gizmos/GLGizmosManager.hpp"
|
||||
#include "slic3r/GUI/Jobs/Worker.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/NativeCommandRows.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/Notebook.hpp"
|
||||
#include "slic3r/GUI/NotificationManager.hpp"
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
#include "slic3r/GUI/PrintHostDialogs.hpp"
|
||||
#include "slic3r/Utils/CloudProvider.hpp"
|
||||
#include "slic3r/Utils/NetworkAgent.hpp"
|
||||
#include "slic3r/Utils/bambu_networking.hpp"
|
||||
#include "slic3r/plugin/PythonInterpreter.hpp"
|
||||
#ifdef SLIC3R_CAD
|
||||
#include "McpToolsCad.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#endif
|
||||
#if defined(__WXGTK__)
|
||||
#include "slic3r/GUI/LinuxDisplayBackend.hpp"
|
||||
#endif
|
||||
|
||||
#include "libslic3r/AppConfig.hpp"
|
||||
#include "libslic3r/Model.hpp"
|
||||
#include "libslic3r/PresetBundle.hpp"
|
||||
#include "libslic3r/Utils.hpp"
|
||||
@@ -53,6 +61,7 @@
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <deque>
|
||||
#include <istream>
|
||||
#include <string>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
@@ -123,7 +132,7 @@ json app_state(AutomationRuntime& runtime)
|
||||
{"jobs", runtime.jobs().list()}};
|
||||
if (json recording = runtime.recorder().state(); !recording.is_null())
|
||||
state["recording"] = std::move(recording);
|
||||
// Each display's work area, where set_window can place a window.
|
||||
// Each display's work area, where window_set can place a window.
|
||||
json displays = json::array();
|
||||
for (unsigned i = 0; i < wxDisplay::GetCount(); ++i) {
|
||||
const wxDisplay display(i);
|
||||
@@ -133,12 +142,24 @@ json app_state(AutomationRuntime& runtime)
|
||||
displays.push_back(std::move(area));
|
||||
}
|
||||
state["displays"] = std::move(displays);
|
||||
// Whether a person is signed in to the Orca cloud and to Bambu Lab's, and the Bambu network plug-in as the app found
|
||||
// it: installed (the setting that has the app load it), loaded, its version and why it did not load.
|
||||
GUI_App& app = wxGetApp();
|
||||
state["account"] = {{"signed_in", app.is_user_login(ORCA_CLOUD_PROVIDER)}, {"bambu_signed_in", app.is_user_login(BBL_CLOUD_PROVIDER)}};
|
||||
const bool loaded = NetworkAgent::is_network_module_loaded();
|
||||
const NetworkLibraryLoadError load_error = NetworkAgent::get_load_error();
|
||||
state["network_plugin"] = {{"installed", app.app_config->get_bool("installed_networking")},
|
||||
{"loaded", loaded},
|
||||
{"version", loaded ? NetworkAgent::get_version() : std::string()},
|
||||
{"error", load_error.has_error ? load_error.message : std::string()}};
|
||||
// The folder Help > Show Configuration Folder opens: the presets, the app configuration and the logs.
|
||||
state["config_folder"] = data_dir();
|
||||
MainFrame* frame = wxGetApp().mainframe;
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (frame == nullptr || plater == nullptr)
|
||||
return state;
|
||||
|
||||
// The size and state list_windows reports, and the place where the platform knows it.
|
||||
// The size and state window_list reports, and the place where the platform knows it.
|
||||
const wxSize size = window_size(*frame);
|
||||
const std::string frame_state = window_state(*frame);
|
||||
state["window"] = {{"title", into_u8(frame->GetTitle())},
|
||||
@@ -188,6 +209,7 @@ json app_state(AutomationRuntime& runtime)
|
||||
// plater's while it is shown.
|
||||
if (GLCanvas3D* canvas = shown_canvas(); canvas != nullptr && canvas->get_wxglcanvas()->IsShownOnScreen())
|
||||
state["camera"] = camera_state(plater->get_camera(), canvas->get_scale());
|
||||
state["view"] = view_state(*plater);
|
||||
// The open gizmo, on the canvas shown first.
|
||||
state["gizmo"] = nullptr;
|
||||
std::vector<GLCanvas3D*> canvases = live_canvases();
|
||||
@@ -199,7 +221,7 @@ json app_state(AutomationRuntime& runtime)
|
||||
}
|
||||
state["objects"] = plater->model().objects.size();
|
||||
state["slicing"] = plater->is_slicing_any();
|
||||
// The selection select_objects acts on: the assemble view's while it is shown, else Prepare's.
|
||||
// The selection object_select acts on: the assemble view's while it is shown, else Prepare's.
|
||||
GLCanvas3D* assemble = plater->get_assmeble_canvas3D();
|
||||
GLCanvas3D* scene = assemble != nullptr && plater->get_current_canvas3D() == assemble ? assemble : plater->get_view3D_canvas3D();
|
||||
state["selection"] = scene != nullptr ? selection_state(*scene) : json();
|
||||
@@ -248,30 +270,79 @@ bool condition_holds(AutomationRuntime& runtime, const std::string& condition, c
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_app_tools(CommandCatalog& catalog)
|
||||
std::vector<std::string> log_tail(std::istream& in, const std::string& min_level, std::size_t lines)
|
||||
{
|
||||
// The log file sink starts an entry with its level, "[error]\t" (set_log_path_and_level(), utils.cpp); a line
|
||||
// without one continues the message of the entry above it.
|
||||
static const std::vector<std::string> levels{"trace", "debug", "info", "warning", "error", "fatal"};
|
||||
const auto level_of = [](const std::string& line) {
|
||||
for (std::size_t i = 0; i < levels.size(); ++i)
|
||||
if (const std::string field = "[" + levels[i] + "]\t"; line.compare(0, field.size(), field) == 0)
|
||||
return int(i);
|
||||
return -1;
|
||||
};
|
||||
const int min = int(std::find(levels.begin(), levels.end(), min_level) - levels.begin());
|
||||
// The newest entries kept, each its first line and those that continue it, as many as fit in `lines`.
|
||||
std::deque<std::vector<std::string>> entries;
|
||||
std::size_t held = 0;
|
||||
// Lines before the file's first entry, which continue an entry of an earlier file, have no level to filter by.
|
||||
bool keeping = min == 0;
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
if (const int level = level_of(line); level >= 0) {
|
||||
keeping = level >= min;
|
||||
if (keeping)
|
||||
entries.emplace_back();
|
||||
} else if (keeping && entries.empty()) {
|
||||
entries.emplace_back();
|
||||
}
|
||||
if (!keeping)
|
||||
continue;
|
||||
entries.back().push_back(std::move(line));
|
||||
++held;
|
||||
while (held > lines && entries.size() > 1) {
|
||||
held -= entries.front().size();
|
||||
entries.pop_front();
|
||||
}
|
||||
}
|
||||
// An entry longer than `lines` gives its first lines.
|
||||
std::vector<std::string> out;
|
||||
for (std::vector<std::string>& entry : entries)
|
||||
for (std::string& kept : entry)
|
||||
if (out.size() < lines)
|
||||
out.push_back(std::move(kept));
|
||||
return out;
|
||||
}
|
||||
|
||||
void register_app_tools(CommandCatalog& catalog, [[maybe_unused]] bool cad)
|
||||
{
|
||||
catalog.add(inspect_tool(
|
||||
"core", "get_app_state", L("Get app state"),
|
||||
"app_state", L("Get app state"),
|
||||
"Snapshot of OrcaSlicer. Call it first and whenever you are unsure what the app is doing. The app: version, platform "
|
||||
"and display backend, whether it is ready, the main window, the displays (each one's work area x, y, width and "
|
||||
"height, as set_window takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python "
|
||||
"height, as window_set takes positions, its scale and whether it is primary), the MCP endpoint (mcp), python "
|
||||
"(available: Python runs "
|
||||
"in this build; scripts_unrestricted: a script's own file, network, process and thread access is not held to "
|
||||
"OrcaSlicer's folders, which only a person turns on, in Preferences > AI features > Python scripts or for one run "
|
||||
"with --unrestricted-scripts), design_tab "
|
||||
"(the Design tab is on, and call_tool runs its commands, search_tools' group Design) and, when they do not run, "
|
||||
"cad_note, how a person turns the CAD feature on. The project: current tab and mode, printer technology, name, path and unsaved changes, "
|
||||
"(the Design tab is on, and tool_call runs its commands, tool_search's group Design) and, when they do not run, "
|
||||
"cad_note, how a person turns the CAD feature on; account (signed_in to the Orca cloud, bambu_signed_in to Bambu "
|
||||
"Lab's), network_plugin (installed, loaded, version, error: the Bambu network plug-in as the app found it) and "
|
||||
"config_folder (presets, app configuration and logs). The view outside the Design tab (view: sidebar_collapsed, "
|
||||
"sidebar_width, legend_collapsed, gcode_window, projection, section and the display switches labels, overhangs, "
|
||||
"outline, wireframe, gridlines, axes and navigator, under the names view_set takes them). "
|
||||
"The project: current tab and mode, printer technology, name, path and unsaved changes, "
|
||||
"selected printer/process/filament presets, plates (count, current), object count, the selection (objects, the "
|
||||
"instances [[object, instance]] they are selected in and, when parts rather than whole instances are selected, "
|
||||
"parts [[object, part]], in the indices select_objects takes; wipe_tower when a prime tower is selected; canvas is the 3D "
|
||||
"parts [[object, part]], in the indices object_select takes; wipe_tower when a prime tower is selected; canvas is the 3D "
|
||||
"view it belongs to), slicing state, "
|
||||
"the Preview's view type, time mode and layer range (1-based, with their Z), and the camera of the 3D view shown "
|
||||
"(camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as set_view replies with it). What "
|
||||
"(camera: type, look_at, position, zoom, click_px_per_mm, elevation and azimuth, as view_set replies with it). What "
|
||||
"is going on: open modal "
|
||||
"dialogs, each with its title, buttons (enabled: false when disabled) and a message that reads it as shown: its "
|
||||
"text and its controls row by row, fields [value], choices [value ▾], checkboxes [x] / [ ] / [-], radio and "
|
||||
"selector options (*) / ( ), list rows \"- row | cells\", secrets [******], \" (disabled)\" after a disabled "
|
||||
"control; menus closed unseen (a menu a call opened that no reply listed), auto_answer_dialogs rules in force, "
|
||||
"control; menus closed unseen (a menu a call opened that no reply listed), dialog_auto_answer rules in force, "
|
||||
"notifications, print host uploads (state, progress, error), the open gizmo, running jobs and a running "
|
||||
"recording.",
|
||||
object_schema({}), [](const json&, ToolContext& ctx) {
|
||||
@@ -280,9 +351,9 @@ void register_app_tools(CommandCatalog& catalog)
|
||||
}));
|
||||
|
||||
NativeCommand wait = inspect_tool(
|
||||
"core", "wait", L("Wait for a condition"),
|
||||
"app_wait", L("Wait for a condition"),
|
||||
"Block until a condition holds or timeout_s passes (max 50). for: \"ready\" (startup finished), \"idle\" (no dialog, "
|
||||
"no running job, nothing slicing or arranging, no gizmo working in the background; a run_script run counts only "
|
||||
"no running job, nothing slicing or arranging, no gizmo working in the background; a script_run run counts only "
|
||||
"through the calls it makes), \"dialog\" / \"no_dialog\", or \"job\" with a job id an earlier call returned, whose "
|
||||
"result is then the reply. On timeout the reply is {satisfied: false}, or for a job {status: \"running\", job, "
|
||||
"note}: call it again.",
|
||||
@@ -319,34 +390,124 @@ void register_app_tools(CommandCatalog& catalog)
|
||||
catalog.add(wait);
|
||||
|
||||
catalog.add(inspect_tool(
|
||||
"core", "get_log", L("Read the log"),
|
||||
"The last lines of OrcaSlicer's current log file, optionally only those at or above a level.",
|
||||
object_schema({{"lines", {{"type", "integer"}, {"minimum", 1}, {"maximum", 2000}, {"description", "Default 200."}}},
|
||||
"app_log", L("Read the log"),
|
||||
"The last lines of OrcaSlicer's current log file, optionally only those at or above a level. An entry's level is "
|
||||
"the one its first line starts with ([error]); the lines of its message after the first come with it, and the "
|
||||
"reply holds whole entries.",
|
||||
object_schema({{"lines", {{"type", "integer"}, {"minimum", 1}, {"maximum", 2000},
|
||||
{"description", "The most lines, of the newest whole entries; an entry longer than that gives its "
|
||||
"first lines. Default 200."}}},
|
||||
{"level", enum_prop({"trace", "debug", "info", "warning", "error", "fatal"}, "Minimum level.")}}),
|
||||
[](const json& args, ToolContext&) {
|
||||
const boost::filesystem::path file = get_log_file_name();
|
||||
if (file.empty())
|
||||
throw ToolFailure("No log file is open");
|
||||
static const std::vector<std::string> levels{"trace", "debug", "info", "warning", "error", "fatal"};
|
||||
const std::string min_level = arg_string(args, "level", "trace");
|
||||
const auto min_it = std::find(levels.begin(), levels.end(), min_level);
|
||||
const std::size_t lines = std::size_t(arg_int(args, "lines", 200));
|
||||
flush_logs();
|
||||
boost::nowide::ifstream in(path_to_utf8(file).c_str());
|
||||
std::deque<std::string> tail;
|
||||
std::string line;
|
||||
while (std::getline(in, line)) {
|
||||
bool keep = min_it == levels.begin();
|
||||
for (auto it = min_it; !keep && it != levels.end(); ++it)
|
||||
keep = line.find("[" + *it + "]") != std::string::npos;
|
||||
if (!keep)
|
||||
continue;
|
||||
tail.push_back(line);
|
||||
if (tail.size() > lines)
|
||||
tail.pop_front();
|
||||
}
|
||||
return ToolResult::ok({{"file", path_to_utf8(file)}, {"lines", json(std::vector<std::string>(tail.begin(), tail.end()))}});
|
||||
const std::vector<std::string> tail = log_tail(in, arg_string(args, "level", "trace"),
|
||||
std::size_t(arg_int(args, "lines", 200)));
|
||||
return ToolResult::ok({{"file", path_to_utf8(file)}, {"lines", json(tail)}});
|
||||
}));
|
||||
|
||||
// Undo and Redo act on the shown tab's history, as the Edit menu's do; history names one for automation, which acts
|
||||
// whatever tab is shown. Each has a tile of its own, in the Speed Dial's section Commands.
|
||||
const json history = object_schema(
|
||||
{{"history", enum_prop({"design", "project"}, "The history: design, the Design tab's (with the CAD feature on), or project. "
|
||||
"Default: the Design tab's while it is shown, else the project's.")}});
|
||||
// A person's pick does what the Edit menu's item does, and shows nothing where it would be greyed. An automated
|
||||
// call, action_run of the tile included, acts on the history Rows::undo_redo() picks: the Design tab's through its
|
||||
// gate, whose refusals say why, and the project's as the Edit menu's item does.
|
||||
const auto history_command = [&history](std::string key, std::string title, std::string icon, std::string description, bool redo) {
|
||||
NativeCommand command = row_command(std::move(key), std::move(title), std::move(description), history, json(),
|
||||
[redo](const json& args) { return Rows::undo_redo(args, redo); });
|
||||
const CommandFn picked = NativeCommands::ui_command(command.key, command.title, command.group, history,
|
||||
[redo](const json& args) { return Rows::picked_undo_redo(args, redo); })
|
||||
.run;
|
||||
command.run = [picked, automated = std::move(command.run)](const json& args, ToolContext& ctx) {
|
||||
return ctx.person() ? picked(args, ctx) : automated(args, ctx);
|
||||
};
|
||||
command.in_palette = true;
|
||||
command.tile_group = L("Commands");
|
||||
command.icon = std::move(icon);
|
||||
return command;
|
||||
};
|
||||
NativeCommand undo = history_command(
|
||||
"undo", L("Undo"), "menu_undo",
|
||||
"Take back the last change of a history, as Edit > Undo does. history design is the Design tab's: the last feature "
|
||||
"added, edited, deleted, moved, shown or hidden, or renamed, or variable changed, or in a sketch session the last "
|
||||
"drawn shape; project is the project's. Without history, the Design tab's while it is shown, else the project's. "
|
||||
"Reply: history and, for the Design tab's, result: scope (design or sketch), undo_depth, redo_depth, features, "
|
||||
"bodies and generation; entities in a sketch.",
|
||||
false);
|
||||
NativeCommand redo = history_command("redo", L("Redo"), "menu_redo",
|
||||
"Put back what undo took back, until the next change, as Edit > Redo does, in the history "
|
||||
"undo takes. Reply as undo's.",
|
||||
true);
|
||||
#ifdef SLIC3R_CAD
|
||||
// An example calls Design commands, so only a catalog that holds them documents the Design history.
|
||||
if (cad) {
|
||||
undo.examples = json::parse(R"json([
|
||||
{"title": "Take back an extrude, its sketch with it", "calls": [
|
||||
{"tool": "extrude", "args": {"width": 20, "height": 20, "distance": 5}},
|
||||
{"tool": "undo", "args": {"history": "design"}}]},
|
||||
{"title": "Take back the last shape drawn in a sketch", "calls": [
|
||||
{"tool": "sketch_create", "args": {"plane": "XY"}},
|
||||
{"tool": "sketch_draw", "args": {"type": "rectangle_2_point", "p0": [-15, -10], "p1": [15, 10]}},
|
||||
{"tool": "sketch_draw", "args": {"entities": [{"type": "circle_center", "center": [0, 0], "radius": 4}]}},
|
||||
{"tool": "undo", "args": {"history": "design"}}]}])json");
|
||||
redo.examples = json::parse(R"json([
|
||||
{"title": "Put back an extrude undo took back", "calls": [
|
||||
{"tool": "extrude", "args": {"width": 20, "height": 20, "distance": 5}},
|
||||
{"tool": "undo", "args": {"history": "design"}},
|
||||
{"tool": "redo", "args": {"history": "design"}}]},
|
||||
{"title": "Put back the shape undo took off a sketch", "calls": [
|
||||
{"tool": "sketch_create", "args": {"plane": "XY"}},
|
||||
{"tool": "sketch_draw", "args": {"type": "rectangle_2_point", "p0": [-15, -10], "p1": [15, 10]}},
|
||||
{"tool": "sketch_draw", "args": {"entities": [{"type": "circle_center", "center": [0, 0], "radius": 4}]}},
|
||||
{"tool": "undo", "args": {"history": "design"}},
|
||||
{"tool": "redo", "args": {"history": "design"}}]}])json");
|
||||
}
|
||||
#endif
|
||||
catalog.add(std::move(undo));
|
||||
catalog.add(std::move(redo));
|
||||
|
||||
// ---- The app's commands made from the Help and Plugins menus' rows ----
|
||||
using NativeCommands::tile;
|
||||
NativeCommand web_page = row_command(
|
||||
"app_open_web_page", L("Open a web page"),
|
||||
"Open one of OrcaSlicer's web pages in the default web browser, as its menu row does: wiki, the OrcaSlicer wiki; "
|
||||
"youtube, the OrcaSlicer YouTube channel; plugin_hub, the plugin hub's page, where a person picks a plugin to install. "
|
||||
"Nothing opens in OrcaSlicer.",
|
||||
object_schema({{"page", enum_prop({"wiki", "youtube", "plugin_hub"}, "The page.")}}, {"page"}),
|
||||
json::array({tile("open_wiki", L("Open Wiki"), L("Help"), "link_wiki_img", {{"page", "wiki"}}, "Open the OrcaSlicer wiki in the browser."),
|
||||
tile("open_youtube", L("Open YouTube Channel"), L("Help"), "", {{"page", "youtube"}},
|
||||
"Open the OrcaSlicer YouTube channel in the browser."),
|
||||
tile("install_plugin", L("Install Plugin"), L("Plugins"), "", {{"page", "plugin_hub"}},
|
||||
"Open the plugin hub's page in the default web browser, where a person picks a plugin to install; "
|
||||
"nothing opens in OrcaSlicer.")}),
|
||||
[](const json& args) { return Rows::open_web_page(arg_string(args, "page")); });
|
||||
// The browser it opens reaches the network.
|
||||
web_page.open_world = true;
|
||||
catalog.add(std::move(web_page));
|
||||
const std::string updates = "Check for a newer OrcaSlicer.";
|
||||
NativeCommand check_updates = row_command("app_check_for_updates", L("Check for Updates"), updates, object_schema({}),
|
||||
json::array({tile("help_check_updates", L("Check for Updates"), L("Help"), "refresh",
|
||||
json::object(), updates)}),
|
||||
[](const json&) { return Rows::check_for_updates(); });
|
||||
// It asks the update server.
|
||||
check_updates.open_world = true;
|
||||
catalog.add(std::move(check_updates));
|
||||
const std::string folder = "Open the configuration folder in the file manager.";
|
||||
catalog.add(row_command("app_show_config_folder", L("Show Configuration Folder"), folder, object_schema({}),
|
||||
json::array({tile("help_open_config_folder", L("Show Configuration Folder"), L("Help"), "open_project",
|
||||
json::object(), folder)}),
|
||||
[](const json&) { return Rows::show_config_folder(); }));
|
||||
const std::string benchmark = "Time the 3D views on a test model. It asks first (Start or Cancel), then replaces the project with "
|
||||
"the OrcaSliced Combo as New Project does, which may ask about unsaved changes, slices it and shows "
|
||||
"the results.";
|
||||
catalog.add(row_command("app_benchmark_3d_scene", L("Benchmark 3D Scene"), benchmark, object_schema({}),
|
||||
json::array({tile("help_benchmark_3d_scene", L("Benchmark 3D Scene"), L("Help"), "", json::object(), benchmark)}),
|
||||
[](const json&) { return Rows::benchmark_3d_scene(); }));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -51,7 +51,7 @@
|
||||
#include "McpArguments.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "McpPaths.hpp"
|
||||
#include "UiInspector.hpp" // gizmo_name: the name get_app_state reports
|
||||
#include "UiInspector.hpp" // gizmo_name: the name app_state reports
|
||||
#include "slic3r/GUI/CAD/DesignPanel.hpp"
|
||||
#include "slic3r/GUI/CAD/DesignCanvas.hpp"
|
||||
#include "slic3r/GUI/CAD/DesignSketchTool.hpp"
|
||||
@@ -193,7 +193,7 @@ std::string mode_note(const DesignTool& t, bool no_arguments = false)
|
||||
// catalog holds the Design commands only when the feature was on at startup (the preference, or the command
|
||||
// line's --cad), and the main window creates the Design page only then too (its panel is built on first use),
|
||||
// so turning the feature on takes a restart.
|
||||
const char* const kCadOffNote = "call_tool runs no Design command now: they need the CAD feature on when OrcaSlicer "
|
||||
const char* const kCadOffNote = "tool_call runs no Design command now: they need the CAD feature on when OrcaSlicer "
|
||||
"started, in Preferences > Features or with --cad. A person turns it on there if it is "
|
||||
"off and restarts OrcaSlicer, or starts it with --cad.";
|
||||
|
||||
@@ -2827,7 +2827,7 @@ json action_commit_to_plate(DesignPanel* panel, const json& params)
|
||||
{"tab", "prepare"}};
|
||||
}
|
||||
|
||||
// New Design without its confirmation dialog: discard_changes confirms, as new_project's does.
|
||||
// New Design without its confirmation dialog: discard_changes confirms, as project_new's does.
|
||||
json action_new_design(DesignPanel* panel, const json& params)
|
||||
{
|
||||
const CadDocument& doc = panel->mcp_doc();
|
||||
@@ -3469,7 +3469,7 @@ json sketch_transform(DesignSketchTool& t, const json& params, bool pattern)
|
||||
SketchConstraintType constraint_type_arg(const json& v)
|
||||
{
|
||||
if (!v.is_string())
|
||||
throw std::runtime_error("type must be a constraint type, such as \"parallel\" (search_tools {tool: \"sketch_constrain\"} lists "
|
||||
throw std::runtime_error("type must be a constraint type, such as \"parallel\" (tool_search {tool: \"sketch_constrain\"} lists "
|
||||
"them, and {tool: \"sketch_dimension\"} the dimensions)");
|
||||
const std::string s = v.get<std::string>();
|
||||
if (s == "equal") return SketchConstraintType::EqualLength;
|
||||
@@ -3480,7 +3480,7 @@ SketchConstraintType constraint_type_arg(const json& v)
|
||||
if (edit_distance(boost::algorithm::to_lower_copy(s), n) <= 2 + s.size() / 4)
|
||||
close += std::string(close.empty() ? "" : ", ") + "\"" + n + "\"";
|
||||
throw std::runtime_error("unknown constraint type \"" + s + "\"" + (close.empty() ? "" : "; did you mean " + close) +
|
||||
" (search_tools {tool: \"sketch_constrain\"} lists them, and {tool: \"sketch_dimension\"} the dimensions)");
|
||||
" (tool_search {tool: \"sketch_constrain\"} lists them, and {tool: \"sketch_dimension\"} the dimensions)");
|
||||
}
|
||||
|
||||
// Why the CONSTRAIN bar refuses a pick, in ConstraintReject order: a code an agent can test and the
|
||||
@@ -4980,11 +4980,11 @@ void cad_apply_feature_refs(CadFeature& f, const json& refs, const CadDocument&
|
||||
|
||||
std::vector<int> cad_commit_to_plate_replace(const json& replace, const Model& model)
|
||||
{
|
||||
if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (list_objects)");
|
||||
if (!replace.is_array()) throw std::runtime_error("replace takes a list of object indices (object_list)");
|
||||
const int count = int(model.objects.size());
|
||||
std::vector<int> out;
|
||||
for (const json& v : replace) {
|
||||
if (!v.is_number_integer()) throw std::runtime_error("replace takes object indices (list_objects), not " + v.dump());
|
||||
if (!v.is_number_integer()) throw std::runtime_error("replace takes object indices (object_list), not " + v.dump());
|
||||
const auto i = v.get<std::int64_t>();
|
||||
if (i < 0 || i >= count)
|
||||
throw std::runtime_error("object " + std::to_string(i) + " is out of range; the project has " + std::to_string(count) +
|
||||
@@ -4994,7 +4994,7 @@ std::vector<int> cad_commit_to_plate_replace(const json& replace, const Model& m
|
||||
// Deleting one opens the "part of a cut object" warning, which the person answers.
|
||||
if (model.objects[size_t(i)]->is_cut())
|
||||
throw std::runtime_error("object " + std::to_string(i) +
|
||||
" is part of a cut object; delete it with select_objects + run_action obj_delete, which asks first");
|
||||
" is part of a cut object; delete it with object_select, then object_delete, which asks first");
|
||||
out.push_back(int(i));
|
||||
}
|
||||
std::sort(out.begin(), out.end());
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
// The Design tab's commands, one per entry of its table (kDesignTools, DesignOffer.hpp, generated from
|
||||
// scripts/CAD/tool_atlas.json) that has an action or a tool block and is no folded row (is_design_command()): its
|
||||
// tools, sketches, features, measurements and edits, which an agent finds with search_tools (group Design) and
|
||||
// runs with call_tool, and a person picks as Speed Dial tiles while the Design tab is shown, those of the mode it
|
||||
// tools, sketches, features, measurements and edits, which an agent finds with tool_search (group Design) and
|
||||
// runs with tool_call, and a person picks as Speed Dial tiles while the Design tab is shown, those of the mode it
|
||||
// is in. A call with exactly the arguments that choose one of the command's rows (opened_row()) does what that
|
||||
// right-click menu row does, in the mode the row belongs to (open_refusal()); any other call, or one with
|
||||
// silent: true, runs the entry's tool block's silent form. They run on the UI thread through the GUI's own
|
||||
@@ -80,7 +80,7 @@ void register_cad_commands(CommandCatalog& catalog);
|
||||
// started and how a person turns it on (CommandCatalog::leave_out()).
|
||||
void leave_out_cad_commands(CommandCatalog& catalog);
|
||||
|
||||
// What search_tools' description says of the Design commands, which tools/list does not show, so that an agent
|
||||
// What tool_search's description says of the Design commands, which tools/list does not show, so that an agent
|
||||
// learns without a search that they exist and are CAD: a lead saying what they cover, that one is looked up with
|
||||
// tool before it is called, and that a command whose schema has silent does what its menu row does when called
|
||||
// with no arguments unless silent is true; then each heading of kDesignSections with the keys of its commands
|
||||
@@ -169,7 +169,7 @@ nlohmann::json run_cad_tool(const std::string& id, const nlohmann::json& args);
|
||||
// generation. Fails (-32000) when there is nothing to take back or put back. UI thread only.
|
||||
nlohmann::json cad_undo_redo(bool redo);
|
||||
|
||||
// get_app_state's cad_note: how a person turns the CAD feature on, in the editor while the Design commands
|
||||
// app_state's cad_note: how a person turns the CAD feature on, in the editor while the Design commands
|
||||
// cannot run, because `catalog` holds none of them (the feature was off at startup) or the feature is off
|
||||
// now; null otherwise. UI thread.
|
||||
nlohmann::json cad_note(const CommandCatalog& catalog);
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "libslic3r/Model.hpp"
|
||||
|
||||
#include "UiInspector.hpp"
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
@@ -24,6 +25,7 @@
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
@@ -57,10 +59,10 @@ json enum_prop(std::vector<std::string> values, const std::string& description)
|
||||
|
||||
json array_prop(json items, const std::string& description) { return {{"type", "array"}, {"items", std::move(items)}, {"description", description}}; }
|
||||
|
||||
NativeCommand inspect_tool(std::string group, std::string name, std::string title, std::string description, json schema, CommandFn handler)
|
||||
NativeCommand inspect_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler)
|
||||
{
|
||||
NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), std::move(group), std::move(schema),
|
||||
std::move(handler), /*inline_call=*/true);
|
||||
NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler),
|
||||
/*inline_call=*/true);
|
||||
d.description = std::move(description);
|
||||
d.listed = true;
|
||||
d.read_only = true;
|
||||
@@ -76,11 +78,9 @@ NativeCommand reaching(std::vector<std::string> operations, NativeCommand comman
|
||||
return command;
|
||||
}
|
||||
|
||||
NativeCommand mutate_tool(std::string group, std::string name, std::string title, std::string description, json schema, CommandFn handler,
|
||||
bool destructive)
|
||||
NativeCommand mutate_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler, bool destructive)
|
||||
{
|
||||
NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), std::move(group), std::move(schema),
|
||||
std::move(handler));
|
||||
NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler));
|
||||
d.description = std::move(description);
|
||||
d.listed = true;
|
||||
d.destructive = destructive;
|
||||
@@ -88,6 +88,30 @@ NativeCommand mutate_tool(std::string group, std::string name, std::string title
|
||||
return d;
|
||||
}
|
||||
|
||||
NativeCommand row_command(std::string name, std::string title, std::string description, json schema, json tiles,
|
||||
std::function<AppActionRunResult(const json& args)> fn)
|
||||
{
|
||||
NativeCommand d = NativeCommands::ui_command(std::move(name), std::move(title), {}, std::move(schema), std::move(fn));
|
||||
d.description = std::move(description);
|
||||
d.tiles = std::move(tiles);
|
||||
d.listed = true;
|
||||
return d;
|
||||
}
|
||||
|
||||
AppActionRunResult row_reply(const json& reply)
|
||||
{
|
||||
AppActionRunResult result{AppActionRunResult::Level::Succeeded};
|
||||
result.reply = reply.dump();
|
||||
return result;
|
||||
}
|
||||
|
||||
AppActionRunResult quiet_refusal(const Ops::Refusal& refusal)
|
||||
{
|
||||
AppActionRunResult kept{AppActionRunResult::Level::Info, {}, false};
|
||||
kept.refusal = std::make_shared<const Ops::Refusal>(refusal);
|
||||
return kept;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// Whether a 3D view is shown but can't draw yet. On Wayland a canvas gets its GL surface from the
|
||||
@@ -179,7 +203,7 @@ Plater& ui_plater()
|
||||
throw ToolFailure("OrcaSlicer is shutting down");
|
||||
Plater* plater = wxGetApp().plater();
|
||||
if (plater == nullptr || wxGetApp().mainframe == nullptr)
|
||||
throw ToolFailure("OrcaSlicer is still starting; wait {for:\"ready\"} first");
|
||||
throw ToolFailure("OrcaSlicer is still starting; app_wait {for:\"ready\"} first");
|
||||
return *plater;
|
||||
}
|
||||
|
||||
@@ -246,7 +270,7 @@ json expected_id_prop(const char* of)
|
||||
{
|
||||
return {{"type", "integer"},
|
||||
{"minimum", 0},
|
||||
{"description", std::string("The id list_objects reports for this ") + of +
|
||||
{"description", std::string("The id object_list reports for this ") + of +
|
||||
": the call is refused when the index names another one now."}};
|
||||
}
|
||||
|
||||
@@ -264,12 +288,12 @@ void check_expected_ids(const ModelObject& object, const ModelVolume* volume, co
|
||||
if (args.contains("object_id") && args["object_id"].get<std::size_t>() != object.id().id)
|
||||
throw ToolFailure("The object at this index is now \"" + object.name + "\" (id " + std::to_string(object.id().id) +
|
||||
"), not the expected id " + std::to_string(args["object_id"].get<std::size_t>()) +
|
||||
": list_objects again",
|
||||
": object_list again",
|
||||
{{"id", object.id().id}});
|
||||
if (volume != nullptr && args.contains("part_id") && args["part_id"].get<std::size_t>() != volume->id().id)
|
||||
throw ToolFailure("The part at this index is now \"" + volume->name + "\" (id " + std::to_string(volume->id().id) +
|
||||
"), not the expected id " + std::to_string(args["part_id"].get<std::size_t>()) +
|
||||
": list_objects again",
|
||||
": object_list again",
|
||||
{{"id", volume->id().id}});
|
||||
}
|
||||
|
||||
|
||||
+1697
-416
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,337 @@
|
||||
// printer_list_models, printer_install and printer_uninstall: what the Printer Selection dialog lists and its Confirm
|
||||
// installs; filament_install and filament_uninstall: what the System Filaments dialog's Confirm installs. On the
|
||||
// operations of GUI/Operations/InstallOps.hpp.
|
||||
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/Operations/InstallOps.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Operations/PresetOps.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
#include <future>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
// Runs `load` on a thread of its own with a flag that turns true once the call is cancelled (job_cancel, a stop of
|
||||
// the replay or script it runs in, the app closing), which the load of the vendors reads between vendors.
|
||||
template<class Result> Result cancellable(ToolContext& ctx, const std::function<Result(const std::atomic<bool>*)>& load)
|
||||
{
|
||||
std::atomic<bool> cancel{false};
|
||||
std::future<Result> result = std::async(std::launch::async, [&load, &cancel] { return load(&cancel); });
|
||||
while (result.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready)
|
||||
if (ctx.cancelled())
|
||||
cancel = true;
|
||||
return result.get();
|
||||
}
|
||||
|
||||
// What the install commands reply when an operation refuses: the names a refusal carries under the key that says
|
||||
// what they are, and the preset tools' hint where the presets have unsaved changes.
|
||||
ToolFailure install_refused(const Ops::Refusal& refusal)
|
||||
{
|
||||
const std::string code = refusal.code;
|
||||
if (code == "no_such_vendor" || code == "no_such_model")
|
||||
return refused(refusal, "printer_list_models lists them.", "similar");
|
||||
if (code == "ambiguous_model" || code == "vendors_not_loaded")
|
||||
return refused(refusal, "", "vendors");
|
||||
if (code == "no_such_nozzle")
|
||||
return refused(refusal, "", "nozzles");
|
||||
return preset_refused(refusal);
|
||||
}
|
||||
|
||||
// Every printer model the app ships or has installed, which a call's names are checked against. On the call's thread,
|
||||
// as the first read after a profile update loads every vendor.
|
||||
std::vector<Ops::PrinterModel> known_models(ToolContext& ctx)
|
||||
{
|
||||
using Known = Ops::Outcome<std::vector<Ops::PrinterModel>>;
|
||||
const Known known = cancellable<Known>(ctx, [](const std::atomic<bool>* cancel) {
|
||||
Ops::PrinterModelsArgs all;
|
||||
all.cancel = cancel;
|
||||
return Ops::printer_models(all);
|
||||
});
|
||||
if (!known)
|
||||
throw install_refused(known.refusal());
|
||||
return known.value();
|
||||
}
|
||||
|
||||
json models_json(const std::vector<Ops::ModelNozzles>& models)
|
||||
{
|
||||
json out = json::array();
|
||||
for (const Ops::ModelNozzles& model : models)
|
||||
out.push_back({{"vendor", model.vendor}, {"model", model.model}, {"nozzles", model.nozzles}});
|
||||
return out;
|
||||
}
|
||||
|
||||
// printer_install's and printer_uninstall's function: the models a call names, applied on the UI thread.
|
||||
CommandFn change_printers(bool install)
|
||||
{
|
||||
return [install](const json& args, ToolContext& ctx) {
|
||||
Ops::InstallPrintersArgs op;
|
||||
for (const json& item : args.at("models")) {
|
||||
Ops::ModelNozzles model{arg_string(item, "vendor"), arg_string(item, "model"), {}};
|
||||
if (const auto nozzles = item.find("nozzles"); nozzles != item.end())
|
||||
for (const json& nozzle : *nozzles)
|
||||
model.nozzles.push_back(nozzle.get<std::string>());
|
||||
op.models.push_back(std::move(model));
|
||||
}
|
||||
op.changes = preset_changes_answer(args);
|
||||
op.known = known_models(ctx);
|
||||
json reply = ctx.run_ui([&] {
|
||||
ui_plater();
|
||||
const json before = unsaved_changes();
|
||||
const Ops::Outcome<Ops::InstalledPrinters> done = install ? Ops::install_printers(op) : Ops::uninstall_printers(op);
|
||||
if (!done)
|
||||
throw install_refused(done.refusal());
|
||||
const Ops::InstalledPrinters& printers = done.value();
|
||||
json out{{"models", models_json(printers.models)}, {"selected", printers.selected}};
|
||||
out[install ? "added" : "removed"] = install ? printers.added : printers.removed;
|
||||
if (!(install ? printers.removed : printers.added).empty())
|
||||
out[install ? "removed" : "added"] = install ? printers.removed : printers.added;
|
||||
if (!printers.missing.empty())
|
||||
out[install ? "not_offered" : "still_offered"] = models_json(printers.missing);
|
||||
if (!printers.filaments_installed.empty())
|
||||
out["filaments_installed"] = printers.filaments_installed;
|
||||
if (!printers.filaments_uninstalled.empty())
|
||||
out["filaments_uninstalled"] = printers.filaments_uninstalled;
|
||||
out.update(unsaved_changes_outcome(before));
|
||||
return out;
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(reply);
|
||||
};
|
||||
}
|
||||
|
||||
// What the filament commands reply when an operation refuses: the names a refusal carries under the key that says
|
||||
// what they are.
|
||||
ToolFailure filament_refused(const Ops::Refusal& refusal)
|
||||
{
|
||||
const std::string code = refusal.code;
|
||||
if (code == "no_such_filament" || code == "no_filament_vendor")
|
||||
return refused(refusal, "preset_list {type: \"filament\", include_uninstalled: true} lists the system filaments.", "similar");
|
||||
if (code == "fits_no_printer")
|
||||
return refused(refusal, "Name one of its presets.", "presets");
|
||||
if (code == "no_matching_filament")
|
||||
return refused(refusal, "", "filament_types");
|
||||
if (code == "filament_in_use")
|
||||
return refused(refusal, "Select another filament for the slot first (preset_select with filament_slot).", "presets");
|
||||
return refused(refusal);
|
||||
}
|
||||
|
||||
// filament_install's and filament_uninstall's function: the names, or the vendor and filament type, a call gives.
|
||||
CommandFn change_filaments(bool install)
|
||||
{
|
||||
return [install](const json& args, ToolContext& ctx) {
|
||||
Ops::InstallFilamentsArgs op;
|
||||
if (const auto names = args.find("names"); names != args.end())
|
||||
for (const json& name : *names)
|
||||
op.names.push_back(name.get<std::string>());
|
||||
op.vendor = arg_string(args, "vendor");
|
||||
op.filament_type = arg_string(args, "filament_type");
|
||||
if (op.names.empty() && op.vendor.empty() && op.filament_type.empty())
|
||||
throw ToolFailure("Give names, or vendor and filament_type");
|
||||
if (!op.names.empty() && (args.contains("vendor") || args.contains("filament_type")))
|
||||
throw ToolFailure("Give names, or vendor and filament_type, not both");
|
||||
if (op.names.empty() && (op.vendor.empty() || op.filament_type.empty()))
|
||||
throw ToolFailure("vendor and filament_type go together");
|
||||
json reply = ctx.run_ui([&] {
|
||||
ui_plater();
|
||||
const Ops::Outcome<Ops::InstalledFilaments> done = install ? Ops::install_filaments(op) : Ops::uninstall_filaments(op);
|
||||
if (!done)
|
||||
throw filament_refused(done.refusal());
|
||||
json out{{install ? "installed" : "uninstalled", done.value().changed}};
|
||||
if (!done.value().unchanged.empty())
|
||||
out[install ? "installed_already" : "not_installed"] = done.value().unchanged;
|
||||
if (!done.value().defaults_installed.empty())
|
||||
out["filaments_installed"] = done.value().defaults_installed;
|
||||
return out;
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(reply);
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_install_tools(CommandCatalog& catalog)
|
||||
{
|
||||
const json models_prop = {
|
||||
{"type", "array"},
|
||||
{"minItems", 1},
|
||||
{"items", object_schema({{"model", prop("string", "The model, as printer_list_models lists it (\"Bambu Lab X1 Carbon\").")},
|
||||
{"vendor", prop("string", "Its vendor (\"BBL\"), needed where several vendors have a model of that "
|
||||
"name.")},
|
||||
{"nozzles", {{"type", "array"},
|
||||
{"minItems", 1},
|
||||
{"items", {{"type", "string"}}},
|
||||
{"description", "Its nozzles, as printer_list_models lists them (\"0.4\"). Default: "
|
||||
"all of them, as the dialog's tick of a model."}}}},
|
||||
{"model"})},
|
||||
{"description", "The printer models, each with its nozzles."}};
|
||||
const json preset_changes_prop = enum_prop({"transfer", "discard"},
|
||||
"The presets' unsaved changes, which reloading the presets drops: move them to the "
|
||||
"presets selected after it, or drop them, as the Transfer and Discard of the question "
|
||||
"the dialog's Confirm asks. Needed while presets have unsaved changes; without it the "
|
||||
"call is refused.");
|
||||
const std::string reload = "Reloading the presets drops their unsaved changes, so while there are some preset_changes says what "
|
||||
"becomes of them; without it the call is refused. A call that changes nothing reloads nothing. The "
|
||||
"reload installs a printer's default filaments where no installed filament fits it, as the dialog "
|
||||
"does, and where a vendor's profile lists default filaments of its own, which none of the shipped "
|
||||
"profiles does, swaps a @System filament for the vendor's: those are under filaments_installed and "
|
||||
"filaments_uninstalled. Two errors come after a change and say what it was: vendors_not_installed, "
|
||||
"where a vendor's profiles cannot be installed (the installed printers are as they were, the "
|
||||
"unsaved changes discarded if preset_changes said so, and the profiles copied before it stay in "
|
||||
"the configuration folder), and presets_not_reloaded (the installed printers were written, the "
|
||||
"presets not reloaded). Not in the undo history.";
|
||||
|
||||
NativeCommand list = NativeCommands::long_command(
|
||||
"printer_list_models", L("List printer models"), {},
|
||||
object_schema({{"vendor", prop("string", "A vendor's models only (\"BBL\", \"Prusa\"), in any case.")},
|
||||
{"query", prop("string", "Models whose name holds this, in any case.")},
|
||||
{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 500}, {"description", "Default 100."}}},
|
||||
{"offset", {{"type", "integer"}, {"minimum", 0}}}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
Ops::PrinterModelsArgs op;
|
||||
op.vendor = arg_string(args, "vendor");
|
||||
op.query = arg_string(args, "query");
|
||||
ctx.run_ui([&op] {
|
||||
ui_plater();
|
||||
op.installed = Ops::installed_set();
|
||||
return json();
|
||||
});
|
||||
using Models = Ops::Outcome<std::vector<Ops::PrinterModel>>;
|
||||
const Models models = cancellable<Models>(ctx, [&op](const std::atomic<bool>* cancel) {
|
||||
Ops::PrinterModelsArgs run = op;
|
||||
run.cancel = cancel;
|
||||
return Ops::printer_models(run);
|
||||
});
|
||||
if (!models)
|
||||
throw install_refused(models.refusal());
|
||||
json items = json::array();
|
||||
for (const Ops::PrinterModel& model : models.value())
|
||||
items.push_back({{"vendor", model.vendor},
|
||||
{"model", model.model},
|
||||
{"nozzles", model.nozzles},
|
||||
{"installed_nozzles", model.installed_nozzles}});
|
||||
return ToolResult::ok(page(items, args, 100));
|
||||
});
|
||||
list.description = "Every printer model OrcaSlicer ships or has installed, of every vendor, as the Printer Selection dialog "
|
||||
"lists them: each with its vendor (the vendor's id, \"BBL\"), model, nozzles and installed_nozzles, the "
|
||||
"nozzles whose printer presets the printer selector offers. vendor keeps one vendor's models, and query "
|
||||
"those whose name holds it. The first call after the shipped profiles change reads every vendor, which "
|
||||
"takes a while and can reply with a job to wait for; later calls read the result kept in the configuration "
|
||||
"folder. printer_install and printer_uninstall change what is installed.";
|
||||
list.listed = true;
|
||||
list.read_only = true;
|
||||
list.idempotent = true;
|
||||
list.guard = GuardClass::Inspect;
|
||||
list.journal = false;
|
||||
list.cancellable = true;
|
||||
list.operations = {"printer_models"};
|
||||
list.examples = json::parse(R"json([
|
||||
{"title": "Find a printer model and its nozzles", "calls": [
|
||||
{"tool": "printer_list_models", "args": {"query": "X1 Carbon"}}]},
|
||||
{"title": "List one vendor's printer models", "calls": [
|
||||
{"tool": "printer_list_models", "args": {"vendor": "Prusa"}}]}])json");
|
||||
catalog.add(std::move(list));
|
||||
|
||||
NativeCommand install = reaching(
|
||||
{"install_printers"},
|
||||
mutate_tool("printer_install", L("Install printer models"),
|
||||
"Install printer models, for good, as ticking them in the Printer Selection dialog and pressing Confirm "
|
||||
"does: a vendor's profiles are installed from the ones OrcaSlicer ships, the presets reloaded, and a printer "
|
||||
"newly added selected. The other installed models are kept, and the installed filaments but for what the "
|
||||
"reload changes. A name no model has, a vendor or a nozzle a model lacks, is refused with the closest "
|
||||
"names. " +
|
||||
reload +
|
||||
" Reply: models (what was named, resolved), added (the printer presets the printer selector offers "
|
||||
"that it did not before the call), selected, not_offered (named nozzles whose presets it still does "
|
||||
"not offer), and discarded/modified as preset_select's.",
|
||||
object_schema({{"models", models_prop}, {"preset_changes", preset_changes_prop}}, {"models"}),
|
||||
change_printers(true)));
|
||||
install.examples = json::parse(R"json([
|
||||
{"title": "Install a printer model with one of its nozzles", "calls": [
|
||||
{"tool": "printer_list_models", "args": {"query": "Velo"}},
|
||||
{"tool": "printer_install", "args": {"models": [{"vendor": "Goofoo", "model": "Goofoo Velo+", "nozzles": ["0.4"]}]}}]},
|
||||
{"title": "Install every nozzle of a model, dropping the presets' unsaved changes", "calls": [
|
||||
{"tool": "printer_install", "args": {"models": [{"model": "Bambu Lab X1 Carbon"}], "preset_changes": "discard"}}]}])json");
|
||||
catalog.add(std::move(install));
|
||||
|
||||
NativeCommand uninstall = reaching(
|
||||
{"uninstall_printers"},
|
||||
mutate_tool("printer_uninstall", L("Uninstall printer models"),
|
||||
"Uninstall printer models, for good, as unticking them in the Printer Selection dialog and pressing "
|
||||
"Confirm does: the printer selector no longer offers their printer presets, and the vendor's profiles stay "
|
||||
"on disk. Without nozzles a model goes whole. A printer removed while selected is replaced by another "
|
||||
"installed one. Removing the last installed printer model is refused, and so are names as printer_install "
|
||||
"refuses them. " +
|
||||
reload +
|
||||
" Reply: models, removed (the printer presets the printer selector no longer offers), selected, "
|
||||
"still_offered (named nozzles whose presets it still offers), and discarded/modified as preset_select's.",
|
||||
object_schema({{"models", models_prop}, {"preset_changes", preset_changes_prop}}, {"models"}),
|
||||
change_printers(false)));
|
||||
uninstall.examples = json::parse(R"json([
|
||||
{"title": "Uninstall a printer model", "calls": [
|
||||
{"tool": "printer_uninstall", "args": {"models": [{"vendor": "Goofoo", "model": "Goofoo Velo+"}]}}]}])json");
|
||||
catalog.add(std::move(uninstall));
|
||||
|
||||
const json names_prop = {{"type", "array"},
|
||||
{"minItems", 1},
|
||||
{"items", {{"type", "string"}}},
|
||||
{"description", "System filaments: a preset's name, or the short name the filament selector "
|
||||
"shows (\"Bambu PLA Basic\"), which stands for its preset of every installed "
|
||||
"printer it fits."}};
|
||||
const std::string kept = "The app keeps an installed printer's default filaments installed while no other installed filament "
|
||||
"fits it: where the call leaves one so, they are installed again and listed under "
|
||||
"filaments_installed, as the next start would. The other filaments, and the presets' unsaved "
|
||||
"changes, are kept, and the selectors are refreshed. Not in the undo history.";
|
||||
NativeCommand install_filaments = reaching(
|
||||
{"install_filaments"},
|
||||
mutate_tool("filament_install", L("Install system filaments"),
|
||||
"Install system filaments, for good, as ticking them in the System Filaments dialog and pressing Confirm "
|
||||
"does: the filament selectors offer them. Name them by names, or with vendor and filament_type every "
|
||||
"filament of that vendor and type that an installed printer fits. preset_list {type: \"filament\", "
|
||||
"include_uninstalled: true} lists the system filaments, those not installed with installed: false. A name "
|
||||
"no filament has is refused with the closest names. " +
|
||||
kept + " Reply: installed (the presets installed), installed_already, filaments_installed.",
|
||||
object_schema({{"names", names_prop},
|
||||
{"vendor", prop("string", "With filament_type, in place of names: a filament maker (\"Bambu "
|
||||
"Lab\", \"Generic\"), in any case.")},
|
||||
{"filament_type", prop("string", "With vendor: a filament type (\"PLA\"), in any case.")}}),
|
||||
change_filaments(true)));
|
||||
install_filaments.examples = json::parse(R"json([
|
||||
{"title": "Install a filament by the name the selector shows", "calls": [
|
||||
{"tool": "preset_list", "args": {"type": "filament", "include_uninstalled": true, "query": "PETG HF"}},
|
||||
{"tool": "filament_install", "args": {"names": ["Bambu PETG HF"]}}]},
|
||||
{"title": "Install every filament of a vendor and type", "calls": [
|
||||
{"tool": "filament_install", "args": {"vendor": "Generic", "filament_type": "PETG"}}]}])json");
|
||||
catalog.add(std::move(install_filaments));
|
||||
|
||||
NativeCommand uninstall_filaments = reaching(
|
||||
{"uninstall_filaments"},
|
||||
mutate_tool("filament_uninstall", L("Uninstall system filaments"),
|
||||
"Uninstall system filaments, for good, as unticking them in the System Filaments dialog and pressing "
|
||||
"Confirm does: the filament selectors no longer offer them. names as filament_install takes them. A "
|
||||
"filament a slot of the project uses is refused, naming the slot. " +
|
||||
kept + " Reply: uninstalled (the presets uninstalled), not_installed, filaments_installed.",
|
||||
object_schema({{"names", names_prop}}, {"names"}), change_filaments(false)));
|
||||
uninstall_filaments.examples = json::parse(R"json([
|
||||
{"title": "Uninstall a filament", "calls": [
|
||||
{"tool": "filament_uninstall", "args": {"names": ["Bambu PETG HF"]}}]}])json");
|
||||
catalog.add(std::move(uninstall_filaments));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -1,9 +1,11 @@
|
||||
// set_height_ranges: an object's height range modifiers (the object list's Height Range Modifier),
|
||||
// given as the whole set of ranges. set_variable_layer_height: the Variable layer height panel's
|
||||
// Adaptive, Smooth and Reset on an object. And how list_objects reports both. set_custom_gcode_at_layer: the
|
||||
// pauses, custom G-codes and filament changes of a plate's layers, through the Preview's layer slider.
|
||||
// object_set_height_ranges: an object's height range modifiers (the object list's Height Range Modifier),
|
||||
// given as the whole set of ranges, whose settings the settings tools set. object_set_variable_layer_height: the
|
||||
// Variable layer height panel's Adaptive, Smooth and Reset on an object. And how object_list reports both.
|
||||
// plate_set_custom_gcode: the pauses, custom G-codes and filament changes of a plate's layers, through the Preview's
|
||||
// layer slider.
|
||||
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include "McpTargets.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GCodeViewer.hpp"
|
||||
@@ -12,8 +14,11 @@
|
||||
#include "slic3r/GUI/GUI_ObjectList.hpp"
|
||||
#include "slic3r/GUI/IMSlider.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/Operations/ObjectOps.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
#include "slic3r/GUI/Plater.hpp"
|
||||
#include "slic3r/GUI/Selection.hpp"
|
||||
#include "slic3r/GUI/TickCode.hpp"
|
||||
|
||||
#include "libslic3r/Config.hpp"
|
||||
@@ -32,9 +37,7 @@
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <exception>
|
||||
#include <functional>
|
||||
#include <iterator>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
@@ -58,26 +61,12 @@ std::string mm(double z)
|
||||
return out.str();
|
||||
}
|
||||
|
||||
std::string range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); }
|
||||
|
||||
ToolFailure overlap(const Slic3r::t_layer_height_range& lower, const Slic3r::t_layer_height_range& upper)
|
||||
{
|
||||
return ToolFailure("Ranges " + range_text(lower) + " and " + range_text(upper) +
|
||||
return ToolFailure("Ranges " + height_range_text(lower) + " and " + height_range_text(upper) +
|
||||
" overlap; ranges may touch, one's max_z being the next one's min_z");
|
||||
}
|
||||
|
||||
// For "did you mean": keys holding the first half of `key`, those that begin as it does first.
|
||||
json similar_keys(const std::string& key, const std::vector<std::string>& keys)
|
||||
{
|
||||
const std::string part = key.substr(0, std::max<std::size_t>(3, key.size() / 2));
|
||||
std::vector<std::string> hits;
|
||||
std::copy_if(keys.begin(), keys.end(), std::back_inserter(hits), [&part](const std::string& k) { return k.find(part) != std::string::npos; });
|
||||
const auto common = [&key](const std::string& k) { return std::mismatch(k.begin(), k.end(), key.begin(), key.end()).first - k.begin(); };
|
||||
std::stable_sort(hits.begin(), hits.end(), [&common](const std::string& a, const std::string& b) { return common(a) > common(b); });
|
||||
hits.resize(std::min<std::size_t>(hits.size(), 5));
|
||||
return hits;
|
||||
}
|
||||
|
||||
bool same_ranges(const t_layer_config_ranges& a, const t_layer_config_ranges& b)
|
||||
{
|
||||
return a.size() == b.size() &&
|
||||
@@ -101,38 +90,46 @@ json layer_height_warnings(const ModelObject& object)
|
||||
return warnings;
|
||||
}
|
||||
|
||||
// The object a layer call names, on an FFF printer.
|
||||
ModelObject& layer_object(Plater& plater, const json& args)
|
||||
// The index of the object a layer call names, else of the one selected in the Prepare view (or of the object of the
|
||||
// selected instance or part), on an FFF printer.
|
||||
int layer_object(Plater& plater, const json& args)
|
||||
{
|
||||
const ModelObjectPtrs& objects = plater.model().objects;
|
||||
const int oi = arg_int(args, "object", -1);
|
||||
if (oi < 0 || oi >= int(objects.size()))
|
||||
throw ToolFailure("object index out of range");
|
||||
if (plater.printer_technology() != ptFFF)
|
||||
throw ToolFailure("Height range modifiers and variable layer heights are for FFF printers");
|
||||
check_expected_ids(*objects[std::size_t(oi)], nullptr, args);
|
||||
return *objects[std::size_t(oi)];
|
||||
const Ops::Outcome<Ops::Targets> target =
|
||||
resolve_targets(plater.model(), &plater.get_view3D_canvas3D()->get_selection(), args, kObjects | kObjectOfSelection, true);
|
||||
if (!target)
|
||||
throw refused(target.refusal());
|
||||
return target.value().objects.front();
|
||||
}
|
||||
|
||||
// The object set_variable_layer_height names, after the checks that need no view, such as an argument
|
||||
// that goes with another action.
|
||||
ModelObject& profile_object(Plater& plater, const json& args)
|
||||
// The reply's naming of object `oi`, as every command with a target gives it.
|
||||
json named_object(const Plater& plater, int oi)
|
||||
{
|
||||
ModelObject& object = layer_object(plater, args);
|
||||
Ops::Targets object;
|
||||
object.objects = {oi};
|
||||
return targets_reply(plater.model(), object);
|
||||
}
|
||||
|
||||
// The object object_set_variable_layer_height names, or the one selected, after the checks that need no view, such as
|
||||
// an argument that goes with another action.
|
||||
int profile_object(Plater& plater, const json& args)
|
||||
{
|
||||
const int oi = layer_object(plater, args);
|
||||
const std::string action = arg_string(args, "action");
|
||||
if (args.contains("quality") && action != "adaptive")
|
||||
throw ToolFailure("quality goes with action adaptive");
|
||||
if ((args.contains("radius") || args.contains("keep_min")) && action != "smooth")
|
||||
throw ToolFailure("radius and keep_min go with action smooth");
|
||||
return object;
|
||||
return oi;
|
||||
}
|
||||
|
||||
// What the panel's Adaptive, Smooth and Reset buttons run, on the object selected as the panel's
|
||||
// object is, without opening the panel. Reset of an object without a profile changes nothing.
|
||||
json set_variable_layer_height(Plater& plater, const json& args)
|
||||
{
|
||||
ModelObject& object = profile_object(plater, args);
|
||||
const int oi = arg_int(args, "object", -1);
|
||||
const int oi = profile_object(plater, args);
|
||||
ModelObject& object = *plater.model().objects[std::size_t(oi)];
|
||||
const std::string action = arg_string(args, "action");
|
||||
GLCanvas3D& canvas = require_prepare_scene(plater);
|
||||
|
||||
@@ -153,7 +150,8 @@ json set_variable_layer_height(Plater& plater, const json& args)
|
||||
canvas.reset_layer_height_profile();
|
||||
}
|
||||
|
||||
json out{{"object", oi}, {"height", object.instance_bounding_box(0).max.z()}};
|
||||
json out = named_object(plater, oi);
|
||||
out.update({{"object", oi}, {"height", object.instance_bounding_box(0).max.z()}});
|
||||
if (json profile = layer_height_profile_json(object.layer_height_profile.get()); !profile.is_null())
|
||||
out["layer_height_profile"] = std::move(profile);
|
||||
if (json warnings = layer_height_warnings(object); !warnings.empty())
|
||||
@@ -161,17 +159,16 @@ json set_variable_layer_height(Plater& plater, const json& args)
|
||||
return out;
|
||||
}
|
||||
|
||||
// What the object list does when a person adds, edits and removes ranges, with the whole set given at
|
||||
// once. Everything the arguments can tell is checked before anything changes.
|
||||
// What the object list does when a person adds and removes ranges, with the whole set given at once, on the object the
|
||||
// call names or the one selected. A range's settings are the settings tools' (target height_range). Everything the
|
||||
// arguments can tell is checked before anything changes.
|
||||
json set_height_ranges(Plater& plater, const json& args)
|
||||
{
|
||||
ModelObject* object = &layer_object(plater, args);
|
||||
const int oi = arg_int(args, "object", -1);
|
||||
const int oi = layer_object(plater, args);
|
||||
ModelObject* object = plater.model().objects[std::size_t(oi)];
|
||||
ObjectList* list = wxGetApp().obj_list();
|
||||
t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("ranges", json()), list->get_default_layer_config(oi),
|
||||
wxGetApp().filaments_cnt(), [](int extruder) {
|
||||
return std::make_pair(get_min_layer_height(extruder), get_max_layer_height(extruder));
|
||||
});
|
||||
t_layer_config_ranges ranges = layer_config_ranges_from_json(args.value("ranges", json()), object->layer_config_ranges,
|
||||
list->get_default_layer_config(oi));
|
||||
require_prepare_scene(plater);
|
||||
|
||||
if (!same_ranges(ranges, object->layer_config_ranges)) {
|
||||
@@ -184,15 +181,16 @@ json set_height_ranges(Plater& plater, const json& args)
|
||||
plater.changed_object(oi);
|
||||
}
|
||||
|
||||
json out{{"object", oi},
|
||||
{"height", object->instance_bounding_box(0).max.z()},
|
||||
{"layer_config_ranges", layer_config_ranges_json(object->layer_config_ranges)}};
|
||||
json out = named_object(plater, oi);
|
||||
out.update({{"object", oi},
|
||||
{"height", object->instance_bounding_box(0).max.z()},
|
||||
{"layer_config_ranges", layer_config_ranges_json(object->layer_config_ranges)}});
|
||||
if (json warnings = layer_height_warnings(*object); !warnings.empty())
|
||||
out["warnings"] = std::move(warnings);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The plate set_custom_gcode_at_layer names (default: the current one), after the checks that need neither its
|
||||
// The plate plate_set_custom_gcode names (default: the current one), after the checks that need neither its
|
||||
// layers nor a view.
|
||||
int gcode_plate(Plater& plater, const json& args)
|
||||
{
|
||||
@@ -201,7 +199,7 @@ int gcode_plate(Plater& plater, const json& args)
|
||||
const bool edits = arg_bool(args, "clear", false) || !args.value("add", json::array()).empty() ||
|
||||
!args.value("remove", json::array()).empty();
|
||||
if (!edits)
|
||||
throw ToolFailure("Give add, remove or clear; list_plates lists each plate's layer_gcode");
|
||||
throw ToolFailure("Give add, remove or clear; plate_list lists each plate's layer_gcode");
|
||||
PartPlateList& plates = plater.get_partplate_list();
|
||||
const int index = arg_int(args, "plate", plates.get_curr_plate_index());
|
||||
if (index < 0 || index >= plates.get_plate_count())
|
||||
@@ -216,7 +214,7 @@ int gcode_plate(Plater& plater, const json& args)
|
||||
throw ToolFailure(name + " prints by object (print_sequence), which takes no layer G-codes");
|
||||
// A slice would replace the layers under the edit.
|
||||
if (plater.is_slicing_any())
|
||||
throw ToolFailure("Slicing is in progress; wait {for: \"idle\"} first");
|
||||
throw ToolFailure("Slicing is in progress; app_wait {for: \"idle\"} first");
|
||||
return index;
|
||||
}
|
||||
|
||||
@@ -234,7 +232,7 @@ bool preview_shows_plate(Plater& plater, int index)
|
||||
viewer.get_layers_slider()->GetMaxValue() + 1 == int(preview->get_gcode_layers_zs().size());
|
||||
}
|
||||
|
||||
// A plate's codes as list_plates' layer_gcode lists them: by height, z to the G-code's 0.001 mm, layer
|
||||
// A plate's codes as plate_list's layer_gcode lists them: by height, z to the G-code's 0.001 mm, layer
|
||||
// (1-based) where `zs` has a layer at or above z, the slider's rule for a stored height.
|
||||
json plate_layer_gcode(const CustomGCode::Info& codes, const std::vector<double>& zs)
|
||||
{
|
||||
@@ -258,7 +256,7 @@ json plate_layer_gcode(const CustomGCode::Info& codes, const std::vector<double>
|
||||
return out;
|
||||
}
|
||||
|
||||
// set_custom_gcode_at_layer's reply, once the plater has the slider's codes. UI thread.
|
||||
// plate_set_custom_gcode's reply, once the plater has the slider's codes. UI thread.
|
||||
json layer_gcode_reply(Plater& plater, int index, bool changed, const json& args)
|
||||
{
|
||||
const Model& model = plater.model();
|
||||
@@ -273,13 +271,13 @@ json layer_gcode_reply(Plater& plater, int index, bool changed, const json& args
|
||||
const PresetBundle& bundle = *wxGetApp().preset_bundle;
|
||||
for (const json& item : args.value("add", json::array()))
|
||||
if (arg_string(item, "type") == "pause" && bundle.printers.get_edited_preset().config.opt_string("machine_pause_gcode").empty()) {
|
||||
out["warnings"] = json::array({"machine_pause_gcode is empty, so a pause adds no command (set it with set_settings scope printer)"});
|
||||
out["warnings"] = json::array({"machine_pause_gcode is empty, so a pause adds no command (set it with settings_set type printer)"});
|
||||
break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Selects the plate set_custom_gcode_at_layer names and shows it in the Preview, unless the Preview shows its layers
|
||||
// Selects the plate plate_set_custom_gcode names and shows it in the Preview, unless the Preview shows its layers
|
||||
// already, and returns its index. Refused calls leave the view alone. Only a plate with an up-to-date slice
|
||||
// is opened: opening the Preview on one that is not starts a slice.
|
||||
int show_plate_layers(Plater& plater, const json& args)
|
||||
@@ -289,7 +287,7 @@ int show_plate_layers(Plater& plater, const json& args)
|
||||
return index;
|
||||
PartPlateList& plates = plater.get_partplate_list();
|
||||
if (!plates.get_plate(index)->is_slice_result_valid())
|
||||
throw ToolFailure("plate " + std::to_string(index) + " has no up-to-date slice to place codes on; slice it first (slice {plates: " +
|
||||
throw ToolFailure("plate " + std::to_string(index) + " has no up-to-date slice to place codes on; slice it first (plate_slice {plates: " +
|
||||
std::to_string(index) + "})");
|
||||
plater.select_view_3D("Preview");
|
||||
// What clicking a sliced plate in the Preview's plate toolbar does: select it and load its result, which
|
||||
@@ -332,6 +330,8 @@ json set_custom_gcode_at_layer(Plater& plater, int index, const json& args, Cust
|
||||
|
||||
} // namespace
|
||||
|
||||
std::string height_range_text(const Slic3r::t_layer_height_range& range) { return mm(range.first) + "-" + mm(range.second); }
|
||||
|
||||
std::vector<std::string> layer_range_option_keys(int filaments)
|
||||
{
|
||||
// A range's page in the sidebar edits layer_height and the per-region settings, of which the object
|
||||
@@ -351,49 +351,28 @@ std::vector<std::string> layer_range_option_keys(int filaments)
|
||||
return keys;
|
||||
}
|
||||
|
||||
t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, const DynamicPrintConfig& defaults, int filaments,
|
||||
const std::function<std::pair<double, double>(int extruder)>& layer_height_bounds)
|
||||
t_layer_config_ranges layer_config_ranges_from_json(const json& ranges,
|
||||
const t_layer_config_ranges& current,
|
||||
const DynamicPrintConfig& defaults)
|
||||
{
|
||||
if (!ranges.is_array())
|
||||
throw ToolFailure("layer_config_ranges must be a list of {min_z, max_z, values}");
|
||||
const std::vector<std::string> keys = layer_range_option_keys(filaments);
|
||||
t_layer_config_ranges out;
|
||||
throw ToolFailure("ranges must be a list of {min_z, max_z}");
|
||||
t_layer_config_ranges out;
|
||||
for (const json& r : ranges) {
|
||||
if (!r.is_object())
|
||||
throw ToolFailure("A range is {min_z, max_z, values}");
|
||||
throw ToolFailure("A range is {min_z, max_z}");
|
||||
const Slic3r::t_layer_height_range range{arg_double(r, "min_z", -1.), arg_double(r, "max_z", -1.)};
|
||||
if (!(range.first >= 0. && range.first < range.second))
|
||||
throw ToolFailure("A height range needs 0 <= min_z < max_z, not " + range_text(range));
|
||||
const json values = r.value("values", json::object());
|
||||
if (!values.is_object())
|
||||
throw ToolFailure("A range's values are {key: value}");
|
||||
DynamicPrintConfig config = defaults;
|
||||
for (auto it = values.begin(); it != values.end(); ++it) {
|
||||
if (std::find(keys.begin(), keys.end(), it.key()) == keys.end())
|
||||
throw ToolFailure("\"" + it.key() +
|
||||
"\" is not a height range setting; a range takes layer_height, extruder and per-region "
|
||||
"process settings such as sparse_infill_density",
|
||||
{{"similar", similar_keys(it.key(), keys)}});
|
||||
try {
|
||||
config.set_deserialize_strict(it.key(), to_config_string(it.value(), it.key()));
|
||||
} catch (const std::exception& e) {
|
||||
throw ToolFailure("Invalid value for " + it.key() + ": " + e.what());
|
||||
}
|
||||
}
|
||||
const int extruder = config.opt_int("extruder");
|
||||
if (extruder < 0 || extruder > filaments)
|
||||
throw ToolFailure("extruder " + std::to_string(extruder) + " is not a filament: 0 (the object's) or " +
|
||||
(filaments > 1 ? "1-" + std::to_string(filaments) : std::string("1")));
|
||||
// Only a layer height given is checked, as the range editor checks only what a person types.
|
||||
if (values.contains("layer_height")) {
|
||||
const double height = config.opt_float("layer_height");
|
||||
const std::pair<double, double> bounds = layer_height_bounds(extruder);
|
||||
if (!(height >= bounds.first && height <= bounds.second))
|
||||
throw ToolFailure("layer_height " + mm(height) + " is outside this printer's " + mm(bounds.first) + "-" + mm(bounds.second));
|
||||
}
|
||||
throw ToolFailure("A height range needs 0 <= min_z < max_z, not " + height_range_text(range));
|
||||
if (out.count(range) != 0)
|
||||
throw overlap(range, range);
|
||||
out[range].assign_config(std::move(config));
|
||||
// A range of the object's with these heights keeps its settings, as the object list keeps a range it is not asked
|
||||
// to change.
|
||||
const auto kept = current.find(range);
|
||||
if (kept != current.end())
|
||||
out[range].assign_config(kept->second.get());
|
||||
else
|
||||
out[range].assign_config(defaults);
|
||||
}
|
||||
// Sorted by min_z; the slicer would trim an overlap silently, which from an agent is always a mistake.
|
||||
const Slic3r::t_layer_height_range* lower = nullptr;
|
||||
@@ -405,6 +384,20 @@ t_layer_config_ranges layer_config_ranges_from_json(const json& ranges, const Dy
|
||||
return out;
|
||||
}
|
||||
|
||||
void check_height_range_layer_height(const DynamicPrintConfig& values, const DynamicPrintConfig& range,
|
||||
const std::function<std::pair<double, double>(int extruder)>& layer_height_bounds)
|
||||
{
|
||||
// Only a layer height given is checked, as the range editor checks only what a person types.
|
||||
if (!values.has("layer_height"))
|
||||
return;
|
||||
const DynamicPrintConfig& source = values.has("extruder") ? values : range;
|
||||
const int extruder = source.has("extruder") ? source.opt_int("extruder") : 0;
|
||||
const double height = values.opt_float("layer_height");
|
||||
const std::pair<double, double> bounds = layer_height_bounds(extruder);
|
||||
if (!(height >= bounds.first && height <= bounds.second))
|
||||
throw ToolFailure("layer_height " + mm(height) + " is outside this printer's " + mm(bounds.first) + "-" + mm(bounds.second));
|
||||
}
|
||||
|
||||
json layer_config_ranges_json(const t_layer_config_ranges& ranges)
|
||||
{
|
||||
json out = json::array();
|
||||
@@ -513,7 +506,7 @@ bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool ha
|
||||
if (code.extra.empty() || code.extra.size() > 1023)
|
||||
throw ToolFailure("gcode must be 1 to 1023 bytes, as the Custom G-code dialog takes");
|
||||
} else if (type == CustomGCode::Template && !has_template) {
|
||||
throw ToolFailure("The printer's template_custom_gcode is empty; set it (set_settings scope printer) or use type custom");
|
||||
throw ToolFailure("The printer's template_custom_gcode is empty; set it (settings_set type printer) or use type custom");
|
||||
} else if (type == CustomGCode::ToolChange) {
|
||||
// The slider colours each filament change from the filaments of the slice.
|
||||
const int slots = int(slider.GetExtruderColors().size());
|
||||
@@ -563,7 +556,7 @@ bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool ha
|
||||
slider.add_custom_gcode(code.extra, tick);
|
||||
else if (!slider.add_code_as_tick(code.type, code.type == CustomGCode::ToolChange ? code.extruder : -1, tick))
|
||||
throw ToolFailure(std::string("The layer slider refused the ") + custom_gcode_type_name(code.type) + " on " + layer(tick) +
|
||||
(changed ? "; the codes before it changed (list_plates lists them)" : ""));
|
||||
(changed ? "; the codes before it changed (plate_list lists them)" : ""));
|
||||
changed = true;
|
||||
event = code.type;
|
||||
}
|
||||
@@ -574,25 +567,20 @@ bool edit_layer_gcode(IMSlider& slider, const json& args, int filaments, bool ha
|
||||
|
||||
void register_layer_tools(CommandCatalog& catalog)
|
||||
{
|
||||
const json range = object_schema(
|
||||
{{"min_z", {{"type", "number"}, {"minimum", 0}, {"description", "Bottom, mm above the bed."}}},
|
||||
{"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}},
|
||||
{"values", {{"type", "object"},
|
||||
{"description", "{key: value} as set_settings takes them: layer_height, extruder (0 = the object's "
|
||||
"filament) and per-region process settings such as sparse_infill_density or wall_loops."}}}},
|
||||
{"min_z", "max_z"});
|
||||
const json range = object_schema({{"min_z", {{"type", "number"}, {"minimum", 0}, {"description", "Bottom, mm above the bed."}}},
|
||||
{"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}}},
|
||||
{"min_z", "max_z"});
|
||||
|
||||
catalog.add(with_expected_ids(mutate_tool(
|
||||
"api", "set_height_ranges", L("Set height range modifiers"),
|
||||
"object_set_height_ranges", L("Set height range modifiers"),
|
||||
"Replace an object's height range modifiers (Height Range Modifier in the object list): Z ranges in mm, each printed "
|
||||
"with its own layer_height, filament and process settings, starting from the object's layer height and filament. "
|
||||
"Ranges may touch but not overlap; [] removes them all. One undo step; the object is selected. Reply: the "
|
||||
"object's height and its ranges as list_objects shows them, and warnings, such as a variable layer height profile "
|
||||
"deciding the layer heights instead.",
|
||||
object_schema({{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (list_objects)."}}},
|
||||
{"object_id", expected_id_prop("object")},
|
||||
{"ranges", array_prop(range, "The object's ranges afterwards, in any order.")}},
|
||||
{"object", "ranges"}),
|
||||
"with its own layer_height, filament and process settings, which settings_get and settings_set read and write with "
|
||||
"the target height_range. A range given with the min_z and max_z of one the object has keeps its settings; a new "
|
||||
"one starts from the object's layer height and filament. Ranges may touch but not overlap; [] removes them all. "
|
||||
"The object is the one named, else the one selected in the Prepare view. One undo step; the object is selected. "
|
||||
"Reply: the object (objects, object), its height and its ranges as object_list shows them, with their settings, and "
|
||||
"warnings, such as a variable layer height profile deciding the layer heights instead.",
|
||||
with_targets(object_schema({{"ranges", array_prop(range, "The object's ranges afterwards, in any order.")}}, {"ranges"}), kObjects, true),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
json out = ctx.run_ui([&] { return set_height_ranges(ui_plater(), args); });
|
||||
settle(ctx);
|
||||
@@ -600,26 +588,28 @@ void register_layer_tools(CommandCatalog& catalog)
|
||||
})));
|
||||
|
||||
catalog.add(with_expected_ids(mutate_tool(
|
||||
"api", "set_variable_layer_height", L("Set a variable layer height profile"),
|
||||
"object_set_variable_layer_height", L("Set a variable layer height profile"),
|
||||
"Run the Variable layer height panel's Adaptive, Smooth or Reset on an object, without opening the panel: adaptive "
|
||||
"computes layer heights from the object's shape (inside a height range, the range's layer_height), smooth smooths "
|
||||
"its profile (or the one its height ranges give), reset goes back to its layer height and ranges. One undo step; "
|
||||
"the object is selected. Reply: the object's height, its layer_height_profile {points, min_height, "
|
||||
"max_height} as list_objects shows it (absent after reset), and warnings.",
|
||||
object_schema({{"object", {{"type", "integer"}, {"minimum", 0}, {"description", "Object index (list_objects)."}}},
|
||||
{"object_id", expected_id_prop("object")},
|
||||
{"action", enum_prop({"adaptive", "smooth", "reset"}, "The panel's button.")},
|
||||
{"quality", {{"type", "number"}, {"minimum", 0}, {"maximum", 1},
|
||||
{"description", "adaptive: 0 = quality .. 1 = speed (default 0.5, as the panel)."}}},
|
||||
{"radius", {{"type", "integer"}, {"minimum", 1}, {"maximum", 10}, {"description", "smooth: default 5."}}},
|
||||
{"keep_min", prop("boolean", "smooth: keep the minimum layer heights (default false).")}},
|
||||
{"object", "action"}),
|
||||
"its profile (or the one its height ranges give), reset goes back to its layer height and ranges. The object is "
|
||||
"the one named, else the one selected in the Prepare view. One undo step; the object is selected. Reply: the "
|
||||
"object (objects, object), its height, its layer_height_profile {points, min_height, max_height} as object_list "
|
||||
"shows it (absent after reset), and warnings.",
|
||||
with_targets(object_schema({{"action", enum_prop({"adaptive", "smooth", "reset"}, "The panel's button.")},
|
||||
{"quality", {{"type", "number"}, {"minimum", 0}, {"maximum", 1},
|
||||
{"description", "adaptive: 0 = quality .. 1 = speed (default 0.5, as the panel)."}}},
|
||||
{"radius", {{"type", "integer"}, {"minimum", 1}, {"maximum", 10}, {"description", "smooth: default 5."}}},
|
||||
{"keep_min", prop("boolean", "smooth: keep the minimum layer heights (default false).")}},
|
||||
{"action"}),
|
||||
kObjects, true),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
// Refused calls leave the view alone. The Prepare canvas edits layer heights only once it has drawn:
|
||||
// GLCanvas3D::init() makes the texture the tool needs, and the app starts on Home.
|
||||
// GLCanvas3D::init() makes the texture the tool needs, and the app starts on Home. The object is read once,
|
||||
// before the wait, and named in the call that follows it.
|
||||
json call = args;
|
||||
ctx.run_ui([&] {
|
||||
Plater& plater = ui_plater();
|
||||
profile_object(plater, args);
|
||||
call["object"] = profile_object(plater, args);
|
||||
require_prepare_scene(plater);
|
||||
return json();
|
||||
});
|
||||
@@ -630,7 +620,7 @@ void register_layer_tools(CommandCatalog& catalog)
|
||||
return canvas->is_initialized() && !canvas->is_reload_delayed() ? json(true) : json();
|
||||
},
|
||||
std::chrono::seconds(15), "the Prepare view to draw");
|
||||
json out = ctx.run_ui([&] { return set_variable_layer_height(ui_plater(), args); });
|
||||
json out = ctx.run_ui([&] { return set_variable_layer_height(ui_plater(), call); });
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
})));
|
||||
@@ -638,14 +628,14 @@ void register_layer_tools(CommandCatalog& catalog)
|
||||
const json layer = {{"type", "integer"}, {"minimum", 1}, {"description", "1-based, as the Preview's layer slider numbers layers."}};
|
||||
const json z = {{"type", "number"}, {"minimum", 0}, {"description", "mm: the layer whose top is at or above it."}};
|
||||
catalog.add(mutate_tool(
|
||||
"api", "set_custom_gcode_at_layer", L("Set custom G-code at a layer"),
|
||||
"plate_set_custom_gcode", L("Set custom G-code at a layer"),
|
||||
"Add or remove pauses, custom G-code, custom templates and filament changes at the start of a layer, as the Preview "
|
||||
"layer slider's menu does; they are saved per plate in the project. They go on the plate's sliced layers, so the "
|
||||
"plate needs an up-to-date slice, or must be the one the Preview still shows after an earlier edit; the call selects "
|
||||
"it and shows the Preview. Applies clear, then remove, then add, all checked first. One code per layer: adding "
|
||||
"where a code of the same type is replaces it, and where another type is, is refused (remove it first). Not "
|
||||
"undoable, as in the slider. A change invalidates the "
|
||||
"plate's slice: slice again before exporting. Reply: the plate's codes as list_plates' layer_gcode lists them, "
|
||||
"plate's slice: slice again before exporting. Reply: the plate's codes as plate_list's layer_gcode lists them, "
|
||||
"each with z and layer.",
|
||||
object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Default: the current plate."}}},
|
||||
{"add", array_prop(object_schema({{"layer", layer},
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
// The plugin commands: what the Plugins window lists and does (plugin_list, plugin_enable, plugin_uninstall,
|
||||
// plugin_reload) on the operations of GUI/Operations/PluginOps.hpp, and the Plugins menu's rows (plugin_install_local,
|
||||
// plugin_refresh).
|
||||
|
||||
#include "McpArguments.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include "slic3r/GUI/NativeCommandRows.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Operations/PluginOps.hpp"
|
||||
#include "slic3r/plugin/PluginDescriptor.hpp"
|
||||
#include "slic3r/plugin/PluginManager.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
json row_json(const Ops::PluginRow& row)
|
||||
{
|
||||
json capabilities = json::array();
|
||||
for (const Ops::PluginCapabilityRow& capability : row.capabilities)
|
||||
capabilities.push_back({{"name", capability.name}, {"type", capability.type}, {"enabled", capability.enabled}});
|
||||
return {{"key", row.key}, {"name", row.name}, {"version", row.version}, {"installed", row.installed},
|
||||
{"enabled", row.enabled}, {"status", row.status}, {"source", row.source}, {"capabilities", std::move(capabilities)},
|
||||
{"error", row.error}};
|
||||
}
|
||||
|
||||
json rows_json()
|
||||
{
|
||||
json rows = json::array();
|
||||
for (const Ops::PluginRow& row : Ops::plugin_rows())
|
||||
rows.push_back(row_json(row));
|
||||
return rows;
|
||||
}
|
||||
|
||||
// The row of plugin `key` as the window lists it now, or null where it lists none. UI thread.
|
||||
json row_of(const std::string& key)
|
||||
{
|
||||
for (const Ops::PluginRow& row : Ops::plugin_rows())
|
||||
if (row.key == key)
|
||||
return row_json(row);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// How a plugin stands, for an error after a step that changed it: "installed, disabled", or "no longer listed".
|
||||
std::string state_of(const json& row)
|
||||
{
|
||||
if (row.is_null())
|
||||
return "no longer listed";
|
||||
std::string state = std::string(row.value("installed", false) ? "installed" : "not installed") + ", " +
|
||||
(row.value("enabled", false) ? "enabled" : "disabled");
|
||||
if (const std::string error = row.value("error", std::string()); !error.empty())
|
||||
state += ", with the error \"" + error + "\"";
|
||||
return state;
|
||||
}
|
||||
|
||||
// `text`, then how a plugin stands (state_of(`row`)) as a sentence of its own: "<text>. It is installed, disabled.". A
|
||||
// plugin's own error, which `text` may be, need not end in a full stop.
|
||||
std::string with_state(std::string text, const json& row)
|
||||
{
|
||||
text.erase(std::min(text.size(), text.find_last_not_of(" \t\r\n") + 1));
|
||||
if (!text.empty() && std::string(".!?").find(text.back()) == std::string::npos)
|
||||
text += '.';
|
||||
return (text.empty() ? text : text + " ") + "It is " + state_of(row) + ".";
|
||||
}
|
||||
|
||||
// A refusal of a plugin command, with the names it carries under the key that says what they are.
|
||||
ToolFailure plugin_refused(const Ops::Refusal& refusal)
|
||||
{
|
||||
const std::string code = refusal.code;
|
||||
if (code == "no_such_plugin")
|
||||
return refused(refusal, "plugin_list lists the plugins by key.", "similar");
|
||||
if (code == "ambiguous_plugin")
|
||||
return refused(refusal, "", "plugins");
|
||||
if (code == "no_such_capability")
|
||||
return refused(refusal, "", "capabilities");
|
||||
if (code == "ambiguous_capability")
|
||||
return refused(refusal, "", "types");
|
||||
return refused(refusal);
|
||||
}
|
||||
|
||||
// The plugin a call names, by its key or its name. UI thread.
|
||||
PluginDescriptor named_plugin(const json& args)
|
||||
{
|
||||
const Ops::Outcome<PluginDescriptor> found = Ops::find_plugin(arg_string(args, "plugin"));
|
||||
if (!found)
|
||||
throw plugin_refused(found.refusal());
|
||||
return found.value();
|
||||
}
|
||||
|
||||
ToolResult enable_plugin(const json& args, ToolContext& ctx)
|
||||
{
|
||||
Ops::SetPluginEnabledArgs op;
|
||||
op.capability = arg_string(args, "capability");
|
||||
op.enabled = args.at("enabled").get<bool>();
|
||||
// The operation reads no capability as the plugin itself, which enabled false would unload.
|
||||
if (args.contains("capability") && op.capability.empty())
|
||||
throw ToolFailure("capability is empty: name one of the plugin's capabilities, or leave capability out to turn the plugin "
|
||||
"itself on or off",
|
||||
{{"code", "empty_capability"}});
|
||||
Ops::PluginChange change = Ops::PluginChange::None;
|
||||
ctx.run_ui([&] {
|
||||
ui_plater();
|
||||
op.plugin = named_plugin(args).plugin_key;
|
||||
const json before = row_of(op.plugin);
|
||||
std::optional<Ops::Outcome<Ops::PluginEnabled>> done;
|
||||
std::string thrown;
|
||||
try {
|
||||
done.emplace(Ops::set_plugin_enabled(op));
|
||||
} catch (const std::exception& ex) {
|
||||
thrown = ex.what();
|
||||
}
|
||||
// The Plugins window shows the plugin as it stands, whatever came of the call.
|
||||
wxGetApp().update_plugins_dialog();
|
||||
if (!done.has_value()) {
|
||||
const json after = row_of(op.plugin);
|
||||
throw ToolFailure(with_state(thrown, after), {{"code", op.enabled ? "not_loaded" : "not_unloaded"}, {"plugin", after}});
|
||||
}
|
||||
if (!*done)
|
||||
throw plugin_refusal_after(done->refusal(), before, row_of(op.plugin));
|
||||
change = done->value().change;
|
||||
return json();
|
||||
});
|
||||
bool still_loading = false;
|
||||
if (change == Ops::PluginChange::LoadStarted) {
|
||||
// The load runs in the background, and may ask for a permission in its dialog, which the caller answers; the
|
||||
// call waits for its end on its own thread, as the window's Activating... does.
|
||||
const std::string key = op.plugin;
|
||||
const json done = poll_until(
|
||||
ctx, [&key] { return PluginManager::instance().is_plugin_load_in_progress(key) ? json() : json(true); },
|
||||
std::chrono::minutes(5), std::chrono::milliseconds(200));
|
||||
still_loading = done.is_null();
|
||||
if (still_loading && ctx.cancelled())
|
||||
throw ToolFailure("Stopped waiting for " + key + " to load; its load goes on, and plugin_list shows how it ends");
|
||||
}
|
||||
const json row = ctx.run_ui([&] { return row_of(op.plugin); });
|
||||
return ToolResult::ok(
|
||||
plugin_enable_reply(op.plugin, change != Ops::PluginChange::None, change == Ops::PluginChange::LoadStarted, still_loading, row));
|
||||
}
|
||||
|
||||
ToolResult uninstall(const json& args, ToolContext& ctx)
|
||||
{
|
||||
std::optional<Ops::PluginUninstall> plan;
|
||||
ctx.run_ui([&] {
|
||||
ui_plater();
|
||||
const Ops::Outcome<Ops::PluginUninstall> planned = Ops::plugin_uninstall_plan(named_plugin(args).plugin_key);
|
||||
if (!planned)
|
||||
throw plugin_refused(planned.refusal());
|
||||
plan = planned.value();
|
||||
return json();
|
||||
});
|
||||
// The window runs this behind its progress dialog; the call runs it here, on its own thread.
|
||||
std::optional<Ops::Refusal> failed;
|
||||
try {
|
||||
if (const Ops::Outcome<Ops::Done> removed = Ops::uninstall_plugin(*plan); !removed)
|
||||
failed = removed.refusal();
|
||||
} catch (const std::exception& ex) {
|
||||
failed = Ops::Refusal{Ops::RefusalKind::Failed, "not_uninstalled", ex.what()};
|
||||
}
|
||||
// A removal that fails may have unloaded the plugin already, so the window shows it as it stands on every path.
|
||||
const json row = ctx.run_ui([&] {
|
||||
if (!failed)
|
||||
Ops::plugin_uninstalled();
|
||||
wxGetApp().update_plugins_dialog();
|
||||
return row_of(plan->plugin);
|
||||
});
|
||||
if (failed)
|
||||
throw ToolFailure(with_state(failed->english(), row), {{"code", failed->code}, {"plugin", row}});
|
||||
json reply{{"uninstalled", plan->plugin}, {"name", plan->name}, {"unsubscribed", plan->unsubscribe}};
|
||||
// A cloud plugin deleted stays listed, to be installed again.
|
||||
if (!row.is_null())
|
||||
reply["plugin"] = row;
|
||||
return ToolResult::ok(std::move(reply));
|
||||
}
|
||||
|
||||
ToolResult reload(const json& args, ToolContext& ctx)
|
||||
{
|
||||
std::optional<Ops::PluginReload> plan;
|
||||
ctx.run_ui([&] {
|
||||
ui_plater();
|
||||
const Ops::Outcome<Ops::PluginReload> planned =
|
||||
Ops::plugin_reload_plan(named_plugin(args).plugin_key, arg_bool(args, "clear_cache", false));
|
||||
if (!planned)
|
||||
throw plugin_refused(planned.refusal());
|
||||
plan = planned.value();
|
||||
return json();
|
||||
});
|
||||
// The window runs this behind its progress dialog; the call runs it here, on its own thread.
|
||||
std::optional<Ops::Refusal> failed;
|
||||
try {
|
||||
if (const Ops::Outcome<Ops::Done> reloaded = Ops::reload_plugin(*plan); !reloaded)
|
||||
failed = reloaded.refusal();
|
||||
} catch (const std::exception& ex) {
|
||||
failed = Ops::Refusal{Ops::RefusalKind::Failed, "not_loaded", ex.what()};
|
||||
}
|
||||
const json row = ctx.run_ui([&] {
|
||||
wxGetApp().update_plugins_dialog();
|
||||
return row_of(plan->plugin);
|
||||
});
|
||||
if (failed)
|
||||
throw ToolFailure(with_state(failed->english(), row), {{"code", failed->code}, {"plugin", row}});
|
||||
return ToolResult::ok({{"reloaded", plan->plugin}, {"reinstalled", plan->cloud}, {"plugin", row}});
|
||||
}
|
||||
|
||||
ToolResult refresh(const json&, ToolContext& ctx)
|
||||
{
|
||||
// The closure runs while the call waits for it, so it hands the ticket over in place.
|
||||
Ops::RefreshRun::Ticket ticket;
|
||||
ctx.run_ui([&ticket] {
|
||||
ui_plater();
|
||||
ticket = wxGetApp().refresh_plugins();
|
||||
return json();
|
||||
});
|
||||
// The refresh runs off the UI thread, after the ones asked for before it; the call waits on its own thread.
|
||||
const std::optional<Ops::RefreshRun::Status> status =
|
||||
Ops::wait_for_refresh(Ops::plugin_refresh_run(), ticket, [&ctx] { return ctx.cancelled(); }, std::chrono::milliseconds(200));
|
||||
if (!status)
|
||||
throw ToolFailure("Stopped waiting for the plugin refresh, which goes on; plugin_list shows the plugins as they stand");
|
||||
json plugins = ctx.run_ui([] { return rows_json(); });
|
||||
if (status->state == Ops::RefreshRun::State::Failed)
|
||||
throw ToolFailure("The plugin refresh failed: " + status->error, {{"code", "refresh_failed"}, {"plugins", std::move(plugins)}});
|
||||
return ToolResult::ok({{"plugins", std::move(plugins)}});
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
json plugin_enable_reply(const std::string& plugin, bool changed, bool load_started, bool still_loading, const json& row)
|
||||
{
|
||||
if (load_started && !still_loading && (row.is_null() || !row.value("enabled", false)))
|
||||
throw ToolFailure(with_state(plugin + " did not load", row), {{"code", "not_loaded"}, {"plugin", row}});
|
||||
json reply{{"plugin", row}, {"changed", changed}};
|
||||
if (row.is_null())
|
||||
reply["note"] = plugin + " is no longer listed.";
|
||||
else if (still_loading)
|
||||
reply["note"] = "The plugin is still loading after five minutes; plugin_list shows how its load ends.";
|
||||
return reply;
|
||||
}
|
||||
|
||||
ToolFailure plugin_refusal_after(const Ops::Refusal& refusal, const json& before, const json& after)
|
||||
{
|
||||
ToolFailure bare = plugin_refused(refusal);
|
||||
const auto stands_as = [](const json& row) {
|
||||
return row.is_null() ? json() :
|
||||
json{row.value("installed", false), row.value("enabled", false), row.value("error", std::string())};
|
||||
};
|
||||
if (stands_as(before) == stands_as(after))
|
||||
return bare;
|
||||
json details = bare.details.is_object() ? bare.details : json::object();
|
||||
details["plugin"] = after;
|
||||
return ToolFailure(with_state(bare.what(), after), std::move(details));
|
||||
}
|
||||
|
||||
void register_plugin_tools(CommandCatalog& catalog)
|
||||
{
|
||||
using NativeCommands::tile;
|
||||
const json plugin_prop = prop("string", "The plugin's key, as plugin_list gives it, or its name where one plugin has it.");
|
||||
|
||||
NativeCommand list = inspect_tool(
|
||||
"plugin_list", L("List plugins"),
|
||||
"The plugins, as the Plugins window lists them: each with its key (which the other plugin commands take), name, "
|
||||
"version (the one installed, else the latest offered), installed (a package is on disk), enabled (loaded: the row's "
|
||||
"switch), status (Activated, Error, RuntimeError, Inactive or Loading), source (local, subscribed, mine or "
|
||||
"orphaned), capabilities (a loaded plugin's: name, type, enabled) and error.",
|
||||
object_schema({}), [](const json&, ToolContext& ctx) {
|
||||
json plugins = ctx.run_ui([] { return rows_json(); });
|
||||
return ToolResult::ok({{"total", plugins.size()}, {"plugins", std::move(plugins)}});
|
||||
});
|
||||
list.examples = json::parse(R"json([
|
||||
{"title": "List the plugins and how each stands", "calls": [{"tool": "plugin_list", "args": {}}]}])json");
|
||||
catalog.add(std::move(list));
|
||||
|
||||
// The file its dialog asks for, which every call but the tile's gives.
|
||||
const std::string replacing = "A plugin of that name installed already is replaced only with overwrite true; without it the "
|
||||
"call is refused with the question the dialog asks.";
|
||||
NativeCommand local = row_command(
|
||||
"plugin_install_local", L("Install Local Plugin"),
|
||||
"Install a plugin from a .py or .whl file by absolute path, as the Plugins dialog's Install local plugin does, without its "
|
||||
"file dialog. " + replacing + " Called with no arguments, the file dialog asks for the file (blocked_by_dialog), and "
|
||||
"replacing an installed plugin asks first (dialog_answer).",
|
||||
object_schema({{"path", Rows::input_file("a .py or .whl plugin package")},
|
||||
{"overwrite", prop("boolean", "Replace a plugin of that name installed already. Default false.")}},
|
||||
{"path"}),
|
||||
json::array({tile("install_local_plugin", L("Install Local Plugin"), L("Plugins"), "", json::object(),
|
||||
"Install a plugin from the .py or .whl file a dialog asks for, as the Plugins dialog's Install local "
|
||||
"plugin does, asking before it replaces one installed; plugin_install_local with a path installs that "
|
||||
"file without a dialog. " + replacing)}),
|
||||
[](const json& args) { return Rows::install_local_plugin(args); });
|
||||
local.input_schema = with_silent(std::move(local.input_schema), person_forms(local));
|
||||
catalog.add(std::move(local));
|
||||
|
||||
NativeCommand enable = reaching(
|
||||
{"set_plugin_enabled"},
|
||||
mutate_tool("plugin_enable", L("Enable or disable a plugin"),
|
||||
"Turn a plugin, or with capability one of its capabilities, on or off, as the Plugins window's switches do. "
|
||||
"A plugin turned on is loaded, and the call waits for its load to end; a cloud plugin not installed is "
|
||||
"downloaded and installed first. A plugin that needs a permission while it loads asks in its permission "
|
||||
"dialog (blocked_by_dialog), which the caller answers. A plugin turned off is unloaded and loses its error. "
|
||||
"A capability is one of a loaded plugin's, by its name; an empty one is refused. Reply: plugin (its row, as "
|
||||
"plugin_list gives it) and changed; a call that fails once it has changed the plugin, a load that fails "
|
||||
"among them, is an error naming how the plugin is left.",
|
||||
object_schema({{"plugin", plugin_prop},
|
||||
{"capability", {{"type", "string"},
|
||||
{"minLength", 1},
|
||||
{"description", "One of the plugin's capabilities, by name, in place of the "
|
||||
"plugin itself. The plugin must be enabled."}}},
|
||||
{"enabled", prop("boolean", "On (true) or off (false).")}},
|
||||
{"plugin", "enabled"}),
|
||||
enable_plugin));
|
||||
// A plugin turned on runs its code, and a cloud plugin is downloaded.
|
||||
enable.open_world = true;
|
||||
enable.examples = json::parse(R"json([
|
||||
{"title": "Turn a plugin on", "calls": [
|
||||
{"tool": "plugin_list", "args": {}},
|
||||
{"tool": "plugin_enable", "args": {"plugin": "my_plugin", "enabled": true}}]},
|
||||
{"title": "Turn one of a plugin's capabilities off", "calls": [
|
||||
{"tool": "plugin_enable", "args": {"plugin": "my_plugin", "capability": "Export report", "enabled": false}}]}])json");
|
||||
catalog.add(std::move(enable));
|
||||
|
||||
NativeCommand reload_command = reaching(
|
||||
{"reload_plugin"},
|
||||
mutate_tool("plugin_reload", L("Reload a plugin"),
|
||||
"Load a plugin again after its files changed, as its row's Reload does: it is unloaded and loaded, and a "
|
||||
"plugin that was not loaded is unloaded again. clear_cache also removes its extracted wheel cache first, as "
|
||||
"Delete cache and reload does. A cloud plugin is installed again from the cloud, as its Reinstall does, and "
|
||||
"takes no clear_cache; one no longer available is refused. Reply: reloaded, reinstalled and plugin (its row); "
|
||||
"a reload that fails is an error naming how the plugin is left.",
|
||||
object_schema({{"plugin", plugin_prop},
|
||||
{"clear_cache", prop("boolean", "Remove the plugin's extracted wheel cache before loading it. "
|
||||
"Default false.")}},
|
||||
{"plugin"}),
|
||||
reload));
|
||||
// A plugin loaded runs its code, and a cloud plugin is downloaded again.
|
||||
reload_command.open_world = true;
|
||||
reload_command.examples = json::parse(R"json([
|
||||
{"title": "Reload a plugin after editing its files", "calls": [
|
||||
{"tool": "plugin_reload", "args": {"plugin": "my_plugin"}}]},
|
||||
{"title": "Reload a plugin with its wheel cache removed", "calls": [
|
||||
{"tool": "plugin_reload", "args": {"plugin": "my_plugin", "clear_cache": true}}]}])json");
|
||||
catalog.add(std::move(reload_command));
|
||||
|
||||
NativeCommand uninstall_command = reaching(
|
||||
{"uninstall_plugin"},
|
||||
mutate_tool("plugin_uninstall", L("Uninstall a plugin"),
|
||||
"Remove a plugin for good, without asking, as its row's Delete does once confirmed: it is unloaded where it "
|
||||
"runs, and its files are removed. A cloud plugin subscribed to is unsubscribed, as its row's Unsubscribe "
|
||||
"does, which also ends the subscription in the cloud account; the person's own cloud plugin loses its "
|
||||
"package alone and stays listed, to be installed again. Reply: uninstalled (the key), name, unsubscribed, "
|
||||
"and plugin where it stays listed; a removal that fails is an error naming how the plugin is left.",
|
||||
object_schema({{"plugin", plugin_prop}}, {"plugin"}), uninstall, /*destructive=*/true));
|
||||
// Unsubscribe reaches the cloud account.
|
||||
uninstall_command.open_world = true;
|
||||
uninstall_command.examples = json::parse(R"json([
|
||||
{"title": "Uninstall a plugin", "calls": [
|
||||
{"tool": "plugin_list", "args": {}},
|
||||
{"tool": "plugin_uninstall", "args": {"plugin": "my_plugin"}}]}])json");
|
||||
catalog.add(std::move(uninstall_command));
|
||||
|
||||
NativeCommand refresh_command = reaching(
|
||||
{"start_plugin_refresh"},
|
||||
NativeCommands::long_command("plugin_refresh", L("Refresh Plugins"), {}, object_schema({}), refresh));
|
||||
refresh_command.description =
|
||||
"Reload the plugins, as Refresh Plugins does: the installed plugins are rescanned and the plugin hub's list fetched "
|
||||
"again, and a notification says how it went. The call waits for the refresh to end and replies with the plugins, as "
|
||||
"plugin_list gives them; a refresh already running, or waiting, runs before the call's own, so the reply comes from a "
|
||||
"rescan that began after the call. job_cancel stops the wait, not the refresh.";
|
||||
refresh_command.listed = true;
|
||||
refresh_command.cancellable = true;
|
||||
// It fetches the plugin hub's list.
|
||||
refresh_command.open_world = true;
|
||||
refresh_command.tiles =
|
||||
json::array({tile("refresh_plugins", L("Refresh Plugins"), L("Plugins"), "", json::object(), "Reload plugins.")});
|
||||
// A person's pick starts the refresh and returns, its notification saying how it went; a call waits for it.
|
||||
catalog.add(NativeCommands::with_row_forms(
|
||||
std::move(refresh_command), [](const json&) { return Rows::refresh_plugins(); }, /*person_form_behind_dialogs=*/false,
|
||||
std::vector<json>{json::object()}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -0,0 +1,255 @@
|
||||
// preferences_get and preferences_set: the app's preferences as the Preferences dialog shows them, read from and
|
||||
// written through the table of GUI/Operations/PreferenceOps.hpp, which the dialog builds its rows from too.
|
||||
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Operations/PreferenceOps.hpp"
|
||||
|
||||
#include "libslic3r/AppConfig.hpp"
|
||||
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <set>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
using nlohmann::json;
|
||||
|
||||
namespace {
|
||||
|
||||
const char* kind_name(Ops::PreferenceKind kind)
|
||||
{
|
||||
switch (kind) {
|
||||
case Ops::PreferenceKind::Checkbox: return "checkbox";
|
||||
case Ops::PreferenceKind::Choice: return "choice";
|
||||
case Ops::PreferenceKind::Number: return "number";
|
||||
case Ops::PreferenceKind::Text: return "text";
|
||||
}
|
||||
return "text";
|
||||
}
|
||||
|
||||
std::string lower(std::string s)
|
||||
{
|
||||
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return char(std::tolower(c)); });
|
||||
return s;
|
||||
}
|
||||
|
||||
// A bound of a number's range, whole where the row takes whole numbers.
|
||||
json bound(const Ops::Preference& p, double value)
|
||||
{
|
||||
if (p.decimals == 0)
|
||||
return std::int64_t(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
// What a call learns of `p`'s refusal to be written: its reason, in English.
|
||||
std::string refused_reason(const Ops::Preference& p)
|
||||
{
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "preference_refused", p.refused, {p.key}}.english();
|
||||
}
|
||||
|
||||
// preferences_get's item for `p`: its row, and the value the dialog shows: `shown` where the dialog shows a value of its
|
||||
// own (Ops::shown_texts()), else the stored one, else the fallback.
|
||||
json preference_item(const AppConfig& config, const Ops::Preference& p, const std::map<std::string, std::string>& shown)
|
||||
{
|
||||
std::string stored;
|
||||
const bool is_stored = config.get("app", p.key, stored);
|
||||
const auto own = shown.find(p.key);
|
||||
const std::string text = own != shown.end() ? own->second : is_stored ? stored : p.fallback;
|
||||
json item{{"key", p.key}, {"tab", p.tab}, {"section", p.section},
|
||||
{"label", p.label}, {"kind", kind_name(p.kind)},
|
||||
{"value", Ops::preference_value(p, text)}};
|
||||
if (!p.choices.empty()) {
|
||||
json choices = json::array();
|
||||
for (const auto& [value, label] : p.choices)
|
||||
choices.push_back({{"value", value}, {"label", label}});
|
||||
item["choices"] = std::move(choices);
|
||||
}
|
||||
if (p.min)
|
||||
item["min"] = bound(p, *p.min);
|
||||
if (p.max)
|
||||
item["max"] = bound(p, *p.max);
|
||||
if (!is_stored)
|
||||
item["stored"] = false;
|
||||
if (p.restart_needed)
|
||||
item["restart_needed"] = true;
|
||||
if (p.refused != nullptr)
|
||||
item["refused"] = refused_reason(p);
|
||||
return item;
|
||||
}
|
||||
|
||||
// What preferences_set replies when the operation refuses: the names the refusal carries under the key that says what
|
||||
// they are, and where a refused preference changes instead.
|
||||
ToolFailure preferences_refused(const Ops::Refusal& refusal, const std::vector<Ops::Preference>& table)
|
||||
{
|
||||
const std::string code = refusal.code;
|
||||
if (code == "not_a_preference")
|
||||
return refused(refusal, "preferences_get lists the Preferences dialog's preferences.", "similar");
|
||||
if (code == "no_such_choice")
|
||||
return refused(refusal, "", "choices");
|
||||
if (code == "out_of_range")
|
||||
return refused(refusal, "", "range");
|
||||
if (code == "preference_refused" && !refusal.args.empty())
|
||||
if (const Ops::Preference* p = Ops::find_preference(table, refusal.args.front()))
|
||||
return refused(refusal, "It changes in the Preferences dialog: window_open {\"window\": \"preferences\", \"tab\": \"" + p->tab +
|
||||
"\", \"key\": \"" + p->key + "\"}, then widget_set_value on the control named " + p->key +
|
||||
" within Preferences.",
|
||||
"keys");
|
||||
return refused(refusal);
|
||||
}
|
||||
|
||||
// preferences_set's reply: each preference changed, with its value before and after, typed as preferences_get gives it,
|
||||
// stored_before: false where `before` is the fallback, restart_needed where the value is read at the next start; and
|
||||
// those already so.
|
||||
json changes_json(const Ops::PreferenceChanges& changes, const std::vector<Ops::Preference>& table)
|
||||
{
|
||||
json changed = json::array();
|
||||
for (const Ops::PreferenceChange& c : changes.changed) {
|
||||
const Ops::Preference& p = *Ops::find_preference(table, c.key);
|
||||
json item{{"key", c.key}, {"before", Ops::preference_value(p, c.before)}, {"after", Ops::preference_value(p, c.after)}};
|
||||
if (!c.stored_before)
|
||||
item["stored_before"] = false;
|
||||
if (p.restart_needed)
|
||||
item["restart_needed"] = true;
|
||||
changed.push_back(std::move(item));
|
||||
}
|
||||
return {{"changed", std::move(changed)}, {"unchanged", changes.unchanged}};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
json preferences_settings(const AppConfig& config, const std::vector<Ops::Preference>& shown, const json& args,
|
||||
const std::map<std::string, std::string>& shown_texts)
|
||||
{
|
||||
const std::string tab = arg_string(args, "tab");
|
||||
std::vector<std::string> words;
|
||||
std::istringstream query(lower(arg_string(args, "query")));
|
||||
for (std::string word; query >> word;)
|
||||
words.push_back(word);
|
||||
std::vector<std::string> asked;
|
||||
if (args.contains("keys"))
|
||||
for (const json& key : args["keys"])
|
||||
asked.push_back(key.get<std::string>());
|
||||
const auto named = [&asked](const std::string& key) { return std::find(asked.begin(), asked.end(), key) != asked.end(); };
|
||||
const auto matches = [&](const Ops::Preference& p) {
|
||||
if ((!tab.empty() && p.tab != tab) || (args.contains("keys") && !named(p.key)))
|
||||
return false;
|
||||
const std::string text = lower(p.key + " " + p.label + " " + p.section);
|
||||
return std::all_of(words.begin(), words.end(), [&text](const std::string& word) { return text.find(word) != std::string::npos; });
|
||||
};
|
||||
|
||||
json items = json::array(), unknown = json::array();
|
||||
for (const Ops::Preference& p : shown)
|
||||
if (matches(p))
|
||||
items.push_back(preference_item(config, p, shown_texts));
|
||||
// A named key the dialog does not show is read as the app configuration stores it.
|
||||
for (const std::string& key : asked) {
|
||||
if (Ops::find_preference(shown, key) != nullptr)
|
||||
continue;
|
||||
std::string value;
|
||||
if (config.get("app", key, value))
|
||||
items.push_back({{"key", key}, {"value", value}});
|
||||
else
|
||||
unknown.push_back(key);
|
||||
}
|
||||
json out{{"total", items.size()}, {"items", std::move(items)}};
|
||||
if (!unknown.empty()) {
|
||||
out["unknown_keys"] = std::move(unknown);
|
||||
// Some preferences are stored only once they are changed.
|
||||
out["note"] = "unknown_keys are not stored and are no preference the Preferences dialog shows now.";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void register_preference_tools(CommandCatalog& catalog)
|
||||
{
|
||||
catalog.add(inspect_tool(
|
||||
"preferences_get", L("Read preferences"),
|
||||
"Read the app's preferences as the Preferences dialog shows them. With no argument, every preference it shows, "
|
||||
"tab by tab in its order, each with key (its control is named after it), tab, section and label (the row's title, "
|
||||
"in English), kind (checkbox, choice, number or text), value (what the dialog shows: true or false for a checkbox, "
|
||||
"a number for a number field), a choice's choices ({value, label}; preferences_set takes the value), a number's "
|
||||
"min and max, stored: false where nothing is stored and the value is the one the dialog shows then, "
|
||||
"restart_needed: true for a preference read at the next start, which a write changes nothing before, and "
|
||||
"refused, the reason, for a preference preferences_set does not write. The MCP server's switch and port read as "
|
||||
"the dialog shows them: on while the server runs, and the port it is on, also where this session's launch "
|
||||
"arguments set them without storing them; their stored says whether a value is stored. keys, query and tab "
|
||||
"narrow the list together; a "
|
||||
"named key the dialog does not show is read as the app configuration stores it ({key, value}), and one that is "
|
||||
"neither is listed under unknown_keys. The app configuration also holds account and device state, which is read "
|
||||
"only by name.",
|
||||
object_schema({{"keys", array_prop({{"type", "string"}}, "Preference keys, e.g. [\"project_load_behaviour\"].")},
|
||||
{"query", prop("string", "Words to find in the keys, labels and section titles, in any case, e.g. "
|
||||
"\"auto slice\".")},
|
||||
{"tab", enum_prop({"general", "files", "behaviour", "control", "graphics", "online", "developer"},
|
||||
"The dialog's tab, as window_open names it.")}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
return ToolResult::ok(ctx.run_ui([&] {
|
||||
ui_plater();
|
||||
return preferences_settings(*wxGetApp().app_config, Ops::shown_preferences(), args, Ops::shown_texts());
|
||||
}));
|
||||
}));
|
||||
|
||||
NativeCommand write = reaching(
|
||||
{"set_preferences"},
|
||||
mutate_tool(
|
||||
"preferences_set", L("Change preferences"),
|
||||
"Change preferences as their controls in the Preferences dialog do: values {key: value}, a checkbox as true or "
|
||||
"false, a choice as one of its values, a number within its range, as preferences_get lists them, and the "
|
||||
"downloads folder (download_path) as the absolute path of an existing folder. All are checked first and written "
|
||||
"together, so nothing changes if one is refused; then each does what its control does in the app, in the keys' "
|
||||
"order (the preview redrawn, the sidebar's lists, the settings' mode, the theme, preset sync started or "
|
||||
"stopped, stealth mode's sign-out of the cloud accounts), and those preferences_get marks restart_needed are "
|
||||
"stored and take effect at the next start. A key whose value is already the one given is left as it is. "
|
||||
"Refused, by name and with the reason: a key the dialog does not show, and those preferences_get marks "
|
||||
"refused, whose control opens a dialog, restarts OrcaSlicer, signs out, or reaches outside it (the language, "
|
||||
"the login region, the network plug-in, file associations, the mixed-temperature warning, the MCP server's "
|
||||
"switch and port); those change in the dialog: window_open {\"window\": \"preferences\", \"tab\", "
|
||||
"\"key\"}, then widget_set_value. Not in the undo history. Reply: changed, [{key, before, after}] typed as "
|
||||
"preferences_get gives them, with stored_before: false where nothing was stored and before is the value the "
|
||||
"dialog showed, and restart_needed: true where preferences_get gives it; and unchanged, the keys already so.",
|
||||
object_schema({{"values", {{"type", "object"},
|
||||
{"description", "{key: value}, e.g. {\"auto_arrange\": false, \"auto_calculate_flush\": "
|
||||
"\"color change\"}."}}}},
|
||||
{"values"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const json values = args.value("values", json::object());
|
||||
if (values.empty())
|
||||
throw ToolFailure("values names no preference: give {key: value}, e.g. {\"auto_arrange\": false}");
|
||||
std::map<std::string, json> asked;
|
||||
for (const auto& [key, value] : values.items())
|
||||
asked[key] = value;
|
||||
json result = ctx.run_ui([&]() -> json {
|
||||
ui_plater();
|
||||
const std::vector<Ops::Preference> table = Ops::shown_preferences();
|
||||
const Ops::Outcome<Ops::PreferenceChanges> done = Ops::set_preferences(asked);
|
||||
if (!done)
|
||||
throw preferences_refused(done.refusal(), table);
|
||||
return changes_json(done.value(), table);
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(result);
|
||||
}));
|
||||
write.examples = json::parse(R"json([
|
||||
{"title": "Find a preference and turn it off", "calls": [
|
||||
{"tool": "preferences_get", "args": {"query": "arrange"}},
|
||||
{"tool": "preferences_set", "args": {"values": {"auto_arrange": false}}}]},
|
||||
{"title": "Set a choice and a number", "calls": [
|
||||
{"tool": "preferences_set", "args": {"values": {"auto_calculate_flush": "color change", "opengl_fps_cap": 60}}}]}])json");
|
||||
catalog.add(std::move(write));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -1,10 +1,12 @@
|
||||
// open_files, new_project, save_project and export: files in and out without file dialogs. generate_calibration_test: the
|
||||
// Calibration menu's tests, which start a new project.
|
||||
// project_new, project_open, project_import, project_save and project_export: the project's files in and out without
|
||||
// file dialogs, and called as their menu rows' tiles, with them. calibration_generate_test: the Calibration menu's
|
||||
// tests, which start a new project.
|
||||
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
#include "JobRegistry.hpp"
|
||||
#include "McpPaths.hpp"
|
||||
#include "AutomationRuntime.hpp"
|
||||
#include "McpTargets.hpp"
|
||||
#include "McpTools.hpp"
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
@@ -12,8 +14,10 @@
|
||||
#include "slic3r/GUI/GUI.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/NativeCommandRows.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/Operations/ExportOps.hpp"
|
||||
#include "slic3r/GUI/Operations/ObjectOps.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Operations/PlateOps.hpp"
|
||||
#include "slic3r/GUI/Operations/ProjectOps.hpp"
|
||||
@@ -75,7 +79,7 @@ json project_json(const Ops::ProjectSummary& project)
|
||||
Ops::UnsavedChanges unsaved_changes_answer(bool discard) { return discard ? Ops::UnsavedChanges::Discard : Ops::UnsavedChanges::Refuse; }
|
||||
|
||||
// What a tool that replaces the project adds to the refusal of unsaved changes.
|
||||
constexpr const char* kUnsavedChangesHint = "save_project first, or pass discard_changes: true.";
|
||||
constexpr const char* kUnsavedChangesHint = "project_save first, or pass discard_changes: true.";
|
||||
|
||||
// Fails when the project has unsaved changes the caller did not say to drop.
|
||||
void require_project_discardable(bool discard)
|
||||
@@ -99,7 +103,7 @@ bool is_belt(const DynamicPrintConfig& printer)
|
||||
return belt != nullptr && belt->value;
|
||||
}
|
||||
|
||||
// generate_calibration_test's test_model values, as each test's dialog lists its models.
|
||||
// calibration_generate_test's test_model values, as each test's dialog lists its models.
|
||||
std::vector<std::string> calib_test_models(CalibMode mode)
|
||||
{
|
||||
switch (mode) {
|
||||
@@ -148,22 +152,22 @@ std::string calib_rule(CalibParamsError error, const Calib_Params& p, const Dyna
|
||||
json calib_result_keys(CalibMode mode, const DynamicPrintConfig& printer)
|
||||
{
|
||||
switch (mode) {
|
||||
case CalibMode::Calib_Temp_Tower: return {{"scope", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}};
|
||||
case CalibMode::Calib_Vol_speed_Tower: return {{"scope", "filament"}, {"keys", {"filament_max_volumetric_speed"}}};
|
||||
case CalibMode::Calib_Temp_Tower: return {{"type", "filament"}, {"keys", {"nozzle_temperature", "nozzle_temperature_initial_layer"}}};
|
||||
case CalibMode::Calib_Vol_speed_Tower: return {{"type", "filament"}, {"keys", {"filament_max_volumetric_speed"}}};
|
||||
case CalibMode::Calib_PA_Tower:
|
||||
case CalibMode::Calib_PA_Line: return {{"scope", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}};
|
||||
case CalibMode::Calib_PA_Line: return {{"type", "filament"}, {"keys", {"enable_pressure_advance", "pressure_advance"}}};
|
||||
case CalibMode::Calib_PA_Pattern:
|
||||
return {{"scope", "filament"},
|
||||
return {{"type", "filament"},
|
||||
{"keys", {"enable_pressure_advance", "pressure_advance", "adaptive_pressure_advance", "adaptive_pressure_advance_model"}}};
|
||||
case CalibMode::Calib_Flow_Rate: return {{"scope", "filament"}, {"keys", {"filament_flow_ratio"}}};
|
||||
case CalibMode::Calib_Retraction_tower: return {{"scope", "filament"}, {"keys", {"filament_retraction_length"}}};
|
||||
case CalibMode::Calib_Flow_Rate: return {{"type", "filament"}, {"keys", {"filament_flow_ratio"}}};
|
||||
case CalibMode::Calib_Retraction_tower: return {{"type", "filament"}, {"keys", {"filament_retraction_length"}}};
|
||||
case CalibMode::Calib_VFA_Tower:
|
||||
return {{"scope", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}};
|
||||
return {{"type", "printer"}, {"keys", {"resonance_avoidance", "min_resonance_avoidance_speed", "max_resonance_avoidance_speed"}}};
|
||||
case CalibMode::Calib_Cornering:
|
||||
return {{"scope", "printer"},
|
||||
return {{"type", "printer"},
|
||||
{"keys", has_junction_deviation(printer) ? json{"machine_max_junction_deviation"} : json{"machine_max_jerk_x", "machine_max_jerk_y"}}};
|
||||
default:
|
||||
return {{"scope", "printer"},
|
||||
return {{"type", "printer"},
|
||||
{"keys", {"input_shaping_emit", "input_shaping_type", "input_shaping_freq_x", "input_shaping_freq_y", "input_shaping_damp_x",
|
||||
"input_shaping_damp_y"}}};
|
||||
}
|
||||
@@ -199,14 +203,16 @@ json apply_vfa_fit(Calib_Params& params, bool auto_adjust, const PresetBundle& b
|
||||
}
|
||||
}
|
||||
|
||||
// export's format for a path given without one, from its extension.
|
||||
// project_export's format for a path given without one, from its extension.
|
||||
std::string format_of(const std::string& path)
|
||||
{
|
||||
static const std::pair<const char*, const char*> formats[]{{".gcode.3mf", "sliced_3mf"}, {".gcode", "gcode"}, {".3mf", "3mf"}, {".stl", "stl"}};
|
||||
static const std::pair<const char*, const char*> formats[]{{".gcode.3mf", "sliced_3mf"}, {".gcode", "gcode"}, {".3mf", "3mf"},
|
||||
{".stl", "stl"}, {".drc", "drc"}, {".obj", "toolpaths_obj"}};
|
||||
for (const auto& [ext, format] : formats)
|
||||
if (boost::algorithm::iends_with(path, ext))
|
||||
return format;
|
||||
throw ToolFailure("Give format (gcode, sliced_3mf, 3mf or stl), or a path ending in .gcode, .gcode.3mf, .3mf or .stl");
|
||||
throw ToolFailure("Give format (gcode, sliced_3mf, 3mf, stl, drc or toolpaths_obj), or a path ending in .gcode, .gcode.3mf, "
|
||||
".3mf, .stl, .drc or .obj");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -214,7 +220,7 @@ std::string format_of(const std::string& path)
|
||||
Calib_Params calib_params_from_args(const json& args, const DynamicPrintConfig& printer, std::vector<std::string>& warnings)
|
||||
{
|
||||
const std::string test = arg_string(args, "test");
|
||||
// The arguments each test takes, besides test, discard_changes and preset_changes.
|
||||
// The arguments each test takes, besides test, silent, discard_changes and preset_changes.
|
||||
std::vector<std::string> takes{"start", "end", "step"};
|
||||
CalibMode mode = CalibMode::Calib_None;
|
||||
std::string method;
|
||||
@@ -258,7 +264,7 @@ Calib_Params calib_params_from_args(const json& args, const DynamicPrintConfig&
|
||||
throw ToolFailure("Unknown test \"" + test + "\"");
|
||||
}
|
||||
for (auto it = args.begin(); it != args.end(); ++it)
|
||||
if (it.key() != "test" && it.key() != "discard_changes" && it.key() != "preset_changes" &&
|
||||
if (it.key() != "test" && it.key() != "silent" && it.key() != "discard_changes" && it.key() != "preset_changes" &&
|
||||
std::find(takes.begin(), takes.end(), it.key()) == takes.end())
|
||||
throw ToolFailure(it.key() + " does not apply to " + test + (method.empty() ? "" : " with method " + method), {{"takes", takes}});
|
||||
|
||||
@@ -392,72 +398,141 @@ json calib_params_json(const json& args, const Calib_Params& p, const DynamicPri
|
||||
|
||||
void register_project_tools(CommandCatalog& catalog)
|
||||
{
|
||||
catalog.add(reaching({"open_project", "import_models"}, mutate_tool(
|
||||
"api", "open_files", L("Open files"),
|
||||
"Open model files (STL, 3MF, STEP, OBJ, AMF, SVG...), a project (.3mf) or G-code by absolute path, without a file "
|
||||
"dialog. Models are added to the current project. A .3mf given alone opens as a project, replacing the current "
|
||||
"one, unless as is \"geometry\"; when the current project has unsaved changes that fails, changing nothing, unless "
|
||||
"discard_changes. Given with other paths, a .3mf adds its models only. A G-code given alone replaces the project "
|
||||
"too, to show its toolpaths: with unsaved changes the app asks first (blocked_by_dialog), whatever discard_changes "
|
||||
"says. Importing can open a dialog (STEP mesh options, for instance); the reply is then blocked_by_dialog.",
|
||||
object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths.")},
|
||||
{"as", enum_prop({"auto", "geometry", "project"}, "How a .3mf given alone opens: as a project (auto, the "
|
||||
"default, and project) or adding its models only "
|
||||
"(geometry).")},
|
||||
{"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail when a .3mf "
|
||||
NativeCommand open = reaching({"open_project"}, mutate_tool(
|
||||
"project_open", L("Open a project"),
|
||||
"Open a project (.3mf) by absolute path, without a file dialog, replacing the current project, with the settings it "
|
||||
"was saved with whatever the Preferences' Load behavior says; when the current project has unsaved changes that "
|
||||
"fails, changing nothing, unless discard_changes. A G-code file replaces the project too, to show its toolpaths: "
|
||||
"with unsaved changes the app asks first (blocked_by_dialog), whatever discard_changes says. project_import adds "
|
||||
"models, or a project's objects alone, to the current project. Called with no arguments it is Load Project: the "
|
||||
"Open dialog asks for the file (blocked_by_dialog), after asking about the unsaved changes. Reply: opened (project "
|
||||
"or gcode), and objects, names and plates for a project, path for a G-code.",
|
||||
object_schema({{"path", prop("string", "Absolute path of a .3mf project, or of a G-code file (.gcode, .bgcode).")},
|
||||
{"discard_changes", prop("boolean", "Drop the project's unsaved changes rather than fail when a project "
|
||||
"replaces it.")}},
|
||||
{"paths"}),
|
||||
{"path"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
AutomationRuntime& runtime = ctx.runtime();
|
||||
std::string err;
|
||||
const auto path = resolve_input_path(arg_string(args, "path"), err);
|
||||
if (!path)
|
||||
throw ToolFailure(err);
|
||||
const bool gcode = has_extension(*path, {".gcode", ".bgcode"});
|
||||
if (!gcode && !has_extension(*path, {".3mf"}))
|
||||
throw ToolFailure("project_open opens a .3mf project or a G-code file; project_import adds models to the project");
|
||||
// A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes.
|
||||
const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage());
|
||||
json out = ctx.run_ui([&]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
if (gcode) {
|
||||
plater.load_gcode(from_path(*path));
|
||||
return {{"opened", "gcode"}, {"path", path_to_utf8(*path)}};
|
||||
}
|
||||
Ops::OpenProjectArgs open;
|
||||
open.path = *path;
|
||||
open.unsaved = unsaved_changes_answer(discard);
|
||||
const Ops::Outcome<Ops::ProjectSummary> opened = Ops::open_project(open);
|
||||
if (!opened)
|
||||
throw refused(opened.refusal(), kUnsavedChangesHint);
|
||||
json o = project_json(opened.value());
|
||||
o["opened"] = "project";
|
||||
return o;
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
open.tiles = json::array({NativeCommands::tile("load_project", L("Load Project"), L("Commands"), "menu_open", json::object(),
|
||||
"Open a project through the Open dialog (it asks first if the current project "
|
||||
"has unsaved changes); project_open with a path opens that file without a "
|
||||
"dialog.")});
|
||||
catalog.add(NativeCommands::with_person_form(std::move(open), [](const json&) { return Rows::load_project(); }));
|
||||
|
||||
NativeCommand import_ = reaching({"import_models"}, mutate_tool(
|
||||
"project_import", L("Import models"),
|
||||
"Add the models of files (STL, 3MF, STEP, OBJ, AMF, SVG...) to the current project by absolute path, without a file "
|
||||
"dialog, as one undo step; a .3mf adds its objects only, not its settings (project_open opens it as a project). A "
|
||||
".zip archive gives the model files it holds (STL, OBJ, AMF, 3MF, STEP; a .3mf its objects only, as above), as Import "
|
||||
"ZIP Archive does: those entries names, by their paths in the archive, else all of them, in place of its file list; "
|
||||
"an entry the archive lacks is refused with the names it has, before anything is imported. Importing can open a "
|
||||
"dialog (STEP mesh options, for instance); the reply is then blocked_by_dialog. Called with no arguments it is "
|
||||
"Import 3MF/STL/STEP/SVG/OBJ/AMF, and with archive: true alone Import ZIP Archive: a file dialog asks for the files, "
|
||||
"or for the archive and then which of its files to import (blocked_by_dialog). Reply: opened (models), added (how "
|
||||
"many objects), archives (each archive's path and the entries taken) and the project's objects, names and plates.",
|
||||
object_schema({{"paths", array_prop({{"type", "string"}}, "Absolute paths of model files, or of a .zip archive of them.")},
|
||||
{"entries", {{"type", "array"},
|
||||
{"items", {{"type", "string"}}},
|
||||
{"minItems", 1},
|
||||
{"description", "The files to take from the one .zip archive among paths, by their paths "
|
||||
"in it (\"parts/cube.stl\"). Default: every model file it holds."}}},
|
||||
{"archive", prop("boolean", "true, alone: ask for a ZIP archive in a file dialog and import the models "
|
||||
"it holds, as Import ZIP Archive does.")}},
|
||||
{"paths"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
if (arg_bool(args, "archive", false))
|
||||
throw ToolFailure("archive asks for the archive in a file dialog, so it goes alone; paths imports files without one");
|
||||
if (args.contains("entries")) {
|
||||
const json& given = args["paths"];
|
||||
const auto zips = std::count_if(given.begin(), given.end(), [](const json& p) {
|
||||
return boost::algorithm::iends_with(p.get<std::string>(), ".zip");
|
||||
});
|
||||
if (zips == 0)
|
||||
throw ToolFailure("entries names files of a .zip archive: give the archive in paths");
|
||||
if (zips > 1)
|
||||
throw ToolFailure("entries names the files of one archive: give one .zip in paths");
|
||||
}
|
||||
std::vector<fs::path> paths;
|
||||
for (const json& p : args["paths"]) {
|
||||
std::string err;
|
||||
auto resolved = resolve_input_path(p.get<std::string>(), err);
|
||||
if (!resolved)
|
||||
throw ToolFailure(err);
|
||||
if (has_extension(*resolved, {".gcode", ".bgcode"}))
|
||||
throw ToolFailure(p.get<std::string>() + " is a G-code file, which project_open opens to show its toolpaths");
|
||||
paths.push_back(*resolved);
|
||||
}
|
||||
if (paths.empty())
|
||||
throw ToolFailure("paths is empty");
|
||||
const std::string as = arg_string(args, "as", "auto");
|
||||
// A run the user let drop unsaved changes (Run Script's "don't save") counts as discard_changes.
|
||||
const bool discard = arg_bool(args, "discard_changes", false) || runtime.jobs().discard_allowed_in(ctx.lineage());
|
||||
json out = ctx.run_ui([&]() -> json {
|
||||
Plater& plater = ui_plater();
|
||||
if (paths.size() == 1 && has_extension(paths[0], {".gcode", ".bgcode"})) {
|
||||
plater.load_gcode(from_path(paths[0]));
|
||||
return {{"opened", "gcode"}, {"path", path_to_utf8(paths[0])}};
|
||||
}
|
||||
if (paths.size() == 1 && as != "geometry" && has_extension(paths[0], {".3mf"})) {
|
||||
Ops::OpenProjectArgs open;
|
||||
open.path = paths[0];
|
||||
open.unsaved = unsaved_changes_answer(discard);
|
||||
const Ops::Outcome<Ops::ProjectSummary> opened = Ops::open_project(open);
|
||||
if (!opened)
|
||||
throw refused(opened.refusal(), kUnsavedChangesHint);
|
||||
json o = project_json(opened.value());
|
||||
o["opened"] = "project";
|
||||
return o;
|
||||
}
|
||||
Plater& plater = ui_plater();
|
||||
Ops::ImportModelsArgs models;
|
||||
models.paths = paths;
|
||||
if (args.contains("entries"))
|
||||
models.entries = args["entries"].get<std::vector<std::string>>();
|
||||
const Ops::Outcome<Ops::ImportModelsResult> imported = Ops::import_models(models);
|
||||
if (!imported)
|
||||
throw refused(imported.refusal(), "See get_log for the reason.");
|
||||
if (!imported) {
|
||||
const bool nothing = std::string(imported.refusal().code) == "nothing_loaded";
|
||||
throw refused(imported.refusal(), nothing ? "See app_log for the reason." : "", "entries");
|
||||
}
|
||||
json o = objects_summary(plater);
|
||||
o["opened"] = "models";
|
||||
o["added"] = imported.value().added;
|
||||
if (!imported.value().archives.empty()) {
|
||||
json archives = json::array();
|
||||
for (const Ops::ImportedArchive& archive : imported.value().archives)
|
||||
archives.push_back({{"path", path_to_utf8(archive.path)}, {"entries", archive.entries}});
|
||||
o["archives"] = std::move(archives);
|
||||
}
|
||||
return o;
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
})));
|
||||
}));
|
||||
import_.tiles = json::array(
|
||||
{NativeCommands::tile("import_file", L("Import 3MF/STL/STEP/SVG/OBJ/AMF"), L("Import"), "menu_open", json::object(),
|
||||
"Import models (3MF/STL/STEP/SVG/OBJ/AMF) through a file dialog, as one undo step; a project "
|
||||
"file's settings are not loaded (project_open opens a project). project_import with paths adds "
|
||||
"files' geometry without a dialog."),
|
||||
NativeCommands::tile("import_zip_archive", L("Import ZIP Archive"), L("Import"), "menu_open", {{"archive", true}},
|
||||
"Import models from a ZIP archive (opens a file dialog).")});
|
||||
catalog.add(NativeCommands::with_person_form(std::move(import_), [](const json& tile_args) {
|
||||
return tile_args.value("archive", false) ? Rows::import_zip_archive() : Rows::import_file();
|
||||
}));
|
||||
|
||||
// The Speed Dial's New Project too: with no arguments it asks as the tile does.
|
||||
catalog.add(NativeCommands::with_person_form(reaching({"new_project"}, mutate_tool(
|
||||
{}, "new_project", {},
|
||||
// New Project's row is its tile: with no arguments it asks as the row does.
|
||||
NativeCommand project_new = reaching({"new_project"}, mutate_tool(
|
||||
"project_new", L("New Project"),
|
||||
"Start a new, empty project. Called with no arguments, it asks as New Project does, about the unsaved changes "
|
||||
"if there are any: the reply is then blocked_by_dialog, and answer_dialog answers it. With arguments, or silent: "
|
||||
"if there are any: the reply is then blocked_by_dialog, and dialog_answer answers it. With arguments, or silent: "
|
||||
"true, it asks nothing: it fails, changing nothing, when the current project has unsaved changes, unless "
|
||||
"discard_changes. The presets' unsaved changes carry over to the new project unless preset_changes is \"discard\", as "
|
||||
"New Project's prompt offers. Reply, with arguments: objects, names, plates; when presets had or have unsaved "
|
||||
@@ -486,28 +561,33 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
})),
|
||||
L("New Project"), L("Commands"), "menu_open", [] {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->new_project();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
}));
|
||||
project_new.tiles = json::array({NativeCommands::tile("new_project", L("New Project"), L("Commands"), "menu_open", json::object(),
|
||||
"Runs project_new with no arguments, as New Project does: a new, empty "
|
||||
"project, after asking about the unsaved changes if there are any.")});
|
||||
catalog.add(NativeCommands::with_person_form(std::move(project_new), [](const json&) {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
plater->new_project();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
}));
|
||||
|
||||
catalog.add(mutate_tool(
|
||||
"api", "generate_calibration_test", L("Generate a calibration test"),
|
||||
NativeCommand calibration = mutate_tool(
|
||||
"calibration_generate_test", L("Generate a calibration test"),
|
||||
"Generate a Calibration menu test as its dialog's OK does: a new project named after the test with the test "
|
||||
"model, and the process, filament and printer presets changed as the test needs (presets_changed). The test prints "
|
||||
"with filament slot 1, so the filament tab is pointed at slot 1's preset. Omitted parameters take the dialog's "
|
||||
"defaults (pressure advance's by the printer's extruder type); temperatures are clamped to 155-500 °C and rounded "
|
||||
"down to 5 °C. Fails, changing nothing, when the project has unsaved changes (pass discard_changes) or presets do "
|
||||
"(pass preset_changes). Reply: test, project, params (the values used, which the journal records), objects, names, "
|
||||
"plates, presets_changed, result_keys (where the measured value belongs), warnings, adjusted (vfa), and discarded "
|
||||
"and modified as new_project. Then slice and export. To save a measured value: new_project {discard_changes, "
|
||||
"preset_changes: \"discard\"}, set_settings the value, save_preset.",
|
||||
"(pass preset_changes). Called with test alone it opens that test's dialog, as the Calibration menu does "
|
||||
"(blocked_by_dialog), and the dialog's OK runs the test; silent: true with test alone runs it with the dialog's "
|
||||
"defaults. Reply: test, project, params (the values used, which the "
|
||||
"journal records), objects, names, plates, presets_changed, result_keys (where the measured value belongs), "
|
||||
"warnings, adjusted (vfa), and discarded and modified as project_new. Then plate_slice and project_export. To save "
|
||||
"a measured value: project_new {discard_changes, preset_changes: \"discard\"}, settings_set the value, preset_save.",
|
||||
object_schema(
|
||||
{{"test", enum_prop({"temperature", "max_volumetric", "pressure_advance", "flow_ratio", "retraction", "vfa", "cornering",
|
||||
"input_shaping_freq", "input_shaping_damp"},
|
||||
"The test, named as the calib_* actions.")},
|
||||
"The test, as the Calibration menu names it.")},
|
||||
{"method", enum_prop({"tower", "line", "pattern", "pass1", "pass2", "yolo", "yolo_perfectionist"},
|
||||
"pressure_advance: tower (default), line or pattern; flow_ratio: pass1, pass2, yolo (default) or "
|
||||
"yolo_perfectionist.")},
|
||||
@@ -617,7 +697,7 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
if (!switched_from.empty())
|
||||
presets_changed["filament"]["tab_switched_from"] = switched_from;
|
||||
if (plater.model().objects.empty())
|
||||
throw ToolFailure("The project was replaced but the test model was not added; see get_log",
|
||||
throw ToolFailure("The project was replaced but the test model was not added; see app_log",
|
||||
{{"presets_changed", presets_changed}});
|
||||
|
||||
json reply = calib_params_json(args, params, printer);
|
||||
@@ -641,19 +721,64 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
ctx.set_journal_args(std::move(recorded));
|
||||
settle(ctx);
|
||||
return ToolResult::ok(out);
|
||||
}));
|
||||
});
|
||||
// The Calibration menu's rows, each the dialog of its test. The tab strip's calib_sf glyph is drawn white for the dark
|
||||
// tab bar and vanishes on the palette's light tile, so each row borrows the matching settings-group icon instead.
|
||||
struct CalibrationRow
|
||||
{
|
||||
const char* key;
|
||||
const char* title;
|
||||
const char* icon;
|
||||
const char* test;
|
||||
CalibKind kind;
|
||||
};
|
||||
// Titles are L("...")-marked here so xgettext extracts them.
|
||||
static const CalibrationRow calibration_rows[] = {
|
||||
{"calib_temperature", L("Temperature Calibration"), "param_temperature", "temperature", CalibKind::Temperature},
|
||||
{"calib_max_volumetric", L("Max Volumetric Speed Calibration"), "param_volumetric_speed", "max_volumetric",
|
||||
CalibKind::MaxVolumetric},
|
||||
{"calib_pressure_advance", L("Pressure Advance Calibration"), "param_flow_ratio_and_pressure_advance", "pressure_advance",
|
||||
CalibKind::PressureAdvance},
|
||||
{"calib_flow_ratio", L("Flow Ratio Calibration"), "param_flow_ratio_and_pressure_advance", "flow_ratio", CalibKind::FlowRatio},
|
||||
{"calib_retraction", L("Retraction Calibration"), "param_retraction", "retraction", CalibKind::Retraction},
|
||||
{"calib_cornering", L("Cornering Calibration"), "param_precision", "cornering", CalibKind::Cornering},
|
||||
{"calib_input_shaping_freq", L("Input Shaping Frequency Calibration"), "param_resonance_avoidance", "input_shaping_freq",
|
||||
CalibKind::InputShapingFreq},
|
||||
{"calib_input_shaping_damp", L("Input Shaping Damping Calibration"), "param_resonance_avoidance", "input_shaping_damp",
|
||||
CalibKind::InputShapingDamp},
|
||||
{"calib_vfa", L("VFA Calibration"), "param_speed", "vfa", CalibKind::VFA},
|
||||
};
|
||||
calibration.tiles = json::array();
|
||||
for (const CalibrationRow& row : calibration_rows)
|
||||
calibration.tiles.push_back(NativeCommands::tile(row.key, row.title, L("Calibration"), row.icon, {{"test", row.test}},
|
||||
std::string("Open the ") + row.title +
|
||||
" dialog; calibration_generate_test with the test's parameters, or "
|
||||
"silent, runs it with no dialog."));
|
||||
catalog.add(NativeCommands::with_person_form(std::move(calibration), [](const json& tile_args) {
|
||||
const std::string test = tile_args.at("test");
|
||||
for (const CalibrationRow& row : calibration_rows)
|
||||
if (test == row.test)
|
||||
return Rows::calib(row.kind);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("Unknown test \"" + test + "\""), false};
|
||||
}));
|
||||
|
||||
// The Speed Dial's Save Project too: with no arguments it saves as the tile does.
|
||||
NativeCommand save = NativeCommands::with_person_form(reaching({"save_project_as"}, mutate_tool(
|
||||
{}, "save_project", {},
|
||||
// Save Project's and Save Project As's rows are its tiles: with no arguments, or with save_as alone, it saves as the
|
||||
// row does.
|
||||
NativeCommand save = reaching({"save_project_as"}, mutate_tool(
|
||||
"project_save", L("Save Project"),
|
||||
"Save the project. Called with no arguments, it saves as Save Project does: to the project's file (reply: ran, "
|
||||
"level), or, when it has none, through a file dialog (blocked_by_dialog; a native picker needs auto_answer_dialogs "
|
||||
"registered first). With path, it saves a .3mf there without the file dialog, and the file becomes the project's "
|
||||
"(reply: path, bytes); a name ending in .gcode.3mf is refused (export writes that). Either way the save can still "
|
||||
"open a dialog (blocked_by_dialog): a warning when settings name a plugin OrcaSlicer cannot identify, or an error "
|
||||
"when the file cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the "
|
||||
"write failed, fails with project_not_saved, and a file already there stays as it was.",
|
||||
object_schema({{"path", prop("string", "Absolute .3mf path.")}, {"overwrite", prop("boolean", "Replace an existing file.")}}, {"path"}),
|
||||
"level), or, when it has none, through a file dialog (blocked_by_dialog; a native picker needs dialog_auto_answer "
|
||||
"registered first); with save_as: true alone, as Save Project As does, always through the file dialog. With path, "
|
||||
"it saves a .3mf there without the file dialog, and the file becomes the project's (reply: path, bytes); a name "
|
||||
"ending in .gcode.3mf is refused (project_export writes that). Either way the save can still open a dialog "
|
||||
"(blocked_by_dialog): a warning when settings name a plugin OrcaSlicer cannot identify, or an error when the file "
|
||||
"cannot be written. A save that writes nothing, its file dialog or that warning cancelled or the write failed, "
|
||||
"fails with project_not_saved, and a file already there stays as it was.",
|
||||
object_schema({{"path", prop("string", "Absolute .3mf path.")},
|
||||
{"overwrite", prop("boolean", "Replace an existing file.")},
|
||||
{"save_as", prop("boolean", "true, alone: ask for the file in the save dialog, as Save Project As does. With "
|
||||
"path it adds nothing: path is the new file.")}},
|
||||
{"path"}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
std::string err;
|
||||
auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err);
|
||||
@@ -665,42 +790,73 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
save.path = *path;
|
||||
if (const Ops::Outcome<Ops::Done> saved = Ops::save_project_as(save); !saved)
|
||||
throw refused(saved.refusal(), std::string(saved.refusal().code) == "sliced_file_name" ?
|
||||
"That is export {format: \"sliced_3mf\"} (plates \"all\" for every plate)." :
|
||||
"See get_log.");
|
||||
"That is project_export {format: \"sliced_3mf\"} (plates \"all\" for every plate)." :
|
||||
"See app_log.");
|
||||
return json();
|
||||
});
|
||||
settle(ctx);
|
||||
return ToolResult::ok({{"path", path_to_utf8(*path)}, {"bytes", fs::file_size(*path)}});
|
||||
})),
|
||||
L("Save Project"), L("Commands"), "menu_save", [] {
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
return NativeCommands::project_save_result(plater->save_project(false));
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
});
|
||||
// Any argument makes path required, and a call with path skips the file dialog: silent has nothing to add here.
|
||||
}));
|
||||
save.tiles = json::array(
|
||||
{NativeCommands::tile("save_project", L("Save Project"), L("Commands"), "menu_save", json::object(),
|
||||
"Runs project_save with no arguments, as Save Project does: to the project's file, or through a "
|
||||
"file dialog when it has none."),
|
||||
NativeCommands::tile("save_project_as", L("Save Project As"), L("Commands"), "menu_save", {{"save_as", true}},
|
||||
"Save the project as a .3mf file through the save dialog. project_save with a path saves there "
|
||||
"without a dialog; a name ending in .gcode.3mf is refused (project_export {format: \"sliced_3mf\"} "
|
||||
"writes that).")});
|
||||
save = NativeCommands::with_person_form(std::move(save), [](const json& tile_args) {
|
||||
if (tile_args.value("save_as", false))
|
||||
return Rows::save_project_as();
|
||||
if (Plater* plater = wxGetApp().plater())
|
||||
return NativeCommands::project_save_result(plater->save_project(false));
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
});
|
||||
// Every call but the two tiles' requires path, and a call with path skips the file dialog: silent has nothing to add.
|
||||
save.input_schema["properties"]["silent"]["description"] =
|
||||
"Goes with path, which any argument makes required, and adds nothing to it: a call with path skips the file dialog already.";
|
||||
"Goes with path, which every call but {} and {save_as: true} requires, and adds nothing to it: a call with path skips "
|
||||
"the file dialog already.";
|
||||
catalog.add(save);
|
||||
|
||||
catalog.add(reaching({"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl"}, mutate_tool(
|
||||
"api", "export", L("Export"),
|
||||
NativeCommand export_ = reaching(
|
||||
{"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl", "export_toolpaths_obj"},
|
||||
with_expected_ids(mutate_tool(
|
||||
"project_export", L("Export"),
|
||||
"Write the project to a file without a dialog. gcode: the plate's G-code (slice first; it is written in the "
|
||||
"background, and the call returns once it is). sliced_3mf: the sliced plate, or all plates, as .gcode.3mf (slice "
|
||||
"first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl: all "
|
||||
"objects as one STL. Both hold every plate's objects. Without format, the path's extension (.gcode, .gcode.3mf, "
|
||||
".3mf, .stl) says which. Reply: path and bytes; for gcode, path and export (ok, or superseded with a note when the "
|
||||
"project changed while it was written).",
|
||||
object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl"}, "What to write; default from the path's extension.")},
|
||||
{"path", prop("string", "Absolute output path.")},
|
||||
{"plates", {{"type", {"string", "integer"}},
|
||||
{"description", "\"current\" (default), a plate index, which is selected first and is the plate "
|
||||
"gcode and sliced_3mf write, or \"all\" (sliced_3mf only)."}}},
|
||||
{"overwrite", prop("boolean", "Replace an existing file.")}},
|
||||
{"path"}),
|
||||
"first: a plate that is not sliced is written without G-code). 3mf: the model without slicing data. stl and drc "
|
||||
"(Draco): the objects as one file, or with per_object each in a file of its own, named after it, into the folder "
|
||||
"path names; every object of every plate, or those objects names. toolpaths_obj: the toolpaths the Preview shows, "
|
||||
"as an OBJ, refused while it shows none (slice the plate and show the Preview first). Without format, the path's "
|
||||
"extension (.gcode, .gcode.3mf, .3mf, .stl, .drc, .obj) says which. Called with exactly the arguments of one of the "
|
||||
"File > Export rows (format alone, sliced_3mf with plates \"all\", stl or drc with per_object), it asks for the file "
|
||||
"or folder in the dialog that row opens (blocked_by_dialog). A file per object of a project with no objects, and the "
|
||||
"toolpaths while the Preview shows none, are refused in either form. Reply: path and bytes; for gcode, path and "
|
||||
"export (ok, or superseded with a note when the project changed while it was written); for per_object, path and "
|
||||
"files (each file written); for stl and drc, objects (those written).",
|
||||
with_targets(object_schema({{"format", enum_prop({"gcode", "sliced_3mf", "3mf", "stl", "drc", "toolpaths_obj"},
|
||||
"What to write; default from the path's extension.")},
|
||||
{"path", prop("string", "Absolute output path: the file, or with per_object an existing folder.")},
|
||||
{"plates", {{"type", {"string", "integer"}},
|
||||
{"description", "\"current\" (default), a plate index, which is selected first and is "
|
||||
"the plate gcode and sliced_3mf write, or \"all\" (sliced_3mf only)."}}},
|
||||
{"per_object", prop("boolean", "stl and drc: a file per object, into a folder. Default false.")},
|
||||
{"overwrite", prop("boolean", "Replace an existing file.")}},
|
||||
{"path"}),
|
||||
kObjects, false),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const std::string format = args.contains("format") ? arg_string(args, "format") : format_of(arg_string(args, "path"));
|
||||
std::string err;
|
||||
auto path = resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err);
|
||||
const std::string format = args.contains("format") ? arg_string(args, "format") : format_of(arg_string(args, "path"));
|
||||
const bool per_object = arg_bool(args, "per_object", false);
|
||||
const bool meshes = format == "stl" || format == "drc";
|
||||
if (per_object && !meshes)
|
||||
throw ToolFailure("per_object goes with format stl or drc");
|
||||
if (per_object && (args.contains("plates") || args.contains("overwrite")))
|
||||
throw ToolFailure("per_object writes every object into the folder path names: plates and overwrite go with one file");
|
||||
if (format == "toolpaths_obj" && args.contains("plates"))
|
||||
throw ToolFailure("toolpaths_obj writes the toolpaths the Preview shows: plates goes with the other formats");
|
||||
std::string err;
|
||||
const auto path = per_object ? resolve_output_dir(arg_string(args, "path"), err) :
|
||||
resolve_output_path(arg_string(args, "path"), arg_bool(args, "overwrite", false), err);
|
||||
if (!path)
|
||||
throw ToolFailure(err);
|
||||
const json plate = args.value("plates", json("current"));
|
||||
@@ -708,12 +864,53 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
if (all && format != "sliced_3mf")
|
||||
throw ToolFailure("plates \"all\" applies to sliced_3mf only");
|
||||
std::optional<Ops::ExportTicket> ticket;
|
||||
json written = json::object(); // what the reply adds for stl and drc
|
||||
ctx.run_ui([&]() -> json {
|
||||
// A G-code export finishes in the background: held from before it starts.
|
||||
if (format == "gcode")
|
||||
ctx.begin_operation();
|
||||
ui_plater();
|
||||
Plater& plater = ui_plater();
|
||||
const std::optional<int> index = plate.is_number_integer() ? std::optional<int>(plate.get<int>()) : std::nullopt;
|
||||
// The objects named, by index or id; none named: every object.
|
||||
Targets named;
|
||||
if (names_targets(args)) {
|
||||
const Ops::Outcome<Targets> found = resolve_targets(plater.model(), nullptr, args, kObjects, false);
|
||||
if (!found)
|
||||
throw refused(found.refusal());
|
||||
named = found.value();
|
||||
}
|
||||
if (const std::optional<Ops::Refusal> refusal =
|
||||
Ops::export_objects_refusal(format, named.objects, per_object, plater.model()))
|
||||
throw refused(*refusal);
|
||||
if (meshes) {
|
||||
Ops::ExportStlArgs mesh;
|
||||
mesh.path = *path;
|
||||
mesh.plate = index;
|
||||
mesh.objects = named.objects;
|
||||
mesh.per_object = per_object;
|
||||
mesh.draco = format == "drc";
|
||||
const Ops::Outcome<std::vector<fs::path>> files = Ops::export_stl(mesh);
|
||||
if (!files)
|
||||
throw refused(files.refusal(), std::string(files.refusal().code) == "file_not_written" ? "See app_log." : "");
|
||||
Targets exported = named;
|
||||
if (exported.objects.empty())
|
||||
for (int o = 0; o < int(plater.model().objects.size()); ++o)
|
||||
exported.objects.push_back(o);
|
||||
written = targets_reply(plater.model(), exported);
|
||||
if (per_object) {
|
||||
written["files"] = json::array();
|
||||
for (const fs::path& file : files.value())
|
||||
written["files"].push_back(path_to_utf8(file));
|
||||
}
|
||||
return json();
|
||||
}
|
||||
if (format == "toolpaths_obj") {
|
||||
if (const Ops::Outcome<Ops::Done> drawn = Ops::export_toolpaths_obj({*path}); !drawn)
|
||||
throw refused(drawn.refusal(), std::string(drawn.refusal().code) == "no_toolpaths" ?
|
||||
"plate_slice {preview: true} slices the plate and shows it." :
|
||||
"See app_log.");
|
||||
return json();
|
||||
}
|
||||
if (format == "gcode") {
|
||||
Ops::ExportGcodeArgs gcode;
|
||||
gcode.path = *path;
|
||||
@@ -721,8 +918,8 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
const Ops::Outcome<Ops::ExportTicket> started = Ops::start_gcode_export(gcode);
|
||||
if (!started) {
|
||||
const std::string code = started.refusal().code;
|
||||
throw refused(started.refusal(), code == "slicing_in_progress" ? "wait {for:\"idle\"} waits for it." :
|
||||
code == "export_not_started" ? "Check get_app_state.notifications." :
|
||||
throw refused(started.refusal(), code == "slicing_in_progress" ? "app_wait {for:\"idle\"} waits for it." :
|
||||
code == "export_not_started" ? "Check app_state.notifications." :
|
||||
"");
|
||||
}
|
||||
ticket = started.value();
|
||||
@@ -735,18 +932,64 @@ void register_project_tools(CommandCatalog& catalog)
|
||||
Ops::ExportFileArgs file;
|
||||
file.path = *path;
|
||||
file.plate = index;
|
||||
const Ops::Outcome<Ops::Done> written = format == "sliced_3mf" ? Ops::export_sliced_3mf(sliced) :
|
||||
format == "3mf" ? Ops::export_model_3mf(file) :
|
||||
Ops::export_stl(file);
|
||||
if (!written)
|
||||
throw refused(written.refusal(), std::string(written.refusal().code) == "file_not_written" ? "See get_log." : "");
|
||||
const Ops::Outcome<Ops::Done> done = format == "sliced_3mf" ? Ops::export_sliced_3mf(sliced) : Ops::export_model_3mf(file);
|
||||
if (!done)
|
||||
throw refused(done.refusal(), std::string(done.refusal().code) == "file_not_written" ? "See app_log." : "");
|
||||
return json();
|
||||
});
|
||||
if (ticket)
|
||||
return await_gcode_export(ctx, *ticket);
|
||||
settle(ctx);
|
||||
return ToolResult::ok({{"path", path_to_utf8(*path)}, {"bytes", fs::file_size(*path)}});
|
||||
json reply{{"path", path_to_utf8(*path)}};
|
||||
if (!per_object)
|
||||
reply["bytes"] = fs::file_size(*path);
|
||||
reply.update(written);
|
||||
return ToolResult::ok(reply);
|
||||
})));
|
||||
// The File > Export rows, each with the dialog it asks for the file or folder in.
|
||||
export_.tiles = json::array({
|
||||
NativeCommands::tile("export_gcode", L("Export G-code"), L("Slice & Export"), "custom-gcode_gcode", {{"format", "gcode"}},
|
||||
"Export the current plate's G-code through the export dialog, in the background. project_export "
|
||||
"with a path exports the sliced plate there without a dialog, and the call returns when the file "
|
||||
"is written; a plate that is not sliced is refused (slice first)."),
|
||||
NativeCommands::tile("export_sliced_file", L("Export Sliced File"), L("Slice & Export"), "save", {{"format", "sliced_3mf"}},
|
||||
"Export the current plate's sliced file (.gcode.3mf) through a file dialog; project_export with a "
|
||||
"path writes there without one."),
|
||||
NativeCommands::tile("export_all_sliced_file", L("Export All Sliced Files"), L("Slice & Export"), "save",
|
||||
{{"format", "sliced_3mf"}, {"plates", "all"}},
|
||||
"Export every plate's sliced file into one .gcode.3mf through a file dialog; project_export with a "
|
||||
"path writes there without one."),
|
||||
NativeCommands::tile("export_3mf", L("Export 3MF"), L("Slice & Export"), "menu_save", {{"format", "3mf"}},
|
||||
"Export the model as a .3mf without slicing data, through a file dialog; project_export with a path "
|
||||
"writes there without one."),
|
||||
NativeCommands::tile("export_stl", L("Export STL"), L("Slice & Export"), "save", {{"format", "stl"}},
|
||||
"Export all objects as one STL through a file dialog; project_export with a path writes there "
|
||||
"without one."),
|
||||
NativeCommands::tile("export_stl_multi", L("Export All Objects as STLs"), L("Export"), "save", {{"format", "stl"}, {"per_object", true}},
|
||||
"Export each object as its own STL into the folder a dialog asks for; project_export with a folder "
|
||||
"as path writes there without one."),
|
||||
NativeCommands::tile("export_drc_single", L("Export All Objects as DRC (one file)"), L("Export"), "save", {{"format", "drc"}},
|
||||
"Export all objects as one Draco (.drc) file."),
|
||||
NativeCommands::tile("export_drc_multi", L("Export All Objects as DRCs"), L("Export"), "save", {{"format", "drc"}, {"per_object", true}},
|
||||
"Export each object as its own Draco (.drc) file."),
|
||||
NativeCommands::tile("export_toolpaths_obj", L("Export Toolpaths as OBJ"), L("Export"), "custom-gcode_gcode",
|
||||
{{"format", "toolpaths_obj"}}, "Export the sliced toolpaths as an OBJ."),
|
||||
});
|
||||
catalog.add(NativeCommands::with_person_form(std::move(export_), [](const json& tile_args) {
|
||||
const std::string format = tile_args.at("format");
|
||||
const bool per_object = tile_args.value("per_object", false);
|
||||
if (format == "gcode")
|
||||
return Rows::export_gcode();
|
||||
if (format == "sliced_3mf")
|
||||
return Rows::export_sliced_file(tile_args.value("plates", std::string()) == "all");
|
||||
if (format == "3mf")
|
||||
return Rows::export_3mf();
|
||||
if (format == "stl")
|
||||
return per_object ? Rows::export_stl_multi() : Rows::export_stl();
|
||||
if (format == "drc")
|
||||
return per_object ? Rows::export_drc_multi() : Rows::export_drc_single();
|
||||
return Rows::export_toolpaths_obj();
|
||||
}));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -1,4 +1,4 @@
|
||||
// run_script and search_python_api: Python scripts against orca.host, the plugin API, and the orca package's
|
||||
// script_run and script_search_api: Python scripts against orca.host, the plugin API, and the orca package's
|
||||
// reference.
|
||||
|
||||
#include "JobRegistry.hpp"
|
||||
@@ -9,7 +9,9 @@
|
||||
#include "AutomationRuntime.hpp"
|
||||
#include "McpTools.hpp"
|
||||
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/NativeCommandRows.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GUI_App.hpp"
|
||||
@@ -44,7 +46,7 @@ namespace py = pybind11;
|
||||
|
||||
namespace {
|
||||
|
||||
// A run's orca.host.tools calls, as child calls of the run_script job, so each has its tool's guards,
|
||||
// A run's orca.host.tools calls, as child calls of the script_run job, so each has its tool's guards,
|
||||
// admission and undo, and a cancel of the run reaches them.
|
||||
class RunBridge final : public ToolBridge
|
||||
{
|
||||
@@ -63,13 +65,13 @@ private:
|
||||
};
|
||||
|
||||
// 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
|
||||
// stop cancels every call in flight, inline ones (app_wait) included, without stopping the session, and the next work's
|
||||
// calls run under a fresh node.
|
||||
class SessionBridge final : public ToolBridge
|
||||
{
|
||||
public:
|
||||
SessionBridge(AutomationRuntime& runtime, const std::string& session_job)
|
||||
: m_runtime(runtime), m_node(runtime.jobs(), "run_script", session_job)
|
||||
: m_runtime(runtime), m_node(runtime.jobs(), "script_run", session_job)
|
||||
{}
|
||||
json call(const std::string& tool, const json& args) override
|
||||
{
|
||||
@@ -79,7 +81,7 @@ public:
|
||||
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_job cancels them.
|
||||
// job_cancel cancels them.
|
||||
void stop_calls()
|
||||
{
|
||||
const std::string node = m_node.id();
|
||||
@@ -257,7 +259,7 @@ bool python_has_numpy()
|
||||
ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx, PythonSession& session, const std::string& filename)
|
||||
{
|
||||
const std::string job = ctx.job_id();
|
||||
// The session waits for the person between works: `wait {for: "idle"}` counts only the calls it makes.
|
||||
// The session waits for the person between works: `app_wait {for: "idle"}` counts only the calls it makes.
|
||||
runtime.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.
|
||||
runtime.begin_run_scope(job);
|
||||
@@ -291,14 +293,14 @@ ToolResult run_python_session_job(AutomationRuntime& runtime, ToolContext& ctx,
|
||||
std::shared_ptr<PersonRun> start_python_session(AutomationRuntime& runtime, std::shared_ptr<PythonSession> session,
|
||||
const boost::filesystem::path& file, PersonRun::Events events)
|
||||
{
|
||||
const NativeCommand* run_script = NativeCommands::instance().find("run_script");
|
||||
if (run_script == nullptr || runtime.stopping() || !session)
|
||||
const NativeCommand* script_run = NativeCommands::instance().find("script_run");
|
||||
if (script_run == nullptr || runtime.stopping() || !session)
|
||||
return nullptr;
|
||||
auto run = std::make_shared<PersonRun>(runtime, std::move(events));
|
||||
auto hosted = std::make_shared<std::atomic<bool>>(false);
|
||||
auto filename = file.empty() ? std::string("<run_script>") : path_to_utf8(file);
|
||||
// run_script's properties, outside the session journal, as a person's run.
|
||||
NativeCommand def = *run_script;
|
||||
auto filename = file.empty() ? std::string("<script_run>") : path_to_utf8(file);
|
||||
// script_run's properties, outside the session journal, as a person's run.
|
||||
NativeCommand def = *script_run;
|
||||
def.journal = false;
|
||||
def.run = [&runtime, run, session, hosted, filename](const json&, ToolContext& ctx) {
|
||||
run->set_job(ctx.job_id());
|
||||
@@ -337,12 +339,12 @@ std::shared_ptr<PersonRun> start_python_session(AutomationRuntime& runtime, std:
|
||||
void register_python_tools(CommandCatalog& catalog)
|
||||
{
|
||||
NativeCommand run = mutate_tool(
|
||||
"core", "run_script", L("Run a Python script"),
|
||||
"script_run", L("Run a Python script"),
|
||||
"Run Python code inside OrcaSlicer as its main program (__name__ == \"__main__\") against orca.host, the whole plugin "
|
||||
"API (search_python_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset "
|
||||
"API (script_search_api searches it): read objects, meshes and settings, compute, use orca.host.ui and the preset "
|
||||
"API, and call these same tools, with their guards and undo, through orca.host.tools.call(name, args). Mesh and "
|
||||
"matrix arrays need numpy, which "
|
||||
"search_python_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker "
|
||||
"script_search_api says is installed or not; a file run's PEP 723 block can install it. The code runs on a worker "
|
||||
"thread, where calls documented as UI thread only raise RuntimeError. The run ends once its code and the non-daemon "
|
||||
"threads and pool tasks it started are done; its windows close with it. `args` holds the args you pass; set `result` "
|
||||
"to a JSON value to return it; print() output comes back as output. Reply: {status: finished | raised | cancelled | "
|
||||
@@ -350,14 +352,14 @@ void register_python_tools(CommandCatalog& catalog)
|
||||
"own file access is held to OrcaSlicer's folders (its data folder, and read only its resources folder and, for a "
|
||||
"file run, the file's folder), and it starts no programs or threads and reaches no network: such an access raises "
|
||||
"PermissionError, unless a person has let Python scripts run unrestricted in Preferences "
|
||||
"(get_app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while "
|
||||
"(app_state.python.scripts_unrestricted), when the threads and pool tasks it starts call the tools too while "
|
||||
"the run lasts; the tools it calls work as they do for you. Recorded "
|
||||
"by export_replay as one step with its code, which a replay runs again against the project as it is then.",
|
||||
"by replay_export as one step with its code, which a replay runs again against the project as it is then.",
|
||||
object_schema({{"code", prop("string", "Python source, run as a module body.")},
|
||||
{"args", {{"type", "object"}, {"description", "Bound to the name `args` in the code."}}},
|
||||
{"timeout_s", {{"type", "integer"}, {"minimum", 1}, {"maximum", 3600},
|
||||
{"description", "The run is stopped as timed_out after this many seconds (default 300)."}}},
|
||||
{"filename", prop("string", "The name tracebacks show for the code (default <run_script>). An existing file's "
|
||||
{"filename", prop("string", "The name tracebacks show for the code (default <script_run>). An existing file's "
|
||||
"path makes it a file run, as `python file.py` runs it: __file__, sys.argv, imports "
|
||||
"from its folder and its PEP 723 dependencies; any other name only names it. "
|
||||
"What runs is still `code`: pass the file's text there.")}},
|
||||
@@ -373,7 +375,7 @@ void register_python_tools(CommandCatalog& catalog)
|
||||
// A run owns what its calls leave behind (auto-answer rules, a recording, a held press) as a JSON
|
||||
// script does: it all ends with the run.
|
||||
const std::string job = ctx.job_id();
|
||||
// A run may wait for a person in its window: `wait {for: "idle"}` counts only the calls it makes.
|
||||
// A run may wait for a person in its window: `app_wait {for: "idle"}` counts only the calls it makes.
|
||||
runtime.jobs().set_idle(job);
|
||||
runtime.begin_run_scope(job);
|
||||
struct ScopeEnd
|
||||
@@ -389,7 +391,7 @@ void register_python_tools(CommandCatalog& catalog)
|
||||
request.code = arg_string(args, "code");
|
||||
request.args = args.value("args", json::object());
|
||||
request.identity = identity;
|
||||
request.filename = arg_string(args, "filename", "<run_script>");
|
||||
request.filename = arg_string(args, "filename", "<script_run>");
|
||||
// 0, below the schema's minimum, is passed only in process, by the Run Script dialog, whose Stop ends a run:
|
||||
// every external path validates the arguments. It means no time limit.
|
||||
request.budget = std::chrono::seconds(arg_int(args, "timeout_s", 300));
|
||||
@@ -405,19 +407,19 @@ void register_python_tools(CommandCatalog& catalog)
|
||||
data["traceback"] = out.traceback;
|
||||
if (!out.message.empty())
|
||||
data["message"] = out.message;
|
||||
// A run that did not finish is reported, not failed, as run_replay reports a failed step: the
|
||||
// A run that did not finish is reported, not failed, as replay_run reports a failed step: the
|
||||
// journal keeps it, and a replay of it fails again (D7).
|
||||
return ToolResult::ok(std::move(data));
|
||||
});
|
||||
// cancel_job {job} stops a run: its code is interrupted at its next bytecode.
|
||||
// job_cancel {job} stops a run: its code is interrupted at its next bytecode.
|
||||
run.cancellable = true;
|
||||
// A script reaches outside the app: files, programs and the network.
|
||||
run.open_world = true;
|
||||
catalog.add(run);
|
||||
|
||||
catalog.add(inspect_tool(
|
||||
"core", "search_python_api", L("Search the Python API"),
|
||||
"Search orca, the Python API of run_script scripts and plugins, in the running build: orca.host (the project's "
|
||||
"script_search_api", L("Search the Python API"),
|
||||
"Search orca, the Python API of script_run scripts and plugins, in the running build: orca.host (the project's "
|
||||
"model and meshes, presets and their editors, slicing data, orca.host.ui windows and dialogs, orca.host.tools "
|
||||
"calling these tools) and the classes, events and pages plugins build on. Each entry has its kind, signature (a "
|
||||
"class's constructors) and documentation. A query ranks them, best match first; without one, the whole package is "
|
||||
@@ -445,6 +447,17 @@ void register_python_tools(CommandCatalog& catalog)
|
||||
out["numpy"] = python_has_numpy();
|
||||
return ToolResult::ok(std::move(out));
|
||||
}));
|
||||
|
||||
// The Run Script panel's menu row, which has no argument form.
|
||||
const std::string panel = "Show or hide the Run Script panel, where a person writes and runs Python scripts cell by cell. Agents "
|
||||
"run Python with the script_run tool instead.";
|
||||
NativeCommand toggle_panel = row_command("script_toggle_panel", L("Run Script"), panel, object_schema({}),
|
||||
json::array({NativeCommands::tile("toggle_run_script_panel", L("Run Script"),
|
||||
L("Commands"), "media_play", json::object(), panel)}),
|
||||
[](const json&) { return Rows::toggle_run_script_panel(); });
|
||||
// A menu row with no argument form: tool_search finds it and tool_call runs it, the tool list does not show it.
|
||||
toggle_panel.listed = false;
|
||||
catalog.add(std::move(toggle_panel));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -1,4 +1,4 @@
|
||||
// start_recording, stop_recording and encode_recording: a video of what OrcaSlicer shows, optionally captioned
|
||||
// recording_start, recording_stop and recording_encode: a video of what OrcaSlicer shows, optionally captioned
|
||||
// with the current tool call and its pointer highlighted, and its encode to MP4.
|
||||
|
||||
#include "McpCore.hpp"
|
||||
@@ -48,10 +48,9 @@ namespace {
|
||||
|
||||
// The recording tools only read the app, so they run behind dialogs and during operations, but each
|
||||
// is a job: ownership is read from the job's ancestry, and an encode outlives the reply budget.
|
||||
NativeCommand record_tool(std::string group, std::string name, std::string title, std::string description, json schema, CommandFn handler)
|
||||
NativeCommand record_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler)
|
||||
{
|
||||
NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), std::move(group), std::move(schema),
|
||||
std::move(handler));
|
||||
NativeCommand d = NativeCommands::long_command(std::move(name), std::move(title), {}, std::move(schema), std::move(handler));
|
||||
d.description = std::move(description);
|
||||
d.listed = true;
|
||||
d.guard = GuardClass::Inspect;
|
||||
@@ -99,30 +98,30 @@ std::vector<std::string> encode_preset_keys()
|
||||
|
||||
ToolResult start_encode(AutomationRuntime& runtime, const json& args)
|
||||
{
|
||||
const NativeCommand* encode = NativeCommands::instance().find("encode_recording");
|
||||
const NativeCommand* encode = NativeCommands::instance().find("recording_encode");
|
||||
if (encode == nullptr || runtime.stopping())
|
||||
return ToolResult::error("OrcaSlicer is shutting down");
|
||||
NativeCommand def = *encode;
|
||||
def.journal = false;
|
||||
def.budget_ms = 0; // the envelope at once; the result comes from wait
|
||||
def.budget_ms = 0; // the envelope at once; the result comes from app_wait
|
||||
return runtime.core().call(def, args);
|
||||
}
|
||||
|
||||
void register_record_tools(CommandCatalog& catalog)
|
||||
{
|
||||
// The Speed Dial's Start Recording too: with no arguments it opens the tile's dialog.
|
||||
catalog.add(NativeCommands::with_person_form(record_tool(
|
||||
{}, "start_recording", {},
|
||||
"Record a video of OrcaSlicer until stop_recording: the main window with any modal dialog on it (target main), or "
|
||||
// The Speed Dial's Start Recording is its tile: with no arguments it opens the tile's dialog.
|
||||
NativeCommand start = record_tool(
|
||||
"recording_start", L("Start Recording"),
|
||||
"Record a video of OrcaSlicer until recording_stop: the main window with any modal dialog on it (target main), or "
|
||||
"the 3D view shown (canvas). Frames are MJPEG in a Matroska (.mkv) file with their real timestamps. With captions, "
|
||||
"the tool call acting on the app shows as a caption at the bottom (secret setting values never show); with pointer, "
|
||||
"the pointer is highlighted, its clicks rippling. Capture takes at most about a third of the UI thread, so "
|
||||
"the frame rate drops where capturing is slow. One recording at a time: one a replay or script starts ends with it, a "
|
||||
"client's when the server is turned off. With encode, the stop_recording that reports it also encodes it to an MP4 "
|
||||
"beside it, as the Start Recording command does, and the .mkv is deleted once the MP4 is written unless "
|
||||
"keep_raw_video_file; encode_recording makes an MP4 of any recording later. Called with no "
|
||||
"arguments, it opens the Start Recording dialog instead, as the Start Recording command does (blocked_by_dialog): "
|
||||
"its controls are named after their settings for set_widget_value, answer_dialog \"Start recording\" starts the "
|
||||
"client's when the server is turned off. With encode, the recording_stop that reports it also encodes it to an MP4 "
|
||||
"beside it, as Start Recording does, and the .mkv is deleted once the MP4 is written unless "
|
||||
"keep_raw_video_file; recording_encode makes an MP4 of any recording later. Called with no "
|
||||
"arguments, it opens the Start Recording dialog instead, as Start Recording does (blocked_by_dialog): "
|
||||
"its controls are named after their settings for widget_set_value, dialog_answer \"Start recording\" starts the "
|
||||
"person's recording, which neither the end of a replay or script nor the server turning off ends, and the dialog "
|
||||
"remembers the settings; silent: true starts one here at once with the defaults.",
|
||||
object_schema({{"target", enum_prop({"main", "canvas"}, "main (default): the main window and its dialogs; canvas: the 3D view shown.")},
|
||||
@@ -225,23 +224,28 @@ void register_record_tools(CommandCatalog& catalog)
|
||||
recorded["save_path"] = out["path"];
|
||||
ctx.set_journal_args(std::move(recorded));
|
||||
return ToolResult::ok(out);
|
||||
}),
|
||||
L("Start Recording"), L("Commands"), "recording_start", NativeCommands::start_person_recording));
|
||||
});
|
||||
start.tiles = json::array({NativeCommands::tile("start_recording", L("Start Recording"), L("Commands"), "recording_start",
|
||||
json::object(),
|
||||
"Runs recording_start with no arguments, as Start Recording does: the Start "
|
||||
"Recording dialog, whose Start recording starts the person's recording, "
|
||||
"which neither the end of a replay or script nor the server turning off ends.")});
|
||||
catalog.add(NativeCommands::with_person_form(std::move(start), [](const json&) { return NativeCommands::start_person_recording(); }));
|
||||
|
||||
// The Speed Dial's Stop Recording too: with no arguments it stops as the tile does.
|
||||
NativeCommand stop = NativeCommands::with_person_form(record_tool({}, "stop_recording", {},
|
||||
// The Speed Dial's Stop Recording is its tile: with no arguments it stops as the tile does.
|
||||
NativeCommand stop = record_tool("recording_stop", L("Stop Recording"),
|
||||
"Stop the running recording. Call it with silent: true for the report: it waits for the file and "
|
||||
"returns it with its seconds, frames captured and "
|
||||
"written, frames dropped when encoding fell behind, failed when they could not be encoded, or "
|
||||
"skipped when the window could not be captured, "
|
||||
"the size, the mean UI-thread time a capture took (capture_ms), and why it ended. A recording that ended on its own (max_seconds, the replay or script that started it ended, a "
|
||||
"write error) is reported once by the next stop_recording. For a recording started with encode, it then "
|
||||
"starts the MP4 encode and returns it under encode: a job, whose wait {for: \"job\"} returns "
|
||||
"encode_recording's result, whose raw_video_file_deleted says whether the .mkv was deleted. "
|
||||
"write error) is reported once by the next recording_stop. For a recording started with encode, it then "
|
||||
"starts the MP4 encode and returns it under encode: a job, whose app_wait {for: \"job\"} returns "
|
||||
"recording_encode's result, whose raw_video_file_deleted says whether the .mkv was deleted. "
|
||||
"Called with no arguments, it stops "
|
||||
"the recording as the Stop Recording command does, whoever started it: without waiting for its "
|
||||
"the recording as Stop Recording does, whoever started it: without waiting for its "
|
||||
"file, it shows the person a notification naming it and replies with its path; the next "
|
||||
"stop_recording with silent: true reports it as ended stopped_in_app.",
|
||||
"recording_stop with silent: true reports it as ended stopped_in_app.",
|
||||
object_schema({}), [](const json&, ToolContext& ctx) {
|
||||
AutomationRuntime& runtime = ctx.runtime();
|
||||
// The last state too, even if the timer has not ticked since the last call. Without the
|
||||
@@ -262,20 +266,26 @@ void register_record_tools(CommandCatalog& catalog)
|
||||
report["encode"] = r.is_error ? json{{"error", r.message}} : r.data;
|
||||
}
|
||||
return ToolResult::ok(report);
|
||||
}),
|
||||
// The person's stop opens nothing: like the silent one, it stops a recording behind a dialog.
|
||||
L("Stop Recording"), L("Commands"), "recording_stop", NativeCommands::stop_recording_in_app, /*person_form_behind_dialogs=*/true);
|
||||
});
|
||||
stop.tiles = json::array({NativeCommands::tile("stop_recording", L("Stop Recording"), L("Commands"), "recording_stop",
|
||||
json::object(),
|
||||
"Runs recording_stop with no arguments, as Stop Recording does: it stops the "
|
||||
"recording, whoever started it, and shows the person a notification naming its "
|
||||
"file.")});
|
||||
// The person's stop opens nothing: like the silent one, it stops a recording behind a dialog.
|
||||
stop = NativeCommands::with_person_form(std::move(stop), [](const json&) { return NativeCommands::stop_recording_in_app(); },
|
||||
/*person_form_behind_dialogs=*/true);
|
||||
// It has no other argument, and neither form asks: silent picks the form that waits and reports.
|
||||
stop.input_schema["properties"]["silent"]["description"] =
|
||||
"true waits for the file and returns the report, and the encode job when the recording has one; a call with no "
|
||||
"arguments stops as the Stop Recording command does.";
|
||||
"arguments stops as Stop Recording does.";
|
||||
catalog.add(stop);
|
||||
|
||||
NativeCommand encode = record_tool(
|
||||
"ui", "encode_recording", L("Encode a recording"),
|
||||
"recording_encode", L("Encode a recording"),
|
||||
"Encode a recording into an H.265 (or H.264) MP4 with the system ffmpeg (ORCA_FFMPEG, else ffmpeg on PATH; it "
|
||||
"needs libx265 or libx264), keeping its timing. Takes this session's last finished recording unless path names "
|
||||
"one, and writes beside it unless save_path says where. A long encode returns a job: wait for it, or cancel_job {job} "
|
||||
"one, and writes beside it unless save_path says where. A long encode returns a job: app_wait waits for it, or job_cancel {job} "
|
||||
"stops it. Once the MP4 is written, it deletes the .mkv if this session recorded it, unless keep_raw_video_file; "
|
||||
"any other .mkv is kept. raw_video_file_deleted in the reply says which.",
|
||||
object_schema({{"path", prop("string", "Absolute .mkv of a finished recording; default this session's last.")},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// run_replay and export_replay: deterministic replays of tool calls, and turning a session into one.
|
||||
// replay_run and replay_export: deterministic replays of tool calls, and turning a session into one.
|
||||
|
||||
#include "JobRegistry.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
@@ -111,7 +111,7 @@ json run_replay_job(AutomationRuntime& runtime, ToolContext& ctx, const Replay&
|
||||
void register_replay_tools(CommandCatalog& catalog)
|
||||
{
|
||||
NativeCommand run = mutate_tool(
|
||||
"core", "run_replay", L("Run a replay"),
|
||||
"replay_run", L("Run a replay"),
|
||||
std::string("Replay a list of tool calls in order and report each step: {orca_replay_version:\"") + REPLAY_VERSION +
|
||||
"\", name, vars, steps:[{tool, args, expect, "
|
||||
"optional, await, save_as, timeout_s}]}, JSON with comments. Strings may use ${replay_dir}, ${out_dir}, ${env:NAME}, "
|
||||
@@ -120,7 +120,7 @@ void register_replay_tools(CommandCatalog& catalog)
|
||||
"matchers (eq ne gt ge lt le contains regex exists empty); the first failed step or expectation stops the run unless "
|
||||
"the step is optional. Writes result.json to out_dir (default: the replay file's name with .out, beside it; for an "
|
||||
"inline replay, replay-<timestamp> in the session's output folder). Reply: passed, steps, failed_step, out_dir and "
|
||||
"result_file. auto_answer_dialogs rules a replay registers end with it. export_replay turns this session into one.",
|
||||
"result_file. dialog_auto_answer rules a replay registers end with it. replay_export turns this session into one.",
|
||||
object_schema({{"path", prop("string", "Absolute path of a replay file.")},
|
||||
{"replay", {{"type", json::array({"object", "string"})},
|
||||
{"description", "The replay itself, as an object or as its JSON text, instead of path."}}},
|
||||
@@ -171,16 +171,16 @@ void register_replay_tools(CommandCatalog& catalog)
|
||||
json result = run_replay_job(runtime, ctx, *replay, sctx, ReplayRunOptions{});
|
||||
return ToolResult::ok(std::move(result));
|
||||
});
|
||||
// Its steps call any tool, run_script included.
|
||||
// Its steps call any tool, script_run included.
|
||||
run.open_world = true;
|
||||
catalog.add(run);
|
||||
|
||||
NativeCommand exp = inspect_tool(
|
||||
"core", "export_replay", L("Export this session as a replay"),
|
||||
"Turn the calls this session made into a replay that run_replay runs: mutating calls, wait, screenshot and the "
|
||||
"recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and screenshot "
|
||||
"replay_export", L("Export this session as a replay"),
|
||||
"Turn the calls this session made into a replay that replay_run runs: mutating calls, app_wait, window_screenshot and the "
|
||||
"recording tools, in order, with refs replaced by locators, job replies replayed with await:false, and window_screenshot "
|
||||
"and recording paths moved under ${out_dir}. "
|
||||
"Calls that failed, at once or as a job later, are left out (a run_script that raised or timed out replied, so it "
|
||||
"Calls that failed, at once or as a job later, are left out (a script_run that raised or timed out replied, so it "
|
||||
"stays); so is a call whose job is still running (unless it "
|
||||
"waits on a dialog), which left_out_running lists as {tool, job}. "
|
||||
"Reply: the replay, which with path is also written there. clear:true then forgets the calls made so far.",
|
||||
@@ -191,7 +191,7 @@ void register_replay_tools(CommandCatalog& catalog)
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
AutomationRuntime& runtime = ctx.runtime();
|
||||
if (!ctx.caller_plugin().empty())
|
||||
throw ToolFailure("export_replay exports the agent's session, which a plugin's calls are not part of");
|
||||
throw ToolFailure("replay_export exports the agent's session, which a plugin's calls are not part of");
|
||||
json running;
|
||||
json replay = runtime.journal().to_replay(arg_string(args, "name", "session " + timestamp()), &running);
|
||||
json out{{"steps", replay["steps"].size()}};
|
||||
|
||||
+1673
-205
File diff suppressed because it is too large.
Load diff
@@ -68,16 +68,16 @@ using namespace std::chrono_literals;
|
||||
|
||||
namespace {
|
||||
|
||||
// The locator grammar is spelled out once, in list_widgets's description, which hands out the refs.
|
||||
// The locator grammar is spelled out once, in widget_list's description, which hands out the refs.
|
||||
const json kTargetSchema = {{"type", json::array({"string", "object"})},
|
||||
{"description", "A ref list_widgets gave (\"w12\"), which later listings leave good (one refused as stale or "
|
||||
{"description", "A ref widget_list gave (\"w12\"), which later listings leave good (one refused as stale or "
|
||||
"unknown needs a new listing), or a locator, such as {label: \"OK\", within: "
|
||||
"\"Preferences\"} or {menu: \"File>Export>Export G-code\"}; list_widgets's description "
|
||||
"\"Preferences\"} or {menu: \"File>Export>Export G-code\"}; widget_list's description "
|
||||
"lists every kind."}};
|
||||
|
||||
// run_javascript's target: a web view or an element of its page, not a widget.
|
||||
// webview_run_javascript's target: a web view or an element of its page, not a widget.
|
||||
const json kPageTargetSchema = {{"type", json::array({"string", "object"})},
|
||||
{"description", "A web view (its ref; list_widgets lists it as kind webview) or an element of its "
|
||||
{"description", "A web view (its ref; widget_list lists it as kind webview) or an element of its "
|
||||
"page (its ref or a {web} / {css} locator), which the code gets as `el`. Default: "
|
||||
"the topmost dialog's web view, else the only one shown."}};
|
||||
|
||||
@@ -88,7 +88,7 @@ const json kPageTimeoutSchema = {{"type", "integer"},
|
||||
|
||||
const json kModifiersSchema = {{"type", "array"},
|
||||
{"items", {{"type", "string"}, {"enum", {"ctrl", "cmd", "rawctrl", "shift", "alt"}}}},
|
||||
{"description", "Modifier keys held during the input, as in press_keys: ctrl and cmd are both Command on macOS "
|
||||
{"description", "Modifier keys held during the input, as in keyboard_press: ctrl and cmd are both Command on macOS "
|
||||
"and Ctrl elsewhere; rawctrl is the macOS Control key."}};
|
||||
|
||||
bool in_top_dialog(AutomationRuntime& runtime, wxWindow* window)
|
||||
@@ -123,11 +123,9 @@ void journal_with_locator(ToolContext& ctx, const json& args, const json& locato
|
||||
ctx.set_journal_args(std::move(recorded));
|
||||
}
|
||||
|
||||
NativeCommand recover_input_tool(std::string group, std::string name, std::string title, std::string description, json schema,
|
||||
CommandFn handler)
|
||||
NativeCommand recover_input_tool(std::string name, std::string title, std::string description, json schema, CommandFn handler)
|
||||
{
|
||||
NativeCommand d = mutate_tool(std::move(group), std::move(name), std::move(title), std::move(description), std::move(schema),
|
||||
std::move(handler));
|
||||
NativeCommand d = mutate_tool(std::move(name), std::move(title), std::move(description), std::move(schema), std::move(handler));
|
||||
d.guard = GuardClass::Recover;
|
||||
return d;
|
||||
}
|
||||
@@ -237,12 +235,12 @@ wxWebView* default_webview(AutomationRuntime& runtime)
|
||||
}
|
||||
}
|
||||
if (webs.empty())
|
||||
throw ToolFailure("No web view is shown (the Home tab has one: set_view tab=home)");
|
||||
throw ToolFailure("No web view is shown (the Home tab has one: view_set tab=home)");
|
||||
if (webs.size() > 1) {
|
||||
json urls = json::array();
|
||||
for (wxWebView* w : webs)
|
||||
urls.push_back(redact_url(into_u8(w->GetCurrentURL())));
|
||||
throw ToolFailure("Several web views are shown" + where + "; pass target (list_widgets query=webview)", {{"web_views", urls}});
|
||||
throw ToolFailure("Several web views are shown" + where + "; pass target (widget_list query=webview)", {{"web_views", urls}});
|
||||
}
|
||||
return webs.front();
|
||||
}
|
||||
@@ -266,7 +264,7 @@ void guard_page(AutomationRuntime& runtime, ToolContext& ctx, wxWebView* web)
|
||||
// The input tools reach a page element through its page's agent (WebPages.hpp): resolve it, guard
|
||||
// its web view as any widget's window, ask the page to act, and observe what followed.
|
||||
|
||||
// A "d" ref from list_widgets, also written {ref: "d12"}, or a {css}/{web} locator.
|
||||
// A "d" ref from widget_list, also written {ref: "d12"}, or a {css}/{web} locator.
|
||||
bool is_web_target(const json& target)
|
||||
{
|
||||
const json& ref = target.is_object() && target.size() == 1 && target.contains("ref") ? target["ref"] : target;
|
||||
@@ -295,13 +293,13 @@ WebHandle web_view_target(AutomationRuntime& runtime, ToolContext& ctx, const js
|
||||
return out;
|
||||
}
|
||||
|
||||
// click and set_widget_value on a web view: the page's elements are the targets.
|
||||
// widget_click and widget_set_value on a web view: the page's elements are the targets.
|
||||
void refuse_web_view(AutomationRuntime& runtime, ToolContext& ctx, const json& target)
|
||||
{
|
||||
std::string within;
|
||||
if (web_view_target(runtime, ctx, target, within) != 0)
|
||||
throw ToolFailure("That is a web view, whose page wx events don't reach; target one of its page elements: a d ref from "
|
||||
"list_widgets, or a {web} / {css} locator");
|
||||
"widget_list, or a {web} / {css} locator");
|
||||
}
|
||||
|
||||
// A page element an input tool acts on.
|
||||
@@ -441,7 +439,7 @@ void check_page_reply(const PageReply& r, std::chrono::seconds timeout, bool act
|
||||
throw ToolFailure("Cancelled: OrcaSlicer is closing or the replay or script was stopped");
|
||||
throw ToolFailure("The page did not answer within " + std::to_string(timeout.count()) + " s" +
|
||||
(acting ? ", so the outcome is unknown: the action may have run, or may still run once the page is free. Call "
|
||||
"list_widgets before trying again (timeout_s waits longer)" :
|
||||
"widget_list before trying again (timeout_s waits longer)" :
|
||||
"; it may be busy"));
|
||||
}
|
||||
if (r.value.contains("error")) {
|
||||
@@ -453,7 +451,7 @@ void check_page_reply(const PageReply& r, std::chrono::seconds timeout, bool act
|
||||
}
|
||||
|
||||
// The pages a locator looks in: the shown ones within `within`, in snapshot order. Without `within`
|
||||
// while the topmost modal dialog shows a page, only that dialog's pages, the ones list_widgets reads
|
||||
// while the topmost modal dialog shows a page, only that dialog's pages, the ones widget_list reads
|
||||
// and the only ones input can reach, so a page behind it never makes a label ambiguous.
|
||||
std::vector<wxWebView*> locator_pages(AutomationRuntime& runtime, const std::string& within)
|
||||
{
|
||||
@@ -480,7 +478,7 @@ WebTarget resolve_web(AutomationRuntime& runtime, ToolContext& ctx, const json&
|
||||
throw ToolFailure("The ref is not a page element");
|
||||
auto* web = dynamic_cast<wxWebView*>(t.window.get());
|
||||
if (web == nullptr)
|
||||
throw ToolFailure("The page's web view is gone; call list_widgets again");
|
||||
throw ToolFailure("The page's web view is gone; call widget_list again");
|
||||
out.web = web_handle(web);
|
||||
out.key = t.web_key;
|
||||
out.doc = t.web_doc;
|
||||
@@ -584,10 +582,10 @@ WebTarget resolve_web(AutomationRuntime& runtime, ToolContext& ctx, const json&
|
||||
throw ToolFailure("No page element matches " + target.dump() + " in what answered" +
|
||||
(unknown.empty() ? "" : "; " + unknown + " did not answer or failed the search") +
|
||||
(failed == 0 ? "" : "; " + count(failed, "page", "pages") + " could not run the page agent") +
|
||||
"; nothing was done. " + (unknown.empty() ? "Call list_widgets" : "Try again once they answer"),
|
||||
"; nothing was done. " + (unknown.empty() ? "Call widget_list" : "Try again once they answer"),
|
||||
{{"unread_pages", unread}});
|
||||
if (matches.empty())
|
||||
throw ToolFailure("No page element matches " + target.dump() + "; call list_widgets");
|
||||
throw ToolFailure("No page element matches " + target.dump() + "; call widget_list");
|
||||
if (matches.size() > 1 && index < 0) {
|
||||
json listed = json::array();
|
||||
for (const Match& m : matches)
|
||||
@@ -633,7 +631,7 @@ json web_locator(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget&
|
||||
return loc;
|
||||
}
|
||||
|
||||
// Why answer_dialog does not press a button refused_press() refuses.
|
||||
// Why dialog_answer does not press a button refused_press() refuses.
|
||||
std::string refused_button(const std::string& button, DialogPress refused)
|
||||
{
|
||||
if (refused == DialogPress::Hidden)
|
||||
@@ -676,7 +674,7 @@ std::string watch_id()
|
||||
// document behind the page (a reload, or a form posted to the same URL). Not IsBusy(), which WebView2
|
||||
// also reports while a page only works. Failing those, for an action the page outlined itself before
|
||||
// (before.watch), `page`: whether what the page lists changed by then (changed), the lines it lists
|
||||
// that it did not (added) and those it no longer does (removed), as list_widgets writes them, partial
|
||||
// that it did not (added) and those it no longer does (removed), as widget_list writes them, partial
|
||||
// when a configuration frame could not be compared (then changed only when a line was found), and how
|
||||
// many messages the page itself sent OrcaSlicer during the action (posted). A change after that is the
|
||||
// next snapshot's to show.
|
||||
@@ -789,7 +787,7 @@ WebActed web_act(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget&
|
||||
throw ToolFailure("The MCP server was turned off before this gesture ran; it was not performed");
|
||||
wxWebView* web = web_view_of(t.web);
|
||||
if (web == nullptr || !web->IsShownOnScreen())
|
||||
throw ToolFailure("The page's web view is gone or hidden; call list_widgets again");
|
||||
throw ToolFailure("The page's web view is gone or hidden; call widget_list again");
|
||||
guard_page(runtime, ctx, web);
|
||||
if (in_top_dialog(runtime, web))
|
||||
before.modal = runtime.modals().serial(runtime.modals().top());
|
||||
@@ -835,7 +833,7 @@ WebActed web_act(AutomationRuntime& runtime, ToolContext& ctx, const WebTarget&
|
||||
return out;
|
||||
}
|
||||
|
||||
// The DOM modifier flags of a click or gesture's `modifiers`, named as press_keys chords name them: ctrl
|
||||
// The DOM modifier flags of a widget_click's or mouse_gesture's `modifiers`, named as keyboard_press chords name them: ctrl
|
||||
// and cmd are Command on macOS and Ctrl elsewhere, rawctrl the macOS Control key.
|
||||
json web_modifiers(const json& args)
|
||||
{
|
||||
@@ -869,7 +867,7 @@ PressAgent agent_of(const WebTarget& t) { return press_agent(t.web, t.doc, t.key
|
||||
|
||||
// Ends every press mouse_gesture downs left on pages but `keep`'s, each released where it was pressed,
|
||||
// all asked at once so an agent that doesn't answer holds up none of the others. Every gesture,
|
||||
// click and answer_dialog does this first, even one the tool then refuses, except that a move or an
|
||||
// widget_click and dialog_answer does this first, even one the tool then refuses, except that a move or an
|
||||
// up keeps the press of the agent it is on, which it belongs to; keys and input leave the presses, as
|
||||
// a person can type while holding the mouse. One whose agent did not take the release (busy,
|
||||
// failing) stays on record, so the next gesture asks again; a release taken late is past its
|
||||
@@ -913,7 +911,7 @@ void end_web_press(AutomationRuntime& runtime, ToolContext& ctx, const std::opti
|
||||
ToolResult web_click(AutomationRuntime& runtime, ToolContext& ctx, const json& args)
|
||||
{
|
||||
if (args.contains("popup_item"))
|
||||
throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call list_widgets after "
|
||||
throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call widget_list after "
|
||||
"the click");
|
||||
const auto timeout = web_timeout(args);
|
||||
WebTarget t = resolve_web(runtime, ctx, args["target"], timeout);
|
||||
@@ -954,7 +952,7 @@ ToolResult web_input(AutomationRuntime& runtime, ToolContext& ctx, const json& a
|
||||
ToolResult web_keys(AutomationRuntime& runtime, ToolContext& ctx, const json& args, WebTarget t)
|
||||
{
|
||||
if (args.contains("popup_item"))
|
||||
throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call list_widgets after "
|
||||
throw ToolFailure("popup_item is for the menus OrcaSlicer opens; a page's own menu is part of the page, so call widget_list after "
|
||||
"the keys");
|
||||
const std::string keys = arg_string(args, "keys"), text = arg_string(args, "text");
|
||||
json a{{"text", text}};
|
||||
@@ -1061,7 +1059,7 @@ wxWebView* key_page(AutomationRuntime& runtime)
|
||||
return webs.size() == 1 && !own_widget ? webs.front() : nullptr;
|
||||
}
|
||||
|
||||
// The window set_window's target names: the main window, the topmost modal dialog, or the window a ref or
|
||||
// The window window_set's target names: the main window, the topmost modal dialog, or the window a ref or
|
||||
// locator is in. Refuses one no tool may size or move. `locator` gets what the journal records for a
|
||||
// ref. UI thread.
|
||||
wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target, json& locator)
|
||||
@@ -1080,30 +1078,30 @@ wxTopLevelWindow& window_target(AutomationRuntime& runtime, const json& target,
|
||||
try {
|
||||
t = runtime.inspector().resolve(target);
|
||||
} catch (const ToolFailure& e) {
|
||||
// A window's ref goes stale once the window is destroyed, and list_windows gives the open ones'.
|
||||
// A window's ref goes stale once the window is destroyed, and window_list gives the open ones'.
|
||||
if (!target.is_string())
|
||||
throw;
|
||||
throw ToolFailure(std::string(e.what()) + ", or list_windows for the open windows", e.details);
|
||||
throw ToolFailure(std::string(e.what()) + ", or window_list for the open windows", e.details);
|
||||
}
|
||||
locator = runtime.inspector().locator_for(t);
|
||||
window = t.window.get() != nullptr ? wxGetTopLevelParent(t.window.get()) : nullptr;
|
||||
}
|
||||
if (dynamic_cast<wxPopupWindow*>(window) != nullptr)
|
||||
throw ToolFailure("The target is in a popup, which the window it opened from places; give that window (list_windows)");
|
||||
throw ToolFailure("The target is in a popup, which the window it opened from places; give that window (window_list)");
|
||||
auto* tlw = dynamic_cast<wxTopLevelWindow*>(window);
|
||||
if (tlw == nullptr)
|
||||
throw ToolFailure("The target is in no window");
|
||||
if (tlw->GetName() == kHiddenFromAutomation)
|
||||
throw ToolFailure("The window is the person's own, which no tool reaches");
|
||||
if (auto* dlg = dynamic_cast<wxDialog*>(tlw); dlg != nullptr && is_native_dialog(dlg))
|
||||
throw ToolFailure("A native dialog is placed by the system; answer it with answer_dialog");
|
||||
throw ToolFailure("A native dialog is placed by the system; answer it with dialog_answer");
|
||||
// A closed dialog may be hidden rather than destroyed, so its ref still resolves.
|
||||
if (!tlw->IsShown())
|
||||
throw ToolFailure("The window is closed; list_windows lists the open windows");
|
||||
throw ToolFailure("The window is closed; window_list lists the open windows");
|
||||
return *tlw;
|
||||
}
|
||||
|
||||
// `window` while it is still one of the app's top-level windows, else null: set_window keeps a plain
|
||||
// `window` while it is still one of the app's top-level windows, else null: window_set keeps a plain
|
||||
// pointer across its UI closures and checks it before following it. UI thread.
|
||||
wxTopLevelWindow* live_window(wxTopLevelWindow* window)
|
||||
{
|
||||
@@ -1113,7 +1111,7 @@ wxTopLevelWindow* live_window(wxTopLevelWindow* window)
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// set_window: checks the request and applies it in one UI closure, waits for the window to take it,
|
||||
// window_set: checks the request and applies it in one UI closure, waits for the window to take it,
|
||||
// then replies with what the window became. A size or position applies to the normal window, so a
|
||||
// maximized or minimized one is restored first. Where the window system restores it later (GTK), the call
|
||||
// waits for that before sizing, as a size given meanwhile is lost: on Wayland the compositor's answer to
|
||||
@@ -1234,7 +1232,7 @@ ToolResult set_window(AutomationRuntime& runtime, ToolContext& ctx, const json&
|
||||
wxTopLevelWindow* w = live_window(window);
|
||||
if (w == nullptr)
|
||||
throw ToolFailure(closed);
|
||||
// list_windows's own entry, so the two report a window alike.
|
||||
// window_list's own entry, so the two report a window alike.
|
||||
const json entry = runtime.inspector().window_entry(*w, modal);
|
||||
json reply{{"title", entry["title"]}, {"kind", entry["kind"]}, {"ref", entry["ref"]}, {"size", {entry["width"], entry["height"]}}};
|
||||
if (entry.contains("x"))
|
||||
@@ -1301,7 +1299,7 @@ std::string window_request_refusal(const json& args, const WindowAbilities& wind
|
||||
{
|
||||
const bool size = args.contains("size"), position = args.contains("position");
|
||||
if (!size && !position && !args.contains("state") && !args.contains("raise"))
|
||||
return "Give at least one of size, position, state or raise; list_windows reads a window's geometry without changing it";
|
||||
return "Give at least one of size, position, state or raise; window_list reads a window's geometry without changing it";
|
||||
// Two whole numbers that fit wx's int coordinates, both positive for a size. Whole floats pass, as
|
||||
// they pass the schema's integer type.
|
||||
const auto is_pair = [](const json& value, bool positive) {
|
||||
@@ -1343,15 +1341,15 @@ json display_area(unsigned index)
|
||||
void register_ui_tools(CommandCatalog& catalog)
|
||||
{
|
||||
catalog.add(inspect_tool(
|
||||
"ui", "list_windows", L("List the windows"),
|
||||
"window_list", L("List the windows"),
|
||||
"List OrcaSlicer's open windows: the main window, then the windows that don't block the app (Plugins, an "
|
||||
"object's settings, a dock panel floating on its own), then the modal dialogs in the order they opened, the "
|
||||
"topmost last. A window's ref goes to screenshot as target to capture that window, to list_widgets as target to "
|
||||
"list it alone, and to press_keys as target; its title is the within of locators for its widgets.\n"
|
||||
"topmost last. A window's ref goes to window_screenshot as target to capture that window, to widget_list as target to "
|
||||
"list it alone, and to keyboard_press as target; its title is the within of locators for its widgets.\n"
|
||||
"Reply: each window's title, kind (main, window, dialog, or panel: a dock panel floating on its own), modal, "
|
||||
"ref, web (it shows a web page), x and y on screen (not on Wayland, which doesn't say), width and height, state "
|
||||
"(normal, maximized or minimized) and resizable (it has a resize border); set_window changes them.\n"
|
||||
"A native dialog (a message box, a file picker) has native: true and no ref: answer_dialog answers it. hidden: "
|
||||
"(normal, maximized or minimized) and resizable (it has a resize border); window_set changes them.\n"
|
||||
"A native dialog (a message box, a file picker) has native: true and no ref: dialog_answer answers it. hidden: "
|
||||
"true marks the person's own windows (Action Replay, the Run Script panel and their prompts, the Python scripts "
|
||||
"setting), which no tool reaches and screenshots leave out.",
|
||||
object_schema({{"limit", {{"type", "integer"}, {"minimum", 1}, {"maximum", 200}, {"description", "Default 100."}}},
|
||||
@@ -1363,11 +1361,11 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
|
||||
{
|
||||
NativeCommand def = recover_input_tool(
|
||||
"ui", "set_window", L("Size, move or raise a window"),
|
||||
"window_set", L("Size, move or raise a window"),
|
||||
"Size, move, maximize, minimize or raise a window: the main window (default), the topmost modal dialog, or one "
|
||||
"list_windows lists, also while a modal dialog is open. Size the main window before set_view fits the camera and "
|
||||
"before start_recording, as a recording keeps its first frame's size. size and position are in the units "
|
||||
"list_windows reports, whose x/y and width/height are read as position and size too. A size or position restores "
|
||||
"window_list lists, also while a modal dialog is open. Size the main window before view_set fits the camera and "
|
||||
"before recording_start, as a recording keeps its first frame's size. size and position are in the units "
|
||||
"window_list reports, whose x/y and width/height are read as position and size too. A size or position restores "
|
||||
"a maximized or minimized window first. A window takes only the states its title bar offers; a modal dialog "
|
||||
"never minimizes. A refused call changes nothing. Replies once the window holds still and the 3D view has drawn "
|
||||
"at its new size (3 s at most): title, kind, ref, size, position, state, resizable, scale (screenshot pixels per "
|
||||
@@ -1375,7 +1373,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
"changed.",
|
||||
object_schema({{"target", {{"type", json::array({"string", "object"})},
|
||||
{"description", "main (default), dialog (the topmost modal "
|
||||
"dialog), or a window's ref or locator from list_windows; a widget's ref or "
|
||||
"dialog), or a window's ref or locator from window_list; a widget's ref or "
|
||||
"locator picks the window it is in."}}},
|
||||
{"size", array_prop({{"type", "integer"}}, "[width, height], held to the window's minimum and maximum size.")},
|
||||
{"position", array_prop({{"type", "integer"}}, "[x, y] of the window's top-left corner on screen; not on Wayland.")},
|
||||
@@ -1391,15 +1389,15 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
|
||||
{
|
||||
NativeCommand def = inspect_tool(
|
||||
"ui", "list_widgets", L("List the widgets"),
|
||||
"Describe what is on screen as an indented tree, one element per line with a ref to pass to click, set_widget_value, "
|
||||
"press_keys and run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the rows of lists, "
|
||||
"widget_list", L("List the widgets"),
|
||||
"Describe what is on screen as an indented tree, one element per line with a ref to pass to widget_click, widget_set_value, "
|
||||
"keyboard_press and webview_run_javascript (a page element's to mouse_gesture too): the widgets of every shown window, the rows of lists, "
|
||||
"trees and tables, each shown popup after the window it opened from, the main menus, the 3D canvas's toolbar "
|
||||
"items and gizmos, each ImGui panel drawn in the last frame with its items and text, and the elements of each "
|
||||
"shown web page (dialogs, the setup wizard, sign-in, plugin windows) under its web view. With a modal dialog "
|
||||
"open, only the topmost dialog's pages are read. Refs go stale when their element goes away: call list_widgets "
|
||||
"again then. Prefer run_action and the typed tools when one fits.\n"
|
||||
"A locator names an element without a ref, in any session (export_replay records them); index (0-based) picks "
|
||||
"open, only the topmost dialog's pages are read. Refs go stale when their element goes away: call widget_list "
|
||||
"again then. Prefer action_run and the typed tools when one fits.\n"
|
||||
"A locator names an element without a ref, in any session (replay_export records them); index (0-based) picks "
|
||||
"one of several matches:\n"
|
||||
"- a widget: {label, class, name, within, index}, within being its window's title; a notebook page: {tab: "
|
||||
"\"General\", within}\n"
|
||||
@@ -1411,11 +1409,11 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
"- a plate or one of its icons in the Prepare view: {plate_icon: \"lock\", plate: 0}, the icon being plate, "
|
||||
"delete, orient, arrange, lock, settings, name, move_to_front, filament_map or imex_mode\n"
|
||||
"- a web page's element: {web: \"Next\", kind?: \"button\", css?: \"#AcceptBtn\", within?, index?}, by the label "
|
||||
"list_widgets lists (exactly, else ignoring case, else a part of it), its kind, a CSS selector (the id a line "
|
||||
"widget_list lists (exactly, else ignoring case, else a part of it), its kind, a CSS selector (the id a line "
|
||||
"shows as name: name=#save is {css: \"#save\"}), or together. Without within it looks in the topmost dialog's "
|
||||
"pages while one is open, else in every shown page, and an action on it waits for its element up to 2 s short of "
|
||||
"the action's timeout_s (8 s by default), but at least 3 s or the whole of a shorter timeout_s.",
|
||||
object_schema({{"target", prop("string", "all (default), main, dialog (the topmost modal), popup, or a window's ref (list_windows).")},
|
||||
object_schema({{"target", prop("string", "all (default), main, dialog (the topmost modal), popup, or a window's ref (window_list).")},
|
||||
{"query", prop("string", "Case-insensitive text to look for in labels, values, names and classes.")},
|
||||
{"max_nodes", {{"type", "integer"}, {"minimum", 1}, {"maximum", 5000}, {"description", "Default 400."}}},
|
||||
{"include_imgui", prop("boolean", "List ImGui items (default true).")},
|
||||
@@ -1481,7 +1479,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}
|
||||
|
||||
catalog.add(recover_input_tool(
|
||||
"ui", "click", L("Click an element"),
|
||||
"widget_click", L("Click an element"),
|
||||
"Click a GUI element as a person would. Menu items, buttons, checkboxes, toggles, radio buttons, toolbar items and "
|
||||
"gizmos are activated the way their owners expect: a gizmo opens and a second click closes it (Text on an object "
|
||||
"without text creates a text part: created). Other widgets and ImGui items get a mouse click once scrolled into "
|
||||
@@ -1500,7 +1498,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
"refused when something else covers that point. The reply reads back checked, and has closed when the click closed "
|
||||
"its dialog (with dialogs, those still open under it, which still need an answer), navigated (with url) when it "
|
||||
"changed the page, or dialogs when it opened another. Otherwise page says what changed on the page within 300 ms: "
|
||||
"changed (false when its lines are as before), the list_widgets lines added and removed, partial when a plugin "
|
||||
"changed (false when its lines are as before), the widget_list lines added and removed, partial when a plugin "
|
||||
"configuration frame could not be compared, and posted, how many messages the page sent OrcaSlicer.",
|
||||
object_schema({{"target", kTargetSchema},
|
||||
{"button", enum_prop({"left", "right", "middle"}, "Default left.")},
|
||||
@@ -1592,7 +1590,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}));
|
||||
|
||||
catalog.add(recover_input_tool(
|
||||
"ui", "set_widget_value", L("Set a widget's value"),
|
||||
"widget_set_value", L("Set a widget's value"),
|
||||
"Set a widget's value and send the events a person's edit would. Widgets: text fields (submit, the default, also "
|
||||
"presses Enter and leaves the field, which is when Orca's setting fields commit), spin controls, sliders, choice, "
|
||||
"combo and list boxes (by option text or index), checkboxes, toggles and a row's checkbox (true or false), and a "
|
||||
@@ -1603,9 +1601,9 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
"beside it, multiline text with \\n), a combo's option is picked by its text or 0-based index, and a checkbox, radio "
|
||||
"or toggle is clicked when it differs. A web page's fields, as typing would leave them: text, number, range, colour "
|
||||
"and date fields and editable text get the value with input and change events (submit then leaves the field; "
|
||||
"press_keys Return presses Enter), a select its option by text, value or index, and a checkbox or radio is clicked when "
|
||||
"it differs; the value is read back and page says what changed, as for click. File fields can't be set. For "
|
||||
"settings, set_settings is more reliable.",
|
||||
"keyboard_press Return presses Enter), a select its option by text, value or index, and a checkbox or radio is clicked when "
|
||||
"it differs; the value is read back and page says what changed, as for widget_click. File fields can't be set. For "
|
||||
"settings, settings_set is more reliable.",
|
||||
object_schema({{"target", kTargetSchema},
|
||||
{"value", {{"type", json::array({"string", "number", "boolean"})}, {"description", "The new value."}}},
|
||||
{"submit", prop("boolean", "Press Enter / commit after setting (default true).")},
|
||||
@@ -1629,15 +1627,15 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}));
|
||||
|
||||
catalog.add(recover_input_tool(
|
||||
"ui", "press_keys", L("Press keys"),
|
||||
"keyboard_press", L("Press keys"),
|
||||
"Send a key chord (\"Ctrl+S\", \"Escape\", \"Return\", \"Delete\", \"Shift+Tab\", \"Left\", \"F5\") and/or type text to "
|
||||
"a target or, without one, to the focused window (the topmost dialog while one is open, the shown 3D view when "
|
||||
"nothing has focus). As with a real key press, the shortcut handling of the target's panels and window sees the keys "
|
||||
"first. Typing reaches ImGui fields and key handlers; fill a widget's text field with set_widget_value. A menu the keys open "
|
||||
"first. Typing reaches ImGui fields and key handlers; fill a widget's text field with widget_set_value. A menu the keys open "
|
||||
"is listed as popup_menu, or popup_item runs one of its items. Keys for a web page (its element, or without a "
|
||||
"target the focused web view or the topmost dialog's only page) go to the page's focused element with the "
|
||||
"browser's default actions: typing, Backspace/Delete, Enter (submits a form, activates a button), Space, Tab moving "
|
||||
"the focus, arrows stepping a select, range or radio group; page says what they changed, as for click.",
|
||||
"the focus, arrows stepping a select, range or radio group; page says what they changed, as for widget_click.",
|
||||
object_schema({{"target", kTargetSchema},
|
||||
{"keys", prop("string", "One chord: a key, after any modifiers joined by +. Keys: one character, Enter, Esc, "
|
||||
"Tab, Space, Backspace, Delete, Insert, Home, End, PageUp, PageDown, Left, Right, "
|
||||
@@ -1710,22 +1708,22 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
mouse_canvases.insert(mouse_canvases.end() - 1, "design");
|
||||
#endif
|
||||
catalog.add(recover_input_tool(
|
||||
"ui", "mouse_gesture", L("Mouse gesture on a 3D view or page element"),
|
||||
"mouse_gesture", L("Mouse gesture on a 3D view or page element"),
|
||||
"Make a mouse gesture on a 3D canvas as a person would: move, down, up, click, drag or wheel. It starts at `at`, a "
|
||||
"point of the model, which is projected through the camera and by default checked to land on that part (check "
|
||||
"\"point\" only projects it), or at x/y, logical pixels from the canvas's top left. A drag goes through `waypoints` to "
|
||||
"`to`, `steps` moves per leg: on an object it moves the object, in a painting gizmo it paints from a press on the "
|
||||
"object being painted (waypoints zigzagging over an area paint all of it), and elsewhere it turns or pans the camera "
|
||||
"as this install's mouse settings say, so turn the camera with set_view camera or orbit instead. A wheel turns delta "
|
||||
"as this install's mouse settings say, so turn the camera with view_set camera or orbit instead. A wheel turns delta "
|
||||
"notches; positive zooms in (out with the Reverse mouse zoom preference on) or scrolls a panel up. Modifiers are "
|
||||
"held as keys for the gesture (shift picks points in Measure and erases in a painting gizmo). A down keeps its button and modifiers held, so moves drag, until an up or another "
|
||||
"gesture. Grabbers are set through the gizmo's panel fields or transform, not dragged. A menu a right click opens "
|
||||
"gesture. Grabbers are set through the gizmo's panel fields or object_transform, not dragged. A menu a right click opens "
|
||||
"is listed as popup_menu, or popup_item (with click or up) runs one of its items. The reply's camera_moved says the "
|
||||
"gesture moved the camera, so earlier screenshots and pixels no longer match the view.\n"
|
||||
"With target, the gesture is on a web page's element instead (a canvas such as the colour picker's spectrum, a "
|
||||
"slider, a sortable or scrolled list): x/y, to and waypoints are logical pixels from its top left, a drag keeps the "
|
||||
"pointer captured where the page asks for it, and a wheel scrolls what is under the pointer unless the page takes "
|
||||
"it; page says what the gesture changed there, as for click.",
|
||||
"it; page says what the gesture changed there, as for widget_click.",
|
||||
object_schema({{"action", enum_prop({"move", "down", "up", "click", "drag", "wheel"}, "Default click.")},
|
||||
{"canvas", enum_prop(mouse_canvases, "Default current, the view shown. design takes x/y only.")},
|
||||
{"at", target_schema},
|
||||
@@ -1768,8 +1766,8 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
const std::string name = arg_string(args, "canvas", "current");
|
||||
GLCanvas3D* canvas = name == "current" ? shown_canvas() : canvas_by_name(name);
|
||||
if (canvas == nullptr || !canvas->get_wxglcanvas()->IsShownOnScreen())
|
||||
throw ToolFailure(name == "design" ? "The Design view is not shown; set_view {\"tab\": \"design\"} first" :
|
||||
"That 3D view is not shown; switch to it with set_view first");
|
||||
throw ToolFailure(name == "design" ? "The Design view is not shown; view_set {\"tab\": \"design\"} first" :
|
||||
"That 3D view is not shown; switch to it with view_set first");
|
||||
// The Design view sets up its GL at its first frame, as DesignCanvas guards its own renders.
|
||||
if (canvas == design_canvas() && !canvas->is_initialized())
|
||||
throw ToolFailure("The Design view has not drawn yet");
|
||||
@@ -1795,12 +1793,12 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}));
|
||||
|
||||
catalog.add(mutate_tool(
|
||||
"ui", "pick_gizmo_file", L("Load or save the open gizmo's SVG or texture file"),
|
||||
"gizmo_pick_file", L("Load or save the open gizmo's SVG or texture file"),
|
||||
"Do what a file picker inside the open gizmo does, with a path instead of its dialog: svg_change loads another SVG "
|
||||
"file into the SVG part being edited, svg_save_as writes that part's SVG to a new file (an existing one only with "
|
||||
"overwrite), texture_import imports a height-map image into the texture library and puts it on Texture "
|
||||
"Displacement's active layer. To add an SVG part, use run_action add_primitive_svg with a path. Gizmos open with "
|
||||
"click {target: {gizmo: name}}, and their panels take set_widget_value / click on the ImGui items list_widgets lists.",
|
||||
"Displacement's active layer. To add an SVG part, use object_add_svg with a path. Gizmos open with "
|
||||
"widget_click {target: {gizmo: name}}, and their panels take widget_set_value / widget_click on the ImGui items widget_list lists.",
|
||||
object_schema({{"action", enum_prop({"svg_change", "svg_save_as", "texture_import"}, "What to do.")},
|
||||
{"path", prop("string", "Absolute path of the file to read or write.")},
|
||||
{"overwrite", prop("boolean", "svg_save_as: replace an existing file.")}},
|
||||
@@ -1842,21 +1840,21 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}));
|
||||
|
||||
catalog.add(recover_input_tool(
|
||||
"core", "answer_dialog", L("Answer a dialog"),
|
||||
"dialog_answer", L("Answer a dialog"),
|
||||
"Press a button of the topmost modal dialog: yes, no, ok, cancel, close, apply, a button's label, or a numeric id. "
|
||||
"A disabled button (enabled: false) is refused, the dialog's message showing what it still needs, and so is one on "
|
||||
"a page the dialog does not show, except a hidden cancel or close, which ends the dialog. On a dialog that is "
|
||||
"neither native nor a web dialog, a standard name or id it has no button for ends it with that answer too, "
|
||||
"without a handler running (pressed: false). The label of an option of a "
|
||||
"selector made of buttons (Orca's radio groups, tab bars and multi-switches, shown as (*) / ( ) in the message) "
|
||||
"selects that option and leaves the dialog open; set other radio buttons and switches with click or set_widget_value "
|
||||
"true, and notebook tabs with click. "
|
||||
"selects that option and leaves the dialog open; set other radio buttons and switches with widget_click or widget_set_value "
|
||||
"true, and notebook tabs with widget_click. "
|
||||
"dialog.title, text the dialog's title contains, makes sure which dialog that is; it must be the topmost. Reply: "
|
||||
"dialog, button, pressed, and id, the wx id pressed or ended with, or web: true for a button on a web dialog's "
|
||||
"page, with what the page did as click reports it; closed: true when it closed, and dialogs, those still open. A "
|
||||
"page, with what the page did as widget_click reports it; closed: true when it closed, and dialogs, those still open. A "
|
||||
"native message box (native: true) is pressed through "
|
||||
"the OS, by one of the buttons get_app_state.dialogs lists for it; a file or folder picker can't be answered here, nor "
|
||||
"any native dialog on macOS (its buttons list is empty): register auto_answer_dialogs before opening them. A web "
|
||||
"the OS, by one of the buttons app_state.dialogs lists for it; a file or folder picker can't be answered here, nor "
|
||||
"any native dialog on macOS (its buttons list is empty): register dialog_auto_answer before opening them. A web "
|
||||
"dialog's buttons are on its page: a label is pressed there, waiting up to 3 s for it to show, so the page's own "
|
||||
"handler runs. With no such page button, or a page busy for those 3 s, cancel and close end the dialog, and ok, yes, "
|
||||
"no and apply are refused rather than skip the page's commit; page_buttons then lists the page's buttons.",
|
||||
@@ -1894,7 +1892,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}
|
||||
if (is_native_dialog(dialog) && message_box_buttons(dialog).empty())
|
||||
throw ToolFailure("This native dialog (a file or folder picker, or a message box on macOS) can't be pressed; "
|
||||
"register auto_answer_dialogs before the action that opens it",
|
||||
"register dialog_auto_answer before the action that opens it",
|
||||
{{"dialog", describe_dialog(dialog)}});
|
||||
return dialog;
|
||||
};
|
||||
@@ -1925,7 +1923,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
throw ToolFailure(refused_button(button, *refused), {{"dialog", describe_dialog(dialog)}});
|
||||
const DialogPress press = press_dialog_button(dialog, id);
|
||||
if (press == DialogPress::Failed)
|
||||
throw ToolFailure("The message box is not shown, so its button could not be pressed; call list_widgets again",
|
||||
throw ToolFailure("The message box is not shown, so its button could not be pressed; call widget_list again",
|
||||
{{"dialog", describe_dialog(dialog)}});
|
||||
return {{"dialog", dialog_title}, {"button", button}, {"id", id}, {"pressed", press == DialogPress::Pressed}};
|
||||
});
|
||||
@@ -1959,7 +1957,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
wxDialog* dialog = find_dialog();
|
||||
wxWebView* web = web_view_of(page.web);
|
||||
if (dialog != web_dialog || web == nullptr)
|
||||
throw ToolFailure("The dialog changed while its page was being asked; call list_widgets again");
|
||||
throw ToolFailure("The dialog changed while its page was being asked; call widget_list again");
|
||||
before.modal = runtime.modals().serial(dialog);
|
||||
before.stack = runtime.modals().stack().size();
|
||||
before.url = into_u8(web->GetCurrentURL());
|
||||
@@ -2021,15 +2019,15 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
|
||||
{
|
||||
NativeCommand def = recover_input_tool(
|
||||
"core", "auto_answer_dialogs", L("Answer dialogs automatically"),
|
||||
"dialog_auto_answer", L("Answer dialogs automatically"),
|
||||
"Answer modal dialogs automatically when their title or message matches a rule's regex (case-insensitive). "
|
||||
"get_app_state.auto_answer_rules lists the rules in force. Called from a replay or script, the rules join those "
|
||||
"app_state.auto_answer_rules lists the rules in force. Called from a replay or script, the rules join those "
|
||||
"it set before and last until it ends, and a plugin's likewise until it unloads; an MCP client's replace the "
|
||||
"ones MCP clients set before and last until the MCP server stops, and an empty list clears them. Reply: scope (run, plugin or session), rules (uses counts "
|
||||
"a rule's answers) and answered_open_dialog. A native dialog "
|
||||
"returns the rule's button at once and never shows. A file or folder picker takes button ok with an absolute path "
|
||||
"and returns it without showing (on Linux such a rule cancels it); without a path a picker can only be cancelled, "
|
||||
"and a multi-select picker takes no path. A wx dialog is answered as answer_dialog does. A matching dialog "
|
||||
"and a multi-select picker takes no path. A wx dialog is answered as dialog_answer does. A matching dialog "
|
||||
"already open is answered too "
|
||||
"(answered_open_dialog), so a prompt that shows around the same time, such as the restore prompt after startup, "
|
||||
"is caught either way. A web dialog is matched by its title: a button that names one of its shown wx buttons (by "
|
||||
@@ -2056,7 +2054,7 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
// 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 = runtime.modals().top();
|
||||
// A message box is pressed as answer_dialog presses it; a picker can't be.
|
||||
// A message box is pressed as dialog_answer presses it; a picker can't be.
|
||||
const bool native = top != nullptr && is_native_dialog(top);
|
||||
if (top == nullptr || (native && message_box_buttons(top).empty()))
|
||||
return json();
|
||||
@@ -2103,15 +2101,15 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
}
|
||||
|
||||
NativeCommand eval = recover_input_tool(
|
||||
"ui", "run_javascript", L("Run JavaScript in a web view"),
|
||||
"webview_run_javascript", L("Run JavaScript in a web view"),
|
||||
"Evaluate JavaScript in one of OrcaSlicer's web views (Home, the device page, dialogs, plugin windows). Prefer "
|
||||
"list_widgets and the input tools (click, set_widget_value, press_keys, mouse_gesture), which see and drive pages as they do widgets. The code runs in the target's page: "
|
||||
"a web view's (kind webview in list_widgets), or a page element's, with the element as `el`; without a target, in "
|
||||
"widget_list and the input tools (widget_click, widget_set_value, keyboard_press, mouse_gesture), which see and drive pages as they do widgets. The code runs in the target's page: "
|
||||
"a web view's (kind webview in widget_list), or a page element's, with the element as `el`; without a target, in "
|
||||
"the topmost dialog's web view, else in the only shown one. While a modal dialog is open, only its pages run "
|
||||
"code. Reply: result, the value of the last expression (JSON values come back parsed), and url; closed: true when "
|
||||
"the code closed its dialog, navigated: true when it changed the page, dialogs when it opened another. Messages "
|
||||
"the page posts to OrcaSlicer reach it once the code has returned. It runs through eval, which a page whose "
|
||||
"Content-Security-Policy forbids it may refuse (list_widgets and the input tools still work there).",
|
||||
"Content-Security-Policy forbids it may refuse (widget_list and the input tools still work there).",
|
||||
object_schema({{"code", prop("string", "JavaScript statements, run through eval: the last expression's value is the "
|
||||
"result. No top-level return or await; a Promise or a DOM node comes back as {}.")},
|
||||
{"target", kPageTargetSchema},
|
||||
@@ -2141,11 +2139,11 @@ void register_ui_tools(CommandCatalog& catalog)
|
||||
locator = runtime.inspector().locator_for(t);
|
||||
web = dynamic_cast<wxWebView*>(target_window(t));
|
||||
if (web == nullptr)
|
||||
throw ToolFailure("The target is not a web view (list_widgets lists them as kind webview)");
|
||||
throw ToolFailure("The target is not a web view (widget_list lists them as kind webview)");
|
||||
} else
|
||||
web = default_webview(runtime);
|
||||
if (web == nullptr)
|
||||
throw ToolFailure("The page's web view is gone; call list_widgets again");
|
||||
throw ToolFailure("The page's web view is gone; call widget_list again");
|
||||
guard_page(runtime, ctx, web);
|
||||
page.web = web_handle(web);
|
||||
before.modal = in_top_dialog(runtime, web) ? runtime.modals().serial(runtime.modals().top()) : 0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// screenshot, get_slice_stats and set_view: what the agent looks at and reads off the Preview, and
|
||||
// pointing the view before looking.
|
||||
// window_screenshot, plate_slice_stats and view_set: what the agent looks at and reads off the Preview, and
|
||||
// pointing the view before looking; and the window commands made from menu rows, window_open and
|
||||
// window_save_screenshot.
|
||||
|
||||
#include "libvgcode/include/ColorRange.hpp"
|
||||
#include "slic3r/GUI/I18N.hpp"
|
||||
@@ -11,7 +12,9 @@
|
||||
#include "ModalTracker.hpp"
|
||||
#include "ScreenCapture.hpp"
|
||||
#include "UiInspector.hpp"
|
||||
#include "slic3r/GUI/ActionRegistry.hpp"
|
||||
#include "slic3r/GUI/Camera.hpp"
|
||||
#include "slic3r/GUI/CommandCatalog.hpp"
|
||||
#include "slic3r/GUI/CommandTypes.hpp"
|
||||
#include "slic3r/GUI/GCodeViewer.hpp"
|
||||
#include "slic3r/GUI/GLCanvas3D.hpp"
|
||||
@@ -20,6 +23,9 @@
|
||||
#include "slic3r/GUI/IMSlider.hpp"
|
||||
#include "slic3r/GUI/LibVGCode/LibVGCodeWrapper.hpp"
|
||||
#include "slic3r/GUI/MainFrame.hpp"
|
||||
#include "slic3r/GUI/NativeCommandRows.hpp"
|
||||
#include "slic3r/GUI/NativeCommands.hpp"
|
||||
#include "slic3r/GUI/Notebook.hpp"
|
||||
#include "slic3r/GUI/Operations/Outcome.hpp"
|
||||
#include "slic3r/GUI/Operations/PlateOps.hpp"
|
||||
#include "slic3r/GUI/PartPlate.hpp"
|
||||
@@ -29,6 +35,7 @@
|
||||
#include "slic3r/GUI/CAD/DesignPanel.hpp"
|
||||
#endif
|
||||
|
||||
#include "libslic3r/AppConfig.hpp"
|
||||
#include "libslic3r/Config.hpp"
|
||||
#include "libslic3r/ExtrusionEntity.hpp"
|
||||
#include "libslic3r/GCode/GCodeProcessor.hpp"
|
||||
@@ -80,19 +87,13 @@ std::string base64(const std::string& bytes)
|
||||
return out;
|
||||
}
|
||||
|
||||
const char* tab_id(const std::string& name)
|
||||
// The ids of the main window's notebook pages, in the notebook's order.
|
||||
std::vector<std::string> notebook_pages(const Notebook& notebook)
|
||||
{
|
||||
if (name == "home") return TAB_ID_HOME;
|
||||
if (name == "prepare") return TAB_ID_PREPARE;
|
||||
if (name == "preview") return TAB_ID_PREVIEW;
|
||||
if (name == "device" || name == "monitor") return TAB_ID_MONITOR;
|
||||
if (name == "multi_device") return TAB_ID_MULTI_DEVICE;
|
||||
if (name == "project") return TAB_ID_PROJECT;
|
||||
if (name == "calibration") return TAB_ID_CALIBRATION;
|
||||
#ifdef SLIC3R_CAD
|
||||
if (name == "design") return TAB_ID_DESIGN;
|
||||
#endif
|
||||
return nullptr;
|
||||
std::vector<std::string> pages;
|
||||
for (size_t i = 0; i < notebook.GetPageCount(); ++i)
|
||||
pages.push_back(into_u8(notebook.GetPageName(i)));
|
||||
return pages;
|
||||
}
|
||||
|
||||
// Rounded for a reply, which reads like the legend rather than the raw floats.
|
||||
@@ -158,7 +159,7 @@ bool any_legend_row(const std::string& key)
|
||||
return false;
|
||||
}
|
||||
|
||||
// set_view's legend argument: each named row shown or hidden as a click on it does, clicked only when its
|
||||
// view_set's legend argument: each named row shown or hidden as a click on it does, clicked only when its
|
||||
// state differs. The rows are the feature types and options the print has, whatever the view type: the
|
||||
// viewer keeps one visibility set, though the legend lists feature types only in Line Type. The keys are
|
||||
// checked here, before the Preview changes; the returned function applies them and gives each row's
|
||||
@@ -226,13 +227,13 @@ std::pair<double, double> camera_angles(Camera& camera)
|
||||
return {std::asin(std::clamp(offset.z() / distance, -1., 1.)), std::atan2(flat.y(), flat.x())};
|
||||
}
|
||||
|
||||
// Angles in radians as set_view replies with them: whole degrees, the azimuth from -180 to 180.
|
||||
// Angles in radians as view_set replies with them: whole degrees, the azimuth from -180 to 180.
|
||||
json angles_json(double elevation, double azimuth)
|
||||
{
|
||||
return {{"elevation", std::lround(Geometry::rad2deg(elevation))}, {"azimuth", std::lround(std::remainder(Geometry::rad2deg(azimuth), 360.))}};
|
||||
}
|
||||
|
||||
// set_view's orbit: the camera moved around the point it looks at, `yaw` degrees to its right
|
||||
// view_set's orbit: the camera moved around the point it looks at, `yaw` degrees to its right
|
||||
// (counterclockwise seen from above) and `pitch` degrees up, at the same distance. It is placed from its
|
||||
// position rather than turned as a mouse drag turns it, so the result is the same whatever the user's
|
||||
// mouse settings and free-camera preference. The elevation stops a degree short of straight up or down,
|
||||
@@ -258,15 +259,23 @@ bool fit_pending(const Camera& camera)
|
||||
return camera.requires_zoom_to_bed || camera.requires_zoom_to_volumes || camera.requires_zoom_to_plate != REQUIRES_ZOOM_TO_PLATE_IDLE;
|
||||
}
|
||||
|
||||
// set_view's camera: a named direction or a fit of the shown 3D view. On the Design tab it points the Design
|
||||
// view as its own controls do, `default` being its Home view and `sketch_normal` the sketch's N key. UI thread.
|
||||
void point_camera(Plater& plater, const std::string& cam)
|
||||
// Why fit_bed does nothing on the Design tab, which a pick of Fit Bed to View shows there.
|
||||
Ops::Refusal no_bed_in_design()
|
||||
{
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "no_bed_in_design", L("The Design tab has no bed to fit the view to.")};
|
||||
}
|
||||
|
||||
// view_set's camera, and a pick of a camera tile: a named direction or a fit of the shown 3D view. On the Design tab
|
||||
// it points the Design view as its own controls do, `default` being its Home view and `sketch_normal` the sketch's N
|
||||
// key. The refusal is the one a tile can reach, fit_bed on the Design tab; fit_selection and sketch_normal, which no
|
||||
// tile gives, throw. UI thread.
|
||||
std::optional<Ops::Refusal> point_camera(Plater& plater, const std::string& cam)
|
||||
{
|
||||
#ifdef SLIC3R_CAD
|
||||
if (DesignPanel* design = wxGetApp().mainframe->shown_design_panel()) {
|
||||
DesignCanvas* view = design->mcp_viewport();
|
||||
if (cam == "fit_bed")
|
||||
throw ToolFailure("fit_bed is not offered in the Design tab");
|
||||
return no_bed_in_design();
|
||||
if (cam == "fit_objects")
|
||||
view->fit_view();
|
||||
else if (cam == "fit_selection") {
|
||||
@@ -277,7 +286,7 @@ void point_camera(Plater& plater, const std::string& cam)
|
||||
throw ToolFailure("No sketch is open in the Design tab");
|
||||
} else
|
||||
view->set_view(cam == "default" ? "iso" : cam);
|
||||
return;
|
||||
return std::nullopt;
|
||||
}
|
||||
#endif
|
||||
GLCanvas3D* canvas = plater.get_current_canvas3D();
|
||||
@@ -297,6 +306,7 @@ void point_camera(Plater& plater, const std::string& cam)
|
||||
} else {
|
||||
plater.select_view(cam);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// Asks the shown 3D view, the Design view on the Design tab, to draw again. UI thread.
|
||||
@@ -309,6 +319,142 @@ void repaint_shown_canvas()
|
||||
}
|
||||
}
|
||||
|
||||
// The 3D view of Prepare or the Preview whose axes switch app_state reads: the one shown, else Prepare's. UI thread.
|
||||
GLCanvas3D* axes_canvas(Plater& plater)
|
||||
{
|
||||
GLCanvas3D* preview = plater.get_preview_canvas3D();
|
||||
return plater.is_preview_shown() && preview != nullptr ? preview : plater.get_view3D_canvas3D();
|
||||
}
|
||||
|
||||
// view_set's display switches of Prepare and the Preview, under the names it and app_state give them: the switches of
|
||||
// the View menu and of the 3D view's own menu (the canvas toolbar's), each read as its check mark or eye shows it and set
|
||||
// as its item sets it, where it differs. labels and overhangs are Prepare's 3D view's, which its items set while it is
|
||||
// shown, and are set on it from any tab; Prepare's and the Preview's 3D views each draw the axes by a switch of their
|
||||
// own, which the menu sets on the view shown, and axes sets both. The others are the app's. UI thread.
|
||||
struct ViewSwitch
|
||||
{
|
||||
const char* name;
|
||||
bool (*shown)(Plater&);
|
||||
void (*show)(Plater&, bool);
|
||||
};
|
||||
|
||||
const ViewSwitch kViewSwitches[] = {
|
||||
{"labels", [](Plater& plater) { return plater.get_view3D_canvas3D()->are_labels_shown(); },
|
||||
[](Plater& plater, bool on) {
|
||||
plater.get_view3D_canvas3D()->show_labels(on);
|
||||
wxGetApp().app_config->set_bool("show_labels", on);
|
||||
}},
|
||||
{"overhangs", [](Plater& plater) { return plater.get_view3D_canvas3D()->is_overhang_shown(); },
|
||||
[](Plater& plater, bool on) {
|
||||
plater.get_view3D_canvas3D()->show_overhang(on);
|
||||
wxGetApp().app_config->set_bool("show_overhang", on);
|
||||
}},
|
||||
{"outline", [](Plater&) { return wxGetApp().show_outline(); },
|
||||
[](Plater&, bool on) {
|
||||
if (wxGetApp().show_outline() != on)
|
||||
wxGetApp().toggle_show_outline();
|
||||
}},
|
||||
{"wireframe", [](Plater& plater) { return plater.is_show_wireframe(); },
|
||||
[](Plater& plater, bool on) {
|
||||
if (plater.is_show_wireframe() != on)
|
||||
plater.toggle_show_wireframe();
|
||||
}},
|
||||
{"gridlines", [](Plater&) { return wxGetApp().show_plate_gridlines(); },
|
||||
[](Plater&, bool on) {
|
||||
if (wxGetApp().show_plate_gridlines() != on)
|
||||
wxGetApp().toggle_show_plate_gridlines();
|
||||
}},
|
||||
{"axes", [](Plater& plater) { return axes_canvas(plater)->are_world_axes_shown(); },
|
||||
[](Plater& plater, bool on) {
|
||||
for (GLCanvas3D* canvas : {plater.get_view3D_canvas3D(), plater.get_preview_canvas3D()})
|
||||
if (canvas != nullptr && canvas->are_world_axes_shown() != on)
|
||||
canvas->toggle_world_axes_visibility(false);
|
||||
}},
|
||||
{"navigator", [](Plater&) { return wxGetApp().show_3d_navigator(); },
|
||||
[](Plater&, bool on) {
|
||||
if (wxGetApp().show_3d_navigator() != on)
|
||||
wxGetApp().toggle_show_3d_navigator();
|
||||
}},
|
||||
};
|
||||
|
||||
// The section view of Prepare and the Preview, whose 3D views share it: on, as a right click on its toolbar button turns
|
||||
// it on, at the cut it had or through the middle, and off. UI thread.
|
||||
bool section_view_on(Plater& plater) { return plater.get_view3D_canvas3D()->is_section_view_active(); }
|
||||
|
||||
void show_section_view(Plater& plater, bool on)
|
||||
{
|
||||
GLCanvas3D* canvas = plater.get_view3D_canvas3D();
|
||||
if (canvas->is_section_view_active() != on)
|
||||
canvas->toggle_section_view();
|
||||
}
|
||||
|
||||
// view_set's tab, and a pick of Go to tab: shows the main window's page `tab` names (view_tab_page()). Refused when no
|
||||
// page has that name, named as given, or when the page refuses to open, named by its id as the Speed Dial lists it.
|
||||
// UI thread.
|
||||
std::optional<Ops::Refusal> show_tab(MainFrame& frame, const std::string& tab)
|
||||
{
|
||||
const std::optional<std::string> page = frame.m_tabpanel != nullptr ? view_tab_page(tab, notebook_pages(*frame.m_tabpanel)) :
|
||||
std::nullopt;
|
||||
if (!page)
|
||||
// TRN %1% is the tab id the command was given, such as "preview".
|
||||
return Ops::Refusal{Ops::RefusalKind::Precondition, "no_such_tab", L("No tab has the id \"%1%\"."), {tab}};
|
||||
frame.select_tab(from_u8(*page));
|
||||
// The tab can refuse to open: the Device tab of a Bambu Lab printer without its network plugin.
|
||||
if (frame.m_tabpanel->GetSelectedPageName() != from_u8(*page))
|
||||
// TRN %1% is the id of the tab that could not be opened, such as "monitor".
|
||||
return Ops::Refusal{Ops::RefusalKind::Failed, "tab_not_opened", L("The \"%1%\" tab could not be opened."), {*page}};
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// The Preview tab, which a preview field given without tab or canvas, and a pick of Go to layer, show. UI thread.
|
||||
void show_preview(Plater& plater, MainFrame& frame)
|
||||
{
|
||||
plater.select_view_3D("Preview", false);
|
||||
frame.select_tab(wxString(TAB_ID_PREVIEW));
|
||||
}
|
||||
|
||||
// view_set's layer_percent, and a pick of Go to layer: the top of the Preview's shown range moves to the layer that
|
||||
// share of the plate's layers stands for, and its bottom stays. UI thread.
|
||||
Ops::Outcome<Ops::ShownLayers> show_layer_percent(double percent)
|
||||
{
|
||||
const Ops::Outcome<int> count = Ops::layer_count();
|
||||
if (!count)
|
||||
return count.refusal();
|
||||
Ops::ShowLayerRangeArgs range;
|
||||
range.last = int(std::lround(percent / 100.0 * double(count.value() - 1))) + 1;
|
||||
return Ops::show_layer_range(range);
|
||||
}
|
||||
|
||||
// A person's pick of one of view_set's tiles, in place on the UI thread as its row ran: for each argument the function
|
||||
// a call's UI closure runs, and a refusal in the UI's language, Go to tab's as an error and the others, which say that
|
||||
// the view has nothing to show it, as information.
|
||||
AppActionRunResult picked_view(const json& tile_args)
|
||||
{
|
||||
Plater* plater = wxGetApp().plater();
|
||||
MainFrame* frame = wxGetApp().mainframe;
|
||||
if (plater == nullptr || frame == nullptr)
|
||||
return AppActionRunResult{};
|
||||
if (tile_args.contains("layout"))
|
||||
return Rows::reset_window_layout();
|
||||
if (tile_args.contains("projection"))
|
||||
return Rows::toggle_perspective();
|
||||
if (tile_args.contains("tab")) {
|
||||
if (const std::optional<Ops::Refusal> refusal = show_tab(*frame, arg_string(tile_args, "tab")))
|
||||
return NativeCommands::refused(*refusal);
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
}
|
||||
if (tile_args.contains("layer_percent")) {
|
||||
show_preview(*plater, *frame);
|
||||
const Ops::Outcome<Ops::ShownLayers> shown = show_layer_percent(tile_args.at("layer_percent").get<double>());
|
||||
return shown ? AppActionRunResult{AppActionRunResult::Level::Succeeded} :
|
||||
NativeCommands::refused(shown.refusal(), AppActionRunResult::Level::Info);
|
||||
}
|
||||
if (const std::optional<Ops::Refusal> refusal = point_camera(*plater, arg_string(tile_args, "camera")))
|
||||
return NativeCommands::refused(*refusal, AppActionRunResult::Level::Info);
|
||||
repaint_shown_canvas();
|
||||
return AppActionRunResult{AppActionRunResult::Level::Succeeded};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
json camera_state(Camera& camera, double canvas_scale)
|
||||
@@ -325,6 +471,33 @@ json camera_state(Camera& camera, double canvas_scale)
|
||||
return state;
|
||||
}
|
||||
|
||||
json view_state(Plater& plater)
|
||||
{
|
||||
GLCanvas3D* preview = plater.get_preview_canvas3D();
|
||||
json state{{"sidebar_collapsed", plater.is_sidebar_collapsed()},
|
||||
{"sidebar_width", plater.sidebar_width()},
|
||||
{"legend_collapsed", preview != nullptr && preview->get_gcode_viewer().is_legend_folded()},
|
||||
{"gcode_window", wxGetApp().show_gcode_window()},
|
||||
{"projection", plater.get_camera().get_type_as_string()},
|
||||
{"section", {{"on", section_view_on(plater)}}}};
|
||||
for (const ViewSwitch& view_switch : kViewSwitches)
|
||||
state[view_switch.name] = view_switch.shown(plater);
|
||||
return state;
|
||||
}
|
||||
|
||||
std::optional<std::string> view_tab_page(const std::string& tab, const std::vector<std::string>& pages)
|
||||
{
|
||||
const auto has = [&pages](const std::string& page) { return std::find(pages.begin(), pages.end(), page) != pages.end(); };
|
||||
for (const TabWord& w : kTabWords) {
|
||||
if (tab == w.word)
|
||||
return has(w.page) ? std::optional<std::string>(w.page) : std::nullopt;
|
||||
// A page a word names is reached by its word: the Device tab is device, never monitor.
|
||||
if (tab == w.page)
|
||||
return std::nullopt;
|
||||
}
|
||||
return has(tab) ? std::optional<std::string>(tab) : std::nullopt;
|
||||
}
|
||||
|
||||
std::string legend_feature_key(libvgcode::EGCodeExtrusionRole role) { return ExtrusionEntity::role_to_string(libvgcode::convert(role)); }
|
||||
|
||||
const char* legend_option_key(libvgcode::EOptionType type)
|
||||
@@ -423,17 +596,17 @@ json preview_state(GCodeViewer& viewer)
|
||||
void register_view_tools(CommandCatalog& catalog)
|
||||
{
|
||||
NativeCommand screenshot = inspect_tool(
|
||||
"ui", "screenshot", L("Take a screenshot"),
|
||||
"window_screenshot", L("Take a screenshot"),
|
||||
"Capture what OrcaSlicer shows and return it as an image, downscaled to max_dim on the long edge (default 1280), "
|
||||
"plus the full-size PNG written to save_path (or the session's output folder). target: \"main\" (the main "
|
||||
"window), \"canvas\" (the visible 3D view exactly as rendered: scene, toolpaths, toolbars, ImGui panels; on the "
|
||||
"Design tab its view), "
|
||||
"\"dialog\" (the topmost modal dialog), or a ref: a window's from list_windows (one that is not modal, say), or a "
|
||||
"widget's from list_widgets, cropped to that widget (a page element's ref captures its whole web view). The result "
|
||||
"\"dialog\" (the topmost modal dialog), or a ref: a window's from window_list (one that is not modal, say), or a "
|
||||
"widget's from widget_list, cropped to that widget (a page element's ref captures its whole web view). The result "
|
||||
"says when parts may differ from the "
|
||||
"screen (approximate). Point the view first with set_view.",
|
||||
"screen (approximate). Point the view first with view_set.",
|
||||
object_schema({{"target", {{"type", json::array({"string", "object"})},
|
||||
{"description", "main (default), canvas, dialog, or a widget's ref or locator from list_widgets."}}},
|
||||
{"description", "main (default), canvas, dialog, or a widget's ref or locator from widget_list."}}},
|
||||
{"max_dim", {{"type", "integer"}, {"minimum", 256}, {"maximum", 2000}, {"description", "Long edge of the returned image."}}},
|
||||
{"save_path", prop("string", "Absolute .png path for the full-size image.")},
|
||||
{"overwrite", prop("boolean", "Replace an existing save_path.")},
|
||||
@@ -473,7 +646,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
ui_plater(); // refuses while OrcaSlicer starts or closes
|
||||
GLCanvas3D* canvas = shown_canvas();
|
||||
if (canvas == nullptr)
|
||||
throw ToolFailure("No 3D view is shown; switch to one with set_view tab");
|
||||
throw ToolFailure("No 3D view is shown; switch to one with view_set tab");
|
||||
cap = capture_canvas(*canvas, err);
|
||||
} else if (target == "dialog") {
|
||||
wxDialog* top = runtime.modals().top();
|
||||
@@ -490,7 +663,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
throw ToolFailure("target must be main, canvas, dialog or the ref of a widget");
|
||||
if (t.kind == UiTarget::Kind::WebElement) {
|
||||
// A replay captures the same web view, by its own locator: a page element's
|
||||
// has none the screenshot's target takes.
|
||||
// has none the window_screenshot's target takes.
|
||||
UiTarget view;
|
||||
view.kind = UiTarget::Kind::Window;
|
||||
view.window = w;
|
||||
@@ -503,9 +676,9 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
// A tab: its page, which only the selected tab shows.
|
||||
auto* book = dynamic_cast<wxBookCtrlBase*>(w);
|
||||
if (book == nullptr || t.page >= int(book->GetPageCount()))
|
||||
throw ToolFailure("The tab is gone; call list_widgets again");
|
||||
throw ToolFailure("The tab is gone; call widget_list again");
|
||||
if (book->GetSelection() != t.page)
|
||||
throw ToolFailure("The tab's page is not shown; click the tab (click) first");
|
||||
throw ToolFailure("The tab's page is not shown; click the tab (widget_click) first");
|
||||
w = book->GetPage(size_t(t.page));
|
||||
}
|
||||
if (GLCanvas3D* canvas = runtime.inspector().canvas_of(&t); canvas != nullptr && canvas->get_wxglcanvas() == w) {
|
||||
@@ -514,7 +687,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
wxWindow* top = wxGetTopLevelParent(w);
|
||||
// A popup is a native window of its own, which its window's capture draws in.
|
||||
if (dynamic_cast<wxPopupWindow*>(top) != nullptr)
|
||||
throw ToolFailure("The widget is in a popup; a screenshot of its window shows the popup, and list_widgets "
|
||||
throw ToolFailure("The widget is in a popup; a screenshot of its window shows the popup, and widget_list "
|
||||
"{target: \"popup\"} lists it");
|
||||
auto* tlw = dynamic_cast<wxTopLevelWindow*>(top);
|
||||
if (tlw == nullptr)
|
||||
@@ -583,11 +756,11 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
catalog.add(screenshot);
|
||||
|
||||
catalog.add(inspect_tool(
|
||||
"api", "get_slice_stats", L("Get slice statistics"),
|
||||
"What the Preview shows for a sliced plate. summary: the slice reply's, plus prepare and travel time and travel "
|
||||
"plate_slice_stats", L("Get slice statistics"),
|
||||
"What the Preview shows for a sliced plate. summary: plate_slice's, plus prepare and travel time and travel "
|
||||
"distance. features: seconds, share of the print time and grams per feature type (the Line Type legend), and "
|
||||
"travel. layers: per layer (1-based, as set_view's layer) Z, height, seconds and grams, paged; layer_features adds "
|
||||
"each feature type's seconds. objects: grams per object instance, with its list_objects index when its name is "
|
||||
"travel. layers: per layer (1-based, as view_set's layer) Z, height, seconds and grams, paged; layer_features adds "
|
||||
"each feature type's seconds. objects: grams per object instance, with its object_list index when its name is "
|
||||
"unique. view, for the plate the Preview shows: view type, time mode, layer range, which legend rows are visible, "
|
||||
"and each view type's colour range for what the legend shows. Times are normal-mode estimates. A G-code file "
|
||||
"opened for viewing reads the same.",
|
||||
@@ -605,7 +778,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
throw ToolFailure("The Preview needs an FFF printer");
|
||||
// The background process may be rewriting a result whatever its valid flag says.
|
||||
if (plater.is_slicing_any())
|
||||
throw ToolFailure("Slicing is in progress; wait {\"for\": \"idle\"} first");
|
||||
throw ToolFailure("Slicing is in progress; app_wait {\"for\": \"idle\"} first");
|
||||
PartPlateList& plates = plater.get_partplate_list();
|
||||
const int current = plates.get_curr_plate_index();
|
||||
const int index = arg_int(args, "plate", current);
|
||||
@@ -621,7 +794,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
// shows, without marking the plate sliced.
|
||||
const bool gcode_file = plater.only_gcode_mode() && shown;
|
||||
const std::string name = "Plate " + std::to_string(index);
|
||||
const std::string slice_it = "slice {\"plates\": " + std::to_string(index) + "}";
|
||||
const std::string slice_it = "plate_slice {\"plates\": " + std::to_string(index) + "}";
|
||||
if (result == nullptr || !(plate->is_slice_result_valid() || gcode_file))
|
||||
throw ToolFailure(name + " has no up-to-date slice; " + slice_it + " first");
|
||||
// Of a project opened from a sliced 3MF, a plate the Preview has not shown keeps only the file's totals.
|
||||
@@ -649,9 +822,9 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
out["view"] = shown ? preview_view(*canvas) : json();
|
||||
if (index != current)
|
||||
out["note"] = "The Preview shows plate " + std::to_string(current) + "; show plate " + std::to_string(index) +
|
||||
" there (run_action orca_command:plate_goto:orca, args {\"plate\": " + std::to_string(index) + "}) to read its legend";
|
||||
" there (plate_select {\"plate\": " + std::to_string(index) + "}) to read its legend";
|
||||
else if (!shown)
|
||||
out["note"] = "The Preview has not loaded this plate's toolpaths; show it with set_view {\"tab\": \"preview\"}";
|
||||
out["note"] = "The Preview has not loaded this plate's toolpaths; show it with view_set {\"tab\": \"preview\"}";
|
||||
}
|
||||
return out;
|
||||
}));
|
||||
@@ -663,13 +836,13 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
if (std::string name = GCodeViewer::view_type_to_config_name(libvgcode::EViewType(i)); !name.empty())
|
||||
view_types.push_back(std::move(name));
|
||||
|
||||
std::vector<std::string> tabs{"home", "prepare", "preview", "device", "multi_device", "project", "calibration"};
|
||||
#ifdef SLIC3R_CAD
|
||||
tabs.insert(tabs.begin() + 1, "design");
|
||||
#endif
|
||||
// The words of tab, as the description lists them.
|
||||
std::string tab_words;
|
||||
for (const TabWord& w : kTabWords)
|
||||
tab_words += (tab_words.empty() ? "" : ", ") + std::string(w.word);
|
||||
|
||||
catalog.add(reaching({"show_layer_range"}, mutate_tool(
|
||||
"ui", "set_view", L("Set up the view"),
|
||||
NativeCommand view = reaching({"show_layer_range"}, mutate_tool(
|
||||
"view_set", L("Set up the view"),
|
||||
"Set up what the window shows, for screenshots and GUI work: the main tab, the 3D view (canvas: Prepare's, the "
|
||||
"preview or the assemble view, which has its own gizmos), the camera of the 3D view shown (a named direction, the "
|
||||
"default view, or fit to bed / objects / selection, then look_at, the point it looks at, an orbit to look from "
|
||||
@@ -679,9 +852,18 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
"sketch_normal looks straight at the open sketch), and with tab design, section, origin_planes, world_axes, origin and bed "
|
||||
"set the Design view's switches. The reply echoes them; preview layers as [first, last, count] with z, the heights of "
|
||||
"first and last; with tab design, design: the section view and the four switches as they then are; with any camera "
|
||||
"field, camera_state, the camera it leaves as get_app_state.camera gives it, and adjusted: [\"zoom\"] when the zoom "
|
||||
"was held to its limits.",
|
||||
object_schema({{"tab", enum_prop(tabs, "Main window tab.")},
|
||||
"field, camera_state, the camera it leaves as app_state.camera gives it, and adjusted: [\"zoom\"] when the zoom "
|
||||
"was held to its limits. tab takes the id of any other page of the window too, such as a plugin's. projection "
|
||||
"sets the 3D camera's, layout default restores the default window layout, and layer_percent shows the Preview "
|
||||
"at that share of the layer range, as Go to layer does. Outside the Design tab, from any tab: section {on} turns "
|
||||
"the section view of Prepare and the Preview on or off; labels, overhangs, outline, wireframe, gridlines, axes and "
|
||||
"navigator set the display switches of the View menu and of the 3D view's own menu; sidebar_collapsed and "
|
||||
"sidebar_width set the sidebar of Prepare and the Preview; in the Preview, legend_collapsed folds the legend and "
|
||||
"gcode_window shows the G-code window. Each is echoed as the app reads it back, and app_state's view gives them "
|
||||
"under these names. A pick of a view tile runs the same code in place, so a camera tile turns the Design tab's "
|
||||
"camera too.",
|
||||
object_schema({{"tab", prop("string", "Main window tab: " + tab_words + ", or the id of another page of the window "
|
||||
"(monitor_web, the web Device page where the app shows one, or a plugin's page).")},
|
||||
{"canvas", enum_prop({"3d", "preview", "assemble"}, "3D view: Prepare's, the preview, or the assemble view (needs an object; leave it with 3d, as its Return button does).")},
|
||||
{"camera", enum_prop({"iso", "top", "bottom", "front", "rear", "left", "right", "default", "fit_bed", "fit_objects", "fit_selection",
|
||||
"sketch_normal"},
|
||||
@@ -694,15 +876,18 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
{"keep", enum_prop({"lower", "upper"}, "The half that stays: lower (the default) or upper.")}}},
|
||||
{"required", {"on"}},
|
||||
{"additionalProperties", false},
|
||||
{"description", "Design tab: the section view, a horizontal cut that hides half of the model to show "
|
||||
"inside it, as the toolbar's Section View and Flip set it."}}},
|
||||
{"description", "The section view, a cut that hides part of the model to show inside it. With tab "
|
||||
"design, the Design view's horizontal cut, as its toolbar's Section View and "
|
||||
"Flip set it, at z, keeping one half. Without it, the section view of Prepare "
|
||||
"and the Preview, on alone, as a right click on its toolbar button turns it on "
|
||||
"and off."}}},
|
||||
{"origin_planes", {{"type", "boolean"}, {"description", "Design tab: show the origin helper planes (key P)."}}},
|
||||
{"world_axes", {{"type", "boolean"}, {"description", "Design tab: show the world axis triad (key A)."}}},
|
||||
{"origin", {{"type", "boolean"}, {"description", "Design tab: the Origin row's eye, the XY, XZ and YZ planes kept up "
|
||||
"where a click picks one; off lets go of a picked plane."}}},
|
||||
{"bed", {{"type", "boolean"}, {"description", "Design tab: the Bed row's eye, the printer bed drawn."}}},
|
||||
{"look_at", array_prop({{"type", "number"}}, "[x, y, z] in mm: the point the camera looks at, in the 3D view's "
|
||||
"world coordinates, as list_objects gives positions; on the Design tab, "
|
||||
"world coordinates, as object_list gives positions; on the Design tab, "
|
||||
"the Design view's, which the Design commands' world points use (describe_design's "
|
||||
"modeling_origin is the sketch planes' origin). The camera moves "
|
||||
"parallel, keeping its direction and distance. After camera.")},
|
||||
@@ -717,21 +902,60 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
{"layer_z", {{"type", "number"}, {"minimum", 0}, {"description", "Preview: show layers up to the first whose top is at or above this height (mm), as the slider places a custom G-code."}}},
|
||||
{"view_type", enum_prop(view_types, "Preview color scheme.")},
|
||||
{"legend", {{"type", "object"}, {"additionalProperties", {{"type", "boolean"}}},
|
||||
{"description", "Preview: show (true) or hide (false) legend rows: feature types by name as get_slice_stats lists them "
|
||||
{"description", "Preview: show (true) or hide (false) legend rows: feature types by name as plate_slice_stats lists them "
|
||||
"(\"Sparse infill\"), and travel, wipe, retract, unretract, seams, filament_changes, color_changes, "
|
||||
"pauses, custom_gcode, in any case and with _ or a space between words. Hiding a row this "
|
||||
"print lacks does nothing. Applied after view_type."}}},
|
||||
{"time_mode", enum_prop({"normal", "silent"}, "Preview: the time estimate the legend and layer times show; silent only when the print has its own.")}}),
|
||||
{"time_mode", enum_prop({"normal", "silent"}, "Preview: the time estimate the legend and layer times show; silent only when the print has its own.")},
|
||||
{"layer_percent", {{"type", "number"}, {"minimum", 0}, {"maximum", 100},
|
||||
{"description", "Preview: show the layers up to this share of the layer range, as Go to "
|
||||
"layer does; the bottom of the shown range stays."}}},
|
||||
{"projection", enum_prop({"perspective", "orthographic", "toggle"}, "The 3D camera's projection; toggle "
|
||||
"switches between the two.")},
|
||||
{"layout", enum_prop({"default"}, "default restores the default window layout, as View > Reset Window "
|
||||
"Layout does.")},
|
||||
{"sidebar_collapsed", prop("boolean", "Collapse (true) or expand (false) the sidebar of Prepare and the "
|
||||
"Preview, as its collapse button does.")},
|
||||
{"sidebar_width", {{"type", {"integer", "string"}},
|
||||
{"minimum", 1},
|
||||
{"description", "The sidebar's width in pixels, as a drag of its edge sets it, or "
|
||||
"\"default\", its width in the default window layout. A sidebar "
|
||||
"floating in a window of its own is sized with window_set."}}},
|
||||
{"legend_collapsed", prop("boolean", "Preview: fold the legend to its title row (true) or unfold it (false), "
|
||||
"as its fold button does.")},
|
||||
{"gcode_window", prop("boolean", "Preview: show (true) or hide (false) the G-code window, as View > Show "
|
||||
"G-code Window does.")},
|
||||
{"labels", prop("boolean", "Prepare: the object labels, as View > Show Labels sets them.")},
|
||||
{"overhangs", prop("boolean", "Prepare: the overhang highlight, as View > Show Overhang sets it.")},
|
||||
{"outline", prop("boolean", "The outline around the selected objects, as View > Show Selected Outline sets "
|
||||
"it.")},
|
||||
{"wireframe", prop("boolean", "The objects' wireframe, as the 3D view's own menu sets it.")},
|
||||
{"gridlines", prop("boolean", "The plate's gridlines, as View > Show Gridlines sets them.")},
|
||||
{"axes", prop("boolean", "The axes on the bed of Prepare and the Preview, as the 3D view's own menu sets "
|
||||
"them; with tab design, world_axes is the Design view's.")},
|
||||
{"navigator", prop("boolean", "The 3D navigator of Prepare and the Preview, as View > Show 3D Navigator "
|
||||
"sets it.")}}),
|
||||
[](const json& args, ToolContext& ctx) {
|
||||
const bool preview_args = args.contains("layer") || args.contains("layer_range") || args.contains("layer_z") ||
|
||||
args.contains("view_type") || args.contains("legend") || args.contains("time_mode");
|
||||
if (arg_string(args, "tab") == "design" && (args.contains("canvas") || preview_args))
|
||||
args.contains("layer_percent") || args.contains("view_type") || args.contains("legend") ||
|
||||
args.contains("time_mode") || args.contains("legend_collapsed") || args.contains("gcode_window");
|
||||
const bool design_tab = arg_string(args, "tab") == "design";
|
||||
if (design_tab && (args.contains("canvas") || preview_args))
|
||||
throw ToolFailure("canvas and the Preview fields show Prepare or Preview; give them without tab design");
|
||||
const bool design_args = args.contains("section") || args.contains("origin_planes") || args.contains("world_axes") ||
|
||||
args.contains("origin") || args.contains("bed") || arg_string(args, "camera") == "sketch_normal";
|
||||
if (design_args && arg_string(args, "tab") != "design")
|
||||
throw ToolFailure("sketch_normal, section, origin_planes, world_axes, origin and bed are the Design tab's: give them "
|
||||
"with tab design");
|
||||
// The section view is the Design view's with tab design, else Prepare's and the Preview's.
|
||||
const bool design_args = (args.contains("section") && design_tab) || args.contains("origin_planes") ||
|
||||
args.contains("world_axes") || args.contains("origin") || args.contains("bed") ||
|
||||
arg_string(args, "camera") == "sketch_normal";
|
||||
if (design_args && !design_tab)
|
||||
throw ToolFailure("sketch_normal, origin_planes, world_axes, origin and bed are the Design tab's: give them with "
|
||||
"tab design");
|
||||
const bool view_section = args.contains("section") && !design_tab;
|
||||
if (view_section && (args["section"].contains("z") || args["section"].contains("keep")))
|
||||
throw ToolFailure("z and keep are the Design view's cut: give them with tab design. Without it, section is the "
|
||||
"section view of Prepare and the Preview, which takes on alone");
|
||||
if (args.contains("sidebar_width") && args["sidebar_width"].is_string() && args["sidebar_width"] != "default")
|
||||
throw ToolFailure("sidebar_width is a width in pixels or \"default\"");
|
||||
const bool sidebar_args = args.contains("sidebar_collapsed") || args.contains("sidebar_width");
|
||||
if (args.contains("orbit") && args["orbit"].size() != 2)
|
||||
throw ToolFailure("orbit is [yaw, pitch] in degrees");
|
||||
if (args.contains("look_at") && args["look_at"].size() != 3)
|
||||
@@ -742,6 +966,11 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
Plater& plater = ui_plater();
|
||||
MainFrame* frame = wxGetApp().mainframe;
|
||||
json done = json::object();
|
||||
// The sidebar's state, refused before anything changes where it takes none.
|
||||
if (sidebar_args && !plater.is_sidebar_enabled())
|
||||
throw ToolFailure("The sidebar is off while a G-code file is shown without its settings");
|
||||
if (args.contains("sidebar_width") && plater.is_sidebar_floating())
|
||||
throw ToolFailure("The sidebar floats in a window of its own, whose size window_set sets");
|
||||
#ifdef SLIC3R_CAD
|
||||
// The Design tab's panel, which its options set and the reply reads. They, and the cameras the
|
||||
// Design view refuses (point_camera()), are refused here, before the tab or anything else
|
||||
@@ -760,21 +989,25 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
if (arg_string(args, "camera") == "sketch_normal" && !design->mcp_viewport()->is_sketching())
|
||||
throw ToolFailure("No sketch is open in the Design tab");
|
||||
}
|
||||
if (design != nullptr && arg_string(args, "camera") == "fit_bed")
|
||||
throw ToolFailure("fit_bed is not offered in the Design tab");
|
||||
if (design != nullptr && arg_string(args, "camera") == "fit_selection" && !design->mcp_viewport()->selection_box().defined)
|
||||
// The Design view the camera points once the tab is handled: the one asked for, or the one shown, which
|
||||
// a call with no tab, canvas or Preview field leaves shown. Its refusals (point_camera()) come here too.
|
||||
DesignPanel* aimed = design;
|
||||
if (aimed == nullptr && !args.contains("tab") && !args.contains("canvas") && !preview_args)
|
||||
aimed = frame->shown_design_panel();
|
||||
if (aimed != nullptr && arg_string(args, "camera") == "fit_bed")
|
||||
throw refused(no_bed_in_design());
|
||||
if (aimed != nullptr && arg_string(args, "camera") == "fit_selection" && !aimed->mcp_viewport()->selection_box().defined)
|
||||
throw ToolFailure("Nothing is selected in the Design tab");
|
||||
#endif
|
||||
if (args.contains("tab")) {
|
||||
const char* id = tab_id(arg_string(args, "tab"));
|
||||
if (id == nullptr)
|
||||
throw ToolFailure("Unknown tab");
|
||||
const std::string tab = arg_string(args, "tab");
|
||||
#ifdef SLIC3R_CAD
|
||||
if (id == std::string(TAB_ID_DESIGN) && frame->m_design_page == nullptr)
|
||||
if (tab == "design" && frame->m_design_page == nullptr)
|
||||
throw ToolFailure("The Design tab is off; enable the CAD feature in Preferences and restart");
|
||||
#endif
|
||||
frame->select_tab(wxString(id));
|
||||
done["tab"] = arg_string(args, "tab");
|
||||
if (const std::optional<Ops::Refusal> refusal = show_tab(*frame, tab))
|
||||
throw refused(*refusal);
|
||||
done["tab"] = tab;
|
||||
}
|
||||
#ifdef SLIC3R_CAD
|
||||
if (design != nullptr) {
|
||||
@@ -828,10 +1061,8 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
frame->select_tab(wxString(TAB_ID_PREVIEW));
|
||||
done["canvas"] = view;
|
||||
}
|
||||
if (preview_args && !args.contains("tab") && !args.contains("canvas")) {
|
||||
plater.select_view_3D("Preview", false);
|
||||
frame->select_tab(wxString(TAB_ID_PREVIEW));
|
||||
}
|
||||
if (preview_args && !args.contains("tab") && !args.contains("canvas"))
|
||||
show_preview(plater, *frame);
|
||||
if (preview_args) {
|
||||
GLCanvas3D* canvas = plater.get_preview_canvas3D();
|
||||
if (canvas == nullptr)
|
||||
@@ -839,6 +1070,8 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
GCodeViewer& viewer = canvas->get_gcode_viewer();
|
||||
if (args.contains("layer_z") && (args.contains("layer") || args.contains("layer_range")))
|
||||
throw ToolFailure("Give layer_z or layer/layer_range, not both");
|
||||
if (args.contains("layer_percent") && (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z")))
|
||||
throw ToolFailure("Give layer_percent alone, without layer, layer_range or layer_z");
|
||||
if ((args.contains("legend") || args.contains("time_mode")) && !viewer.has_data())
|
||||
throw ToolFailure("legend and time_mode need the Preview's toolpaths; slice first");
|
||||
const std::function<json()> show_legend = args.contains("legend") ? legend_change(viewer, args["legend"]) : nullptr;
|
||||
@@ -865,7 +1098,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
viewer.set_time_mode(mode);
|
||||
done["time_mode"] = arg_string(args, "time_mode");
|
||||
}
|
||||
if (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z")) {
|
||||
if (args.contains("layer") || args.contains("layer_range") || args.contains("layer_z") || args.contains("layer_percent")) {
|
||||
const Ops::Outcome<int> count = Ops::layer_count();
|
||||
if (!count)
|
||||
throw refused(count.refusal());
|
||||
@@ -886,7 +1119,7 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
range.last = r[1].get<int>();
|
||||
}
|
||||
if (args.contains("layer_z")) {
|
||||
// The slider's own rule for a height, which set_custom_gcode_at_layer's z follows too.
|
||||
// The slider's own rule for a height, which plate_set_custom_gcode's z follows too.
|
||||
const double z = args["layer_z"].get<double>();
|
||||
const int tick = layers->get_tick_from_value(z, true);
|
||||
if (tick < 0 || tick > max)
|
||||
@@ -894,17 +1127,59 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
json(rounded(layers->GetMaxValueD(), 1000.)).dump() + " mm)");
|
||||
range.last = tick + 1;
|
||||
}
|
||||
const Ops::Outcome<Ops::ShownLayers> shown = Ops::show_layer_range(range);
|
||||
const Ops::Outcome<Ops::ShownLayers> shown = args.contains("layer_percent") ?
|
||||
show_layer_percent(args["layer_percent"].get<double>()) :
|
||||
Ops::show_layer_range(range);
|
||||
if (!shown)
|
||||
throw refused(shown.refusal());
|
||||
// The reply echoes the range asked for; z is of the layers the slider shows.
|
||||
done["layers"] = {shown.value().asked_first, shown.value().asked_last, shown.value().count};
|
||||
done["z"] = {rounded(shown.value().z_first, 1000.), rounded(shown.value().z_last, 1000.)};
|
||||
}
|
||||
// After the layers, which can still refuse the call, and after view_type, whose pick unfolds the
|
||||
// legend.
|
||||
if (args.contains("legend_collapsed")) {
|
||||
viewer.fold_legend(args["legend_collapsed"].get<bool>());
|
||||
done["legend_collapsed"] = viewer.is_legend_folded();
|
||||
}
|
||||
if (args.contains("gcode_window")) {
|
||||
if (wxGetApp().show_gcode_window() != args["gcode_window"].get<bool>())
|
||||
wxGetApp().toggle_show_gcode_window();
|
||||
done["gcode_window"] = wxGetApp().show_gcode_window();
|
||||
}
|
||||
canvas->set_as_dirty();
|
||||
}
|
||||
if (args.contains("projection")) {
|
||||
Camera& camera = plater.get_camera();
|
||||
const std::string projection = arg_string(args, "projection");
|
||||
if (projection == "toggle")
|
||||
camera.select_next_type();
|
||||
else
|
||||
camera.set_type(projection == "perspective" ? Camera::EType::Perspective : Camera::EType::Ortho);
|
||||
done["projection"] = camera.get_type_as_string();
|
||||
}
|
||||
if (args.contains("layout")) {
|
||||
plater.reset_window_layout();
|
||||
done["layout"] = arg_string(args, "layout");
|
||||
}
|
||||
if (view_section) {
|
||||
show_section_view(plater, args["section"].at("on").get<bool>());
|
||||
done["section"] = {{"on", section_view_on(plater)}};
|
||||
}
|
||||
for (const ViewSwitch& view_switch : kViewSwitches)
|
||||
if (args.contains(view_switch.name)) {
|
||||
view_switch.show(plater, args[view_switch.name].get<bool>());
|
||||
done[view_switch.name] = view_switch.shown(plater);
|
||||
}
|
||||
// After layout, which expands the sidebar at its default width.
|
||||
if (args.contains("sidebar_collapsed") && plater.is_sidebar_collapsed() != args["sidebar_collapsed"].get<bool>())
|
||||
plater.collapse_sidebar(args["sidebar_collapsed"].get<bool>());
|
||||
if (args.contains("sidebar_width"))
|
||||
plater.set_sidebar_width(args["sidebar_width"].is_string() ? plater.default_sidebar_width() :
|
||||
args["sidebar_width"].get<int>());
|
||||
if (GLCanvas3D* canvas = plater.get_current_canvas3D())
|
||||
canvas->set_as_dirty();
|
||||
repaint_shown_canvas();
|
||||
return done;
|
||||
});
|
||||
if (camera_args) {
|
||||
@@ -939,7 +1214,8 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
Camera& camera = plater.get_camera();
|
||||
json done = json::object();
|
||||
if (args.contains("camera")) {
|
||||
point_camera(plater, arg_string(args, "camera"));
|
||||
if (const std::optional<Ops::Refusal> refusal = point_camera(plater, arg_string(args, "camera")))
|
||||
throw refused(*refusal);
|
||||
done["camera"] = arg_string(args, "camera");
|
||||
}
|
||||
if (args.contains("look_at")) {
|
||||
@@ -965,6 +1241,17 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
},
|
||||
std::chrono::seconds(15), "the assemble view to show its objects");
|
||||
settle(ctx);
|
||||
// The sidebar as the window lays it out once the change is handled.
|
||||
if (sidebar_args)
|
||||
out.update(ctx.observe_ui([&args] {
|
||||
Plater& plater = ui_plater();
|
||||
json read = json::object();
|
||||
if (args.contains("sidebar_collapsed"))
|
||||
read["sidebar_collapsed"] = plater.is_sidebar_collapsed();
|
||||
if (args.contains("sidebar_width"))
|
||||
read["sidebar_width"] = plater.sidebar_width();
|
||||
return read;
|
||||
}));
|
||||
if (camera_args)
|
||||
out.update(ctx.observe_ui([&args] {
|
||||
const GLCanvas3D* canvas = shown_canvas();
|
||||
@@ -976,7 +1263,117 @@ void register_view_tools(CommandCatalog& catalog)
|
||||
return read;
|
||||
}));
|
||||
return ToolResult::ok(out);
|
||||
})));
|
||||
}));
|
||||
// The View menu's rows and the Speed Dial's Go to tab and Go to layer, whose value its second phase collects. Titles
|
||||
// are L("...")-marked here so xgettext extracts them.
|
||||
struct CameraRow
|
||||
{
|
||||
const char* key;
|
||||
const char* title;
|
||||
const char* camera;
|
||||
};
|
||||
static const CameraRow camera_rows[] = {{"view_top", L("View: Top"), "top"}, {"view_bottom", L("View: Bottom"), "bottom"},
|
||||
{"view_front", L("View: Front"), "front"}, {"view_rear", L("View: Rear"), "rear"},
|
||||
{"view_left", L("View: Left"), "left"}, {"view_right", L("View: Right"), "right"},
|
||||
{"view_iso", L("View: Isometric"), "iso"}, {"view_default", L("View: Default"), "default"},
|
||||
{"view_fit_bed", L("Fit Bed to View"), "fit_bed"}};
|
||||
view.tiles = json::array();
|
||||
std::vector<json> camera_forms;
|
||||
for (const CameraRow& row : camera_rows) {
|
||||
const std::string camera = row.camera;
|
||||
std::string does = "Turn the camera of the view shown, the Design tab's too, to the " + camera + " view.";
|
||||
if (camera == "default")
|
||||
does = "Turn the camera of the view shown to the default view and fit the plate; on the Design tab, its Home view.";
|
||||
else if (camera == "fit_bed")
|
||||
does = "Fit the build plate in the 3D view shown; refused on the Design tab, which has no bed to fit.";
|
||||
view.tiles.push_back(NativeCommands::tile(row.key, row.title, L("View"), "", {{"camera", camera}}, does));
|
||||
camera_forms.push_back({{"camera", camera}});
|
||||
}
|
||||
view.tiles.push_back(NativeCommands::tile("view_toggle_perspective", L("Toggle Perspective"), L("View"), "", {{"projection", "toggle"}},
|
||||
"Switch the 3D camera between perspective and orthographic."));
|
||||
view.tiles.push_back(NativeCommands::tile("reset_window_layout", L("Reset Window Layout"), L("View"), "toolbar_reset",
|
||||
{{"layout", "default"}}, "Restore the default window layout."));
|
||||
view.tiles.push_back(NativeCommands::tile("go_to_tab", L("Go to tab..."), L("Commands"), "", json::object(),
|
||||
"Switch to a main window tab.", "tab"));
|
||||
view.tiles.push_back(NativeCommands::tile("go_to_layer", L("Go to layer (percent)"), L("Commands"), "height_range_layer",
|
||||
json::object(),
|
||||
"Show the Preview tab at a layer chosen as a percentage of the layer range; an error "
|
||||
"while the Preview has no layers (slice first).",
|
||||
"percent", "layer_percent"));
|
||||
// A person's pick of any of these tiles runs in place (picked_view()): Toggle Perspective and Reset Window Layout
|
||||
// their rows, the camera tiles, Go to tab and Go to layer the camera, tab and layer functions view_set's UI closure
|
||||
// runs for a call, so a camera tile turns the Design tab's camera too. An automated call of a camera tile, Go to tab
|
||||
// or Go to layer is view_set's own function.
|
||||
catalog.add(NativeCommands::with_row_forms(std::move(view), picked_view, /*person_form_behind_dialogs=*/false,
|
||||
std::move(camera_forms)));
|
||||
|
||||
// ---- The window commands made from menu rows ----
|
||||
struct WindowRow
|
||||
{
|
||||
const char* key;
|
||||
const char* title;
|
||||
const char* group;
|
||||
const char* icon;
|
||||
const char* window;
|
||||
const char* description;
|
||||
};
|
||||
// Titles are L("...")-marked here so xgettext extracts them.
|
||||
static const WindowRow window_rows[] = {
|
||||
{"open_preferences", L("Preferences"), L("Commands"), "cog", "preferences",
|
||||
"Open the Preferences dialog. window_open with a tab, and a key on it, opens it on that tab with that preference's "
|
||||
"control scrolled into view and focused (shown on its own tab)."},
|
||||
{"open_plugins", L("Open Plugins"), L("Plugins"), "", "plugins", "Open the plugins dialog."},
|
||||
{"open_action_replay", L("Action Replay"), L("Commands"), "loop", "action_replay",
|
||||
"Open the Action Replay window, where a person opens a replay file, reads its steps and replays them. Agents run "
|
||||
"replays with the replay_run tool instead."},
|
||||
{"preset_bundle", L("Open Preset Bundle"), L("Presets"), "menu_edit_preset", "preset_bundle", "Open the preset bundle manager."},
|
||||
{"help_keyboard_shortcuts", L("Keyboard Shortcuts"), L("Help"), "", "keyboard_shortcuts", "Show the keyboard shortcuts dialog."},
|
||||
{"help_setup_wizard", L("Setup Wizard"), L("Help"), "", "setup_wizard", "Open the setup wizard."},
|
||||
{"help_network_test", L("Open Network Test"), L("Help"), "", "network_test", "Open the network test dialog."},
|
||||
{"help_troubleshoot", L("Troubleshoot Center"), L("Help"), "", "troubleshoot", "Open the troubleshooting center."},
|
||||
{"help_tip_of_the_day", L("Show Tip of the Day"), L("Help"), "info", "tip_of_the_day", "Show a tip of the day."},
|
||||
{"help_about", L("About OrcaSlicer"), L("Help"), "OrcaSlicer_gradient_circle", "about", "Show the About dialog."},
|
||||
};
|
||||
std::vector<std::string> windows;
|
||||
json window_tiles = json::array();
|
||||
for (const WindowRow& row : window_rows) {
|
||||
windows.emplace_back(row.window);
|
||||
window_tiles.push_back(NativeCommands::tile(row.key, row.title, row.group, row.icon, {{"window", row.window}}, row.description));
|
||||
}
|
||||
catalog.add(row_command(
|
||||
"window_open", L("Open a window"),
|
||||
"Open one of OrcaSlicer's windows or dialogs for a person, as its menu row does: preferences, the Preferences dialog, "
|
||||
"with tab, and key on it, on that tab with that preference's control scrolled into view and focused (its controls are "
|
||||
"named after their preference keys: preferences_get reads them and preferences_set writes those it does not refuse, "
|
||||
"and widget_set_value {\"target\": {\"name\": key, \"within\": \"Preferences\"}} changes one through the "
|
||||
"dialog); plugins, the Plugins window; action_replay, the "
|
||||
"Action Replay window, where a person replays a replay file (agents run one with replay_run); preset_bundle, the preset "
|
||||
"bundle manager; keyboard_shortcuts; setup_wizard; network_test; troubleshoot, the troubleshooting center; "
|
||||
"tip_of_the_day; about. A modal one replies blocked_by_dialog.",
|
||||
object_schema({{"window", enum_prop(windows, "The window.")},
|
||||
{"tab", enum_prop(Rows::preferences_tabs(), "preferences: the tab to show.")},
|
||||
{"key", prop("string", "preferences, with tab: a preference on that tab, e.g. auto_arrange on behaviour: "
|
||||
"its control is scrolled into view and focused.")}},
|
||||
{"window"}),
|
||||
std::move(window_tiles), [](const json& args) {
|
||||
const std::string window = arg_string(args, "window");
|
||||
if (window != "preferences" && (args.contains("tab") || args.contains("key")))
|
||||
return AppActionRunResult{AppActionRunResult::Level::Error, from_u8("tab and key go with window preferences"), false};
|
||||
json preferences = args;
|
||||
preferences.erase("window");
|
||||
return Rows::open_window(window, preferences);
|
||||
}));
|
||||
|
||||
const std::string saved = "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 window_screenshot tool, which returns the image.";
|
||||
NativeCommand save_screenshot = row_command("window_save_screenshot", L("Take Screenshot"), saved, object_schema({}),
|
||||
json::array({NativeCommands::tile("take_screenshot", L("Take Screenshot"),
|
||||
L("Commands"), "screenshot", json::object(), saved)}),
|
||||
[](const json&) { return Rows::take_screenshot(); });
|
||||
// A menu row with no argument form: tool_search finds it and tool_call runs it, the tool list does not show it.
|
||||
save_screenshot.listed = false;
|
||||
catalog.add(std::move(save_screenshot));
|
||||
}
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -79,7 +79,7 @@ using nlohmann::json;
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t kMaxMessage = 2000;
|
||||
// Rows of one list a message shows; list_widgets lists them all.
|
||||
// Rows of one list a message shows; widget_list lists them all.
|
||||
constexpr std::size_t kMaxListRows = 25;
|
||||
|
||||
std::string lower(std::string s)
|
||||
@@ -400,7 +400,7 @@ private:
|
||||
text += (text.empty() ? "" : "\n") + line;
|
||||
}
|
||||
if (rows.size() > kMaxListRows)
|
||||
text += "\n- … more rows (list_widgets lists them)";
|
||||
text += "\n- … more rows (widget_list lists them)";
|
||||
return content(w, text);
|
||||
}
|
||||
|
||||
@@ -1095,7 +1095,7 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
// An exception must never escape into ShowModal().
|
||||
try {
|
||||
// A window hidden from automation (the Python scripts setting) is the person's alone: no rule
|
||||
// answers it, and leaving it off the stack keeps it out of the dialog tools and get_app_state.
|
||||
// answers it, and leaving it off the stack keeps it out of the dialog tools and app_state.
|
||||
if (dialog != nullptr && dialog->GetName() == kHiddenFromAutomation)
|
||||
return wxID_NONE;
|
||||
// A description that fails leaves the dialog matched by its title alone, and tracked all the same.
|
||||
@@ -1170,10 +1170,10 @@ int ModalTracker::Enter(wxDialog* dialog)
|
||||
}
|
||||
// A wx dialog's buttons do its work in their handlers (Transfer, Discard, Clone's Fill), which
|
||||
// a returned id would skip. So it opens, and the button is pressed once its modal loop runs, as
|
||||
// answer_dialog does; the rule counts as used once that pressed the button or ended the
|
||||
// dialog_answer does; the rule counts as used once that pressed the button or ended the
|
||||
// dialog. A button disabled by then leaves the dialog open. Queued on the dialog, the press goes
|
||||
// with it if it is destroyed first; a modal opened above it before then leaves it to
|
||||
// answer_dialog. The tracker lives as long as the app.
|
||||
// dialog_answer. The tracker lives as long as the app.
|
||||
if (wx_rule)
|
||||
dialog->CallAfter([this, dialog, answer, title, rule = *wx_rule] {
|
||||
const auto& [layer, pattern, button] = rule;
|
||||
|
||||
@@ -116,7 +116,7 @@ private:
|
||||
// {title, message, class, native, buttons:[{id,label,enabled?}], web?} for a dialog. A wx dialog's
|
||||
// message reads it as a person does: its text, and its controls with their values and states, row by
|
||||
// row (DialogReader in the .cpp); `enabled` is false for a disabled button. `web` is true for a dialog
|
||||
// with a web view, whose page holds its controls (list_widgets with target dialog lists them). `text`, when
|
||||
// with a web view, whose page holds its controls (widget_list with target dialog lists them). `text`, when
|
||||
// given, receives the dialog's own text: its static text and html, one per line, without its
|
||||
// controls, which auto-answer rules also search (rule_matches()). UI thread only.
|
||||
nlohmann::json describe_dialog(wxDialog* dialog, std::string* text = nullptr);
|
||||
|
||||
@@ -17,11 +17,11 @@ namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
// remembers them; the command's parameter overrides them for one recording.
|
||||
struct RecordingSettings
|
||||
{
|
||||
int quality = 80; // the frames' JPEG quality, 30-95, as start_recording's
|
||||
bool captions = false; // the overlays, as start_recording's
|
||||
int quality = 80; // the frames' JPEG quality, 30-95, as recording_start's
|
||||
bool captions = false; // the overlays, as recording_start's
|
||||
bool pointer = false;
|
||||
bool encode = false;
|
||||
std::string codec = "h265"; // and the rest as encode_recording takes them
|
||||
std::string codec = "h265"; // and the rest as recording_encode takes them
|
||||
int crf = 28;
|
||||
std::string speed = "medium";
|
||||
std::string profile = "main";
|
||||
@@ -60,13 +60,13 @@ std::string matching_encode_preset(const RecordingSettings& settings);
|
||||
RecordingSettings load_recording_settings(const AppConfig& config);
|
||||
void save_recording_settings(AppConfig& config, const RecordingSettings& settings);
|
||||
|
||||
// Applies start_recording's encode arguments, an object with any of encode, encode_preset, codec, crf, speed,
|
||||
// Applies recording_start's encode arguments, an object with any of encode, encode_preset, codec, crf, speed,
|
||||
// profile and keep_raw_video_file, other keys left alone: encode_preset's fields first, then the fields it
|
||||
// names. A codec named without a profile takes the codec's default profile when the one it had does not fit.
|
||||
// Returns what is wrong, "" when nothing; `settings` is then unchanged.
|
||||
std::string apply_recording_overrides(RecordingSettings& settings, const nlohmann::json& overrides);
|
||||
|
||||
// encode_recording's arguments for the recording at `path` (UTF-8).
|
||||
// recording_encode's arguments for the recording at `path` (UTF-8).
|
||||
nlohmann::json encode_arguments(const RecordingSettings& settings, const std::string& path);
|
||||
|
||||
}}} // namespace Slic3r::GUI::Mcp
|
||||
@@ -644,9 +644,9 @@ std::string no_modal_dialog(ModalTracker& modals)
|
||||
open += (open.empty() ? "\"" : ", \"") + label_of(tlw) + "\"";
|
||||
if (open.empty())
|
||||
return "No modal dialog is open";
|
||||
return "No modal dialog is open. Open without blocking the app: " + open + ". list_windows lists such a window with its ref: "
|
||||
"screenshot captures it with the ref as target, list_widgets reads it alone with the ref as target, and the window's own "
|
||||
"close button or press_keys Escape with its ref as target closes it";
|
||||
return "No modal dialog is open. Open without blocking the app: " + open + ". window_list lists such a window with its ref: "
|
||||
"window_screenshot captures it with the ref as target, widget_list reads it alone with the ref as target, and the window's own "
|
||||
"close button or keyboard_press Escape with its ref as target closes it";
|
||||
}
|
||||
|
||||
// Stable English gizmo names for refs and locators: the names Orca uses for the gizmos it names,
|
||||
@@ -685,7 +685,7 @@ GLGizmosManager::EType gizmo_from_name(const std::string& name)
|
||||
return GLGizmosManager::Undefined;
|
||||
}
|
||||
|
||||
// The mouse tools' modifiers, named as in press_keys's chords so both mean the same keys: ctrl (or cmd) is
|
||||
// The mouse tools' modifiers, named as in keyboard_press's chords so both mean the same keys: ctrl (or cmd) is
|
||||
// the shortcut modifier, Command on macOS, and rawctrl is the macOS Control key.
|
||||
int parse_modifiers(const std::vector<std::string>& mods)
|
||||
{
|
||||
@@ -1042,7 +1042,7 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string&
|
||||
// The assemble view shows only the objects selected when it opened, and clears `visible` on the rest.
|
||||
if (shown == nullptr || shown->mesh_raycaster == nullptr || !shown->visible || (!shown->is_active && !own(shown)))
|
||||
throw ToolFailure(what + " is not shown in the " + std::string(canvas_name(&canvas)) +
|
||||
" view (list_objects lists objects and parts; the assemble view shows the objects selected when it opened)");
|
||||
" view (object_list lists objects and parts; the assemble view shows the objects selected when it opened)");
|
||||
const Transform3d world = shown->world_matrix();
|
||||
const AABBMesh& mesh = shown->mesh_raycaster->get_aabb_mesh();
|
||||
|
||||
@@ -1072,7 +1072,7 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string&
|
||||
const CanvasView view = canvas_view(canvas);
|
||||
const auto projected = project_point(view, point);
|
||||
if (!projected)
|
||||
throw ToolFailure("The point of " + what + " is off screen; turn or zoom the camera with set_view");
|
||||
throw ToolFailure("The point of " + what + " is off screen; turn or zoom the camera with view_set");
|
||||
// Events carry whole logical pixels: the click goes through this one, not the projected point.
|
||||
const wxPoint pixel(int(std::lround(projected->x())), int(std::lround(projected->y())));
|
||||
|
||||
@@ -1098,7 +1098,7 @@ wxPoint target_pixel(GLCanvas3D& canvas, const json& target, const std::string&
|
||||
const std::string why = check_surface(point, pixel_ray(view, Vec2d(pixel.x, pixel.y)), meshes, clip ? &*clip : nullptr, beds, limit);
|
||||
if (!why.empty())
|
||||
throw ToolFailure("A click at the point of " + what + " would miss it: " + why +
|
||||
". Turn the camera with set_view, or pass check:\"point\" for a point off the surface");
|
||||
". Turn the camera with view_set, or pass check:\"point\" for a point off the surface");
|
||||
} else if (check != "point") {
|
||||
throw ToolFailure("check is surface or point");
|
||||
}
|
||||
@@ -1404,7 +1404,7 @@ std::optional<std::string> cell_text(wxDataViewModel& model, const wxDataViewIte
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
// What an object list row stands for, by the indices list_objects uses.
|
||||
// What an object list row stands for, by the indices object_list uses.
|
||||
std::string object_row_note(ObjectDataViewModel& model, const wxDataViewItem& item)
|
||||
{
|
||||
int plate = -1;
|
||||
@@ -1469,8 +1469,15 @@ void data_view_rows(wxDataViewCtrl& ctrl, std::vector<ListRow>& out, std::size_t
|
||||
}
|
||||
if (!labelled)
|
||||
row.path.emplace_back();
|
||||
if (objects != nullptr)
|
||||
if (objects != nullptr) {
|
||||
row.note = object_row_note(*objects, item);
|
||||
// A plate's, an object's, a part's or a height range's settings of its own show as the icon that
|
||||
// resets them.
|
||||
const auto* node = static_cast<const ObjectDataViewModelNode*>(item.GetID());
|
||||
const bool settable = (objects->GetItemType(item) & (itPlate | itObject | itVolume | itLayer)) != 0;
|
||||
if (node != nullptr && settable && node->IsActionEnabled())
|
||||
row.note += ", has settings";
|
||||
}
|
||||
row.selected = ctrl.IsSelected(item);
|
||||
row.shown = shown;
|
||||
row.depth = depth;
|
||||
@@ -1687,7 +1694,7 @@ json click_data_view_row(wxDataViewCtrl& ctrl, const ListRow& row, const std::st
|
||||
// the middle of that rect is a click outside the list, which its owner ignores.
|
||||
const wxRect shown = cell.IsEmpty() ? wxRect() : cell.Intersect(ctrl.GetClientRect());
|
||||
if (shown.IsEmpty())
|
||||
throw ToolFailure("\"" + row.path.back() + "\" can't be scrolled into the list's view; make the window taller with set_window size");
|
||||
throw ToolFailure("\"" + row.path.back() + "\" can't be scrolled into the list's view; make the window taller with window_set size");
|
||||
// The pointer stays on the cell for the click: the object list acts on the cell under it (Printable
|
||||
// toggles printability, Editing resets the row's settings).
|
||||
wxMouseState pointer;
|
||||
@@ -1930,7 +1937,7 @@ std::vector<std::pair<wxWindow*, ListRow>> find_rows(const std::vector<wxWindow*
|
||||
json click_row(wxWindow& list, const ListRow& row, const std::string& column, const ClickOptions& o)
|
||||
{
|
||||
if (!list.IsShownOnScreen())
|
||||
throw ToolFailure("The list is no longer shown; call list_widgets again");
|
||||
throw ToolFailure("The list is no longer shown; call widget_list again");
|
||||
if (!list.IsEnabled())
|
||||
throw ToolFailure("The list is disabled");
|
||||
if (!row.enabled)
|
||||
@@ -1966,11 +1973,11 @@ json click_row(wxWindow& list, const ListRow& row, const std::string& column, co
|
||||
json input_row(wxWindow& list, const ListRow& row, const std::string& column, const json& value)
|
||||
{
|
||||
if (!list.IsShownOnScreen())
|
||||
throw ToolFailure("The list is no longer shown; call list_widgets again");
|
||||
throw ToolFailure("The list is no longer shown; call widget_list again");
|
||||
if (!list.IsEnabled())
|
||||
throw ToolFailure("The list is disabled");
|
||||
if (dynamic_cast<wxGrid*>(&list) != nullptr)
|
||||
throw ToolFailure("Table cells are read-only here; edit object settings with set_settings {scope: \"object\"}");
|
||||
throw ToolFailure("Table cells are read-only here; edit object settings with settings_set {target: \"object\"}");
|
||||
const std::string text = value.is_string() ? lower(value.get<std::string>()) : value.dump();
|
||||
if (!value.is_boolean() && text != "true" && text != "false" && text != "1" && text != "0")
|
||||
throw ToolFailure("A row takes true or false, for its checkbox");
|
||||
@@ -2000,7 +2007,7 @@ json input_row(wxWindow& list, const ListRow& row, const std::string& column, co
|
||||
}
|
||||
return {{"row", joined(row.path, ">")}, {"checked", checks->IsChecked(n)}};
|
||||
}
|
||||
throw ToolFailure("This row has no checkbox; use click");
|
||||
throw ToolFailure("This row has no checkbox; use widget_click");
|
||||
}
|
||||
|
||||
// ---- snapshot ---------------------------------------------------------------------------------
|
||||
@@ -2334,7 +2341,7 @@ void UiInspector::add_imgui_items(GLCanvas3D& canvas, int depth, std::vector<UiN
|
||||
if ((node.cls == "slider" || node.cls == "drag") && (item.flags & ImGuiItemStatusFlags_Inputable) == 0)
|
||||
node.note = "no typing";
|
||||
if (item.clipped)
|
||||
node.note += std::string(node.note.empty() ? "" : ", ") + "clipped: click and set_widget_value scroll it into view";
|
||||
node.note += std::string(node.note.empty() ? "" : ", ") + "clipped: widget_click and widget_set_value scroll it into view";
|
||||
node.depth = depth + 1;
|
||||
node.x = at.x, node.y = at.y, node.w = br.x - at.x, node.h = br.y - at.y;
|
||||
UiTarget t;
|
||||
@@ -2644,10 +2651,10 @@ json UiInspector::window_entry(wxTopLevelWindow& tlw, bool modal)
|
||||
if (tlw.GetName() == kHiddenFromAutomation) {
|
||||
w["hidden"] = true;
|
||||
} else if (dlg != nullptr && is_native_dialog(dlg)) {
|
||||
// answer_dialog answers it; no other tool reaches into it.
|
||||
// dialog_answer answers it; no other tool reaches into it.
|
||||
w["native"] = true;
|
||||
} else {
|
||||
// The locator list_widgets gives the window, so a journal records the same.
|
||||
// The locator widget_list gives the window, so a journal records the same.
|
||||
UiTarget t;
|
||||
t.kind = UiTarget::Kind::Window;
|
||||
t.window = &tlw;
|
||||
@@ -2716,13 +2723,13 @@ UiTarget UiInspector::resolve(const json& target)
|
||||
return out;
|
||||
}
|
||||
if (!target.is_object())
|
||||
throw ToolFailure("target must be a ref from list_widgets or a locator object");
|
||||
throw ToolFailure("target must be a ref from widget_list or a locator object");
|
||||
// A ref written the way locators are, {ref: "w12"}.
|
||||
if (target.size() == 1 && target.contains("ref") && target["ref"].is_string())
|
||||
return resolve(target["ref"]);
|
||||
if (is_web_locator(target))
|
||||
throw ToolFailure("A {css} or {web} locator names an element of a web page, which click, set_widget_value, press_keys, "
|
||||
"mouse_gesture and run_javascript take; here give a widget's ref or locator");
|
||||
throw ToolFailure("A {css} or {web} locator names an element of a web page, which widget_click, widget_set_value, keyboard_press, "
|
||||
"mouse_gesture and webview_run_javascript take; here give a widget's ref or locator");
|
||||
|
||||
UiTarget t;
|
||||
t.locator = target;
|
||||
@@ -2730,7 +2737,7 @@ UiTarget UiInspector::resolve(const json& target)
|
||||
int id = -1;
|
||||
const std::string path = target["menu"].get<std::string>();
|
||||
if (find_menu_path(path, id) == nullptr)
|
||||
throw ToolFailure("No menu item " + path + " (list_widgets lists them)");
|
||||
throw ToolFailure("No menu item " + path + " (widget_list lists them)");
|
||||
t.kind = UiTarget::Kind::MenuItem;
|
||||
t.window = wxGetApp().mainframe;
|
||||
t.menu_id = id;
|
||||
@@ -2783,14 +2790,14 @@ UiTarget UiInspector::resolve(const json& target)
|
||||
names.push_back(gizmo_name(g));
|
||||
throw ToolFailure("No gizmo " + t.name, {{"gizmos", names}});
|
||||
}
|
||||
t.name = gizmo_name(t.gizmo); // replies name it as get_app_state does
|
||||
t.name = gizmo_name(t.gizmo); // replies name it as app_state does
|
||||
return t;
|
||||
}
|
||||
// ImGui item: search the named canvas, or every canvas when none was named.
|
||||
const auto matches = match_imgui(target);
|
||||
const int index = target.value("index", -1);
|
||||
if (matches.empty())
|
||||
throw ToolFailure("No ImGui item matches " + target.dump() + " in the last frame; show its panel first (list_widgets lists them)");
|
||||
throw ToolFailure("No ImGui item matches " + target.dump() + " in the last frame; show its panel first (widget_list lists them)");
|
||||
if (matches.size() > 1 && index < 0)
|
||||
throw ToolFailure(std::to_string(matches.size()) + " ImGui items match " + target.dump() + "; add \"index\" (0-based) or use a ref");
|
||||
if (index >= int(matches.size()))
|
||||
@@ -2826,8 +2833,8 @@ UiTarget UiInspector::resolve(const json& target)
|
||||
// Global/Objects switch is on Objects.
|
||||
if (any.empty())
|
||||
throw ToolFailure("No shown list has any rows; the Prepare sidebar's object list shows when its Global/Objects "
|
||||
"switch, the SwitchButton list_widgets labels \"Process\", is on Objects (click it)");
|
||||
throw ToolFailure("No shown list has a row " + target["row"].dump() + "; call list_widgets", {{"rows", similar.empty() ? any : similar}});
|
||||
"switch, the SwitchButton widget_list labels \"Process\", is on Objects (click it)");
|
||||
throw ToolFailure("No shown list has a row " + target["row"].dump() + "; call widget_list", {{"rows", similar.empty() ? any : similar}});
|
||||
}
|
||||
if (matches.size() > 1 && index < 0)
|
||||
throw ToolFailure(std::to_string(matches.size()) + " rows match " + target.dump() + "; add \"index\" (0-based) or use a ref");
|
||||
@@ -2844,7 +2851,7 @@ UiTarget UiInspector::resolve(const json& target)
|
||||
if (target.contains("tab")) {
|
||||
const auto matches = match_tabs(target);
|
||||
if (matches.empty())
|
||||
throw ToolFailure("No tab " + target.dump() + "; call list_widgets");
|
||||
throw ToolFailure("No tab " + target.dump() + "; call widget_list");
|
||||
if (matches.size() > 1 && index < 0)
|
||||
throw ToolFailure(std::to_string(matches.size()) + " tabs match " + target.dump() + "; add \"index\" (0-based) or use a ref");
|
||||
if (index >= int(matches.size()))
|
||||
@@ -2862,7 +2869,7 @@ UiTarget UiInspector::resolve(const json& target)
|
||||
throw ToolFailure("A locator needs option, label, name or class (or menu, tab, row, gltoolbar, gizmo, imgui, imgui_name)");
|
||||
const std::vector<wxWindow*> matches = match_windows(target);
|
||||
if (matches.empty())
|
||||
throw ToolFailure("Nothing matches " + target.dump() + "; call list_widgets");
|
||||
throw ToolFailure("Nothing matches " + target.dump() + "; call widget_list");
|
||||
if (matches.size() > 1 && index < 0)
|
||||
throw ToolFailure(std::to_string(matches.size()) + " elements match " + target.dump() + "; add \"index\" (0-based) or use a ref");
|
||||
if (index >= int(matches.size()))
|
||||
@@ -3060,7 +3067,7 @@ void UiInspector::reveal(UiTarget& target)
|
||||
}
|
||||
if (item.clipped)
|
||||
throw ToolFailure("\"" + target.imgui_label + "\" is outside the visible part of its panel, which does not scroll to it; "
|
||||
"make the window taller with set_window size");
|
||||
"make the window taller with window_set size");
|
||||
target.x = item.x, target.y = item.y, target.w = item.w, target.h = item.h;
|
||||
}
|
||||
|
||||
@@ -3071,7 +3078,7 @@ ImGuiWrapper::RecordedItem UiInspector::imgui_record(const UiTarget& t) const
|
||||
const auto items = wxGetApp().imgui()->recorded_items(t.canvas);
|
||||
if (const auto at = imgui_find_item(items, t.imgui_id, t.imgui_name, t.imgui_window, t.imgui_twins))
|
||||
return items[*at];
|
||||
throw ToolFailure("\"" + t.imgui_label + "\" is no longer shown; call list_widgets again");
|
||||
throw ToolFailure("\"" + t.imgui_label + "\" is no longer shown; call widget_list again");
|
||||
}
|
||||
|
||||
GLCanvas3D* UiInspector::canvas_of(const UiTarget* target) const
|
||||
@@ -3107,7 +3114,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
case UiTarget::Kind::MenuItem: {
|
||||
wxMenuItem* item = find_menu_item(t.menu_id, nullptr);
|
||||
if (item == nullptr || item->GetMenu() == nullptr)
|
||||
throw ToolFailure("The menu item is gone; call list_widgets again");
|
||||
throw ToolFailure("The menu item is gone; call widget_list again");
|
||||
return run_menu_item(*item, *wxGetApp().mainframe, t.menu_path);
|
||||
}
|
||||
case UiTarget::Kind::ToolbarItem: {
|
||||
@@ -3161,7 +3168,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
case GLGizmosManager::ToolbarClick::Nothing: break;
|
||||
}
|
||||
if (type == GLGizmosManager::Svg)
|
||||
throw ToolFailure("The SVG gizmo opens on a selected SVG part: select one, or add one with run_action add_primitive_svg");
|
||||
throw ToolFailure("The SVG gizmo opens on a selected SVG part: select one, or add one with object_add_svg");
|
||||
throw ToolFailure("The " + t.name + " gizmo did not open (select an object first?)");
|
||||
}
|
||||
case UiTarget::Kind::ImGuiItem: {
|
||||
@@ -3170,7 +3177,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
const wxPoint pos = imgui_to_canvas(*shown.canvas, shown.x + shown.w / 2.f, shown.y + shown.h / 2.f);
|
||||
if (const std::string cover = covered_by(*shown.canvas, pos, shown.imgui_window); !cover.empty())
|
||||
throw ToolFailure("\"" + shown.imgui_label + "\" is under " + cover +
|
||||
", which would take the click; close it, or enlarge the window with set_window size");
|
||||
", which would take the click; close it, or enlarge the window with window_set size");
|
||||
canvas_click(*shown.canvas, pos, o);
|
||||
return {{"clicked", shown.imgui_label}, {"at", {pos.x, pos.y}}};
|
||||
}
|
||||
@@ -3178,7 +3185,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
wxWindow* list = t.window.get();
|
||||
const std::optional<ListRow> row = list != nullptr ? find_row(*list, t.row_path, t.row_twin) : std::nullopt;
|
||||
if (!row)
|
||||
throw ToolFailure("The row is gone; call list_widgets again");
|
||||
throw ToolFailure("The row is gone; call widget_list again");
|
||||
return click_row(*list, *row, t.column, o);
|
||||
}
|
||||
case UiTarget::Kind::PlateIcon: {
|
||||
@@ -3186,12 +3193,12 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
// no plate clicks.
|
||||
GLCanvas3D& canvas = *t.canvas;
|
||||
if (!is_live_canvas(t.canvas) || !canvas.get_wxglcanvas()->IsShownOnScreen())
|
||||
throw ToolFailure("Plate icons are on the Prepare view; set_view {\"tab\": \"prepare\"} first");
|
||||
throw ToolFailure("Plate icons are on the Prepare view; view_set {\"tab\": \"prepare\"} first");
|
||||
if (o.button == "middle" || o.double_click || o.at_point)
|
||||
throw ToolFailure("A plate icon takes a single left or right click");
|
||||
if (canvas.is_layers_editing_enabled())
|
||||
throw ToolFailure("Plate icons take no clicks while variable layer height is being edited; close it with "
|
||||
"click {\"target\": {\"gltoolbar\": \"layersediting\"}} first");
|
||||
"widget_click {\"target\": {\"gltoolbar\": \"layersediting\"}} first");
|
||||
if (const auto open = canvas.get_gizmos_manager().get_current_type(); open != GLGizmosManager::Undefined)
|
||||
throw ToolFailure("Close the " + gizmo_name(open) + " gizmo first: plate icons take no clicks while it is open");
|
||||
Plater& plater = *wxGetApp().plater();
|
||||
@@ -3229,7 +3236,7 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
out["started"] = idle && !worker.is_idle();
|
||||
if (!out["started"].get<bool>() && arrange_stuck)
|
||||
out["note"] = "The arrange icon does nothing after an arrange was cancelled or failed, until another arrange "
|
||||
"finishes; arrange with the arrange tool or run_action obj_arrange";
|
||||
"finishes; arrange with object_arrange";
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -3238,20 +3245,20 @@ json UiInspector::click(const UiTarget& t, const ClickOptions& o)
|
||||
|
||||
wxWindow* w = t.window.get();
|
||||
if (w == nullptr)
|
||||
throw ToolFailure("The element is gone; call list_widgets again");
|
||||
throw ToolFailure("The element is gone; call widget_list again");
|
||||
if (!w->IsEnabled())
|
||||
throw ToolFailure("The element is disabled");
|
||||
scroll_into_view(w);
|
||||
if (t.page >= 0) {
|
||||
auto* book = dynamic_cast<wxBookCtrlBase*>(w);
|
||||
if (book == nullptr || t.page >= int(book->GetPageCount()))
|
||||
throw ToolFailure("The tab is gone; call list_widgets again");
|
||||
throw ToolFailure("The tab is gone; call widget_list again");
|
||||
book->SetSelection(size_t(t.page)); // sends the page-changing and page-changed events
|
||||
return {{"clicked", t.name}, {"page", t.page}};
|
||||
}
|
||||
if (o.at_point && dynamic_cast<wxGLCanvas*>(w) == nullptr) {
|
||||
if (is_native_control(w))
|
||||
throw ToolFailure("x/y clicks a point of a custom-drawn widget; this is a native control, so use click without x/y");
|
||||
throw ToolFailure("x/y clicks a point of a custom-drawn widget; this is a native control, so use widget_click without x/y");
|
||||
click_window(w, o);
|
||||
return {{"clicked", label_of(w)}, {"at", {o.x, o.y}}};
|
||||
}
|
||||
@@ -3306,11 +3313,11 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit)
|
||||
wxWindow* list = t.window.get();
|
||||
const std::optional<ListRow> row = list != nullptr ? find_row(*list, t.row_path, t.row_twin) : std::nullopt;
|
||||
if (!row)
|
||||
throw ToolFailure("The row is gone; call list_widgets again");
|
||||
throw ToolFailure("The row is gone; call widget_list again");
|
||||
return input_row(*list, *row, t.column, value);
|
||||
}
|
||||
if (t.kind != UiTarget::Kind::Window || t.window.get() == nullptr)
|
||||
throw ToolFailure("set_widget_value works on controls, list rows and ImGui fields");
|
||||
throw ToolFailure("widget_set_value works on controls, list rows and ImGui fields");
|
||||
wxWindow* w = t.window.get();
|
||||
if (!w->IsEnabled())
|
||||
throw ToolFailure("The control is disabled");
|
||||
@@ -3322,7 +3329,7 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit)
|
||||
// An option, as a radio button, is unselected by selecting another; a click would only select it again.
|
||||
if (!want && checked_of(w) == 1 && (selector_option(w).selector != nullptr || dynamic_cast<wxRadioButton*>(w) != nullptr ||
|
||||
dynamic_cast<Slic3r::GUI::RadioBox*>(w) != nullptr))
|
||||
throw ToolFailure("An option is unselected by selecting another one; set_widget_value true on that one");
|
||||
throw ToolFailure("An option is unselected by selecting another one; widget_set_value true on that one");
|
||||
if ((checked_of(w) == 1) != want)
|
||||
click(t, ClickOptions{});
|
||||
return {{"checked", checked_of(w) == 1}};
|
||||
@@ -3377,7 +3384,7 @@ json UiInspector::input(const UiTarget& t, const json& value, bool submit)
|
||||
}
|
||||
return {{"value", into_u8(te->GetValue())}};
|
||||
}
|
||||
throw ToolFailure("This element (" + short_class(w) + ") takes no input; use click");
|
||||
throw ToolFailure("This element (" + short_class(w) + ") takes no input; use widget_click");
|
||||
}
|
||||
|
||||
// Sets an ImGui control the way a person does, chosen by its kind, and reads the value back.
|
||||
@@ -3478,7 +3485,7 @@ json UiInspector::imgui_input(UiTarget t, const json& value, bool submit)
|
||||
throw ToolFailure("\"" + t.imgui_label + "\" is a slider that takes no typing and has no number field beside it; drag it with mouse_gesture");
|
||||
}
|
||||
if (field_kind != "input" && field_kind != "multiline" && field_kind != "drag" && field_kind != "slider")
|
||||
throw ToolFailure("\"" + t.imgui_label + "\" is a " + field_kind + ", which takes no typed value; use click");
|
||||
throw ToolFailure("\"" + t.imgui_label + "\" is a " + field_kind + ", which takes no typed value; use widget_click");
|
||||
|
||||
// A Ctrl+click turns a slider or drag into a text field; an input field takes a plain click.
|
||||
ClickOptions focus;
|
||||
@@ -3659,7 +3666,7 @@ json UiInspector::mouse(GLCanvas3D& canvas, const json& g, const std::string& ow
|
||||
if (const std::string cover = covered_by(canvas, from); !cover.empty())
|
||||
throw ToolFailure("The model point at pixel (" + std::to_string(from.x) + ", " + std::to_string(from.y) + ") is under " + cover +
|
||||
", which would take the " + (action == "move" ? "pointer" : action == "wheel" ? "wheel" : "click") +
|
||||
"; turn or zoom the camera with set_view, or close it");
|
||||
"; turn or zoom the camera with view_set, or close it");
|
||||
// A painting gizmo takes a press only on the object it paints. One that misses falls through to the
|
||||
// canvas, which turns or pans the camera as the user's mouse settings say, and the stroke paints nothing.
|
||||
if ((action == "down" || action == "drag") && !design && dynamic_cast<GLGizmoPainterBase*>(canvas.get_gizmos_manager().get_current()) != nullptr &&
|
||||
@@ -3669,8 +3676,8 @@ json UiInspector::mouse(GLCanvas3D& canvas, const json& g, const std::string& ow
|
||||
if (const auto hit = first_hit_on_stroke(canvas, from, stops))
|
||||
throw ToolFailure(missed + "The stroke first reaches the object at pixel (" + std::to_string(hit->x) + ", " +
|
||||
std::to_string(hit->y) + "): start it there");
|
||||
throw ToolFailure(missed + "Start the stroke on the object (at a model point, or a pixel inside its list_objects {\"screen\": true} "
|
||||
"box that shows the object), and turn the camera with set_view camera or orbit");
|
||||
throw ToolFailure(missed + "Start the stroke on the object (at a model point, or a pixel inside its object_list {\"screen\": true} "
|
||||
"box that shows the object), and turn the camera with view_set camera or orbit");
|
||||
}
|
||||
json out{{"action", action}, {"canvas", canvas_name(&canvas)}, {"pixels", pixels}};
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ struct UiTarget
|
||||
nlohmann::json locator;
|
||||
};
|
||||
|
||||
// A row of a list, tree, table or drop-down list, as list_widgets lists it and row locators find it.
|
||||
// A row of a list, tree, table or drop-down list, as widget_list lists it and row locators find it.
|
||||
struct ListRow
|
||||
{
|
||||
std::vector<std::string> path; // labels from the top: the row's own label last
|
||||
@@ -123,7 +123,7 @@ struct ClickOptions
|
||||
int x = 0, y = 0;
|
||||
};
|
||||
|
||||
// Lists and drives the GUI for list_widgets and the input tools: wx widgets of every shown top-level window, the
|
||||
// Lists and drives the GUI for widget_list and the input tools: wx widgets of every shown top-level window, the
|
||||
// menus, the 3D canvases' toolbar items, gizmos and ImGui items. Input is synthesized as wx
|
||||
// events delivered to the widgets' own handlers (no OS input, focus or pointer needed), with
|
||||
// semantic activation for controls whose handlers listen to command events. UI thread only.
|
||||
@@ -139,14 +139,14 @@ public:
|
||||
|
||||
// {tree, nodes, omitted}
|
||||
nlohmann::json snapshot(const SnapshotOptions& options);
|
||||
// The open windows as list_windows lists them, in list_widgets's order: the main window, the windows
|
||||
// The open windows as window_list lists them, in widget_list's order: the main window, the windows
|
||||
// that don't block, then the modal dialogs in the order they opened, so the topmost is last. Each
|
||||
// has the ref list_widgets gives it. A native dialog has no ref, and a window hidden from automation
|
||||
// has the ref widget_list gives it. A native dialog has no ref, and a window hidden from automation
|
||||
// is listed by its title and kind alone, so an agent knows it is there and out of reach.
|
||||
nlohmann::json windows();
|
||||
// One window of windows(), `modal` saying whether it blocks the app: its title, kind and modal, then
|
||||
// hidden or native for a window no tool reaches, else a new ref, web, x and y where the platform
|
||||
// knows them, width, height, state and resizable. set_window replies with the same fields.
|
||||
// knows them, width, height, state and resizable. window_set replies with the same fields.
|
||||
nlohmann::json window_entry(wxTopLevelWindow& window, bool modal);
|
||||
// The web views a snapshot with `options` walks whose pages it lists: shown ones under its
|
||||
// roots, and while a modal dialog is open only those in the topmost one. `behind` gets the
|
||||
@@ -303,10 +303,10 @@ std::string no_modal_dialog(ModalTracker& modals);
|
||||
// What a locator's `within` names `w`'s window by: its top-level window's title, empty for the main
|
||||
// window, whose title follows the project name.
|
||||
std::string within_of(wxWindow* w);
|
||||
// The shown popups that opened from `top` or from its widgets, which list_widgets lists after it.
|
||||
// The shown popups that opened from `top` or from its widgets, which widget_list lists after it.
|
||||
std::vector<wxWindow*> popups_of(wxWindow* top);
|
||||
|
||||
// How an agent reads a widget. list_widgets and a modal dialog's description (describe_dialog()) both
|
||||
// How an agent reads a widget. widget_list and a modal dialog's description (describe_dialog()) both
|
||||
// read controls through these, so they say the same about each one. UI thread only.
|
||||
|
||||
// The role a window plays for an agent: button, checkbox, toggle, radio, combo, choice, spin, text,
|
||||
@@ -353,7 +353,7 @@ struct SelectorChoices
|
||||
};
|
||||
std::optional<SelectorChoices> selector_choices(wxWindow* w);
|
||||
|
||||
// Rows of the lists list_widgets reads: wxDataViewCtrl (every row, collapsed branches too), wxListBox and
|
||||
// Rows of the lists widget_list reads: wxDataViewCtrl (every row, collapsed branches too), wxListBox and
|
||||
// wxCheckListBox, wxListCtrl, Orca's DropDown, wxGrid (read-only) and the Design tab's DesignRowList.
|
||||
// Empty for other windows. With a `limit`, only shown rows are read (a tree's collapsed branches are
|
||||
// skipped), and at most `limit` of them: what a summary of the list costs, whatever its size.
|
||||
@@ -378,7 +378,7 @@ nlohmann::json input_row(wxWindow& list, const ListRow& row, const std::string&
|
||||
std::vector<GLCanvas3D*> live_canvases();
|
||||
// The Design tab's view once the tab is built, else null.
|
||||
GLCanvas3D* design_canvas();
|
||||
// live_canvases() and the Design view: the canvases list_widgets lists and the input tools find items in and send
|
||||
// live_canvases() and the Design view: the canvases widget_list lists and the input tools find items in and send
|
||||
// input to. The gizmo state and the idle checks read live_canvases(), since the Design view has no
|
||||
// gizmos.
|
||||
std::vector<GLCanvas3D*> ui_canvases();
|
||||
@@ -435,7 +435,7 @@ std::vector<SurfaceMesh> surface_meshes(const std::vector<GLVolume*>&
|
||||
|
||||
// A GL toolbar's items, with the visibility and enabled state the canvas's idle handler gives them
|
||||
// (GLToolbar::update_items_state()) brought up to date first: until that handler runs they keep the
|
||||
// state of the last idle event, so an item a `select_objects` just enabled would still read disabled.
|
||||
// state of the last idle event, so an item an `object_select` just enabled would still read disabled.
|
||||
// `changed` tells whether a state changed, which the canvas has yet to draw.
|
||||
const std::vector<GLToolbarItem*>& toolbar_items(GLToolbar& toolbar, bool* changed = nullptr);
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s
|
||||
else if (shared->generation && shared->generation() != generation)
|
||||
error = "The UI was recreated (language change) before the call ran; it was not run, so it is safe to retry";
|
||||
else if (guard == GuardClass::Mutate && g.modal) {
|
||||
error = "A modal dialog is open; answer it first (list_widgets, answer_dialog)";
|
||||
error = "A modal dialog is open; answer it first (widget_list, dialog_answer)";
|
||||
details = {{"dialogs", g.dialogs}};
|
||||
} else if (guard == GuardClass::Mutate && !shared->running_tools.empty())
|
||||
error = "Busy: " + shared->running_tools.front() + " is still running; only inspection and dialog tools can run now";
|
||||
@@ -139,7 +139,7 @@ nlohmann::json UiInvoker::run(GuardClass guard, const std::string& tool, const s
|
||||
throw ToolFailure("OrcaSlicer is shutting down");
|
||||
if (nlohmann::json dialogs = open_dialogs(); topmost_dialog_is_native(dialogs))
|
||||
throw ToolFailure("A native dialog holds the UI thread until a person answers it, so the call was not run; register "
|
||||
"auto_answer_dialogs before the step that opens one",
|
||||
"dialog_auto_answer before the step that opens one",
|
||||
{{"dialogs", std::move(dialogs)}});
|
||||
throw ToolFailure("The UI thread is busy and did not run the call; it was not run, so it is safe to retry");
|
||||
}
|
||||
@@ -190,7 +190,7 @@ void UiInvoker::require_mutate() const
|
||||
if (m_shared->guards_on_ui) {
|
||||
const GuardState g = m_shared->guards_on_ui();
|
||||
if (g.modal)
|
||||
throw ToolFailure("A modal dialog is open; answer it first (list_widgets, answer_dialog)", {{"dialogs", g.dialogs}});
|
||||
throw ToolFailure("A modal dialog is open; answer it first (widget_list, dialog_answer)", {{"dialogs", g.dialogs}});
|
||||
}
|
||||
if (m_shared->running_tools.size() > 1)
|
||||
throw ToolFailure("Busy: " + m_shared->running_tools.front() +
|
||||
|
||||
@@ -24,7 +24,7 @@ std::string imgui_label_name(const std::string& label);
|
||||
// windows ("Move##gizmo/##body_1A2B3C4D") count as the panel.
|
||||
std::string imgui_window_label(const std::string& window);
|
||||
|
||||
// One line of list_widgets' reply.
|
||||
// One line of widget_list's reply.
|
||||
struct UiNode
|
||||
{
|
||||
std::string ref; // "w12", "m3", "t5", "z2", "g7"
|
||||
@@ -93,7 +93,7 @@ std::string plate_icon_name(int action);
|
||||
// {plate, action} of a bed picking id.
|
||||
std::pair<int, int> plate_icon_of(int picking_id);
|
||||
|
||||
// The refs list_widgets hands out. Ids are never reused, so two clients can't confuse each other's
|
||||
// The refs widget_list hands out. Ids are never reused, so two clients can't confuse each other's
|
||||
// refs; each stores what it points at and how to tell whether that still exists, plus the UI
|
||||
// generation it was taken in (a rebuilt main window invalidates every ref).
|
||||
template<class Payload> class RefTable
|
||||
@@ -118,11 +118,11 @@ public:
|
||||
{
|
||||
auto it = m_entries.find(ref);
|
||||
if (it == m_entries.end()) {
|
||||
err = "Unknown ref " + ref + "; call list_widgets again";
|
||||
err = "Unknown ref " + ref + "; call widget_list again";
|
||||
return nullptr;
|
||||
}
|
||||
if (it->second.generation != generation || (it->second.alive && !it->second.alive())) {
|
||||
err = "Stale ref " + ref + ": the element is gone or the window was rebuilt; call list_widgets again";
|
||||
err = "Stale ref " + ref + ": the element is gone or the window was rebuilt; call widget_list again";
|
||||
return nullptr;
|
||||
}
|
||||
return &it->second.payload;
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
namespace Slic3r { namespace GUI { namespace Mcp {
|
||||
|
||||
// encode_recording's half: finding the system ffmpeg, its command line, running it, and which files
|
||||
// recording_encode's half: finding the system ffmpeg, its command line, running it, and which files
|
||||
// recordings and encodes are using. The bundled FFmpeg only decodes, so the encode runs the system one.
|
||||
// wx-free.
|
||||
|
||||
|
||||
Loaded 100 of 287 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user