From e6250eca57ee5fd73f956bf3b35d41d1e4fba692 Mon Sep 17 00:00:00 2001 From: SoftFever Date: Mon, 23 Nov 2026 00:06:23 +0800 Subject: [PATCH] Let MCP commands name objects, parts and instances by id An agent that read an object's id in object_list could only pass it as a guard beside the index, and the index moves whenever objects are deleted, split or reordered; an id passed as an index was refused without saying what it was. Every command that names an object, a part or an instance now takes its index or its id, both together still a guard, and object_list gives each instance's id too. An id given as an index is refused with what that id names, and recorded replays keep naming targets by index, so they still run in a new session. --- docs/HLSD/mcp-server.md | 54 +++-- docs/HLSD/mcp-tools.md | 12 +- scripts/CAD/tool_atlas.json | 5 +- src/slic3r/GUI/CAD/DesignOffer.hpp | 23 ++- src/slic3r/GUI/CommandCatalog.hpp | 3 +- src/slic3r/GUI/Mcp/McpArguments.cpp | 9 + src/slic3r/GUI/Mcp/McpArguments.hpp | 17 ++ src/slic3r/GUI/Mcp/McpCore.cpp | 4 +- src/slic3r/GUI/Mcp/McpJournal.cpp | 15 +- src/slic3r/GUI/Mcp/McpJournal.hpp | 16 +- src/slic3r/GUI/Mcp/McpServerInfo.cpp | 4 +- src/slic3r/GUI/Mcp/McpTargets.cpp | 224 ++++++++++++++++++--- src/slic3r/GUI/Mcp/McpTargets.hpp | 29 ++- src/slic3r/GUI/Mcp/McpTools.hpp | 34 ++-- src/slic3r/GUI/Mcp/McpToolsApi.cpp | 3 +- src/slic3r/GUI/Mcp/McpToolsCad.cpp | 6 +- src/slic3r/GUI/Mcp/McpToolsCommon.cpp | 38 +++- src/slic3r/GUI/Mcp/McpToolsConfig.cpp | 12 +- src/slic3r/GUI/Mcp/McpToolsGizmos.cpp | 10 +- src/slic3r/GUI/Mcp/McpToolsLayers.cpp | 4 +- src/slic3r/GUI/Mcp/McpToolsProject.cpp | 2 +- src/slic3r/GUI/Mcp/McpToolsScene.cpp | 89 ++++---- tests/automation/test_mcp_core.cpp | 7 +- tests/data/command_catalog.json | 176 ++++++++++------ tests/slic3rutils/test_command_catalog.cpp | 14 +- tests/slic3rutils/test_mcp_cad.cpp | 4 + tests/slic3rutils/test_mcp_scene.cpp | 118 ++++++++++- tests/slic3rutils/test_mcp_tools.cpp | 75 ++++--- tools/mcp/test-entries/gizmos.md | 4 +- tools/mcp/test-entries/objects.md | 57 +++++- tools/mcp/test_gizmos.py | 2 +- tools/mcp/test_objects.py | 177 +++++++++++++++- 32 files changed, 963 insertions(+), 284 deletions(-) diff --git a/docs/HLSD/mcp-server.md b/docs/HLSD/mcp-server.md index 39663ea54e..37327e9f8e 100644 --- a/docs/HLSD/mcp-server.md +++ b/docs/HLSD/mcp-server.md @@ -116,9 +116,9 @@ job, that a call with exactly a Speed Dial action's arguments may ask as a perso runs from its arguments, say how a gizmo opens and is driven (and that `gizmo_pick_file` only stands in for a file picker inside one, since its name draws agents to it for any gizmo work), that the camera turns with `view_set` rather than a drag, and which indices are 0-based. -They say what the Speed Dial is, the app's command palette, since descriptions name it without saying, and what -the expected ids are (`object_id`, `part_id` and the `*_ids` lists: optional guards, refusing a call whose index -now names another object or part), once, where each of the many schemas that take one only names it. What one +They say what the Speed Dial is, the app's command palette, since descriptions name it without saying, and that an +object, part or instance is named by index or by the id `object_list` gives, both together a guard, once, where each +of the many schemas that take an id only names it. What one command's description says, such as how `recording_start` records, stays there. ## Security, token and discovery @@ -680,7 +680,7 @@ asks they reply `blocked_by_dialog`. **Targets and the selection.** A command that acts on objects, instances or parts takes them in its arguments, read by one resolver (`Mcp::resolve_targets()`, `McpTargets.hpp`): `objects`, `instances` (`[[object, instance], ...]`) and `parts` (`[[object, part], ...]`), or for a command of one target -`object`, `instance` and `part`, each beside its expected ids (below). Every index is checked before +`object`, `instance` and `part`, each by index or by id (below). Every index is checked before anything changes, and naming one target two ways, an instance or a part without its object, and empty lists are refused. With none of them the targets are what is selected in the Prepare view (`Ops::shown_prepare_canvas()` shows that view and loads its scene first): every instance of an object @@ -732,20 +732,36 @@ plugin's grants; and through what they run `action_run`, `tool_call`, `replay_run` and `script_run`, which has the app's access to the computer. No client is known to ask on it. `idempotent`: the same call again changes nothing more. -The commands that take targets take expected ids beside them (`target_props()`): `object_id` beside an -`object`, and where they take a part index a `part_id`, as `object_transform`, `part_add`, -`object_set_height_ranges`, `object_set_variable_layer_height` and `settings_set`'s object and part targets -do; and beside lists `object_ids`, `instance_object_ids` and `part_ids`, one per entry of `objects`, -`instances` and `parts`, as `object_select`, `object_delete` and the other commands of several targets do: -the `ObjectID` values `object_list` reports as `id`, which `orca.host` shows too. `check_expected_ids()` -refuses the call before anything changes when the index names another object -or part now, so a replay or script addresses what it read. `object_list`' description says what the ids are for -and names the commands that take them, so each property only points back at it. Ids are allocated per -process, so a command that takes them names them in its `id_args`, which `with_expected_ids()` reads from -its schema where the command is registered, and the core gives the journal its calls without them -(`without_expected_ids()`, which looks the command up in the catalog), through `tool_call` and inline -`replay_run` steps too, and a replay addresses by index; a `script_run` step's code and `args`, and a plugin -operation's own arguments, are kept as written. +Every argument that names an object, a part or an instance by index has a twin that names it by id +(`kIdArguments`, `McpArguments.hpp`): the `ObjectID` values `object_list` reports as `id`, which `orca.host` +shows too. Beside one target (`target_props()`) they are `object_id`, `part_id` and `instance_id`, as +`object_transform`, `part_add`, `object_set_height_ranges`, `object_set_variable_layer_height` and +`settings_set`'s object and part targets take them; beside lists `object_ids`, `part_ids` and `instance_ids`, +one per entry, as `object_select`, `object_delete` and the other commands of several targets do; and outside +the targets `object_arrange`'s `fill_object_id`, `object_order`'s `order_ids` and the Design tab's +`commit_to_plate`'s `replace_ids`. The index is what the app itself works by, a place in its lists, and it moves +when a delete, split, assemble or reorder moves the things before it; the id stays with its object, part or +instance for as long as the app holds it, and is allocated anew when a project is opened. So an agent may keep +the id it read across the calls that move indices, and a stale id is refused where a stale index would quietly +name another object. A part's or an instance's id names its object too. + +A call gives a target by index, by id, or both, the id then a guard. A command that takes ids names them in its +`id_args`, which `with_target_ids()` reads from its schema where the command is registered, and its function +then reads a call's ids as their indices (`with_indices()`, on the UI thread, just before the command runs) and +runs the command's own function on the indices with the ids beside them: what the command reads is the index, +and `check_expected_ids()` refuses the call where the index names another object, part or instance than its id +by the time it acts, before anything changes. `fill_object_id`, `order_ids` and `replace_ids` given with their +indices are checked by `with_indices()` itself, as no reading of the targets reads them. An id the model has +nothing with is refused with `invalid_argument`, and so is an index out of range that is an id the model has, +with what that id names, since an agent that read `"id": 147` beside `"index": 1` may pass the one for the +other. Ids are allocated per process, so a replay addresses by index: `with_target_ids()` gives the journal the +call with the indices its ids named, and the core gives the journal every call without the ids that stand beside +their indices (`without_guard_ids()`, which looks the command up in the catalog), through `tool_call`, +`action_run` and inline `replay_run` steps too. An id with no index beside it stays, so that a step the +journal records before its command has run, or a replay step written with ids, still names its target, and +such a replay runs only in the session that made it; a `script_run` step's code and `args`, and a plugin +operation's own arguments, are kept as written. `object_list`' description says what the ids are for, so each +property only names what it is. Descriptions keep one order: what the tool does, the arguments that change it, `Reply:` with the fields it has, then edge cases. They mark as code the names an agent passes or reads (arguments, reply @@ -754,7 +770,7 @@ word still parses: "unless `silent` is true"; a generated list of names marks ea of `settings_get` and `settings_set`, `widget_click`'s web pages). What several tools share is written once, since every session loads the whole tool list: the locator grammar in `widget_list`'s description, which hands out the refs, each `target` giving two examples and pointing there; the paging shape, that a -ref stays good across listings and what an expected id does in the server instructions. +ref stays good across listings and that an id names what its index does in the server instructions. An argument name means one thing across the tools, so what an agent learns from one tool holds for the next. `target` is the window or element a UI tool acts on (a ref, a locator, or `main`, `dialog` diff --git a/docs/HLSD/mcp-tools.md b/docs/HLSD/mcp-tools.md index 81ce4f6739..0b2a117fc9 100644 --- a/docs/HLSD/mcp-tools.md +++ b/docs/HLSD/mcp-tools.md @@ -361,11 +361,13 @@ for every command (`Mcp::resolve_targets()`, `McpTargets.hpp`): object is selected. - **Checked first.** Every index is checked before anything changes; naming one target two ways, an instance or a part without its object, and an empty list are refused. -- **Expected ids.** Beside each index a command takes the id `object_list` reports for it: `object_id` and - `part_id` beside one target, `object_ids`, `instance_object_ids` and `part_ids` beside lists, one per entry. - A call whose index names another object or part now is refused before anything changes, so a script - addresses what it read. Ids belong to one process, so the journal records calls without them and a replay - addresses by index. +- **By index or by id.** Every index a command takes has a twin that takes the id `object_list` reports + for the same thing: `object_id`, `part_id` and `instance_id` beside one target, `object_ids`, `part_ids` and + `instance_ids` beside lists, and `fill_object_id`, `order_ids` and `replace_ids`. An id stays with its object, + part or instance when a delete, split or reorder moves the indices, so a call may name a target by id alone; + given with its index, the id is a guard, and a call whose index names another thing now is refused before + anything changes. Ids belong to one process, so the journal records each call with the indices its ids named + and a replay addresses by index. - **The reply names what was acted on** (`objects`, `instances`, `parts`, each with its index, id and name), so a caller that gave no targets learns what the selection was. A command that makes, removes or renumbers things replies with their indices as they are afterwards. diff --git a/scripts/CAD/tool_atlas.json b/scripts/CAD/tool_atlas.json index e61e3cdd9f..ce8469c6e5 100644 --- a/scripts/CAD/tool_atlas.json +++ b/scripts/CAD/tool_atlas.json @@ -4337,10 +4337,11 @@ "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 (object_list 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, object_id, 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": "object_list 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."}, + {"name": "replace_ids", "type": "array", "default": [], "description": "replace by the objects' ids in object_list."} ], "examples": [ { diff --git a/src/slic3r/GUI/CAD/DesignOffer.hpp b/src/slic3r/GUI/CAD/DesignOffer.hpp index 3744d9231c..fc7c6f1fe6 100644 --- a/src/slic3r/GUI/CAD/DesignOffer.hpp +++ b/src/slic3r/GUI/CAD/DesignOffer.hpp @@ -1334,17 +1334,18 @@ static const DesignTool kDesignTools[] = { "{\"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 (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}, + "_list index after replace, object_id, name, parts: how many), bodies_sent, bodies_hidden, replac" + "ed.\",\"params\":[{\"name\":\"mode\",\"type\":\"string\",\"default\":\"\",\"enum\":[\"assembly\",\"bodies\"],\"descrip" + "tion\":\"assembly: one object with a part per body; bodies: an object per body. Default: the Commi" + "t button's mode, which this leaves as it is.\"},{\"name\":\"replace\",\"type\":\"array\",\"default\":[],\"de" + "scription\":\"object_list indices to delete in the same undo step, such as an earlier commit. Thei" + "r settings, modifiers and paint go with them.\"},{\"name\":\"replace_ids\",\"type\":\"array\",\"default\":[" + "],\"description\":\"replace by the objects' ids in object_list.\"}],\"examples\":[{\"title\":\"A plate se" + "nt to Prepare as one object\",\"calls\":[{\"tool\":\"extrude\",\"args\":{\"distance\":5,\"height\":20,\"width\"" + ":20}},{\"tool\":\"commit_to_plate\",\"args\":{}}]},{\"title\":\"Two bodies sent to Prepare as an object e" + "ach\",\"calls\":[{\"tool\":\"extrude\",\"args\":{\"distance\":5,\"height\":20,\"width\":20}},{\"tool\":\"extrude\"," + "\"args\":{\"distance\":10,\"operation\":\"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" diff --git a/src/slic3r/GUI/CommandCatalog.hpp b/src/slic3r/GUI/CommandCatalog.hpp index 0b0c9a91ea..972330c8a5 100644 --- a/src/slic3r/GUI/CommandCatalog.hpp +++ b/src/slic3r/GUI/CommandCatalog.hpp @@ -100,7 +100,8 @@ struct NativeCommand bool allowed_during_operation = false, cancellable = false; // How long a call may run before the reply returns a job envelope and the call continues. int budget_ms = 45000; - // The arguments that carry an expected object or part id, which the session journal leaves out. + // The arguments that name an object, a part or an instance by id (Mcp::kIdArguments): the session journal records + // a call by the indices they named, and leaves out those given beside their indices (Mcp::with_target_ids()). std::vector id_args; // The operations (GUI/Operations) the command reaches when it is given arguments, by function name. A // command in the Speed Dial that takes arguments names them or is on the exception list of the catalog test. diff --git a/src/slic3r/GUI/Mcp/McpArguments.cpp b/src/slic3r/GUI/Mcp/McpArguments.cpp index 7c73767a3c..11790bb2fe 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.cpp +++ b/src/slic3r/GUI/Mcp/McpArguments.cpp @@ -135,6 +135,7 @@ const std::vector>>& argument_al static const std::vector>> aliases{ {"ref", {"target"}}, {"key", {"keys"}}, {"text", {"value"}}, {"action", {"id", "button"}}, {"object", {"objects"}}, {"plate", {"plates"}}, {"filter", {"query"}}, {"settings", {"values"}}, + {"object_id", {"object_ids"}}, {"part_id", {"part_ids"}}, {"instance_id", {"instance_ids"}}, // A capture's output file, where the tool has no path of its own. {"path", {"save_path"}}, // The Design commands' feature index and a feature's card fields, which their functions also read @@ -304,6 +305,14 @@ bool is_whole_number(const json& v) return std::isfinite(d) && d == std::floor(d) && d >= -9223372036854775808.0 && d < 9223372036854775808.0; } +const char* index_argument(const std::string& id) +{ + for (const IdArgument& arg : kIdArguments) + if (id == arg.id) + return arg.index; + return nullptr; +} + bool person_form(const json& args) { return args.is_null() || (args.is_object() && args.empty()); } std::vector person_forms(const NativeCommand& command) diff --git a/src/slic3r/GUI/Mcp/McpArguments.hpp b/src/slic3r/GUI/Mcp/McpArguments.hpp index 9d12b2db34..14776cd1bf 100644 --- a/src/slic3r/GUI/Mcp/McpArguments.hpp +++ b/src/slic3r/GUI/Mcp/McpArguments.hpp @@ -34,6 +34,23 @@ std::string validate_arguments(const nlohmann::json& schema, const nlohmann::jso // undefined. The checks that read an integer argument themselves take the same numbers (target indices, generation). bool is_whole_number(const nlohmann::json& v); +// An argument that names objects, parts or instances by the ids `object_list` gives (`object_id`), and the argument +// that names the same things by index (`object`). A call gives either; given both, the index must still name what the +// id does (a guard against a model that changed since the caller read it). Ids are allocated per process, so a call is +// journaled by index (without_guard_ids()). +struct IdArgument +{ + const char* id; + const char* index; +}; +inline constexpr IdArgument kIdArguments[] = { + {"object_id", "object"}, {"part_id", "part"}, {"instance_id", "instance"}, + {"object_ids", "objects"}, {"part_ids", "parts"}, {"instance_ids", "instances"}, + {"fill_object_id", "fill_object"}, {"order_ids", "order"}, {"replace_ids", "replace"}, +}; +// The index form of id argument `id` (kIdArguments), or nullptr when `id` is none. +const char* index_argument(const std::string& id); + // Whether `args` is a call with no arguments: an object with no members, or null. A Design command and a menu // item's function do their person's form then (they ask, as a person's pick does). bool person_form(const nlohmann::json& args); diff --git a/src/slic3r/GUI/Mcp/McpCore.cpp b/src/slic3r/GUI/Mcp/McpCore.cpp index bd060bee13..7fc2cdd729 100644 --- a/src/slic3r/GUI/Mcp/McpCore.cpp +++ b/src/slic3r/GUI/Mcp/McpCore.cpp @@ -142,7 +142,7 @@ public: { notify(m_observer, [&](CallObserver& o) { o.call_args(m_call, args); }); if (m_journal != nullptr && m_seq != 0) - m_journal->set_args(m_seq, without_expected_ids(m_core.catalog(), m_def.key, std::move(args))); + m_journal->set_args(m_seq, without_guard_ids(m_core.catalog(), m_def.key, std::move(args))); } void begin_operation() override @@ -364,7 +364,7 @@ ToolResult McpCore::run(const NativeCommand& def, const nlohmann::json& args, co // Only client calls are journaled; a replay's own steps run again through the replay, and a plugin's calls // are not the agent's. const bool journal = m_journal != nullptr && parent.empty() && plugin.empty() && def.journal; - const uint64_t seq = journal ? m_journal->begin(def.key, without_expected_ids(m_catalog, def.key, args), + const uint64_t seq = journal ? m_journal->begin(def.key, without_guard_ids(m_catalog, def.key, args), def.guard == GuardClass::Recover && !m_ui.open_dialogs().empty()) : 0; auto finish = [&](ToolResult r) { diff --git a/src/slic3r/GUI/Mcp/McpJournal.cpp b/src/slic3r/GUI/Mcp/McpJournal.cpp index 1f14ffcb2e..25141bb036 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.cpp +++ b/src/slic3r/GUI/Mcp/McpJournal.cpp @@ -1,4 +1,5 @@ #include "McpJournal.hpp" +#include "McpArguments.hpp" #include "McpPaths.hpp" #include "McpReplay.hpp" @@ -46,13 +47,18 @@ std::pair called_command(const std::string& tool, json& args } // namespace -json without_expected_ids(const CommandCatalog& catalog, const std::string& command, json args) +json without_guard_ids(const CommandCatalog& catalog, const std::string& command, json args) { if (!args.is_object()) return args; 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"])); + args["args"] = without_guard_ids(catalog, args.value("tool", std::string()), std::move(args["args"])); + return args; + } + if (command == "action_run") { + if (const auto [key, inner] = called_command(command, args); inner != &args) + *inner = without_guard_ids(catalog, key, std::move(*inner)); return args; } if (command == "replay_run") { @@ -66,12 +72,13 @@ json without_expected_ids(const CommandCatalog& catalog, const std::string& comm if (args.contains("replay") && args["replay"].is_object() && args["replay"].contains("steps") && args["replay"]["steps"].is_array()) for (json& step : args["replay"]["steps"]) if (step.is_object() && step.contains("args")) - step["args"] = without_expected_ids(catalog, step.value("tool", std::string()), std::move(step["args"])); + step["args"] = without_guard_ids(catalog, step.value("tool", std::string()), std::move(step["args"])); return args; } if (const std::shared_ptr def = catalog.lookup(command)) for (const std::string& key : def->id_args) - args.erase(key); + if (const char* index = index_argument(key); index != nullptr && args.contains(index)) + args.erase(key); return args; } diff --git a/src/slic3r/GUI/Mcp/McpJournal.hpp b/src/slic3r/GUI/Mcp/McpJournal.hpp index 0d4e55fec7..dcb8fc1d1d 100644 --- a/src/slic3r/GUI/Mcp/McpJournal.hpp +++ b/src/slic3r/GUI/Mcp/McpJournal.hpp @@ -13,12 +13,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 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); +// `args` of a call of `command` as the journal records them: without each of the command's id_args whose index form +// (kIdArguments) the call gives too, as ids are allocated per process and a replay addresses by index. An id the call +// gives alone stays, so that the step still names its target, until the command records the index it named +// (with_target_ids()); a replay that keeps one runs only in the session that made it. So are a tool_call call's +// arguments for its target, an action_run call's for its command 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_guard_ids(const CommandCatalog& catalog, const std::string& command, nlohmann::json args); // 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 @@ -34,7 +36,7 @@ nlohmann::json without_expected_ids(const CommandCatalog& catalog, const std::st // 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 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(). +// through without_guard_ids(). class Journal { public: diff --git a/src/slic3r/GUI/Mcp/McpServerInfo.cpp b/src/slic3r/GUI/Mcp/McpServerInfo.cpp index 6e4bdd1e37..f57712c064 100644 --- a/src/slic3r/GUI/Mcp/McpServerInfo.cpp +++ b/src/slic3r/GUI/Mcp/McpServerInfo.cpp @@ -41,8 +41,8 @@ const char* kInstructions = "from its arguments; a dialog it still opens (`preset_export`'s always) is in its description.\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" - "- `object_id`, `part_id` and the `*_ids` lists are optional guards, the ids `object_list` reports: a call whose " - "index now names another object or part is refused.\n" + "- An object, part or instance takes its index or its `object_list` id (`object` or `object_id`, `parts` or " + "`part_ids`); given both, they must agree.\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" diff --git a/src/slic3r/GUI/Mcp/McpTargets.cpp b/src/slic3r/GUI/Mcp/McpTargets.cpp index 3ff0853a30..ffed29499d 100644 --- a/src/slic3r/GUI/Mcp/McpTargets.cpp +++ b/src/slic3r/GUI/Mcp/McpTargets.cpp @@ -17,7 +17,9 @@ #include #include #include +#include #include +#include #include #include @@ -28,8 +30,8 @@ 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"}; +constexpr const char* kTargetArgs[] = {"object", "objects", "object_id", "object_ids", "instance", "instances", "instance_id", + "instance_ids", "part", "parts", "part_id", "part_ids"}; template void add_once(std::vector& list, const T& item) { @@ -65,6 +67,73 @@ std::int64_t index_among(const json& v, std::size_t count) return d >= 0 && d < double(count) ? std::int64_t(d) : -1; } +// The id a call gives as `v`: a whole number from 0, as the schema's integer type takes one, else nothing. +std::optional as_id(const json& v) +{ + if (v.is_number_unsigned()) + return v.get(); + if (v.is_number_integer()) + return v.get() >= 0 ? std::optional(std::uint64_t(v.get())) : std::nullopt; + if (is_whole_number(v) && v.get() >= 0) + return std::uint64_t(v.get()); + return std::nullopt; +} + +// Where the object, part or instance with an id is: its object's index, and a part's or an instance's index in that +// object (-1 for an object). Ids are unique across objects, parts and instances, so at most one finder finds an id. +struct Place +{ + int object = -1; + int member = -1; +}; + +std::optional find_object(const Model& model, std::uint64_t id) +{ + for (std::size_t i = 0; i < model.objects.size(); ++i) + if (model.objects[i]->id().id == id) + return Place{int(i), -1}; + return std::nullopt; +} + +std::optional find_part(const Model& model, std::uint64_t id) +{ + for (std::size_t i = 0; i < model.objects.size(); ++i) + for (std::size_t j = 0; j < model.objects[i]->volumes.size(); ++j) + if (model.objects[i]->volumes[j]->id().id == id) + return Place{int(i), int(j)}; + return std::nullopt; +} + +std::optional find_instance(const Model& model, std::uint64_t id) +{ + for (std::size_t i = 0; i < model.objects.size(); ++i) + for (std::size_t j = 0; j < model.objects[i]->instances.size(); ++j) + if (model.objects[i]->instances[j]->id().id == id) + return Place{int(i), int(j)}; + return std::nullopt; +} + +// What a refusal of index `v`, out of range, adds when `v` is the id of an object, a part or an instance: the agent +// that read `"id": 147` in object_list and passed it as an index learns what that id names, so that its next call +// can name it by id. Empty when `v` is no id the model has. +std::string id_hint(const Model& model, const json& v) +{ + const std::optional id = as_id(v); + if (!id) + return {}; + const std::string is = "; " + std::to_string(*id) + " is the id of "; + if (const std::optional at = find_object(model, *id)) + return is + "object " + std::to_string(at->object) + " (\"" + model.objects[std::size_t(at->object)]->name + + "\"), which `object_id` or `object_ids` takes"; + if (const std::optional at = find_part(model, *id)) + return is + "part " + std::to_string(at->member) + " of object " + std::to_string(at->object) + + ", which `part_id` or `part_ids` takes"; + if (const std::optional at = find_instance(model, *id)) + return is + "instance " + std::to_string(at->member) + " of object " + std::to_string(at->object) + + ", which `instance_id` or `instance_ids` takes"; + return {}; +} + // The checks of a target's indices against the model, with the texts object_select gives, each naming the index as // the call gave it. struct IndexCheck @@ -77,7 +146,7 @@ struct IndexCheck const std::int64_t index = index_among(v, model.objects.size()); if (index < 0) throw ToolFailure("object index " + v.dump() + " is out of range (the project has " + - index_range("object", model.objects.size()) + ")", + index_range("object", model.objects.size()) + ")" + id_hint(model, v), {{"code", "invalid_argument"}}); return int(index); } @@ -90,7 +159,7 @@ struct IndexCheck const std::int64_t index = index_among(v, count); if (index < 0) throw ToolFailure("object " + std::to_string(owner) + " has no " + (instance ? "instance " : "part ") + v.dump() + - " (it has " + index_range(instance ? "instance" : "part", count) + ")", + " (it has " + index_range(instance ? "instance" : "part", count) + ")" + id_hint(model, v), {{"code", "invalid_argument"}}); return int(index); } @@ -106,8 +175,8 @@ struct IndexCheck } }; -// 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. +// The ids `ids_key` expects for the entries of `list_key`, one each, checked against `expected` (the object, part or +// instance each entry names) as check_expected_ids() checks one. template 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) { @@ -120,6 +189,7 @@ template void check_ids(const json& args, const char* list_key, expected(k, json{{id_key, ids[k]}}); } +// The targets `args` name by index, with_indices() having read those named by id as their indices. Targets named_targets(const Model& model, const json& args, unsigned kinds) { using Forms = std::pair; @@ -133,25 +203,25 @@ Targets named_targets(const Model& model, const json& args, unsigned kinds) if (args.contains("object")) { const int index = check.object(args.at("object")); const ModelObject& object = *model.objects[std::size_t(index)]; - check_expected_ids(object, nullptr, args); + check_expected_ids(object, nullptr, nullptr, args); if ((kinds & kParts) && args.contains("part")) { const int part = check.member(index, args.at("part"), false); - check_expected_ids(object, object.volumes[std::size_t(part)], args); + check_expected_ids(object, object.volumes[std::size_t(part)], nullptr, args); out.parts.emplace_back(index, part); } else if ((kinds & kInstances) && args.contains("instance")) { const int instance = check.member(index, args.at("instance"), true); + check_expected_ids(object, nullptr, object.instances[std::size_t(instance)], args); out.instances.emplace_back(index, instance); } else if (kinds & kObjects) { - if (args.contains("part_id")) - throw ToolFailure("part_id goes with part", {{"code", "invalid_argument"}}); 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"), {{"code", "invalid_argument"}}); } } else { - for (const char* key : {"instance", "part", "object_id", "part_id"}) + // An id names its object too (with_indices()), so only an index can lack one. + for (const char* key : {"instance", "part"}) if (args.contains(key)) - throw ToolFailure(std::string(key) + " goes with object", {{"code", "invalid_argument"}}); + throw ToolFailure(std::string(key) + " goes with object or object_id", {{"code", "invalid_argument"}}); } // Several targets, each checked with its expected id before any is taken. @@ -170,14 +240,15 @@ Targets named_targets(const Model& model, const json& args, unsigned kinds) 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_expected_ids(*model.objects[std::size_t(object_list[k])], nullptr, 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, "instances", "instance_ids", "instance_id", instance_list.size(), [&](std::size_t k, const json& id) { + const ModelObject& object = *model.objects[std::size_t(instance_list[k].first)]; + check_expected_ids(object, nullptr, object.instances[std::size_t(instance_list[k].second)], 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); + check_expected_ids(object, object.volumes[std::size_t(part_list[k].second)], nullptr, id); }); for (int index : object_list) add_once(out.objects, index); @@ -247,31 +318,127 @@ std::vector target_props(unsigned kinds, bool one) std::vector 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("object_id", id_prop("object")); + if (kinds & kInstances) { out.emplace_back("instance", json{{"type", "integer"}, {"minimum", 0}, {"description", "An instance of the object (`object_list`)."}}); + out.emplace_back("instance_id", id_prop("instance")); + } 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")); + out.emplace_back("part_id", 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"}}, "Optional guard: the objects' ids in `object_list`, one each.")); + out.emplace_back("object_ids", array_prop({{"type", "integer"}}, "The objects' ids in `object_list`.")); } if (kinds & kInstances) { out.emplace_back("instances", array_prop({{"type", "array"}}, "`[[object, instance], ...]`")); - out.emplace_back("instance_object_ids", array_prop({{"type", "integer"}}, "Optional guard: the ids in `object_list` of the " - "instances' objects, one each.")); + out.emplace_back("instance_ids", array_prop({{"type", "integer"}}, "The instances' ids in `object_list`.")); } if (kinds & kParts) { out.emplace_back("parts", array_prop({{"type", "array"}}, "`[[object, part], ...]`")); - out.emplace_back("part_ids", array_prop({{"type", "integer"}}, "Optional guard: the parts' ids in `object_list`, one each.")); + out.emplace_back("part_ids", array_prop({{"type", "integer"}}, "The parts' ids in `object_list`.")); } return out; } +json with_indices(const Model& model, json args) +{ + if (!args.is_object()) + return args; + const auto id_in = [](const json& v, const std::string& key) { + if (const std::optional id = as_id(v)) + return *id; + throw ToolFailure(key + " takes the ids `object_list` gives", {{"code", "invalid_argument"}}); + }; + const auto object_of = [&](const json& v, const std::string& key) { + const std::uint64_t id = id_in(v, key); + if (const std::optional at = find_object(model, id)) + return *at; + throw ToolFailure("No object has id " + std::to_string(id) + ": `object_list` gives the ids there are now", + {{"code", "invalid_argument"}}); + }; + const auto part_of = [&](const json& v, const std::string& key) { + const std::uint64_t id = id_in(v, key); + if (const std::optional at = find_part(model, id)) + return *at; + throw ToolFailure("No part has id " + std::to_string(id) + ": `object_list {detail: true}` gives the ids there are now", + {{"code", "invalid_argument"}}); + }; + const auto instance_of = [&](const json& v, const std::string& key) { + const std::uint64_t id = id_in(v, key); + if (const std::optional at = find_instance(model, id)) + return *at; + throw ToolFailure("No instance has id " + std::to_string(id) + ": `object_list` gives the ids there are now", + {{"code", "invalid_argument"}}); + }; + + // One target: its object by index or id, and a part or an instance of it by index or id. A part's or an instance's + // id names its object too, which must be the object the call names, if it names one. + if (args.contains("object_id") && !args.contains("object")) + args["object"] = object_of(args["object_id"], "object_id").object; + for (const auto& [id_key, index_key] : {std::pair{"part_id", "part"}, {"instance_id", "instance"}}) { + if (!args.contains(id_key)) + continue; + const Place at = std::string(id_key) == "part_id" ? part_of(args[id_key], id_key) : instance_of(args[id_key], id_key); + if (!args.contains("object")) + args["object"] = at.object; + else if (index_among(args["object"], model.objects.size()) != at.object) + throw ToolFailure(std::string(id_key) + " " + args[id_key].dump() + " is of object " + std::to_string(at.object) + + ", not of object " + args["object"].dump(), + {{"code", "invalid_argument"}}); + if (!args.contains(index_key)) + args[index_key] = at.member; + } + + // Several targets: a list of ids gives the list of indices it stands for, entry by entry. + const auto list = [&](const char* ids_key, const char* index_key, const auto& index_of) { + if (!args.contains(ids_key) || args.contains(index_key) || !args[ids_key].is_array()) + return; + json indices = json::array(); + for (const json& v : args[ids_key]) + indices.push_back(index_of(v)); + args[index_key] = std::move(indices); + }; + list("object_ids", "objects", [&](const json& v) { return json(object_of(v, "object_ids").object); }); + list("instance_ids", "instances", [&](const json& v) { + const Place at = instance_of(v, "instance_ids"); + return json::array({at.object, at.member}); + }); + list("part_ids", "parts", [&](const json& v) { + const Place at = part_of(v, "part_ids"); + return json::array({at.object, at.member}); + }); + + // The arguments that name objects outside the targets: given by id, the indices; given both ways, the ids guard the + // indices here, as no reading of the targets checks them. + for (const auto& [ids_key, index_key, one] : + {std::tuple{"fill_object_id", "fill_object", true}, {"order_ids", "order", false}, + {"replace_ids", "replace", false}}) { + if (!args.contains(ids_key)) + continue; + const json ids = one ? json::array({args[ids_key]}) : args[ids_key]; + if (!ids.is_array()) + continue; + if (!args.contains(index_key)) { + json indices = json::array(); + for (const json& v : ids) + indices.push_back(object_of(v, ids_key).object); + args[index_key] = one ? indices.front() : std::move(indices); + continue; + } + const json given = one ? json::array({args[index_key]}) : args[index_key]; + if (!given.is_array() || given.size() != ids.size()) + throw ToolFailure(std::string(ids_key) + " takes one id per entry of " + index_key, {{"code", "invalid_argument"}}); + for (std::size_t k = 0; k < ids.size(); ++k) + if (const std::int64_t index = index_among(given[k], model.objects.size()); index >= 0) + check_expected_ids(*model.objects[std::size_t(index)], nullptr, nullptr, json{{"object_id", ids[k]}}); + } + return args; +} + json with_targets(json schema, unsigned kinds, bool one) { for (Property& property : target_props(kinds, one)) @@ -295,7 +462,7 @@ Ops::Outcome resolve_targets(const Model& model, const Selection* selec { Targets targets; if (names_targets(args)) { - targets = named_targets(model, args, kinds); + targets = named_targets(model, with_indices(model, args), kinds); } else { Ops::Outcome selected = selected_targets(model, selection, kinds); if (!selected) @@ -318,8 +485,13 @@ json targets_reply(const Model& model, const Targets& targets) 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}}); + if (const ModelObject* object = object_at(index)) { + json entry{{"object", index}, {"instance", instance}, {"object_id", object->id().id}, {"name", object->name}}; + // A deleted instance is named by the index it had, which the object may not have now. + if (instance >= 0 && std::size_t(instance) < object->instances.size()) + entry["instance_id"] = object->instances[std::size_t(instance)]->id().id; + instances.push_back(std::move(entry)); + } 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}, diff --git a/src/slic3r/GUI/Mcp/McpTargets.hpp b/src/slic3r/GUI/Mcp/McpTargets.hpp index 75bf09e3ac..63f5b3844b 100644 --- a/src/slic3r/GUI/Mcp/McpTargets.hpp +++ b/src/slic3r/GUI/Mcp/McpTargets.hpp @@ -39,10 +39,19 @@ enum TargetKind : unsigned { }; // 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. +// them: objects, object_ids, instances ([[object, instance], ...]), instance_ids, parts ([[object, part], ...]) and +// part_ids; or with `one`, for a command of one target, object and object_id, then instance and instance_id, and part +// and part_id, each of the object. Each target is named by index or by id, or by both, the id then a guard. std::vector target_props(unsigned kinds, bool one); + +// `args` with the index form of every object, part and instance they name by id alone (kIdArguments): object_id gives +// object, part_id and instance_id their object and their index in it, object_ids, part_ids and instance_ids the lists +// of indices, and fill_object_id, order_ids and replace_ids, which name objects outside the targets, fill_object, +// order and replace. The ids stay beside the indices: a target's id is checked where the targets are read +// (check_expected_ids()), and fill_object_id, order_ids and replace_ids given with their indices are checked here, as +// no reading of the targets reads them. An id the model has nothing with, a part's or an instance's id of another +// object than the call names, and an id that is no whole number are refused (ToolFailure, invalid_argument). +nlohmann::json with_indices(const Model& model, nlohmann::json args); // `schema` (object_schema()) with target_props(kinds, one) among its properties. nlohmann::json with_targets(nlohmann::json schema, unsigned kinds, bool one); @@ -52,10 +61,11 @@ bool names_targets(const nlohmann::json& args); // 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). +// The targets of `kinds` that `args` name, by index or by id (with_indices()), each once, in the order named. Every +// index is checked to be in range and every id given beside one 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). An index out of range that is +// an id the model has is refused with what that id names. // 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 @@ -64,8 +74,9 @@ bool names_empty_lists(const nlohmann::json& args); Ops::Outcome 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. +// object_id, instance_id, name}], "parts": [{object, part, part_id, name}]}, each key there when `targets` holds that +// kind. The indices, ids and names are as `model` has them now; an instance index the object no longer has (a deleted +// instance's) has no instance_id. nlohmann::json targets_reply(const Model& model, const Targets& targets); } // namespace Mcp diff --git a/src/slic3r/GUI/Mcp/McpTools.hpp b/src/slic3r/GUI/Mcp/McpTools.hpp index 391dcddcac..2fb33da877 100644 --- a/src/slic3r/GUI/Mcp/McpTools.hpp +++ b/src/slic3r/GUI/Mcp/McpTools.hpp @@ -33,6 +33,7 @@ struct Calib_Params; class ConfigOptionDef; class DynamicPrintConfig; class Model; +class ModelInstance; class ModelObject; class ModelVolume; enum class ModelVolumeType : int; @@ -166,20 +167,23 @@ AppActionRunResult menu_reply(const nlohmann::json& reply); // a pick shows nothing more, and a call learns the refusal. AppActionRunResult quiet_refusal(const Ops::Refusal& refusal); -// ---- expected object IDs --------------------------------------------------------------------- +// ---- object, part and instance ids ----------------------------------------------------------- -// 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. Its description only names the guard: what a guard -// does is said once, in the server instructions, rather than in each of the many schemas that have one. -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 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`, -// or `volume`, which its index names now: the model changed since the caller read the index. Call it -// before the tool changes anything. -void check_expected_ids(const ModelObject& object, const ModelVolume* volume, const nlohmann::json& args); +// The schema of an id argument: the id object_list reports for an object, part or instance (`of`), which orca.host +// shows too, so a script addresses what it read. Its description only names what it is: that an id names its target +// in place of the index, or beside it as a guard, is said once, in the server instructions, rather than in each of +// the many schemas that have one. +nlohmann::json id_prop(const char* of); +// `command` with its id_args, the id arguments its schema has (kIdArguments), and with a function that runs the +// command's own on the arguments with the index form of each target the call names by id (with_indices(), read on +// the UI thread just before), and journals the call so: ids are allocated per process, and a replay addresses by +// index (without_guard_ids()). The ids stay beside the indices, so the command checks them where it acts. +NativeCommand with_target_ids(NativeCommand command); +// Refuses the call when `args` names an object_id, part_id or instance_id that is not the id of `object`, `volume` +// or `instance`, which its index names now: the model changed since the caller read the index. Call it before the +// tool changes anything. +void check_expected_ids(const ModelObject& object, const ModelVolume* volume, const ModelInstance* instance, + const nlohmann::json& args); // ---- handler helpers ------------------------------------------------------------------------- @@ -675,8 +679,8 @@ nlohmann::json volume_info(const ModelVolume& volume, std::size_t index); // 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. -// A row is object_summary()'s with `instances` the indices of those instances, or with `detail` in `args` -// object_info()'s with their entries. +// A row is object_summary()'s with `instances` the indices of those instances and `instance_ids` their ids in +// the same order, or with `detail` in `args` object_info()'s with their entries, each with its id. // `plate_of(object, instance)` is the plate an instance is on, or -1, and `plate_names` has a name per // plate. Of `args`, plate lists that plate alone, without `outside`, and limit (default 200) and offset // page the objects listed, in the model's order: total counts them, each once, and next_offset is there diff --git a/src/slic3r/GUI/Mcp/McpToolsApi.cpp b/src/slic3r/GUI/Mcp/McpToolsApi.cpp index d2dc098524..7169832239 100644 --- a/src/slic3r/GUI/Mcp/McpToolsApi.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsApi.cpp @@ -252,7 +252,8 @@ const std::map& classes_by_name() // The project. {"object", objects}, {"objects", objects}, {"object_id", objects}, {"object_ids", objects}, {"part", objects}, {"parts", objects}, {"part_id", objects}, {"part_ids", objects}, {"instance", objects}, {"instances", objects}, - {"instance_object_ids", objects}, {"fill_object", objects}, {"order", objects}, {"replace", objects}, + {"instance_id", objects}, {"instance_ids", objects}, {"fill_object", objects}, {"fill_object_id", objects}, + {"order", objects}, {"order_ids", objects}, {"replace", objects}, {"replace_ids", objects}, {"plate", plates}, {"plates", plates}, {"filament_slot", slots}, {"filament", slots}, {"components", slots}, {"merge_into", slots}, {"prime_volume_mode", slots}, diff --git a/src/slic3r/GUI/Mcp/McpToolsCad.cpp b/src/slic3r/GUI/Mcp/McpToolsCad.cpp index bba8e3c90d..c7799b1c33 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCad.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCad.cpp @@ -2851,7 +2851,8 @@ json action_commit_to_plate(DesignPanel* panel, const json& params) json objects = json::array(); for (const ModelObject* o : made) { const auto it = std::find(model.objects.begin(), model.objects.end(), o); - objects.push_back(json{{"index", int(it - model.objects.begin())}, {"name", o->name}, {"parts", o->volumes.size()}}); + objects.push_back(json{{"index", int(it - model.objects.begin())}, {"object_id", o->id().id}, {"name", o->name}, + {"parts", o->volumes.size()}}); } json hidden = json::array(); for (int b = 0; b < int(doc.bodies.size()); ++b) @@ -4214,7 +4215,8 @@ NativeCommand design_command(const DesignTool& t) c.idempotent = c.read_only; c.description = std::move(description); c.examples = doc.at("examples"); - return c; + // commit_to_plate's replace_ids names Prepare's objects by id. + return with_target_ids(std::move(c)); } } // namespace diff --git a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp index 46b9cbacff..58267cbebc 100644 --- a/src/slic3r/GUI/Mcp/McpToolsCommon.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsCommon.cpp @@ -1,5 +1,8 @@ #include "McpTools.hpp" +#include "McpArguments.hpp" +#include "McpTargets.hpp" + #include "libslic3r/Model.hpp" #include "UiInspector.hpp" @@ -303,23 +306,35 @@ json poll_ui(ToolContext& ctx, const std::function& poll, std::chrono::m throw ToolFailure("Timed out waiting for " + what + (undrawn.empty() ? "" : ": " + undrawn)); } -json expected_id_prop(const char* of) +json id_prop(const char* of) { - return {{"type", "integer"}, - {"minimum", 0}, - {"description", std::string("Optional guard: the ") + of + "'s id in `object_list`."}}; + return {{"type", "integer"}, {"minimum", 0}, {"description", std::string("The ") + of + "'s id in `object_list`."}}; } -NativeCommand with_expected_ids(NativeCommand command) +NativeCommand with_target_ids(NativeCommand command) { const json properties = command.input_schema.value("properties", json::object()); - for (const char* name : {"object_id", "part_id", "object_ids", "part_ids", "instance_object_ids"}) - if (properties.contains(name)) - command.id_args.emplace_back(name); + for (const IdArgument& arg : kIdArguments) + if (properties.contains(arg.id)) + command.id_args.emplace_back(arg.id); + if (command.id_args.empty()) + return command; + command.run = [run = std::move(command.run), ids = command.id_args](const json& args, ToolContext& ctx) { + const auto by_id = [&args](const std::string& id) { return args.contains(id); }; + if (!args.is_object() || std::none_of(ids.begin(), ids.end(), by_id)) + return run(args, ctx); + json indexed; + ctx.run_ui([&] { + indexed = with_indices(ui_plater().model(), args); + return json(); + }); + ctx.set_journal_args(indexed); + return run(indexed, ctx); + }; return command; } -void check_expected_ids(const ModelObject& object, const ModelVolume* volume, const json& args) +void check_expected_ids(const ModelObject& object, const ModelVolume* volume, const ModelInstance* instance, const json& args) { if (args.contains("object_id") && args["object_id"].get() != object.id().id) throw ToolFailure("The object at this index is now \"" + object.name + "\" (id " + std::to_string(object.id().id) + @@ -331,6 +346,11 @@ void check_expected_ids(const ModelObject& object, const ModelVolume* volume, co "), not the expected id " + std::to_string(args["part_id"].get()) + ": object_list again", {{"id", volume->id().id}}); + if (instance != nullptr && args.contains("instance_id") && args["instance_id"].get() != instance->id().id) + throw ToolFailure("The instance of \"" + object.name + "\" at this index is now id " + std::to_string(instance->id().id) + + ", not the expected id " + std::to_string(args["instance_id"].get()) + + ": object_list again", + {{"id", instance->id().id}}); } }}} // namespace Slic3r::GUI::Mcp diff --git a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp index de7ab9c498..8b4e6bc335 100644 --- a/src/slic3r/GUI/Mcp/McpToolsConfig.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsConfig.cpp @@ -3166,7 +3166,7 @@ void register_config_tools(CommandCatalog& catalog) })); })); - catalog.add(inspect_tool( + catalog.add(with_target_ids(inspect_tool( "settings_get", L("Read settings"), "Read the settings named: each item has its `value`, as OrcaSlicer writes it, and `meta`: `label`, " "`description` (what the setting does, when to change it), `where` (its settings page and group), `type`, `unit`, " @@ -3194,6 +3194,8 @@ void register_config_tools(CommandCatalog& catalog) {"keys", array_prop({{"type", "string"}}, "Option keys, e.g. `[\"layer_height\", \"wall_loops\"]`.")}, {"object", object_prop}, {"part", part_prop}, + {"object_id", id_prop("object")}, + {"part_id", id_prop("part")}, {"min_z", min_z_prop}, {"max_z", max_z_prop}, {"filament_slot", {{"type", "integer"}, {"minimum", 1}, @@ -3213,9 +3215,9 @@ void register_config_tools(CommandCatalog& catalog) ui_plater(); // the presets and the settings pages exist once the main window does return read_settings(args); })); - })); + }))); - catalog.add(with_expected_ids(mutate_tool( + catalog.add(with_target_ids(mutate_tool( "settings_set", L("Change settings"), "Change settings as typing them into their settings tab would: a type's preset (target global, the default), or " "the overrides of an object, a part or a height range. Values are strings in OrcaSlicer's format (\"15%\", \"0.2\", " @@ -3253,8 +3255,8 @@ void register_config_tools(CommandCatalog& catalog) {"part", part_prop}, {"min_z", min_z_prop}, {"max_z", max_z_prop}, - {"object_id", expected_id_prop("object")}, - {"part_id", expected_id_prop("part")}, + {"object_id", id_prop("object")}, + {"part_id", id_prop("part")}, {"filament_slot", {{"type", "integer"}, {"minimum", 1}, {"description", "Type filament: the slot whose preset is changed, 1-based (default 1). " "The filament tab switches to it, which can ask about the unsaved " diff --git a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp index 694f27b036..f0eb6756c8 100644 --- a/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsGizmos.cpp @@ -254,7 +254,7 @@ json brim_ears_from_args(const json& args) NativeCommand gizmo_command(std::string name, std::string title, std::string description, json schema, EType type, GizmoTargets reading, json examples) { - NativeCommand command = with_expected_ids(mutate_tool(std::move(name), std::move(title), description + kWorkTheGizmo, + NativeCommand command = with_target_ids(mutate_tool(std::move(name), std::move(title), description + kWorkTheGizmo, std::move(schema), [type, reading](const json& args, ToolContext& ctx) { json out = ctx.run_ui([&] { return open_on(args, type, reading); }); settle(ctx); @@ -288,7 +288,7 @@ void register_gizmo_tools(CommandCatalog& catalog) std::vector paint_types; for (const auto& [name, type] : kPaintTypes) paint_types.push_back(name); - NativeCommand paint = with_expected_ids(mutate_tool( + NativeCommand paint = with_target_ids(mutate_tool( "object_paint", L("Paint on an object"), std::string("Open a painting gizmo on an object's instance, the first unless instance is given: type supports opens " "Support Painting, seam Seam Painting, color Color Painting (two filaments or more) and `fuzzy_skin` Paint-on " @@ -348,7 +348,7 @@ void register_gizmo_tools(CommandCatalog& catalog) point["minItems"] = normal["minItems"] = 3; json plane = object_schema({{"point", std::move(point)}, {"normal", std::move(normal)}}, {"point", "normal"}); plane["description"] = "Cut along this plane. Not with z."; - NativeCommand cut = with_expected_ids(mutate_tool( + NativeCommand cut = with_target_ids(mutate_tool( "object_cut", L("Cut"), std::string( "Cut an object's instance, the first unless instance is given, along a plane, as the Cut gizmo's Perform cut does. " @@ -383,7 +383,7 @@ void register_gizmo_tools(CommandCatalog& catalog) {"tool": "object_cut", "args": {"object": 1, "plane": {"point": [100, 100, 10], "normal": [1, 0, 1]}, "keep": "upper"}}]}])json"); catalog.add(reaching({"open_gizmo", "cut_object"}, std::move(cut))); - NativeCommand lay = with_expected_ids(mutate_tool( + NativeCommand lay = with_target_ids(mutate_tool( "object_lay_on_face", L("Lay on face"), std::string( "Lay an object's instance, the first unless instance is given, on one of its faces, as a click on that face in " @@ -417,7 +417,7 @@ void register_gizmo_tools(CommandCatalog& catalog) json ear = object_schema({{"position", array_prop({{"type", "number"}}, "`[x, y]` mm: where on the bed.")}, {"radius", prop("number", "mm. Default: the gizmo's, eight first-layer line widths.")}}, {"position"}); - NativeCommand brim = with_expected_ids(mutate_tool( + NativeCommand brim = with_target_ids(mutate_tool( "object_set_brim_ears", L("Brim ears"), std::string( "Set an object's brim ears from positions on the bed, as the Brim Ears gizmo places them, through the instance " diff --git a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp index c9900b29f5..158c2be248 100644 --- a/src/slic3r/GUI/Mcp/McpToolsLayers.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsLayers.cpp @@ -571,7 +571,7 @@ void register_layer_tools(CommandCatalog& catalog) {"max_z", {{"type", "number"}, {"minimum", 0}, {"description", "Top, mm above the bed."}}}}, {"min_z", "max_z"}); - catalog.add(with_expected_ids(mutate_tool( + catalog.add(with_target_ids(mutate_tool( "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, which `settings_get` and `settings_set` read and write with " @@ -587,7 +587,7 @@ void register_layer_tools(CommandCatalog& catalog) return ToolResult::ok(out); }))); - catalog.add(with_expected_ids(mutate_tool( + catalog.add(with_target_ids(mutate_tool( "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 " diff --git a/src/slic3r/GUI/Mcp/McpToolsProject.cpp b/src/slic3r/GUI/Mcp/McpToolsProject.cpp index 9acafe0c28..076110ec0d 100644 --- a/src/slic3r/GUI/Mcp/McpToolsProject.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsProject.cpp @@ -841,7 +841,7 @@ void register_project_tools(CommandCatalog& catalog) NativeCommand export_ = reaching( {"start_gcode_export", "export_sliced_3mf", "export_model_3mf", "export_stl", "export_toolpaths_obj"}, - with_expected_ids(mutate_tool( + with_target_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 " diff --git a/src/slic3r/GUI/Mcp/McpToolsScene.cpp b/src/slic3r/GUI/Mcp/McpToolsScene.cpp index 34d1aba674..aa1777672a 100644 --- a/src/slic3r/GUI/Mcp/McpToolsScene.cpp +++ b/src/slic3r/GUI/Mcp/McpToolsScene.cpp @@ -254,6 +254,7 @@ json instance_info(const ModelObject& object, std::size_t index) { const ModelInstance& inst = *object.instances[index]; return {{"index", index}, + {"id", inst.id().id}, {"offset", vec3(inst.get_offset())}, {"rotation_deg", degrees(inst.get_rotation())}, {"scale", vec3(inst.get_scaling_factor())}, @@ -904,18 +905,22 @@ json objects_by_plate(const Model& model, const std::vector& plate_ for (std::size_t n = offset; n < total && n - offset < limit; ++n) { const std::size_t i = listed[n]; json item = detail ? object_info(*model.objects[i], i) : object_summary(*model.objects[i], i); - // Each instance's entry with detail, else its index. + // Each instance's entry with detail, else its index, with its id at the same place in instance_ids. const json every = detail ? std::move(item["instances"]) : json(); // The object's row where it has an instance; one without any instance is on no plate either. const auto add_row = [&](int plate, json& into) { - json instances = json::array(); + json instances = json::array(), ids = json::array(); for (std::size_t j = 0; j < on[i].size(); ++j) - if (on[i][j] == plate) + if (on[i][j] == plate) { instances.push_back(detail ? every[j] : json(j)); + ids.push_back(model.objects[i]->instances[j]->id().id); + } if (instances.empty() && (plate >= 0 || !on[i].empty())) return; json row = item; row["instances"] = std::move(instances); + if (!detail) + row["instance_ids"] = std::move(ids); into.push_back(std::move(row)); }; for (json& plate : plates) @@ -1407,7 +1412,7 @@ json plate_objects(int sorted, bool all) if (all || plate == sorted) for (std::size_t i = 0; i < objects.size(); ++i) if (plates.find_instance(int(i), 0) == plate) - order.push_back({{"object", i}, {"name", objects[i]->name}, {"plate", plate}}); + order.push_back({{"object", i}, {"object_id", objects[i]->id().id}, {"name", objects[i]->name}, {"plate", plate}}); return order; } @@ -1735,7 +1740,7 @@ void register_object_menu_commands(CommandCatalog& catalog) }; const std::string text = "Add a text: a part on the selected object, or a new object when nothing is selected. It is created " "in the background (`app_wait {for: \"idle\"}` waits for it), and the Text gizmo opens on it."; - catalog.add(with_expected_ids(menu_command( + catalog.add(with_target_ids(menu_command( "object_add_text", L("Text"), text + " With object, the text becomes a part of that object, which is selected first; type makes it a negative part " "or a modifier, as the object's Add menu does. Reply: only that it ran (`ran`, `level`), since the text is made " @@ -1744,7 +1749,7 @@ void register_object_menu_commands(CommandCatalog& catalog) json::array({action("add_primitive_text", L("Text"), L("Add Primitive"), "menu_obj_text", json::object(), text)}), [](const json& args) { return MenuItems::add_primitive_text(args); }))); - catalog.add(with_expected_ids(menu_command( + catalog.add(with_target_ids(menu_command( "object_add_svg", L("SVG"), "Add an SVG as a new object, or as a part of the selected object. With a path, uses that file without a dialog; the " "part is created in the background (`app_wait {for: \"idle\"}` waits for it), and the SVG gizmo opens on it. With " @@ -1779,7 +1784,7 @@ void register_object_menu_commands(CommandCatalog& catalog) action("obj_delete_all", L("Delete All Objects"), object_section, "delete", {{"all", true}}, "Delete all objects.")}), delete_command); del.input_schema = with_silent(std::move(del.input_schema), person_forms(del)); - catalog.add(reaching({"delete_objects"}, with_expected_ids(std::move(del)))); + catalog.add(reaching({"delete_objects"}, with_target_ids(std::move(del)))); // The Rename dialog's name, which every call but the action's gives. NativeCommand rename = menu_command( @@ -1792,7 +1797,7 @@ void register_object_menu_commands(CommandCatalog& catalog) "Rename the selected object or part (select one) in the Rename dialog; object_rename with a name skips it.")}), rename_command); rename.input_schema = with_silent(std::move(rename.input_schema), person_forms(rename)); - catalog.add(reaching({"rename_object"}, with_expected_ids(std::move(rename)))); + catalog.add(reaching({"rename_object"}, with_target_ids(std::move(rename)))); // The count the dialog asks for, which every call but the actions' gives; delta is the toolbar's + and -. NativeCommand instances = menu_command( @@ -1823,7 +1828,7 @@ void register_object_menu_commands(CommandCatalog& catalog) instances.input_schema["properties"]["silent"]["description"] = "true runs the command without asking; it then needs count or delta. A call with no arguments, or with exactly an " "action's arguments, does what a person's pick of that action does."; - catalog.add(reaching({"set_instance_count"}, with_expected_ids(std::move(instances)))); + catalog.add(reaching({"set_instance_count"}, with_target_ids(std::move(instances)))); NativeCommand separate = menu_command( "object_separate_instances", L("Set as Individual Objects"), @@ -1837,7 +1842,7 @@ void register_object_menu_commands(CommandCatalog& catalog) "of its instances selected, only those. New objects are added last; the reply lists the objects that " "hold those instances (objects).")}), separate_command); - catalog.add(reaching({"separate_instances"}, with_expected_ids(std::move(separate)))); + catalog.add(reaching({"separate_instances"}, with_target_ids(std::move(separate)))); // The answer to Split's Auto-Drop question, which every call but the actions' gives where the split asks it. NativeCommand split = menu_command( @@ -1863,11 +1868,11 @@ void register_object_menu_commands(CommandCatalog& catalog) "Split the selected object into parts.")}), split_command); split.input_schema = with_silent(std::move(split.input_schema), person_forms(split)); - catalog.add(reaching({"split_object"}, with_expected_ids(std::move(split)))); + catalog.add(reaching({"split_object"}, with_target_ids(std::move(split)))); catalog.add(reaching( {"assemble_objects"}, - with_expected_ids(menu_command( + with_target_ids(menu_command( "object_assemble", L("Assemble"), "Assemble two or more objects into one object of parts named Assembly, as Assemble does: those named, else the " "object and instance rows selected in the object list, an instance becoming an object of its own first. Cut objects " @@ -1900,7 +1905,7 @@ void register_object_menu_commands(CommandCatalog& catalog) std::string("Order the current plate's objects by ") + item.what + ", which sets the object list and print order, as the plate menu's Order By does. " "Choosing the order they already have reverses it. Object indices change; the reply " - "lists the new order (order: [{object, name, plate}]) and descending.")); + "lists the new order (order: [{object, object_id, name, plate}]) and descending.")); NativeCommand order = reaching( {"order_objects", "reorder_objects"}, menu_command("object_order", L("Order objects"), @@ -1909,10 +1914,10 @@ void register_object_menu_commands(CommandCatalog& catalog) "Order By does: ascending, or with descending true descending. Called with by alone, as its Speed Dial " "actions, it shows the Prepare view and, as Order By does, reverses the order the objects already have. " "With order in place of by, the plate's objects go in the order given, as dragging them in the object list " - "puts them: order names each of the plate's objects once, by index, and anything else is refused; the " + "puts them: order names each of the plate's objects once, by index (`order_ids` by id), and anything else is refused; the " "other plates' objects keep their order. One undo step, none when the order stays as it was; object indices " "change. Reply: the new order (order: " - "[`{object, name, plate}`]), and descending with by.", + "[`{object, object_id, name, plate}`]), and descending with by.", object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "Order this plate's objects. Default: the current plate."}}}, {"by", enum_prop({"name", "filament", "height", "size"}, "What to order by.")}, {"order", {{"type", "array"}, @@ -1920,6 +1925,10 @@ void register_object_menu_commands(CommandCatalog& catalog) {"items", {{"type", "integer"}, {"minimum", 0}}}, {"description", "In place of by: the plate's objects, by index (`object_list`), each " "once, in the order wanted."}}}, + {"order_ids", {{"type", "array"}, + {"minItems", 1}, + {"items", {{"type", "integer"}, {"minimum", 0}}}, + {"description", "`order` by the objects' ids in `object_list`."}}}, {"descending", prop("boolean", "With by: descending order. Default false.")}, {"all", prop("boolean", "With by: order the objects of every plate. Default false: one plate's.")}}), std::move(order_actions), order_command)); @@ -1928,11 +1937,11 @@ void register_object_menu_commands(CommandCatalog& catalog) check_order_arguments(args); return run(args, ctx); }; - catalog.add(std::move(order)); + catalog.add(with_target_ids(std::move(order))); catalog.add(reaching( {"drop_objects"}, - with_expected_ids(menu_command( + with_target_ids(menu_command( "object_drop", L("Drop to Bed"), "Drop objects or parts onto the bed, as Drop does: those named, each instance and each part that does not rest on " "the bed dropped on its own, else what is selected in the Prepare view, dropped as one by its lowest point. What " @@ -1945,7 +1954,7 @@ void register_object_menu_commands(CommandCatalog& catalog) catalog.add(reaching( {"mirror_objects"}, - with_expected_ids(menu_command( + with_target_ids(menu_command( "object_mirror", L("Mirror objects"), "Mirror objects or parts along an axis, as Mirror > Along X Axis, Y Axis and Z Axis do: those named, each instance " "of an object and the parts of each object in turn, else what is selected in the Prepare view, which Mirror takes " @@ -1962,7 +1971,7 @@ void register_object_menu_commands(CommandCatalog& catalog) catalog.add(reaching( {"center_objects"}, - with_expected_ids(menu_command( + with_target_ids(menu_command( "object_center", L("Center Selected on Plate"), "Centre objects on their plate, as Center does: those named, each plate's as one group on the plate it stands on (an " "object on no plate goes with the current plate's), or all on plate; with none named, what is selected in the " @@ -1978,7 +1987,7 @@ void register_object_menu_commands(CommandCatalog& catalog) catalog.add(reaching( {"scale_to_fit"}, - with_expected_ids(menu_command( + with_target_ids(menu_command( "object_scale_to_fit", L("Scale to Fit Print Volume"), "Scale objects as one to fit the current plate's print volume and move them into it, as Scale to build volume does: " "those named, else the objects and instances selected in the Prepare view. Cut objects and a bed of another shape " @@ -1994,7 +2003,7 @@ void register_object_menu_commands(CommandCatalog& catalog) "is done."; NativeCommand orient = reaching( {"orient_objects"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "object_auto_orient", L("Auto-Orient"), "Turn objects to the orientation that prints best, as Auto-Orient does: those named and those that stand on plates, " "else what is selected in the Prepare view, an instance or a part standing for its object, or every object when " @@ -2090,7 +2099,7 @@ void register_object_menu_commands(CommandCatalog& catalog) type_actions.push_back(action(item.key, item.title, object_section, "", {{"type", item.type}}, item.description)); catalog.add(reaching( {"change_part_type"}, - with_expected_ids(menu_command( + with_target_ids(menu_command( "part_change_type", L("Change a part's type"), "Change what parts are, as Change Type does: those named, else the part rows selected in the object list. type is " "part, negative, modifier, `support_blocker`, `support_enforcer`, or `precise_seam`, a Center precise seam where a seam " @@ -2145,7 +2154,7 @@ void register_object_tools(CommandCatalog& catalog) { NativeCommand printable = reaching( {"set_objects_printable"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "object_set_printable", L("Set printable"), "Mark objects, or some of their instances, printable or not, as the object list's Printable cell does: those " "named (objects: every instance of each; instances: those alone), else what is selected in the Prepare view. An " @@ -2185,7 +2194,7 @@ void register_object_tools(CommandCatalog& catalog) NativeCommand auto_drop = reaching( {"set_objects_auto_drop"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "object_set_auto_drop", L("Set Auto Drop"), "Turn Auto Drop on or off for objects, as the 3D view's Auto Drop does: those named, else the objects of what is " "selected in the Prepare view, an instance or a part standing for its object. With it off an object stays where " @@ -2227,7 +2236,7 @@ void register_object_tools(CommandCatalog& catalog) // changed (a part of an object repaired before the cancel keeps its new mesh). NativeCommand fix = reaching( {"fix_objects"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "object_fix", L("Fix Model"), "Repair objects' meshes, as Fix Model does: those named (objects whole, or parts), the objects on a plate (plate, " "as Fix All on the current plate), every object (all), else what is selected in the Prepare view, an instance " @@ -2289,7 +2298,7 @@ void register_object_tools(CommandCatalog& catalog) // Clone waits for the arrangement it starts, as object_arrange does. NativeCommand clone = reaching( {"clone_objects"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "object_clone", L("Clone"), "Make copies of objects as new objects, as the Clone dialog does: those named, else what is selected in the " "Prepare view (an object whole, or some of its instances, which a copy holds as one new object). count copies of " @@ -2359,7 +2368,7 @@ void register_object_tools(CommandCatalog& catalog) NativeCommand reload = reaching( {"reload_parts"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "object_reload_from_disk", L("Reload from disk"), "Load parts again from the files they were loaded from, as Reload from disk does: every part of the objects " "named, the parts named, every object's (all, as Reload All does, cut objects left out), else what is selected in " @@ -2422,7 +2431,7 @@ void register_object_tools(CommandCatalog& catalog) NativeCommand replace = reaching( {"replace_part"}, - with_expected_ids(mutate_tool( + with_target_ids(mutate_tool( "part_replace", L("Replace 3D file"), "Replace a part's mesh with the mesh of a model file, as Replace 3D file does: the part named (object and part, or " "an object of one part), else the one selected in the Prepare view. The part keeps its settings, type, filament " @@ -2474,13 +2483,13 @@ void register_scene_tools(CommandCatalog& catalog) "object_list", L("List objects"), "The project as the Objects panel lists it. `plates`: each `{index, name, objects}`, with the objects that have an " "instance on it, each time with that plate's instances; `outside`: those with an instance on no plate. An object has " - "`index`, `id`, `name`, `filament`, `part_count`, `size` (mm, of its bbox) and `instances`, the indices of its " - "instances there. With `detail` it also has `auto_drop`, `bbox` (instance 0), `brim_ears` (a count), `overrides` " + "`index`, `id`, `name`, `filament`, `part_count`, `size` (mm, of its bbox), `instances`, the indices of its " + "instances there, and `instance_ids`, their ids in the same order. With `detail` it also has `auto_drop`, `bbox` (instance 0), `brim_ears` (a count), `overrides` " "(the keys of the settings it overrides, which `settings_get` target object reads), `mesh_errors` as the list's " "warning icon reads them (`open_edges`, manifold, and the loader's or a repair's `degenerate_facets`, `edges_fixed`, " "`facets_removed`, `facets_reversed` and `backwards_edges`; `object_fix` repairs them), `instances` as entries " - "(`index`, `offset`, `rotation_deg`, `scale`, `mirrored`, `bbox`), and `parts`: parts, negative parts, modifiers, " - "support blockers and enforcers and precise seams, each with `type` (`subtype` for a precise seam), `filament` (a " + "(`index`, `id`, `offset`, `rotation_deg`, `scale`, `mirrored`, `bbox`), and `parts`: parts, negative parts, " + "modifiers, support blockers and enforcers and precise seams, each with `id`, `type` (`subtype` for a precise seam), `filament` (a " "part's own or its object's, a modifier's only when it sets one), `position`, `bbox` and `scaled_volume` (mm3) on " "the bed for instance 0, `rotation_deg` and `scale` in the object's frame, `mirrored`, `triangles`, `mesh_volume` " "(the unscaled mesh's mm3), `painted` facets (supports, seam enforcers/blockers, `fuzzy_skin`, mmu per filament, " @@ -2488,8 +2497,9 @@ void register_scene_tools(CommandCatalog& catalog) "`layer_config_ranges`, its height range modifiers (`[{min_z, max_z, values}]`, for `object_set_height_ranges` and " "`settings_set` target `height_range`), and `layer_height_profile` (`{points, min_height, max_height}`). A bbox is " "`{min, max, size}` in mm of model parts only, so unlike the panel's Size it leaves out modifiers. An object's index " - "numbers it in the project and a part's in its object, whatever the plate; an id stays with its object or part when " - "a delete, split or assemble shifts the indices, for the guards (`object_id`, `part_id`, `*_ids`). `limit` and " + "numbers it in the project and a part's in its object, whatever the plate; an id stays with its object, part or " + "instance when a delete, split or assemble shifts the indices, and names it wherever an index does (`object_id`, " + "`part_id`, `instance_id`, `*_ids`). `limit` and " "`offset` page the objects and `total` counts them, each once.", object_schema({{"plate", {{"type", "integer"}, {"minimum", 0}, {"description", "List this plate alone, without `outside`."}}}, {"detail", prop("boolean", "Each object whole: its instances, parts, bounding boxes, mesh errors, paint and " @@ -2500,7 +2510,7 @@ void register_scene_tools(CommandCatalog& catalog) {"offset", {{"type", "integer"}, {"minimum", 0}}}}), [](const json& args, ToolContext& ctx) { return ToolResult::ok(ctx.run_ui([&] { return list_objects(args); })); })); - NativeCommand select = with_expected_ids(mutate_tool( + NativeCommand select = with_target_ids(mutate_tool( "object_select", L("Select objects"), "Select objects, instances or parts in the 3D view (the assemble view while it is shown, else Prepare, switching to it), as clicking them would. Give objects, " "instances (`[[object, instance], ...]`) or parts (`[[object, part], ...]`); add keeps the current selection; all / " @@ -2581,7 +2591,7 @@ void register_scene_tools(CommandCatalog& catalog) }, /*person_form_behind_dialogs=*/false, std::vector{json{{"none", true}}, json{{"all", true}}})); - catalog.add(with_expected_ids(mutate_tool( + catalog.add(with_target_ids(mutate_tool( "object_transform", L("Move, rotate or scale an instance or a part"), "Change one instance's placement, or one part's with part. translate is in mm, position where it goes (mm, as " "the Move panel shows it, whatever mode says), rotate in degrees about X/Y/Z, " @@ -2643,7 +2653,7 @@ void register_scene_tools(CommandCatalog& catalog) return ToolResult::ok(out); }))); - catalog.add(with_expected_ids(mutate_tool( + catalog.add(with_target_ids(mutate_tool( "part_add", L("Add a part or modifier to an object"), "Add a part, negative part, modifier, support blocker or enforcer, or precise seam to an object, as its context " "menu's Add items do: a primitive shape at a size, or a model file as Load... adds it. The part lands where the " @@ -2687,7 +2697,7 @@ void register_scene_tools(CommandCatalog& catalog) NativeCommand arrange = reaching({"start_arrange"}, mutate_tool( "object_arrange", L("Arrange objects or fill the bed"), "Arrange the objects of every unlocked plate as the toolbar's Arrange does, or of one plate (plates: an index or " - "\"current\") as its Arrange icon does. With `fill_object`, fill that object's plate with more of it instead, as Fill " + "\"current\") as its Arrange icon does. With `fill_object` (or `fill_object_id`), fill that object's plate with more of it instead, as Fill " "bed with instances (or copies, by `fill_with`) does (reply: added, how many). spacing, rotate, `align_y` and `multi_material` are the Arrange options " "panel's settings: the values given stay in the panel, so later arranges use them too. Waits for the arrangement " "(a longer one replies with a job). Reply: the settings in force, instances left off every plate, plates the " @@ -2700,6 +2710,7 @@ void register_scene_tools(CommandCatalog& catalog) {"align_y", prop("boolean", "Align to Y axis (off while rotate is on).")}, {"multi_material", prop("boolean", "Allow multiple materials on same plate.")}, {"fill_object", {{"type", "integer"}, {"minimum", 0}, {"description", "An object index: instead of arranging, fill that object's plate with more of it."}}}, + {"fill_object_id", id_prop("object")}, {"fill_with", enum_prop({"instances", "copies"}, "Default instances.")}, {"timeout_s", {{"type", "integer"}, {"minimum", 10}, {"maximum", 1800}, {"description", "Cancel it after this long (default 300)."}}}}), [](const json& args, ToolContext& ctx) { @@ -2742,7 +2753,7 @@ void register_scene_tools(CommandCatalog& catalog) // of the action's arguments is object_arrange's own function, which waits and replies. Both are Ops::start_arrange() // on every unlocked plate with the panel's settings. catalog.add(NativeCommands::with_menu_item_forms( - std::move(arrange), [](const json&) { return MenuItems::obj_arrange(); }, /*person_form_behind_dialogs=*/false, + with_target_ids(std::move(arrange)), [](const json&) { return MenuItems::obj_arrange(); }, /*person_form_behind_dialogs=*/false, std::vector{json::object()})); NativeCommand slice = reaching({"start_slice"}, mutate_tool( diff --git a/tests/automation/test_mcp_core.cpp b/tests/automation/test_mcp_core.cpp index 34c3689d6f..38971b8a6a 100644 --- a/tests/automation/test_mcp_core.cpp +++ b/tests/automation/test_mcp_core.cpp @@ -972,7 +972,7 @@ TEST_CASE("an observer that throws fails no call", "[Mcp]") CHECK(acted.data["done"] == true); } -TEST_CASE("the journal records a call without its command's id arguments", "[Mcp]") +TEST_CASE("the journal records a call without the id arguments that stand beside their indices", "[Mcp]") { Harness h; NativeCommand move = tool("move", GuardClass::Mutate, [](const json& args, ToolContext& ctx) { @@ -990,11 +990,14 @@ TEST_CASE("the journal records a call without its command's id arguments", "[Mcp REQUIRE_FALSE(h.call("move", {{"object", 1}, {"object_id", 9}}).is_error); REQUIRE_FALSE(h.call("move", {{"rewrite", true}, {"object_id", 9}}).is_error); REQUIRE_FALSE(h.call("measure", {{"object_id", 4}}).is_error); + // An id given alone names the target until the command records its index, so it stays. + REQUIRE_FALSE(h.call("move", {{"object_id", 7}}).is_error); const json steps = h.journal.to_replay("s")["steps"]; - REQUIRE(steps.size() == 3); + REQUIRE(steps.size() == 4); CHECK(steps[0]["args"] == json{{"object", 1}}); CHECK(steps[1]["args"] == json{{"object", 2}}); CHECK(steps[2]["args"] == json{{"object_id", 4}}); + CHECK(steps[3]["args"] == json{{"object_id", 7}}); } TEST_CASE("without a blocking slot a job call returns its envelope at once and an inline call returns pending", "[Mcp]") diff --git a/tests/data/command_catalog.json b/tests/data/command_catalog.json index 69b95b808b..fe58fe56ba 100644 --- a/tests/data/command_catalog.json +++ b/tests/data/command_catalog.json @@ -1175,7 +1175,7 @@ "type": "string" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -1297,7 +1297,7 @@ }, { "completion": "immediate", - "description": "The project as the Objects panel lists it. `plates`: each `{index, name, objects}`, with the objects that have an instance on it, each time with that plate's instances; `outside`: those with an instance on no plate. An object has `index`, `id`, `name`, `filament`, `part_count`, `size` (mm, of its bbox) and `instances`, the indices of its instances there. With `detail` it also has `auto_drop`, `bbox` (instance 0), `brim_ears` (a count), `overrides` (the keys of the settings it overrides, which `settings_get` target object reads), `mesh_errors` as the list's warning icon reads them (`open_edges`, manifold, and the loader's or a repair's `degenerate_facets`, `edges_fixed`, `facets_removed`, `facets_reversed` and `backwards_edges`; `object_fix` repairs them), `instances` as entries (`index`, `offset`, `rotation_deg`, `scale`, `mirrored`, `bbox`), and `parts`: parts, negative parts, modifiers, support blockers and enforcers and precise seams, each with `type` (`subtype` for a precise seam), `filament` (a part's own or its object's, a modifier's only when it sets one), `position`, `bbox` and `scaled_volume` (mm3) on the bed for instance 0, `rotation_deg` and `scale` in the object's frame, `mirrored`, `triangles`, `mesh_volume` (the unscaled mesh's mm3), `painted` facets (supports, seam enforcers/blockers, `fuzzy_skin`, mmu per filament, texture per layer), and a text part's text and font or an SVG part's file. When it has them: `layer_config_ranges`, its height range modifiers (`[{min_z, max_z, values}]`, for `object_set_height_ranges` and `settings_set` target `height_range`), and `layer_height_profile` (`{points, min_height, max_height}`). A bbox is `{min, max, size}` in mm of model parts only, so unlike the panel's Size it leaves out modifiers. An object's index numbers it in the project and a part's in its object, whatever the plate; an id stays with its object or part when a delete, split or assemble shifts the indices, for the guards (`object_id`, `part_id`, `*_ids`). `limit` and `offset` page the objects and `total` counts them, each once.", + "description": "The project as the Objects panel lists it. `plates`: each `{index, name, objects}`, with the objects that have an instance on it, each time with that plate's instances; `outside`: those with an instance on no plate. An object has `index`, `id`, `name`, `filament`, `part_count`, `size` (mm, of its bbox), `instances`, the indices of its instances there, and `instance_ids`, their ids in the same order. With `detail` it also has `auto_drop`, `bbox` (instance 0), `brim_ears` (a count), `overrides` (the keys of the settings it overrides, which `settings_get` target object reads), `mesh_errors` as the list's warning icon reads them (`open_edges`, manifold, and the loader's or a repair's `degenerate_facets`, `edges_fixed`, `facets_removed`, `facets_reversed` and `backwards_edges`; `object_fix` repairs them), `instances` as entries (`index`, `id`, `offset`, `rotation_deg`, `scale`, `mirrored`, `bbox`), and `parts`: parts, negative parts, modifiers, support blockers and enforcers and precise seams, each with `id`, `type` (`subtype` for a precise seam), `filament` (a part's own or its object's, a modifier's only when it sets one), `position`, `bbox` and `scaled_volume` (mm3) on the bed for instance 0, `rotation_deg` and `scale` in the object's frame, `mirrored`, `triangles`, `mesh_volume` (the unscaled mesh's mm3), `painted` facets (supports, seam enforcers/blockers, `fuzzy_skin`, mmu per filament, texture per layer), and a text part's text and font or an SVG part's file. When it has them: `layer_config_ranges`, its height range modifiers (`[{min_z, max_z, values}]`, for `object_set_height_ranges` and `settings_set` target `height_range`), and `layer_height_profile` (`{points, min_height, max_height}`). A bbox is `{min, max, size}` in mm of model parts only, so unlike the panel's Size it leaves out modifiers. An object's index numbers it in the project and a part's in its object, whatever the plate; an id stays with its object, part or instance when a delete, split or assemble shifts the indices, and names it wherever an index does (`object_id`, `part_id`, `instance_id`, `*_ids`). `limit` and `offset` page the objects and `total` counts them, each once.", "destructive": false, "group": "Objects", "guard": "inspect", @@ -1380,8 +1380,8 @@ "description": "Select all objects.", "type": "boolean" }, - "instance_object_ids": { - "description": "Optional guard: the ids in `object_list` of the instances' objects, one each.", + "instance_ids": { + "description": "The instances' ids in `object_list`.", "items": { "type": "integer" }, @@ -1399,7 +1399,7 @@ "type": "boolean" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -1413,7 +1413,7 @@ "type": "array" }, "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -1456,6 +1456,11 @@ "minimum": 0, "type": "integer" }, + "instance_id": { + "description": "The instance's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "mode": { "description": "Default relative.", "enum": [ @@ -1470,7 +1475,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -1480,7 +1485,7 @@ "type": "integer" }, "part_id": { - "description": "Optional guard: the part's id in `object_list`.", + "description": "The part's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -1863,7 +1868,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -1913,7 +1918,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -1975,8 +1980,8 @@ "description": "Delete every object. Default false: the targets.", "type": "boolean" }, - "instance_object_ids": { - "description": "Optional guard: the ids in `object_list` of the instances' objects, one each.", + "instance_ids": { + "description": "The instances' ids in `object_list`.", "items": { "type": "integer" }, @@ -1990,7 +1995,7 @@ "type": "array" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2004,7 +2009,7 @@ "type": "array" }, "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -2075,7 +2080,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -2085,7 +2090,7 @@ "type": "integer" }, "part_id": { - "description": "Optional guard: the part's id in `object_list`.", + "description": "The part's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -2173,7 +2178,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -2217,8 +2222,8 @@ "input_schema": { "additionalProperties": false, "properties": { - "instance_object_ids": { - "description": "Optional guard: the ids in `object_list` of the instances' objects, one each.", + "instance_ids": { + "description": "The instances' ids in `object_list`.", "items": { "type": "integer" }, @@ -2237,7 +2242,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" } @@ -2316,7 +2321,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -2366,7 +2371,7 @@ "additionalProperties": false, "properties": { "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2397,7 +2402,7 @@ "args": { "by": "name" }, - "description": "Order the current plate's objects by name, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", + "description": "Order the current plate's objects by name, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, object_id, name, plate}]) and descending.", "group": "Object", "icon": "", "key": "obj_order_by_name", @@ -2407,7 +2412,7 @@ "args": { "by": "filament" }, - "description": "Order the current plate's objects by filament, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", + "description": "Order the current plate's objects by filament, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, object_id, name, plate}]) and descending.", "group": "Object", "icon": "", "key": "obj_order_by_filament", @@ -2417,7 +2422,7 @@ "args": { "by": "height" }, - "description": "Order the current plate's objects by height, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", + "description": "Order the current plate's objects by height, which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, object_id, name, plate}]) and descending.", "group": "Object", "icon": "", "key": "obj_order_by_height", @@ -2427,7 +2432,7 @@ "args": { "by": "size" }, - "description": "Order the current plate's objects by size (bounding box volume), which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, name, plate}]) and descending.", + "description": "Order the current plate's objects by size (bounding box volume), which sets the object list and print order, as the plate menu's Order By does. Choosing the order they already have reverses it. Object indices change; the reply lists the new order (order: [{object, object_id, name, plate}]) and descending.", "group": "Object", "icon": "", "key": "obj_order_by_size", @@ -2435,7 +2440,7 @@ } ], "completion": "immediate", - "description": "Order the objects of a plate (the current one, or plate), or with all of every plate, by name, filament, height or size (bounding box volume), which sets the object list and print order, as the plate menu's Order By does: ascending, or with descending true descending. Called with by alone, as its Speed Dial actions, it shows the Prepare view and, as Order By does, reverses the order the objects already have. With order in place of by, the plate's objects go in the order given, as dragging them in the object list puts them: order names each of the plate's objects once, by index, and anything else is refused; the other plates' objects keep their order. One undo step, none when the order stays as it was; object indices change. Reply: the new order (order: [`{object, name, plate}`]), and descending with by.", + "description": "Order the objects of a plate (the current one, or plate), or with all of every plate, by name, filament, height or size (bounding box volume), which sets the object list and print order, as the plate menu's Order By does: ascending, or with descending true descending. Called with by alone, as its Speed Dial actions, it shows the Prepare view and, as Order By does, reverses the order the objects already have. With order in place of by, the plate's objects go in the order given, as dragging them in the object list puts them: order names each of the plate's objects once, by index (`order_ids` by id), and anything else is refused; the other plates' objects keep their order. One undo step, none when the order stays as it was; object indices change. Reply: the new order (order: [`{object, object_id, name, plate}`]), and descending with by.", "destructive": false, "group": "Objects", "guard": "mutate", @@ -2471,6 +2476,15 @@ "minItems": 1, "type": "array" }, + "order_ids": { + "description": "`order` by the objects' ids in `object_list`.", + "items": { + "minimum": 0, + "type": "integer" + }, + "minItems": 1, + "type": "array" + }, "plate": { "description": "Order this plate's objects. Default: the current plate.", "minimum": 0, @@ -2511,7 +2525,7 @@ "additionalProperties": false, "properties": { "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2525,7 +2539,7 @@ "type": "array" }, "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -2603,7 +2617,7 @@ "type": "string" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2617,7 +2631,7 @@ "type": "array" }, "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -2667,7 +2681,7 @@ "additionalProperties": false, "properties": { "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2719,7 +2733,7 @@ "additionalProperties": false, "properties": { "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2766,7 +2780,7 @@ "additionalProperties": false, "properties": { "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2846,8 +2860,8 @@ "input_schema": { "additionalProperties": false, "properties": { - "instance_object_ids": { - "description": "Optional guard: the ids in `object_list` of the instances' objects, one each.", + "instance_ids": { + "description": "The instances' ids in `object_list`.", "items": { "type": "integer" }, @@ -2861,7 +2875,7 @@ "type": "array" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -2936,7 +2950,7 @@ "type": "boolean" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -3010,7 +3024,7 @@ "type": "boolean" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -3024,7 +3038,7 @@ "type": "array" }, "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -3104,7 +3118,7 @@ "type": "integer" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -3171,7 +3185,7 @@ "type": "boolean" }, "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -3185,7 +3199,7 @@ "type": "array" }, "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -3222,7 +3236,7 @@ } ], "completion": "immediate", - "description": "Arrange the objects of every unlocked plate as the toolbar's Arrange does, or of one plate (plates: an index or \"current\") as its Arrange icon does. With `fill_object`, fill that object's plate with more of it instead, as Fill bed with instances (or copies, by `fill_with`) does (reply: added, how many). spacing, rotate, `align_y` and `multi_material` are the Arrange options panel's settings: the values given stay in the panel, so later arranges use them too. Waits for the arrangement (a longer one replies with a job). Reply: the settings in force, instances left off every plate, plates the all-plates arrange skipped and the job's notifications. An arrange may reorder objects, so `object_list` again. One undo step. Called with no arguments it is Auto-Arrange, the toolbar's Arrange with the panel's settings, and waits and replies as any other call.", + "description": "Arrange the objects of every unlocked plate as the toolbar's Arrange does, or of one plate (plates: an index or \"current\") as its Arrange icon does. With `fill_object` (or `fill_object_id`), fill that object's plate with more of it instead, as Fill bed with instances (or copies, by `fill_with`) does (reply: added, how many). spacing, rotate, `align_y` and `multi_material` are the Arrange options panel's settings: the values given stay in the panel, so later arranges use them too. Waits for the arrangement (a longer one replies with a job). Reply: the settings in force, instances left off every plate, plates the all-plates arrange skipped and the job's notifications. An arrange may reorder objects, so `object_list` again. One undo step. Called with no arguments it is Auto-Arrange, the toolbar's Arrange with the panel's settings, and waits and replies as any other call.", "destructive": false, "group": "Objects", "guard": "mutate", @@ -3240,6 +3254,11 @@ "minimum": 0, "type": "integer" }, + "fill_object_id": { + "description": "The object's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "fill_with": { "description": "Default instances.", "enum": [ @@ -3329,13 +3348,18 @@ "minimum": 0, "type": "integer" }, + "instance_id": { + "description": "The instance's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "object": { "description": "Object index (`object_list`).", "minimum": 0, "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -3412,7 +3436,7 @@ "additionalProperties": false, "properties": { "object_ids": { - "description": "Optional guard: the objects' ids in `object_list`, one each.", + "description": "The objects' ids in `object_list`.", "items": { "type": "integer" }, @@ -3479,7 +3503,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -3489,7 +3513,7 @@ "type": "integer" }, "part_id": { - "description": "Optional guard: the part's id in `object_list`.", + "description": "The part's id in `object_list`.", "minimum": 0, "type": "integer" } @@ -3559,6 +3583,11 @@ "minimum": 0, "type": "integer" }, + "instance_id": { + "description": "The instance's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "keep": { "description": "The pieces kept. Default both.", "enum": [ @@ -3583,7 +3612,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -3703,6 +3732,11 @@ "minimum": 0, "type": "integer" }, + "instance_id": { + "description": "The instance's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "normal": { "description": "`[x, y, z]`: the direction the face to lay on the bed points out to; any length but zero.", "items": { @@ -3716,7 +3750,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" } @@ -3806,13 +3840,18 @@ "minimum": 0, "type": "integer" }, + "instance_id": { + "description": "The instance's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "object": { "description": "Object index (`object_list`).", "minimum": 0, "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -3870,7 +3909,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -3941,7 +3980,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -3987,7 +4026,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -4120,7 +4159,7 @@ "additionalProperties": false, "properties": { "part_ids": { - "description": "Optional guard: the parts' ids in `object_list`, one each.", + "description": "The parts' ids in `object_list`.", "items": { "type": "integer" }, @@ -4216,7 +4255,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -4226,7 +4265,7 @@ "type": "integer" }, "part_id": { - "description": "Optional guard: the part's id in `object_list`.", + "description": "The part's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -4288,7 +4327,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" } @@ -5487,6 +5526,11 @@ "minimum": 0, "type": "integer" }, + "object_id": { + "description": "The object's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "offset": { "minimum": 0, "type": "integer" @@ -5496,6 +5540,11 @@ "minimum": 0, "type": "integer" }, + "part_id": { + "description": "The part's id in `object_list`.", + "minimum": 0, + "type": "integer" + }, "preset": { "description": "Read this saved preset of the type (a name from `preset_list`) instead of the one being edited.", "type": "string" @@ -5561,7 +5610,7 @@ "type": "integer" }, "object_id": { - "description": "Optional guard: the object's id in `object_list`.", + "description": "The object's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -5571,7 +5620,7 @@ "type": "integer" }, "part_id": { - "description": "Optional guard: the part's id in `object_list`.", + "description": "The part's id in `object_list`.", "minimum": 0, "type": "integer" }, @@ -8578,7 +8627,7 @@ }, { "completion": "immediate", - "description": "Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions and show Prepare. 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.", + "description": "Commit to Plate: send the visible bodies to Prepare at their Move-gizmo positions and show Prepare. 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, object_id, name, parts: how many), bodies_sent, bodies_hidden, replaced.", "destructive": false, "examples": [ { @@ -8669,6 +8718,11 @@ "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.", "type": "array" + }, + "replace_ids": { + "default": [], + "description": "replace by the objects' ids in object_list.", + "type": "array" } }, "type": "object" diff --git a/tests/slic3rutils/test_command_catalog.cpp b/tests/slic3rutils/test_command_catalog.cpp index df82bd6d46..d1a2719671 100644 --- a/tests/slic3rutils/test_command_catalog.cpp +++ b/tests/slic3rutils/test_command_catalog.cpp @@ -994,18 +994,22 @@ TEST_CASE("a command the catalog leaves out is unknown with the reason", "[Comma CHECK(no_cad.left_out("object_arrange") == nullptr); } -TEST_CASE("every expected-id argument of a schema is in id_args", "[CommandCatalog]") +TEST_CASE("every id argument of a schema is in id_args", "[CommandCatalog]") { for (const NativeCommand& c : NativeCommands::instance().commands()) { INFO(c.key); std::set in_schema; if (c.input_schema.is_object() && c.input_schema.contains("properties")) - for (const char* name : {"object_id", "part_id", "object_ids", "part_ids", "instance_object_ids"}) - if (c.input_schema["properties"].contains(name)) - in_schema.insert(name); + for (const Mcp::IdArgument& arg : Mcp::kIdArguments) { + // An id names what its index does, so a schema with one has the other. + INFO(arg.id); + CHECK(c.input_schema["properties"].contains(arg.id) == c.input_schema["properties"].contains(arg.index)); + if (c.input_schema["properties"].contains(arg.id)) + in_schema.insert(arg.id); + } CHECK(std::set(c.id_args.begin(), c.id_args.end()) == in_schema); } - for (const char* key : {"object_transform", "object_select", "settings_set"}) { + for (const char* key : {"object_transform", "object_select", "settings_set", "object_arrange", "object_order"}) { INFO(key); const NativeCommand* takes_ids = NativeCommands::find(key); REQUIRE(takes_ids != nullptr); diff --git a/tests/slic3rutils/test_mcp_cad.cpp b/tests/slic3rutils/test_mcp_cad.cpp index 472017217d..a35567f218 100644 --- a/tests/slic3rutils/test_mcp_cad.cpp +++ b/tests/slic3rutils/test_mcp_cad.cpp @@ -2665,6 +2665,10 @@ TEST_CASE("commit_to_plate, new_design and export_step change the design or the } // export_step's path has no default, so it is required. CHECK(required_of(command_of(catalog, "export_step")) == std::vector{"path"}); + // commit_to_plate names the objects it replaces by index or by id; the journal records the indices. + const GUI::NativeCommand& commit = command_of(catalog, "commit_to_plate"); + CHECK(commit.input_schema["properties"].contains("replace_ids")); + CHECK(commit.id_args == std::vector{"replace_ids"}); } TEST_CASE("commit_to_plate's replace takes distinct object indices that are not part of a cut", "[Mcp][CAD]") diff --git a/tests/slic3rutils/test_mcp_scene.cpp b/tests/slic3rutils/test_mcp_scene.cpp index 9162976153..86bb05dc8c 100644 --- a/tests/slic3rutils/test_mcp_scene.cpp +++ b/tests/slic3rutils/test_mcp_scene.cpp @@ -170,19 +170,19 @@ TEST_CASE("the commands that replace a dialog take the arguments the table gives REQUIRE(names("object_rename") == Names{"object", "object_id", "part", "part_id", "name", "silent"}); REQUIRE(names("object_set_instances") == Names{"object", "object_id", "count", "delta", "silent"}); REQUIRE(names("object_delete") == - Names{"objects", "object_ids", "instances", "instance_object_ids", "parts", "part_ids", "plate", "all", "silent"}); - REQUIRE(names("object_separate_instances") == Names{"object", "object_id", "instances", "instance_object_ids"}); + Names{"objects", "object_ids", "instances", "instance_ids", "parts", "part_ids", "plate", "all", "silent"}); + REQUIRE(names("object_separate_instances") == Names{"object", "object_id", "instances", "instance_ids"}); REQUIRE(names("object_split") == Names{"object", "object_id", "into", "keep_z", "silent"}); REQUIRE(names("object_assemble") == Names{"objects", "object_ids"}); REQUIRE(names("part_change_type") == Names{"parts", "part_ids", "type", "subtype"}); - REQUIRE(names("object_order") == Names{"plate", "by", "order", "descending", "all"}); + REQUIRE(names("object_order") == Names{"plate", "by", "order", "order_ids", "descending", "all"}); REQUIRE(names("object_add_primitive") == Names{"shape", "size", "plate", "position", "name", "silent"}); REQUIRE(names("object_mirror") == Names{"objects", "object_ids", "parts", "part_ids", "axis"}); REQUIRE(names("object_center") == Names{"objects", "object_ids", "plate"}); REQUIRE(names("object_scale_to_fit") == Names{"objects", "object_ids"}); REQUIRE(names("object_drop") == Names{"objects", "object_ids", "parts", "part_ids"}); REQUIRE(names("object_auto_orient") == Names{"objects", "object_ids", "plates"}); - REQUIRE(names("object_set_printable") == Names{"objects", "object_ids", "instances", "instance_object_ids", "printable"}); + REQUIRE(names("object_set_printable") == Names{"objects", "object_ids", "instances", "instance_ids", "printable"}); REQUIRE(names("object_set_auto_drop") == Names{"objects", "object_ids", "auto_drop"}); REQUIRE(names("object_fix") == Names{"objects", "object_ids", "parts", "part_ids", "plate", "all"}); REQUIRE(names("object_clone") == Names{"objects", "object_ids", "count", "arrange"}); @@ -1008,17 +1008,20 @@ TEST_CASE("object_list lists each plate's objects, then those on no plate", "[Mc CHECK_THAT(side.get(), WithinAbs(10., 1e-6)); CHECK_FALSE(alone.contains("parts")); CHECK_FALSE(alone.contains("bbox")); - // An object keeps its index and id in the project, and lists the instances on this plate only, by index. + // An object keeps its index and id in the project, and lists the instances on this plate only, by index, with + // their ids in the same order. const json& twice = first["objects"][1]; CHECK(twice["index"] == 1); CHECK(twice["id"] == scene.model.objects[1]->id().id); CHECK(twice["instances"] == json::array({0})); + CHECK(twice["instance_ids"] == json::array({scene.model.objects[1]->instances[0]->id().id})); const json& second = out["plates"][1]; CHECK(second["name"] == "second"); REQUIRE(second["objects"].size() == 1); CHECK(second["objects"][0]["index"] == 1); CHECK(second["objects"][0]["instances"] == json::array({1})); + CHECK(second["objects"][0]["instance_ids"] == json::array({scene.model.objects[1]->instances[1]->id().id})); // A plate with nothing on it is listed. CHECK(out["plates"][2]["objects"].empty()); @@ -1042,7 +1045,10 @@ TEST_CASE("object_list with detail gives each instance's and part's entry", "[Mc const json& twice = first["objects"][1]; REQUIRE(twice["instances"].size() == 1); CHECK(twice["instances"][0]["index"] == 0); + CHECK(twice["instances"][0]["id"] == scene.model.objects[1]->instances[0]->id().id); CHECK_FALSE(twice["instances"][0].contains("plate")); + // The ids are in the entries, so no list of them is beside. + CHECK_FALSE(twice.contains("instance_ids")); const json& second = out["plates"][1]["objects"][0]; REQUIRE(second["instances"].size() == 1); CHECK(second["instances"][0]["index"] == 1); @@ -1378,8 +1384,9 @@ TEST_CASE("a command's targets are what its arguments name, else the selection", return out; }; CHECK(names(Mcp::target_props(kEveryKind, false)) == - std::set{"objects", "object_ids", "instances", "instance_object_ids", "parts", "part_ids"}); - CHECK(names(Mcp::target_props(kEveryKind, true)) == std::set{"object", "object_id", "instance", "part", "part_id"}); + std::set{"objects", "object_ids", "instances", "instance_ids", "parts", "part_ids"}); + CHECK(names(Mcp::target_props(kEveryKind, true)) == + std::set{"object", "object_id", "instance", "instance_id", "part", "part_id"}); } TEST_CASE("a reply names what the command acted on", "[Mcp][Scene]") @@ -1396,6 +1403,103 @@ TEST_CASE("a reply names what the command acted on", "[Mcp][Scene]") json{{"object", 1}, {"part", 1}, {"part_id", m.model.objects[1]->volumes[1]->id().id}, {"name", "second part 1"}}); // Only the kinds it holds. CHECK_FALSE(reply.contains("instances")); + + // An instance with its own id and its object's; one the object no longer has, a deleted one's index, without. + Ops::Targets instances; + instances.instances = {{1, 1}, {1, 5}}; + const json named = Mcp::targets_reply(m.model, instances); + REQUIRE(named.at("instances").size() == 2); + CHECK(named["instances"][0] == json{{"object", 1}, + {"instance", 1}, + {"object_id", m.model.objects[1]->id().id}, + {"instance_id", m.model.objects[1]->instances[1]->id().id}, + {"name", "second"}}); + CHECK_FALSE(named["instances"][1].contains("instance_id")); +} + +TEST_CASE("a command's targets are named by index or by the ids object_list reports", "[Mcp][Scene]") +{ + const TargetModel m; + const Model& model = m.model; + const ModelObject& first = *model.objects[0]; + const ModelObject& second = *model.objects[1]; + const ModelObject& third = *model.objects[2]; + const auto refusal = [&model](const json& args, unsigned kinds, bool one = false) { + try { + named_targets(model, args, kinds, one); + } catch (const ToolFailure& f) { + return std::make_pair(std::string(f.what()), f.details.value("code", std::string())); + } + return std::make_pair(std::string("not refused"), std::string()); + }; + + // An object's id names it alone, and a list of ids their objects, in the order given. + const auto by_id = named_targets(model, {{"object_id", second.id().id}}, kEveryKind, true); + REQUIRE(by_id); + CHECK(by_id.value().objects == std::vector{1}); + const auto listed = named_targets(model, {{"object_ids", json::array({third.id().id, first.id().id})}}, Mcp::kObjects); + REQUIRE(listed); + CHECK(listed.value().objects == std::vector{2, 0}); + // A part's or an instance's id names its object too. + const auto part = named_targets(model, {{"part_id", second.volumes[1]->id().id}}, kEveryKind, true); + REQUIRE(part); + CHECK(part.value().parts == std::vector>{{1, 1}}); + const auto instance = named_targets(model, {{"instance_id", second.instances[1]->id().id}}, kEveryKind, true); + REQUIRE(instance); + CHECK(instance.value().instances == std::vector>{{1, 1}}); + const auto parts = named_targets(model, {{"part_ids", json::array({second.volumes[0]->id().id, first.volumes[0]->id().id})}}, + Mcp::kParts); + REQUIRE(parts); + CHECK(parts.value().parts == std::vector>{{1, 0}, {0, 0}}); + const auto instances = named_targets(model, {{"instance_ids", json::array({second.instances[0]->id().id})}}, Mcp::kInstances); + REQUIRE(instances); + CHECK(instances.value().instances == std::vector>{{1, 0}}); + // The object by id and the part by index. + const auto mixed = named_targets(model, {{"object_id", second.id().id}, {"part", 1}}, kEveryKind, true); + REQUIRE(mixed); + CHECK(mixed.value().parts == std::vector>{{1, 1}}); + + // Given both, the id guards the index: instance 0 of the second object is not the instance with that id. + CHECK_THAT(refusal({{"object", 1}, {"instance", 0}, {"instance_id", second.instances[1]->id().id}}, kEveryKind, true).first, + ContainsSubstring("not the expected id")); + CHECK_THAT(refusal({{"instances", json::array({json::array({1, 0})})}, {"instance_ids", json::array({second.instances[1]->id().id})}}, + Mcp::kInstances) + .first, + ContainsSubstring("not the expected id")); + // A part's id of another object than the call names. + CHECK(refusal({{"object", 0}, {"part_id", second.volumes[1]->id().id}}, kEveryKind, true) == + std::make_pair("part_id " + std::to_string(second.volumes[1]->id().id) + " is of object 1, not of object 0", + std::string("invalid_argument"))); + // An id the model has nothing with, as a project opened again gives every object a new one. + const std::size_t none = third.instances[0]->id().id + 100000; + for (const auto& [args, kinds, text] : std::vector>{ + {json{{"object_id", none}}, kEveryKind, "No object has id "}, + {json{{"part_ids", json::array({none})}}, Mcp::kParts, "No part has id "}, + {json{{"instance_ids", json::array({none})}}, Mcp::kInstances, "No instance has id "}}) { + INFO(args.dump()); + const auto [what, code] = refusal(args, kinds, args.contains("object_id")); + CHECK(what.rfind(text + std::to_string(none), 0) == 0); + CHECK(code == "invalid_argument"); + } + // An id given as an index is refused with what that id names. + CHECK_THAT(refusal({{"object", second.id().id}}, kEveryKind, true).first, + ContainsSubstring(std::to_string(second.id().id) + " is the id of object 1")); + + // The ids stay beside the indices they are read as, so the command still checks them where it acts. + CHECK(Mcp::with_indices(model, {{"object_id", third.id().id}}) == json{{"object", 2}, {"object_id", third.id().id}}); + CHECK(Mcp::with_indices(model, {{"part_id", second.volumes[1]->id().id}}) == + json{{"object", 1}, {"part", 1}, {"part_id", second.volumes[1]->id().id}}); + // The objects outside the targets: Fill bed's, an order's and a Design commit's replaced ones. + CHECK(Mcp::with_indices(model, {{"fill_object_id", second.id().id}})["fill_object"] == 1); + CHECK(Mcp::with_indices(model, {{"order_ids", json::array({third.id().id, first.id().id, second.id().id})}})["order"] == + json::array({2, 0, 1})); + CHECK(Mcp::with_indices(model, {{"replace_ids", json::array({first.id().id})}})["replace"] == json::array({0})); + // Given with their indices, those ids are checked there, as no reading of the targets reads them. + CHECK_NOTHROW(Mcp::with_indices(model, {{"order", json::array({1, 0})}, {"order_ids", json::array({second.id().id, first.id().id})}})); + CHECK_THROWS_WITH(Mcp::with_indices(model, {{"replace", json::array({1})}, {"replace_ids", json::array({first.id().id})}}), + ContainsSubstring("not the expected id")); + CHECK_THROWS_WITH(Mcp::with_indices(model, {{"order", json::array({1, 0})}, {"order_ids", json::array({first.id().id})}}), + ContainsSubstring("order_ids takes one id per entry of order")); } TEST_CASE("a command's target is optional, and a plate defaults to the current one", "[Mcp][Scene]") diff --git a/tests/slic3rutils/test_mcp_tools.cpp b/tests/slic3rutils/test_mcp_tools.cpp index 19226885d6..5e881aa2fe 100644 --- a/tests/slic3rutils/test_mcp_tools.cpp +++ b/tests/slic3rutils/test_mcp_tools.cpp @@ -1670,69 +1670,86 @@ TEST_CASE("view_set takes the Design tab's camera, section view and switches", " TEST_CASE("a call naming an object's id is refused once its index names another object", "[Mcp]") { Slic3r::Model model; - Slic3r::ModelObject* first = model.add_object(); - Slic3r::ModelObject* second = model.add_object(); - first->name = "bracket"; - second->name = "lid"; - Slic3r::ModelVolume* part = first->add_volume(Slic3r::TriangleMesh()); + Slic3r::ModelObject* first = model.add_object(); + Slic3r::ModelObject* second = model.add_object(); + first->name = "bracket"; + second->name = "lid"; + Slic3r::ModelVolume* part = first->add_volume(Slic3r::TriangleMesh()); + Slic3r::ModelInstance* instance = first->add_instance(); + Slic3r::ModelInstance* other = first->add_instance(); - CHECK_NOTHROW(check_expected_ids(*first, nullptr, json{{"object", 0}, {"object_id", first->id().id}})); - CHECK_NOTHROW(check_expected_ids(*first, part, json{{"object", 0}, {"part_id", part->id().id}})); - // Without expected ids the index alone decides, as before. - CHECK_NOTHROW(check_expected_ids(*second, nullptr, json{{"object", 0}})); + CHECK_NOTHROW(check_expected_ids(*first, nullptr, nullptr, json{{"object", 0}, {"object_id", first->id().id}})); + CHECK_NOTHROW(check_expected_ids(*first, part, nullptr, json{{"object", 0}, {"part_id", part->id().id}})); + CHECK_NOTHROW(check_expected_ids(*first, nullptr, instance, json{{"object", 0}, {"instance_id", instance->id().id}})); + // Without ids the index alone decides. + CHECK_NOTHROW(check_expected_ids(*second, nullptr, nullptr, json{{"object", 0}})); try { - check_expected_ids(*second, nullptr, json{{"object", 0}, {"object_id", first->id().id}}); + check_expected_ids(*second, nullptr, nullptr, json{{"object", 0}, {"object_id", first->id().id}}); FAIL("the call was not refused"); } catch (const ToolFailure& f) { CHECK(std::string(f.what()).find("lid") != std::string::npos); CHECK(f.details["id"] == second->id().id); } - CHECK_THROWS_AS(check_expected_ids(*first, part, json{{"part_id", part->id().id + 1000}}), ToolFailure); + CHECK_THROWS_AS(check_expected_ids(*first, part, nullptr, json{{"part_id", part->id().id + 1000}}), ToolFailure); + try { + check_expected_ids(*first, nullptr, other, json{{"instance_id", instance->id().id}}); + FAIL("the call was not refused"); + } catch (const ToolFailure& f) { + CHECK(f.details["id"] == other->id().id); + } } -TEST_CASE("the journal records indices without expected ids, except a Python step's arguments", "[Mcp]") +TEST_CASE("the journal records indices without the ids beside them, except a Python step's arguments", "[Mcp]") { const CommandCatalog& catalog = Slic3r::GUI::NativeCommands::instance(); - CHECK(without_expected_ids(catalog, "settings_set", json{{"object", 0}, {"object_id", 7}, {"part_id", 8}}) == json{{"object", 0}}); - CHECK(without_expected_ids(catalog, "object_set_height_ranges", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); - CHECK(without_expected_ids(catalog, "object_set_variable_layer_height", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); + CHECK(without_guard_ids(catalog, "settings_set", json{{"object", 0}, {"object_id", 7}, {"part", 1}, {"part_id", 8}}) == + json{{"object", 0}, {"part", 1}}); + CHECK(without_guard_ids(catalog, "object_set_height_ranges", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); + CHECK(without_guard_ids(catalog, "object_set_variable_layer_height", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); const json replay{{"replay", {{"orca_replay_version", "0.2.0"}, {"steps", {{{"tool", "object_transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}, {{"tool", "script_run"}, {"args", {{"code", "x"}, {"args", {{"object_id", 9}}}}}}}}}}}; - const json recorded = without_expected_ids(catalog, "replay_run", replay); + const json recorded = without_guard_ids(catalog, "replay_run", replay); CHECK(recorded["replay"]["steps"][0]["args"] == json{{"object", 1}}); CHECK(recorded["replay"]["steps"][1]["args"]["args"]["object_id"] == 9); - CHECK(without_expected_ids(catalog, "script_run", json{{"code", "x"}, {"args", {{"object_id", 3}}}})["args"]["object_id"] == 3); + CHECK(without_guard_ids(catalog, "script_run", json{{"code", "x"}, {"args", {{"object_id", 3}}}})["args"]["object_id"] == 3); } -TEST_CASE("the journal records an inline replay given as JSON text as its object, without expected ids", "[Mcp]") +TEST_CASE("the journal records an inline replay given as JSON text as its object, without the ids beside indices", "[Mcp]") { const CommandCatalog& catalog = Slic3r::GUI::NativeCommands::instance(); const json as_text{{"replay", "// moves the lid\n" R"({"orca_replay_version": "0.2.0", "steps": [{"tool": "object_transform", "args": {"object": 1, "object_id": 9}}]})"}}; - const json recorded = without_expected_ids(catalog, "replay_run", as_text); + const json recorded = without_guard_ids(catalog, "replay_run", as_text); REQUIRE(recorded["replay"].is_object()); CHECK(recorded["replay"]["steps"][0]["args"] == json{{"object", 1}}); // Text that doesn't parse is the call's error; it is recorded as given. - CHECK(without_expected_ids(catalog, "replay_run", json{{"replay", "{\"orca_replay_version\": \"0.2.0\","}}) == json{{"replay", "{\"orca_replay_version\": \"0.2.0\","}}); + CHECK(without_guard_ids(catalog, "replay_run", json{{"replay", "{\"orca_replay_version\": \"0.2.0\","}}) == json{{"replay", "{\"orca_replay_version\": \"0.2.0\","}}); } -TEST_CASE("the journal strips a command's id arguments", "[Mcp]") +TEST_CASE("the journal leaves out a command's ids that stand beside their indices", "[Mcp]") { const CommandCatalog& catalog = Slic3r::GUI::NativeCommands::instance(); - CHECK(without_expected_ids(catalog, "object_transform", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); - // Inside the tool_call and replay_run wrappers too. - CHECK(without_expected_ids(catalog, "tool_call", json{{"tool", "object_transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}) == + CHECK(without_guard_ids(catalog, "object_transform", json{{"object", 0}, {"object_id", 7}}) == json{{"object", 0}}); + // An id given alone still names its target: the command records its index once it reads it (with_target_ids()). + CHECK(without_guard_ids(catalog, "object_transform", json{{"object_id", 7}}) == json{{"object_id", 7}}); + CHECK(without_guard_ids(catalog, "object_order", json{{"order", {1, 0}}, {"order_ids", {7, 5}}}) == json{{"order", {1, 0}}}); + CHECK(without_guard_ids(catalog, "object_arrange", json{{"fill_object", 1}, {"fill_object_id", 7}}) == json{{"fill_object", 1}}); + // Inside the tool_call, action_run and replay_run wrappers too. + CHECK(without_guard_ids(catalog, "action_run", json{{"id", "object_transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}) == + json{{"id", "object_transform"}, {"args", {{"object", 1}}}}); + CHECK(without_guard_ids(catalog, "tool_call", json{{"tool", "object_transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}) == json{{"tool", "object_transform"}, {"args", {{"object", 1}}}}); const json replay{{"replay", {{"orca_replay_version", "0.2.0"}, {"steps", {{{"tool", "tool_call"}, {"args", {{"tool", "object_transform"}, {"args", {{"object", 1}, {"object_id", 9}}}}}}}}}}}; - CHECK(without_expected_ids(catalog, "replay_run", replay)["replay"]["steps"][0]["args"]["args"] == json{{"object", 1}}); + CHECK(without_guard_ids(catalog, "replay_run", replay)["replay"]["steps"][0]["args"]["args"] == json{{"object", 1}}); // A plugin operation's own fields of the same names are its arguments, recorded as given. - CHECK(without_expected_ids(catalog, "plugin.measure.area", json{{"object_id", 4}}) == json{{"object_id", 4}}); - CHECK(without_expected_ids(catalog, "tool_call", json{{"tool", "plugin.measure.area"}, {"args", {{"object_id", 4}}}})["args"]["object_id"] == 4); - CHECK(without_expected_ids(catalog, "object_select", json{{"objects", {0, 1}}, {"object_ids", {5, 6}}}) == json{{"objects", {0, 1}}}); - CHECK(without_expected_ids(catalog, "object_select", json{{"instances", {{0, 1}}}, {"instance_object_ids", {5}}}) == + CHECK(without_guard_ids(catalog, "plugin.measure.area", json{{"object_id", 4}}) == json{{"object_id", 4}}); + CHECK(without_guard_ids(catalog, "tool_call", json{{"tool", "plugin.measure.area"}, {"args", {{"object_id", 4}}}})["args"]["object_id"] == 4); + CHECK(without_guard_ids(catalog, "object_select", json{{"objects", {0, 1}}, {"object_ids", {5, 6}}}) == json{{"objects", {0, 1}}}); + CHECK(without_guard_ids(catalog, "object_select", json{{"instances", {{0, 1}}}, {"instance_ids", {5}}}) == json{{"instances", {{0, 1}}}}); + CHECK(without_guard_ids(catalog, "object_select", json{{"parts", {{0, 1}}}, {"part_ids", {5}}}) == json{{"parts", {{0, 1}}}}); } TEST_CASE("app_log keeps a line by the level its entry starts with, and a continuation line with its first line", "[Mcp]") diff --git a/tools/mcp/test-entries/gizmos.md b/tools/mcp/test-entries/gizmos.md index 6ed8bc6673..c3b761a81f 100644 --- a/tools/mcp/test-entries/gizmos.md +++ b/tools/mcp/test-entries/gizmos.md @@ -391,7 +391,7 @@ start reads back, make it. The scenarios from here on call the commands. No step clicks the canvas, reads a panel's text or captures a picture, so where on an object a text or an SVG part lands, which follows the camera and the window, is not checked. A reply is written as the fields the row fixes; a target in a reply is written by its `index` (or `object`, -`instance`, `part`) and `name`, and its `object_id` or `part_id` is not checked. Before each step that acts, +`instance`, `part`) and `name`, and its `object_id`, `part_id` or `instance_id` is not checked. Before each step that acts, `undo_steps()` sets its mark, and the step lists the undo steps it takes; a refused step takes none. **Scenario: opening a gizmo on a target** @@ -646,7 +646,7 @@ negative text and the SVG parts there stand for the text part, the negative text grabber at the bed under the object's edge, and the panel shows no state of it (`has_selected_points()` reads the ears, not the flag a click reads). `reload_on_next_opening()` clears it with the gizmo's own `select_point(NoPoints)`. -- `object_id` and `part_id` in replies. +- `object_id`, `part_id` and `instance_id` in replies: the objects entry's naming by id checks them. - What the painting, fuzzy skin, brim ears and connectors do to a slice: the test checks what the gizmos leave on the model and in the project file; turning it into toolpaths is the slicer's. - What other tests assert: Select All with Move open, and refused with Lay on face open, in diff --git a/tools/mcp/test-entries/objects.md b/tools/mcp/test-entries/objects.md index 5869ab0d07..dd35558be0 100644 --- a/tools/mcp/test-entries/objects.md +++ b/tools/mcp/test-entries/objects.md @@ -10,7 +10,7 @@ the list orders them (parts and their types, names, order, meshes and the files saves and reopens one project that holds what each part keeps in the file. ## `test_objects` -`test_objects.py` · Python, 1258 checks · in `sweep.json` as `{"path": "test_objects.py"}` +`test_objects.py` · Python, 1354 checks · in `sweep.json` as `{"path": "test_objects.py"}` **Tests:** The plates of the Prepare view: adding, duplicating, naming, locking, selecting and deleting plates, and undoing that; what a lock keeps Arrange and Auto-Orient from doing; the settings a plate sets for itself; the filament @@ -24,7 +24,8 @@ Objects and to Parts, and Assemble; adding parts of every type, changing a part' plate's objects by a property or in a given order, and the print order that sets; Fix Model by index and through the object's menu; Reload from disk and Replace 3D file; and the keep_painting preference, shown against its control. Last, what the project file keeps of the plates and objects. Each object command is called by index and, where its menu item -acts on the selection, with no target on the selection. It runs on the Generic Klipper Printer 0.4 nozzle: a bed 250 +acts on the selection, with no target on the selection; a scenario of its own names objects, parts and instances by the +ids `object_list` gives, and replays what it recorded on objects with other ids. It runs on the Generic Klipper Printer 0.4 nozzle: a bed 250 mm square and 250 mm high with no excluded area (`bed_exclude_area`), plates laid out 300 mm apart (the bed and a fifth of it), two to a row, and by-object printing that lets objects lower than its rod (36 mm, `extruder_clearance_height_to_rod`) print in the object list's order when they stand more than its clearance radius @@ -77,7 +78,8 @@ and reading the state back, not from the log. the `mixed` of each `filament_list` row, one digit per slot (`"0,0,1"`: three slots, the third a mixed filament). - `scene()`: each object of `object_list {detail: true}` in index order, its entry whole (`name`, `id`, `filament`, `auto_drop`, `bbox`, `mesh_errors`, `parts`, and `layer_config_ranges` and `layer_height_profile` when it has them), with its - `instances` gathered from every plate and from `outside`, each given its `plate` (−1 outside). A part is its entry + `instances` gathered from every plate and from `outside`, each its entry whole (its `id` among the fields) and given + its `plate` (−1 outside). A part is its entry whole: `name`, `id`, `type`, `subtype`, `filament`, `position`, `rotation_deg`, `scale`, `mirrored`, `triangles`, `mesh_volume`, `scaled_volume`, `bbox`, `painted`, `svg`. - `selection()`: `app_state`'s `selection` as `{objects, instances, parts}`, `parts` absent when whole instances are @@ -458,6 +460,39 @@ Three 20 mm cubes are added with `object_add_primitive` at `corner(0) + (40, 60, | 8 | layered, a 20 mm cube at `+ (60, 160, 0)`, `object_select {objects: [1]}`, then `object_set_height_ranges {ranges: [{min_z: 0, max_z: 5}]}` | Cube · layered | the reply's `object` 1, `objects` `[{index: 1, name: "layered"}]` and `layer_config_ranges` one range, `min_z` 0 and `max_z` 5; `object_list` gives layered that range and Cube no `layer_config_ranges` | | 9 | `object_set_variable_layer_height {action: "adaptive"}` | Cube · layered | the reply's `object` 1 and `objects` naming layered, with a `layer_height_profile`; `object_list` gives layered a `layer_height_profile` with `points` and Cube none | +**Scenario: naming by id** + +a, b and c are 20 mm cubes added with `object_add_primitive` at `corner(0) + (40, 60, 0)`, `+ (100, 60, 0)` and +`+ (160, 60, 0)` with those names, `object_select {none: true}` between them. An id is the app's name for an object, a +part or an instance, and cannot be written out before the run, so the test reads each id once and from then on checks +what it names: A, B and C are the `id`s `scene()` gives a, b and c after step 1; I0, I1 and I2 those of c's instances +after step 9; P that of bee's part 1 after step 14. `replay_export {clear: true}` after step 1 forgets the calls made +before it, so that step 19 reads this scenario's calls alone. The app places the instances step 9 adds; from there +each keeps its place until a row moves it. + +| # | Step | Objects after | Also checked | +|---|---|---|---| +| 1 | the three cubes | a · b · c | A, B and C differ, and each is more than 2, so that none is an index the project has; each object's short row (`object_list` without `detail`) gives `instances` `[0]` and `instance_ids` `[n]`, n the `id` its detail entry gives instance 0 | +| 2 | `object_rename {object_id: B, name: "bee"}` | a · bee · c | the reply's `objects` `[{index: 1, object_id: B, name: "bee"}]` | +| 3 | `object_delete {object_ids: [A]}` | bee · c | bee at +(100, 60) and c at +(160, 60); `scene()` gives bee `id` B and c `id` C: an id stays with its object when the indices after it move down | +| 4 | `object_transform {object_id: C, translate: [0, 20, 0]}` | bee · c | c at +(160, 80), bee at +(100, 60): C names c at its new index, 1 | +| 5 | `object_transform {object: 1, object_id: B, translate: [0, 20, 0]}` | bee · c | refused, saying `The object at this index is now "c"`; places as after 4: an index and an id that name different objects are refused | +| 6 | `object_transform {object_id: A, translate: [0, 20, 0]}` | bee · c | refused, `invalid_argument`, saying `No object has id A`; places as after 4 | +| 7 | `object_transform {object: C, translate: [0, 20, 0]}` | bee · c | refused, `invalid_argument`, saying `C is the id of object 1`; places as after 4: an id given as an index is named for what it is | +| 8 | `settings_set {target: "object", object_id: C, values: {wall_loops: 5}}` | bee · c | `scene()` gives c `overrides` with `wall_loops`, and bee's without (each also holds `extruder`, which adding a shape sets) | +| 9 | `object_set_instances {object_id: C, count: 3}` | bee · c×3 | I0 is the id c's instance had after step 1, and I0, I1 and I2 differ; c's short rows give each instance's id in `instance_ids` at the place its index has in `instances` | +| 10 | `object_transform {instance_id: I2, translate: [0, 20, 0]}` | bee · c×3 | c's instance 2 20 mm further along y than step 9 left it, with the same x, and instances 0 and 1 where they were: an instance's id names its object and the instance at once | +| 11 | `object_set_printable {instance_ids: [I1], printable: false}` | bee · c×3 | c's instances `printable` true, false, true; the reply's `instances` `[{object: 1, instance: 1, instance_id: I1}]` | +| 12 | `object_delete {instance_ids: [I0]}` | bee · c×2 | c's instances' ids I1 and I2, `printable` false and true: an id stays with its instance when the indices after it move down | +| 13 | `object_set_printable {instance_ids: [I1], printable: true}` | bee · c×2 | `printable` true and true; the reply's `instances` `[{object: 1, instance: 0, instance_id: I1}]` | +| 14 | `part_add {object_id: B, type: "modifier", shape: "cube"}` | bee: part, modifier · c | | +| 15 | `part_change_type {part_ids: [P], type: "negative"}` | bee: part, negative · c | the reply's `parts` `[{object: 0, part: 1, part_id: P, type: "negative"}]`: a part's id names its object too | +| 16 | `object_rename {part_id: P, name: "hole"}` | bee: part, negative · c | bee's part 1 named hole, and the object still bee | +| 17 | `object_order {order_ids: [C, B]}` | c · bee | the reply's `order` c, then bee, with `object_id` C and B | +| 18 | `object_arrange {fill_object_id: A}` | c · bee | refused, `invalid_argument`, saying `No object has id A`; c×2 and bee, places as after 13 | +| 19 | `replay_export {}` | c · bee | the replay's steps but `app_wait` (which a call answered with a job adds) are, in order, these tools with these targets: `object_rename` `{object: 1}`, `object_delete` `{objects: [0]}`, `object_transform` `{object: 1}`, `settings_set` `{object: 1}`, `object_set_instances` `{object: 1}`, `object_transform` `{object: 1, instance: 2}`, `object_set_printable` `{instances: [[1, 1]]}`, `object_delete` `{instances: [[1, 0]]}`, `object_set_printable` `{instances: [[1, 0]]}`, `part_add` `{object: 0}`, `part_change_type` `{parts: [[0, 1]]}`, `object_rename` `{object: 0, part: 1}` and `object_order` `{order: [1, 0]}`; no step's arguments has a key ending in `_id` or `_ids`: the journal records the index each id named, and leaves the refused calls out | +| 20 | `project_new {discard_changes: true}`, the three cubes again, then `replay_run` of step 19's replay | c×2 · bee: part, negative | the new cubes' ids are none of A, B and C; c's `overrides` with `wall_loops` and its instances `printable` true and true; bee's part 1 named hole: the replay, recorded from calls by id, runs on objects with other ids | + **Scenario: splitting and assembling** Each import is `project_import {paths: [two_hollow_squares.obj]}`, whose reply's `added` is 1; the object is named @@ -743,10 +778,18 @@ unscaled and not mirrored, and a plate's settings as in a plate's own settings. across plates (splitting and assembling; ordering), Fill bed on another plate (arranging, step 17); its closing slice is replaced by the G-code checks of leaving instances out of the print. - `object_list {screen: true}`, paging with `limit` and `offset`, and the short rows `object_list` gives without - `detail`: no replaced replay used them, and they change how `object_list` reports the objects, not what the objects - are. The short rows are checked in the unit tests (`test_mcp_scene.cpp`). -- Deleting instances, parts, a plate's objects (`plate`) and every object (`all`): no replaced replay deleted them but - by index and on the selection; the parts are deleted in `test_menu_items_refusals`. + `detail` but their `instances` and `instance_ids` (naming by id, steps 1 and 9): no replaced replay used them, and they + change how `object_list` reports the objects, not what the objects are. The short rows are checked in the unit tests + (`test_mcp_scene.cpp`). +- Deleting parts, a plate's objects (`plate`) and every object (`all`): no replaced replay deleted them but by index + and on the selection; the parts are deleted in `test_menu_items_refusals`. Instances are deleted only by id (naming by + id, step 12). +- Naming by id where the scenario does not: `fill_object_id` that names an object (step 18 checks only the refusal; Fill + bed itself is checked by index in arranging, and the id only decides which index the call takes), an index and its id + given together in a list (`objects` with `object_ids`, `parts` with `part_ids`), `order_ids` beside `order`, and the + Design tab's `replace_ids` (the Design tab's tests are not under the read-back rule). The unit tests + (`tests/slic3rutils/test_mcp_scene.cpp`, `test_mcp_tools.cpp`) check how each id argument is read as its index and + what the journal records of it. - The layer heights a height range or an adaptive profile gives: the layers entry checks them. Here only which object the selection names. - What `part_replace` does with keep_painting off. It then copies the painting by triangle (`replace_part_with_file()` diff --git a/tools/mcp/test_gizmos.py b/tools/mcp/test_gizmos.py index f37f475cfd..6ae83ffa19 100644 --- a/tools/mcp/test_gizmos.py +++ b/tools/mcp/test_gizmos.py @@ -327,7 +327,7 @@ class GizmosTest: for key in keys: value = reply.get(key) if isinstance(value, list): - value = [{k: v for k, v in item.items() if k not in ("object_id", "part_id")} for item in value] + value = [{k: v for k, v in item.items() if k not in ("object_id", "part_id", "instance_id")} for item in value] out[key] = value return out diff --git a/tools/mcp/test_objects.py b/tools/mcp/test_objects.py index 8396c9ccee..ead9a4fcab 100644 --- a/tools/mcp/test_objects.py +++ b/tools/mcp/test_objects.py @@ -1665,6 +1665,172 @@ class Structure(Part): objects_[1].get("layer_height_profile")) self.t.check(f"{s} 9: Cube has no profile", "layer_height_profile" not in objects_[0], objects_[0]) + def naming_by_id(self): + s = "naming by id" + self.start(s) + + def three_cubes(): + for name, x in (("a", 40), ("b", 100), ("c", 160)): + self.run("object_add_primitive", name=name, position=self.at(x, 60, 0), **CUBE) + self.run("object_select", none=True) + + def short_rows(name): + """The rows object_list gives the named object without detail, one per plate it has instances on.""" + listing = self.c.call("object_list", limit=500) + groups = [p["objects"] for p in listing["plates"]] + [listing.get("outside", [])] + return [row for rows in groups for row in rows if row["name"] == name] + + def ids_beside(label, obj): + """The short rows of `obj` give each instance's id at the place its index has in `instances`.""" + by_index = {inst["index"]: inst["id"] for inst in obj["instances"]} + for row in short_rows(obj["name"]): + self.t.equal(f"{label}: {obj['name']}'s instance_ids beside instances {row.get('instances')}", + row.get("instance_ids"), [by_index.get(i) for i in row.get("instances", [])]) + + def instance_offsets(obj): + return [inst["offset"][:2] for inst in obj["instances"]] + + def picked(items, keys): + return [{k: item.get(k) for k in keys} for item in items or []] + + three_cubes() + objects_ = self.objects_are(f"{s} 1", "a", "b", "c") + A, B, C = (o["id"] for o in objects_) + self.t.check(f"{s} 1: the ids differ", len({A, B, C}) == 3, (A, B, C)) + self.t.check(f"{s} 1: no id is an index the project has", min(A, B, C) > 2, (A, B, C)) + c_instance = objects_[2]["instances"][0]["id"] + for obj in objects_: + rows = short_rows(obj["name"]) + self.t.equal(f"{s} 1: {obj['name']}'s short rows", [(r.get("instances"), r.get("instance_ids")) for r in rows], + [([0], [obj["instances"][0]["id"]])]) + self.run("replay_export", clear=True) + + reply = self.run("object_rename", object_id=B, name="bee") + self.t.equal(f"{s} 2: the reply's objects", picked(reply.get("objects"), ("index", "object_id", "name")), + [{"index": 1, "object_id": B, "name": "bee"}]) + self.objects_are(f"{s} 2", "a", "bee", "c") + + self.run("object_delete", object_ids=[A]) + objects_ = self.objects_are(f"{s} 3", "bee", "c") + self.placed(f"{s} 3", objects_[0], 100, 60) + self.placed(f"{s} 3", objects_[1], 160, 60) + self.t.equal(f"{s} 3: the ids stay with their objects", [o["id"] for o in objects_], [B, C]) + + self.run("object_transform", object_id=C, translate=[0, 20, 0]) + objects_ = self.objects_are(f"{s} 4", "bee", "c") + self.placed(f"{s} 4", objects_[0], 100, 60) + self.placed(f"{s} 4", objects_[1], 160, 80) + + def places_as_after_4(label): + objects_ = self.objects_are(label, "bee", "c") + self.placed(label, objects_[0], 100, 60) + self.placed(label, objects_[1], 160, 80) + + self.t.refused(f"{s} 5: an index and an id of different objects are refused", + lambda: self.c.call("object_transform", object=1, object_id=B, translate=[0, 20, 0]), + words='The object at this index is now "c"') + places_as_after_4(f"{s} 5") + self.t.refused(f"{s} 6: an id no object has is refused", + lambda: self.c.call("object_transform", object_id=A, translate=[0, 20, 0]), + code="invalid_argument", words=f"No object has id {A}") + places_as_after_4(f"{s} 6") + self.t.refused(f"{s} 7: an id given as an index is named for what it is", + lambda: self.c.call("object_transform", object=C, translate=[0, 20, 0]), + code="invalid_argument", words=f"{C} is the id of object 1") + places_as_after_4(f"{s} 7") + + self.run("settings_set", target="object", object_id=C, values={"wall_loops": 5}) + objects_ = self.objects_are(f"{s} 8", "bee", "c") + self.t.check(f"{s} 8: c overrides wall_loops", "wall_loops" in objects_[1].get("overrides", []), objects_[1]) + self.t.check(f"{s} 8: bee does not", "wall_loops" not in objects_[0].get("overrides", []), objects_[0]) + + self.run("object_set_instances", object_id=C, count=3) + objects_ = self.objects_are(f"{s} 9", "bee", "c") + c = objects_[1] + self.t.equal(f"{s} 9: c's instances", len(c["instances"]), 3) + I0, I1, I2 = (inst["id"] for inst in c["instances"]) + self.t.equal(f"{s} 9: instance 0 keeps its id", I0, c_instance) + self.t.check(f"{s} 9: the instances' ids differ", len({I0, I1, I2}) == 3, (I0, I1, I2)) + ids_beside(f"{s} 9", c) + before = instance_offsets(c) + + self.run("object_transform", instance_id=I2, translate=[0, 20, 0]) + objects_ = self.objects_are(f"{s} 10", "bee", "c") + moved = instance_offsets(objects_[1]) + self.t.near(f"{s} 10: instance 2 moved 20 mm along y", moved[2], [before[2][0], before[2][1] + 20], 0.001) + self.t.near(f"{s} 10: instance 0 stays", moved[0], before[0], 0.001) + self.t.near(f"{s} 10: instance 1 stays", moved[1], before[1], 0.001) + + reply = self.run("object_set_printable", instance_ids=[I1], printable=False) + self.t.equal(f"{s} 11: the reply's instances", picked(reply.get("instances"), ("object", "instance", "instance_id")), + [{"object": 1, "instance": 1, "instance_id": I1}]) + objects_ = self.objects_are(f"{s} 11", "bee", "c") + self.t.equal(f"{s} 11: c's printable", [inst["printable"] for inst in objects_[1]["instances"]], + [True, False, True]) + + self.run("object_delete", instance_ids=[I0]) + objects_ = self.objects_are(f"{s} 12", "bee", "c") + self.t.equal(f"{s} 12: c's instances keep their ids", [inst["id"] for inst in objects_[1]["instances"]], [I1, I2]) + self.t.equal(f"{s} 12: c's printable", [inst["printable"] for inst in objects_[1]["instances"]], [False, True]) + + reply = self.run("object_set_printable", instance_ids=[I1], printable=True) + self.t.equal(f"{s} 13: the reply's instances", picked(reply.get("instances"), ("object", "instance", "instance_id")), + [{"object": 1, "instance": 0, "instance_id": I1}]) + objects_ = self.objects_are(f"{s} 13", "bee", "c") + self.t.equal(f"{s} 13: c's printable", [inst["printable"] for inst in objects_[1]["instances"]], [True, True]) + after_13 = instance_offsets(objects_[1]) + + self.run("part_add", object_id=B, type="modifier", shape="cube") + objects_ = self.objects_are(f"{s} 14", "bee: part, modifier", "c") + P = objects_[0]["parts"][1]["id"] + + reply = self.run("part_change_type", part_ids=[P], type="negative") + self.t.equal(f"{s} 15: the reply's parts", picked(reply.get("parts"), ("object", "part", "part_id", "type")), + [{"object": 0, "part": 1, "part_id": P, "type": "negative"}]) + self.objects_are(f"{s} 15", "bee: part, negative", "c") + + self.run("object_rename", part_id=P, name="hole") + objects_ = self.objects_are(f"{s} 16", "bee: part, negative", "c") + self.t.equal(f"{s} 16: bee's part 1 named hole", objects_[0]["parts"][1]["name"], "hole") + + reply = self.run("object_order", order_ids=[C, B]) + self.t.equal(f"{s} 17: the reply's order", picked(reply.get("order"), ("name", "object_id")), + [{"name": "c", "object_id": C}, {"name": "bee", "object_id": B}]) + self.objects_are(f"{s} 17", "c", "bee") + + self.t.refused(f"{s} 18: Fill bed of an id no object has is refused", + lambda: self.c.call("object_arrange", fill_object_id=A), + code="invalid_argument", words=f"No object has id {A}") + objects_ = self.objects_are(f"{s} 18", "c", "bee") + self.t.near(f"{s} 18: c's instances where they were", [v for xy in instance_offsets(objects_[0]) for v in xy], + [v for xy in after_13 for v in xy], 0.001) + self.placed(f"{s} 18", objects_[1], 100, 60) + + replay = self.run("replay_export").get("replay", {}) + targets = ("object", "objects", "instance", "instances", "part", "parts", "order") + steps = [step for step in replay.get("steps", []) if step.get("tool") != "app_wait"] + self.t.equal(f"{s} 19: the replay's steps and their targets", + [(step.get("tool"), {k: v for k, v in step.get("args", {}).items() if k in targets}) for step in steps], + [("object_rename", {"object": 1}), ("object_delete", {"objects": [0]}), + ("object_transform", {"object": 1}), ("settings_set", {"object": 1}), + ("object_set_instances", {"object": 1}), ("object_transform", {"object": 1, "instance": 2}), + ("object_set_printable", {"instances": [[1, 1]]}), ("object_delete", {"instances": [[1, 0]]}), + ("object_set_printable", {"instances": [[1, 0]]}), ("part_add", {"object": 0}), + ("part_change_type", {"parts": [[0, 1]]}), ("object_rename", {"object": 0, "part": 1}), + ("object_order", {"order": [1, 0]})]) + with_ids = [(step.get("tool"), k) for step in steps for k in step.get("args", {}) if k.endswith(("_id", "_ids"))] + self.t.equal(f"{s} 19: no step names an id", with_ids, []) + + self.renew(s) + three_cubes() + fresh = [o["id"] for o in self.objects_are(f"{s} 20: the cubes again", "a", "b", "c")] + self.t.check(f"{s} 20: the new cubes' ids are none of A, B and C", not {A, B, C} & set(fresh), fresh) + self.run("replay_run", replay=replay) + objects_ = self.objects_are(f"{s} 20", "c", "bee: part, negative") + self.t.check(f"{s} 20: c overrides wall_loops", "wall_loops" in objects_[0].get("overrides", []), objects_[0]) + self.t.equal(f"{s} 20: c's printable", [inst["printable"] for inst in objects_[0]["instances"]], [True, True]) + self.t.equal(f"{s} 20: bee's part 1 named hole", objects_[1]["parts"][1]["name"], "hole") + def splitting(self): s = "splitting and assembling" self.start(s) @@ -1854,8 +2020,12 @@ class Structure(Part): self.placed(label, obj, places[obj["name"]], 60) return objects_ + def entries(reply): + """The reply's order with the fields this scenario fixes: each entry's name, index and plate.""" + return [{k: e.get(k) for k in ("name", "object", "plate")} for e in reply.get("order") or []] + def order_is(label, reply, order, descending=None): - self.t.equal(f"{label}: the reply's order", reply.get("order"), + self.t.equal(f"{label}: the reply's order", entries(reply), [{"name": n, "object": i, "plate": 0} for i, n in enumerate(order)]) if descending is None: self.t.check(f"{label}: the reply has no descending", "descending" not in reply, reply) @@ -1903,7 +2073,7 @@ class Structure(Part): order_is(f"{s} 12", reply, given) state(f"{s} 12", given, first) reply = self.run("object_order", plate=0, order=[0, 1, 2]) - self.t.equal(f"{s} 13: the order they have changes nothing: the reply's order", reply.get("order"), + self.t.equal(f"{s} 13: the order they have changes nothing: the reply's order", entries(reply), [{"name": n, "object": i, "plate": 0} for i, n in enumerate(given)]) state(f"{s} 13", given, first) self.undo() @@ -2129,7 +2299,8 @@ class Structure(Part): self.t.equal(f"{s} 5: part 0's triangles", part["triangles"], 14) def scenarios(self): - return [("renaming and deleting", self.renaming), ("splitting and assembling", self.splitting), + return [("renaming and deleting", self.renaming), ("naming by id", self.naming_by_id), + ("splitting and assembling", self.splitting), ("parts", self.parts), ("ordering", self.ordering), ("repairing a mesh", self.repairing), ("the files a part comes from", self.files), ("painting kept through a mesh change", self.painting)]